Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Profilepage sellshares #66

Merged
merged 2 commits into from
Feb 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 16 additions & 17 deletions backend/handlers/bets/sellpositionhandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,11 @@ import (
"encoding/json"
"net/http"
betutils "socialpredict/handlers/bets/betutils"
dbpm "socialpredict/handlers/math/outcomes/dbpm"
"socialpredict/handlers/positions"
"socialpredict/middleware"
"socialpredict/models"
"socialpredict/util"
"strconv"
"time"
)

Expand All @@ -32,23 +33,16 @@ func SellPositionHandler(w http.ResponseWriter, r *http.Request) {
return
}

// get the marketID in string format
marketIDStr := strconv.FormatUint(uint64(redeemRequest.MarketID), 10)

// Validate the request similar to PlaceBetHandler
betutils.CheckMarketStatus(db, redeemRequest.MarketID)

// Calculate the net aggregate positions for the user
allPositions := dbpm.GetMarketPositionsByUser(db, user.Username) // Assuming this function exists and retrieves all market positions for a user
netPositions := dbpm.NetAggregateMarketPositions(allPositions)

// Find the user's net position for the requested market
var userNetPosition *models.MarketPosition
for _, pos := range netPositions {
if pos.MarketID == redeemRequest.MarketID && pos.Username == user.Username {
userNetPosition = &pos
break
}
}

if userNetPosition == nil {
userNetPosition, err := positions.CalculateMarketPositionForUser_WPAM_DBPM(db, marketIDStr, user.Username)
if userNetPosition.NoSharesOwned == 0 && userNetPosition.YesSharesOwned == 0 {
http.Error(w, "No position found for the given market", http.StatusBadRequest)
return
}
Expand All @@ -61,11 +55,7 @@ func SellPositionHandler(w http.ResponseWriter, r *http.Request) {
}

// Proceed with redemption logic
// Here, you would typically update the user's balance and record the transaction
// as a negative bet or a separate redemption record, depending on your data model.

// For simplicity, we're just creating a negative bet to represent the sale
// Note: Ensure your system correctly handles negative bets in all relevant calculations
redeemRequest.Amount = -redeemRequest.Amount // Negate the amount to indicate sale
redeemRequest.PlacedAt = time.Now() // Set the current time as the redemption time

Expand All @@ -75,6 +65,15 @@ func SellPositionHandler(w http.ResponseWriter, r *http.Request) {
return
}

// Deduct the bet and switching sides fee amount from the user's balance
user.AccountBalance -= redeemRequest.Amount

// Update the user's balance in the database
if err := db.Save(&user).Error; err != nil {
http.Error(w, "Error updating user balance: "+err.Error(), http.StatusInternalServerError)
return
}

// Return a success response
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(redeemRequest)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package marketshandlers
package marketpublicresponse

import (
"errors"
Expand Down
13 changes: 7 additions & 6 deletions backend/handlers/markets/marketdetailshandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package marketshandlers
import (
"encoding/json"
"net/http"
"socialpredict/handlers/marketpublicresponse"
marketmath "socialpredict/handlers/math/market"
"socialpredict/handlers/math/probabilities/wpam"
"socialpredict/handlers/tradingdata"
Expand All @@ -15,11 +16,11 @@ import (

// MarketDetailResponse defines the structure for the market detail response
type MarketDetailHandlerResponse struct {
Market PublicResponseMarket `json:"market"`
Creator usersHandlers.PublicUserType `json:"creator"`
ProbabilityChanges []wpam.ProbabilityChange `json:"probabilityChanges"`
NumUsers int `json:"numUsers"`
TotalVolume int64 `json:"totalVolume"`
Market marketpublicresponse.PublicResponseMarket `json:"market"`
Creator usersHandlers.PublicUserType `json:"creator"`
ProbabilityChanges []wpam.ProbabilityChange `json:"probabilityChanges"`
NumUsers int `json:"numUsers"`
TotalVolume int64 `json:"totalVolume"`
}

func MarketDetailsHandler(w http.ResponseWriter, r *http.Request) {
Expand All @@ -42,7 +43,7 @@ func MarketDetailsHandler(w http.ResponseWriter, r *http.Request) {
bets := tradingdata.GetBetsForMarket(db, marketIDUint)

// return the PublicResponse type with information about the market
publicResponseMarket, err := GetPublicResponseMarketByID(db, marketId)
publicResponseMarket, err := marketpublicresponse.GetPublicResponseMarketByID(db, marketId)
if err != nil {
http.Error(w, "Invalid market ID", http.StatusBadRequest)
return
Expand Down
27 changes: 27 additions & 0 deletions backend/handlers/positions/positionshandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package positions

import (
"encoding/json"
"net/http"
"socialpredict/errors"
"socialpredict/util"

"github.com/gorilla/mux"
)

func MarketDBPMPositionsHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
marketIdStr := vars["marketId"]

// open up database to utilize connection pooling
db := util.GetDB()

marketDBPMPositions, err := CalculateMarketPositions_WPAM_DBPM(db, marketIdStr)
if errors.HandleHTTPError(w, err, http.StatusBadRequest, "Invalid request or data processing error.") {
return // Stop execution if there was an error.
}

// Respond with the bets display information
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(marketDBPMPositions)
}
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
package marketshandlers
package positions

import (
"encoding/json"
"net/http"
"socialpredict/errors"
"socialpredict/handlers/marketpublicresponse"
"socialpredict/handlers/math/outcomes/dbpm"
"socialpredict/handlers/math/probabilities/wpam"
"socialpredict/handlers/tradingdata"
"socialpredict/models"
"socialpredict/util"
"strconv"

"github.com/gorilla/mux"
"gorm.io/gorm"
)

Expand All @@ -28,23 +25,6 @@ type UserMarketPosition struct {
YesSharesOwned int64
}

func MarketDBPMPositionsHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
marketIdStr := vars["marketId"]

// open up database to utilize connection pooling
db := util.GetDB()

marketDBPMPositions, err := CalculateMarketPositions_WPAM_DBPM(db, marketIdStr)
if errors.HandleHTTPError(w, err, http.StatusBadRequest, "Invalid request or data processing error.") {
return // Stop execution if there was an error.
}

// Respond with the bets display information
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(marketDBPMPositions)
}

// FetchMarketPositions fetches and summarizes positions for a given market.
// It returns a slice of MarketPosition as defined in the dbpm package.
func CalculateMarketPositions_WPAM_DBPM(db *gorm.DB, marketIdStr string) ([]dbpm.MarketPosition, error) {
Expand All @@ -58,7 +38,7 @@ func CalculateMarketPositions_WPAM_DBPM(db *gorm.DB, marketIdStr string) ([]dbpm
marketIDUint := uint(marketIDUint64)

// Assuming a function to fetch the market creation time
publicResponseMarket, err := GetPublicResponseMarketByID(db, marketIdStr)
publicResponseMarket, err := marketpublicresponse.GetPublicResponseMarketByID(db, marketIdStr)
if errors.ErrorLogger(err, "Can't convert marketIdStr to publicResponseMarket.") {
return nil, err
}
Expand Down
35 changes: 35 additions & 0 deletions backend/handlers/users/userpositiononmarkethandler.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package usershandlers

import (
"encoding/json"
"net/http"
"socialpredict/handlers/positions"
"socialpredict/middleware"
"socialpredict/util"

"github.com/gorilla/mux"
)

type UserMarketPositionResponse struct {
Username string `json:"username"`
NetPosition int64 `json:"position"`
}

func UserMarketPositionHandler(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
marketId := vars["marketId"]

// open up database to utilize connection pooling
db := util.GetDB()
user, err := middleware.ValidateTokenAndGetUser(r, db)
if err != nil {
http.Error(w, "Invalid token: "+err.Error(), http.StatusUnauthorized)
return
}

userNetPosition, err := positions.CalculateMarketPositionForUser_WPAM_DBPM(db, marketId, user.Username)

w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(userNetPosition)

}
7 changes: 4 additions & 3 deletions backend/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"net/http"
"socialpredict/middleware"
"socialpredict/migration"
"socialpredict/seed"
"socialpredict/server"
"socialpredict/util"
)
Expand All @@ -30,9 +31,9 @@ func main() {
migration.MigrateDB(db)

// Seed the admin user
// seed.SeedUsers(db)
// seed.SeedMarket(db)
// seed.SeedBets(db)
seed.SeedUsers(db)
seed.SeedMarket(db)
seed.SeedBets(db)

server.Start()
}
Expand Down
6 changes: 4 additions & 2 deletions backend/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"socialpredict/handlers"
betshandlers "socialpredict/handlers/bets"
marketshandlers "socialpredict/handlers/markets"
"socialpredict/handlers/positions"
usershandlers "socialpredict/handlers/users"
"socialpredict/middleware"

Expand Down Expand Up @@ -34,7 +35,7 @@ func Start() {
router.HandleFunc("/v0/markets/{marketId}", marketshandlers.MarketDetailsHandler).Methods("GET")
// handle market positions, get trades
router.HandleFunc("/v0/markets/bets/{marketId}", betshandlers.MarketBetsDisplayHandler).Methods("GET")
router.HandleFunc("/v0/markets/positions/{marketId}", marketshandlers.MarketDBPMPositionsHandler).Methods("GET")
router.HandleFunc("/v0/markets/positions/{marketId}", positions.MarketDBPMPositionsHandler).Methods("GET")
// show comments on markets

// handle public user stuff
Expand All @@ -49,7 +50,8 @@ func Start() {
// handle private user actions such as resolve a market, make a bet, create a market, change profile
router.HandleFunc("/v0/resolve/{marketId}", marketshandlers.ResolveMarketHandler).Methods("POST")
router.HandleFunc("/v0/bet", betshandlers.PlaceBetHandler).Methods("POST")
// router.HandleFunc("/v0/sell", betsHandlers.SellShareHandler).Methods("POST")
router.HandleFunc("/v0/userposition", usershandlers.UserMarketPositionHandler)
router.HandleFunc("/v0/sell", betshandlers.SellPositionHandler).Methods("POST")
router.HandleFunc("/v0/create", marketshandlers.CreateMarketHandler)

// Apply the CORS middleware to the Gorilla Mux router
Expand Down