-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbid.go
387 lines (319 loc) · 12.3 KB
/
bid.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
package keeper
import (
"context"
"errors"
"strconv"
"cosmossdk.io/collections"
sdkerrors "cosmossdk.io/errors"
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
errcode "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/ignite/modules/x/fundraising/types"
)
// GetBid returns Bid by auction ID and bid ID.
func (k Keeper) GetBid(ctx context.Context, auctionID, bidID uint64) (types.Bid, error) {
b, err := k.Bid.Get(ctx, collections.Join(auctionID, bidID))
if sdkerrors.IsOf(err, collections.ErrNotFound) {
return types.Bid{}, types.ErrBidNotFound
}
return b, err
}
// GetNextBidIDWithUpdate increments bid id by one and set it.
func (k Keeper) GetNextBidIDWithUpdate(ctx context.Context, auctionID uint64) (uint64, error) {
seq, err := k.BidSeq.Get(ctx, auctionID)
if errors.Is(err, collections.ErrNotFound) {
seq = 0
} else if err != nil {
return 0, err
}
seq++
return seq, k.BidSeq.Set(ctx, auctionID, seq)
}
// GetBidsByAuctionID returns all bids associated with the auction id that are registered in the store.
func (k Keeper) GetBidsByAuctionID(ctx context.Context, auctionID uint64) ([]types.Bid, error) {
bids := make([]types.Bid, 0)
rng := collections.NewPrefixedPairRange[uint64, uint64](auctionID)
err := k.Bid.Walk(ctx, rng, func(key collections.Pair[uint64, uint64], bid types.Bid) (bool, error) {
bids = append(bids, bid)
return false, nil
})
return bids, err
}
// GetBidsByBidder returns all bids associated with the bidder that are registered in the store.
func (k Keeper) GetBidsByBidder(ctx context.Context, bidderAddr sdk.AccAddress) ([]types.Bid, error) {
bids := make([]types.Bid, 0)
// TODO find a way to store by bidder id to avoid read all store
// rng := collections.NewPrefixedPairRange[uint64, uint64](bidderAddr)
err := k.Bid.Walk(ctx, nil, func(key collections.Pair[uint64, uint64], bid types.Bid) (bool, error) {
if bid.Bidder == bidderAddr.String() {
bids = append(bids, bid)
}
return false, nil
})
return bids, err
}
// Bids returns all Bid.
func (k Keeper) Bids(ctx context.Context) ([]types.Bid, error) {
bids := make([]types.Bid, 0)
err := k.Bid.Walk(ctx, nil, func(_ collections.Pair[uint64, uint64], bid types.Bid) (bool, error) {
bids = append(bids, bid)
return false, nil
})
return bids, err
}
// PlaceBid places a bid for the selling coin of the auction.
func (k Keeper) PlaceBid(ctx context.Context, msg *types.MsgPlaceBid) (types.Bid, error) {
auction, err := k.Auction.Get(ctx, msg.AuctionId)
if err != nil {
return types.Bid{}, err
}
if auction.GetStatus() != types.AuctionStatusStarted {
return types.Bid{}, sdkerrors.Wrap(types.ErrInvalidAuctionStatus, auction.GetStatus().String())
}
if auction.GetType() == types.AuctionTypeBatch {
if msg.Price.LT(auction.(*types.BatchAuction).MinBidPrice) {
return types.Bid{}, sdkerrors.Wrap(types.ErrInsufficientMinBidPrice, msg.Price.String())
}
}
bidder, err := k.addressCodec.StringToBytes(msg.GetBidder())
if err != nil {
return types.Bid{}, err
}
_, err = k.AllowedBidder.Get(ctx, collections.Join(auction.GetId(), sdk.AccAddress(bidder)))
if err != nil {
return types.Bid{}, sdkerrors.Wrap(types.ErrNotAllowedBidder, err.Error())
}
if err := k.PayPlaceBidFee(ctx, bidder); err != nil {
return types.Bid{}, sdkerrors.Wrap(err, "failed to pay place bid fee")
}
bidID, err := k.GetNextBidIDWithUpdate(ctx, auction.GetId())
if err != nil {
return types.Bid{}, sdkerrors.Wrap(err, "failed to get next bid id")
}
bid := types.Bid{
AuctionId: msg.AuctionId,
BidId: bidID,
Bidder: msg.Bidder,
Type: msg.BidType,
Price: msg.Price,
Coin: msg.Coin,
IsMatched: false,
}
payingCoinDenom := auction.GetPayingCoinDenom()
// Place a bid depending on the bid type
switch bid.Type {
case types.BidTypeFixedPrice:
if err := k.ValidateFixedPriceBid(ctx, auction, bid); err != nil {
return types.Bid{}, err
}
fa := auction.(*types.FixedPriceAuction)
// Reserve bid amount
bidPayingAmt := bid.ConvertToPayingAmount(payingCoinDenom)
bidPayingCoin := sdk.NewCoin(payingCoinDenom, bidPayingAmt)
if err := k.ReservePayingCoin(ctx, msg.AuctionId, bidder, bidPayingCoin); err != nil {
return types.Bid{}, sdkerrors.Wrap(err, "failed to reserve paying coin")
}
// Subtract bid amount from the remaining
bidSellingAmt := bid.ConvertToSellingAmount(payingCoinDenom)
bidSellingCoin := sdk.NewCoin(auction.GetSellingCoin().Denom, bidSellingAmt)
fa.RemainingSellingCoin = fa.RemainingSellingCoin.Sub(bidSellingCoin)
if err := k.Auction.Set(ctx, fa.GetId(), fa); err != nil {
return types.Bid{}, err
}
bid.SetMatched(true)
case types.BidTypeBatchWorth:
if err := k.ValidateBatchWorthBid(ctx, auction, bid); err != nil {
return types.Bid{}, err
}
if err := k.ReservePayingCoin(ctx, msg.AuctionId, bidder, msg.Coin); err != nil {
return types.Bid{}, sdkerrors.Wrap(err, "failed to reserve paying coin")
}
case types.BidTypeBatchMany:
if err := k.ValidateBatchManyBid(ctx, auction, bid); err != nil {
return types.Bid{}, err
}
reserveAmt := bid.ConvertToPayingAmount(payingCoinDenom)
reserveCoin := sdk.NewCoin(payingCoinDenom, reserveAmt)
if err := k.ReservePayingCoin(ctx, msg.AuctionId, bidder, reserveCoin); err != nil {
return types.Bid{}, sdkerrors.Wrap(err, "failed to reserve paying coin")
}
}
// Call before bid placed hook
if err := k.BeforeBidPlaced(ctx, bid.AuctionId, bid.BidId, bid.Bidder, bid.Type, bid.Price, bid.Coin); err != nil {
return types.Bid{}, err
}
if err := k.Bid.Set(ctx, collections.Join(bid.AuctionId, bid.BidId), bid); err != nil {
return types.Bid{}, err
}
sdkCtx := sdk.UnwrapSDKContext(ctx)
sdkCtx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypePlaceBid,
sdk.NewAttribute(types.AttributeKeyAuctionID, strconv.FormatUint(auction.GetId(), 10)),
sdk.NewAttribute(types.AttributeKeyBidderAddress, msg.GetBidder()),
sdk.NewAttribute(types.AttributeKeyBidPrice, msg.Price.String()),
sdk.NewAttribute(types.AttributeKeyBidCoin, msg.Coin.String()),
),
})
return bid, nil
}
// ValidateFixedPriceBid validates a fixed price bid type.
func (k Keeper) ValidateFixedPriceBid(ctx context.Context, auction types.AuctionI, bid types.Bid) error {
if auction.GetType() != types.AuctionTypeFixedPrice {
return types.ErrIncorrectAuctionType
}
if bid.Coin.Denom != auction.GetPayingCoinDenom() &&
bid.Coin.Denom != auction.GetSellingCoin().Denom {
return types.ErrIncorrectCoinDenom
}
if !bid.Price.Equal(auction.GetStartPrice()) {
return sdkerrors.Wrap(types.ErrInvalidStartPrice, "start price must be equal to the start price of the auction")
}
// For remaining coin validation, convert bid amount in selling coin denom
bidAmt := bid.ConvertToSellingAmount(auction.GetPayingCoinDenom())
bidCoin := sdk.NewCoin(auction.GetSellingCoin().Denom, bidAmt)
remainingCoin := auction.(*types.FixedPriceAuction).RemainingSellingCoin
if remainingCoin.IsLT(bidCoin) {
return sdkerrors.Wrapf(types.ErrInsufficientRemainingAmount, "remaining selling coin amount %s", remainingCoin)
}
bidder, err := k.addressCodec.StringToBytes(bid.Bidder)
if err != nil {
return sdkerrors.Wrap(err, "invalid address")
}
// Get the total bid amount by the bidder
bids, err := k.GetBidsByBidder(ctx, bidder)
if err != nil {
return err
}
totalBidAmt := math.ZeroInt()
for _, bid := range bids {
if bid.AuctionId == auction.GetId() {
bidSellingAmt := bid.ConvertToSellingAmount(auction.GetPayingCoinDenom())
totalBidAmt = totalBidAmt.Add(bidSellingAmt)
}
}
allowedBidder, err := k.AllowedBidder.Get(ctx, collections.Join(bid.AuctionId, sdk.AccAddress(bidder)))
if err != nil {
return sdkerrors.Wrap(err, "bidder is not found in allowed bidder list")
}
totalBidAmt = totalBidAmt.Add(bidAmt)
// The total bid amount can't be greater than the bidder's maximum bid amount
if totalBidAmt.GT(allowedBidder.MaxBidAmount) {
return types.ErrOverMaxBidAmountLimit
}
return nil
}
// ValidateBatchWorthBid validates a batch worth bid type.
func (k Keeper) ValidateBatchWorthBid(ctx context.Context, auction types.AuctionI, bid types.Bid) error {
if auction.GetType() != types.AuctionTypeBatch {
return types.ErrIncorrectAuctionType
}
if bid.Coin.Denom != auction.GetPayingCoinDenom() {
return types.ErrIncorrectCoinDenom
}
bidder, err := k.addressCodec.StringToBytes(bid.Bidder)
if err != nil {
return sdkerrors.Wrap(err, "invalid address")
}
allowedBidder, err := k.AllowedBidder.Get(ctx, collections.Join(bid.AuctionId, sdk.AccAddress(bidder)))
if err != nil {
return sdkerrors.Wrap(err, "bidder is not found in allowed bidder list")
}
bidAmt := bid.ConvertToSellingAmount(auction.GetPayingCoinDenom())
// The total bid amount can't be greater than the bidder's maximum bid amount
if bidAmt.GT(allowedBidder.MaxBidAmount) {
return types.ErrOverMaxBidAmountLimit
}
return nil
}
// ValidateBatchManyBid validates a batch many bid type.
func (k Keeper) ValidateBatchManyBid(ctx context.Context, auction types.AuctionI, bid types.Bid) error {
if auction.GetType() != types.AuctionTypeBatch {
return types.ErrIncorrectAuctionType
}
if bid.Coin.Denom != auction.GetSellingCoin().Denom {
return types.ErrIncorrectCoinDenom
}
bidder, err := k.addressCodec.StringToBytes(bid.Bidder)
if err != nil {
return sdkerrors.Wrap(err, "invalid address")
}
allowedBidder, err := k.AllowedBidder.Get(ctx, collections.Join(bid.AuctionId, sdk.AccAddress(bidder)))
if err != nil {
return sdkerrors.Wrap(err, "bidder is not found in allowed bidder list")
}
bidAmt := bid.ConvertToSellingAmount(auction.GetPayingCoinDenom())
// The total bid amount can't be greater than the bidder's maximum bid amount
if bidAmt.GT(allowedBidder.MaxBidAmount) {
return types.ErrOverMaxBidAmountLimit
}
return nil
}
// ModifyBid handles types.MsgModifyBid and stores the modified bid.
// A bidder must provide either greater bid price or coin amount.
// They are not permitted to modify with less bid price or coin amount.
func (k Keeper) ModifyBid(ctx context.Context, msg *types.MsgModifyBid) error {
auction, err := k.Auction.Get(ctx, msg.AuctionId)
if err != nil {
return err
}
if auction.GetStatus() != types.AuctionStatusStarted {
return types.ErrInvalidAuctionStatus
}
if auction.GetType() != types.AuctionTypeBatch {
return types.ErrIncorrectAuctionType
}
bid, err := k.Bid.Get(ctx, collections.Join(msg.AuctionId, msg.BidId))
if err != nil {
return err
}
bidder, err := k.addressCodec.StringToBytes(msg.GetBidder())
if err != nil {
return sdkerrors.Wrap(err, "invalid address")
}
if bid.Bidder != msg.Bidder {
return sdkerrors.Wrap(errcode.ErrUnauthorized, "only the bid creator can modify the bid")
}
if msg.Price.LT(auction.(*types.BatchAuction).MinBidPrice) {
return types.ErrInsufficientMinBidPrice
}
if bid.Coin.Denom != msg.Coin.Denom {
return types.ErrIncorrectCoinDenom
}
if msg.Price.LT(bid.Price) || msg.Coin.Amount.LT(bid.Coin.Amount) {
return sdkerrors.Wrap(errcode.ErrInvalidRequest, "bid price or coin amount cannot be lower")
}
if msg.Price.Equal(bid.Price) && msg.Coin.Amount.Equal(bid.Coin.Amount) {
return sdkerrors.Wrap(errcode.ErrInvalidRequest, "bid price and coin amount must be changed")
}
// Reserve bid amount difference
switch bid.Type {
case types.BidTypeBatchWorth:
diffReserveCoin := msg.Coin.Sub(bid.Coin)
if diffReserveCoin.IsPositive() {
if err := k.ReservePayingCoin(ctx, msg.AuctionId, bidder, diffReserveCoin); err != nil {
return sdkerrors.Wrap(err, "failed to reserve paying coin")
}
}
case types.BidTypeBatchMany:
prevReserveAmt := math.LegacyNewDecFromInt(bid.Coin.Amount).Mul(bid.Price).Ceil()
currReserveAmt := math.LegacyNewDecFromInt(msg.Coin.Amount).Mul(msg.Price).Ceil()
diffReserveAmt := currReserveAmt.Sub(prevReserveAmt).TruncateInt()
diffReserveCoin := sdk.NewCoin(auction.GetPayingCoinDenom(), diffReserveAmt)
if diffReserveCoin.IsPositive() {
if err := k.ReservePayingCoin(ctx, msg.AuctionId, bidder, diffReserveCoin); err != nil {
return sdkerrors.Wrap(err, "failed to reserve paying coin")
}
}
}
bid.Price = msg.Price
bid.Coin = msg.Coin
// Call the before mid modified hook
if err := k.BeforeBidModified(ctx, bid.AuctionId, bid.BidId, bid.Bidder, bid.Type, bid.Price, bid.Coin); err != nil {
return err
}
if err := k.Bid.Set(ctx, collections.Join(bid.AuctionId, bid.BidId), bid); err != nil {
return err
}
return nil
}