package keeper import ( "context" "fmt" "math/big" "reflect" "cosmos-test/x/cosmostest/memdb" "cosmos-test/x/cosmostest/types" sdk "github.com/cosmos/cosmos-sdk/types" ) func (k msgServer) NewBid(goCtx context.Context, msg *types.MsgNewBid) (*types.MsgNewBidResponse, error) { ctx := sdk.UnwrapSDKContext(goCtx) auction, found := k.Keeper.GetAuction(ctx, msg.AuctionIndex) if !found { return nil, fmt.Errorf("didn't find auction of index %s", msg.AuctionIndex) } auctionExpired, err := k.Keeper.AuctionIsExpired(ctx, msg.AuctionIndex) if err != nil { return nil, fmt.Errorf("error while checking auction %s expiry status: %s", msg.AuctionIndex, err) } if auctionExpired { return nil, fmt.Errorf("auction %s is expired", msg.AuctionIndex) } ok := false amt := new(big.Int) amt, ok = amt.SetString(msg.Amount, 10) if !ok { return nil, fmt.Errorf("failed to convert `%s` to a large integer", msg.Amount) } if amt.Sign() != 1 { return nil, fmt.Errorf("bid amount must be greater than 0") } addr, err := sdk.AccAddressFromBech32(msg.Creator) if err != nil { return nil, fmt.Errorf("sender address `%s` format invalid (bech32 required)", msg.Creator) } spendable := k.bank.SpendableCoins(ctx, addr) // if balance does not exceed or equal proposed bid amount... if spendable.AmountOf(auction.Denom).BigInt().Cmp(amt) == -1 { return nil, fmt.Errorf("not enough balance to bid %s%s", msg.Amount, auction.Denom) } lowestBid, err := memdb.BidDB.GetLowestBid(msg.AuctionIndex) // we manually handle KeyNotFound in GetHighestBid, so should return (nil, nil) if not found if err != nil { return nil, fmt.Errorf("failed to get lowest bid: %s", reflect.TypeOf(err)) } if lowestBid != nil { amtPrev := new(big.Int) amtPrev, ok = amtPrev.SetString(lowestBid.Amount, 10) if !ok { // this should have been checked before, but whatever return nil, fmt.Errorf("failed to convert max bid (%s) to a large integer", msg.Amount) } if amt.Cmp(amtPrev) != -1 { return nil, fmt.Errorf("bid amount must be less than current lowest bid (%s)", amtPrev) } } bid := &types.Bid{ Amount: msg.Amount, Owner: msg.Creator, } if err := memdb.BidDB.AddBid(msg.AuctionIndex, bid); err != nil { return nil, fmt.Errorf("failed to add bid: %s", err) } // auction.Bids = append(auction.Bids, bid) // k.Keeper.SetAuction(ctx, auction) return &types.MsgNewBidResponse{}, nil }