/
auction.go
553 lines (455 loc) · 18.9 KB
/
auction.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
package keeper
import (
"fmt"
"sort"
"strconv"
"time"
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
"github.com/tendermint/fundraising/x/fundraising/types"
)
// GetNextAuctionIdWithUpdate increments auction id by one and store it.
func (k Keeper) GetNextAuctionIdWithUpdate(ctx sdk.Context) uint64 {
id := k.GetLastAuctionId(ctx) + 1
k.SetAuctionId(ctx, id)
return id
}
// CreateFixedPriceAuction handles types.MsgCreateFixedPriceAuction and create a fixed price auction.
// Note that the module is designed to delegate authorization to an external module to add allowed bidders for the auction.
func (k Keeper) CreateFixedPriceAuction(ctx sdk.Context, msg *types.MsgCreateFixedPriceAuction) (types.AuctionI, error) {
if ctx.BlockTime().After(msg.EndTime) { // EndTime < CurrentTime
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "end time must be set after the current time")
}
if len(msg.VestingSchedules) > types.MaxNumVestingSchedules {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "exceed maximum number of vesting schedules")
}
nextId := k.GetNextAuctionIdWithUpdate(ctx)
if err := k.PayCreationFee(ctx, msg.GetAuctioneer()); err != nil {
return nil, sdkerrors.Wrap(err, "failed to pay auction creation fee")
}
if err := k.ReserveSellingCoin(ctx, nextId, msg.GetAuctioneer(), msg.SellingCoin); err != nil {
return nil, sdkerrors.Wrap(err, "failed to reserve selling coin")
}
ba := types.NewBaseAuction(
nextId,
types.AuctionTypeFixedPrice,
msg.Auctioneer,
types.SellingReserveAddress(nextId).String(),
types.PayingReserveAddress(nextId).String(),
msg.StartPrice,
msg.SellingCoin,
msg.PayingCoinDenom,
types.VestingReserveAddress(nextId).String(),
msg.VestingSchedules,
msg.StartTime,
[]time.Time{msg.EndTime}, // it is an array data type to handle BatchAuction
types.AuctionStatusStandBy,
)
// Update status if the start time is already passed over the current time
if ba.ShouldAuctionStarted(ctx.BlockTime()) {
_ = ba.SetStatus(types.AuctionStatusStarted)
}
auction := types.NewFixedPriceAuction(ba, msg.SellingCoin)
// Call hook before storing an auction
k.BeforeFixedPriceAuctionCreated(
ctx,
auction.Auctioneer,
auction.StartPrice,
auction.SellingCoin,
auction.PayingCoinDenom,
auction.VestingSchedules,
auction.StartTime,
auction.EndTimes[0],
)
k.SetAuction(ctx, auction)
// Call hook after storing an auction
k.AfterFixedPriceAuctionCreated(
ctx,
auction.Id,
auction.Auctioneer,
auction.StartPrice,
auction.SellingCoin,
auction.PayingCoinDenom,
auction.VestingSchedules,
auction.StartTime,
auction.EndTimes[0],
)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCreateFixedPriceAuction,
sdk.NewAttribute(types.AttributeKeyAuctionId, strconv.FormatUint(nextId, 10)),
sdk.NewAttribute(types.AttributeKeyAuctioneerAddress, auction.GetAuctioneer().String()),
sdk.NewAttribute(types.AttributeKeySellingReserveAddress, auction.GetSellingReserveAddress().String()),
sdk.NewAttribute(types.AttributeKeyPayingReserveAddress, auction.GetPayingReserveAddress().String()),
sdk.NewAttribute(types.AttributeKeyStartPrice, auction.GetStartPrice().String()),
sdk.NewAttribute(types.AttributeKeySellingCoin, auction.GetSellingCoin().String()),
sdk.NewAttribute(types.AttributeKeyPayingCoinDenom, auction.GetPayingCoinDenom()),
sdk.NewAttribute(types.AttributeKeyVestingReserveAddress, auction.GetVestingReserveAddress().String()),
sdk.NewAttribute(types.AttributeKeyRemainingSellingCoin, auction.RemainingSellingCoin.String()),
sdk.NewAttribute(types.AttributeKeyStartTime, auction.GetStartTime().String()),
sdk.NewAttribute(types.AttributeKeyEndTime, msg.EndTime.String()),
sdk.NewAttribute(types.AttributeKeyAuctionStatus, auction.GetStatus().String()),
),
})
return auction, nil
}
// CreateBatchAuction handles types.MsgCreateBatchAuction and create a batch auction.
// Note that the module is designed to delegate authorization to an external module to add allowed bidders for the auction.
func (k Keeper) CreateBatchAuction(ctx sdk.Context, msg *types.MsgCreateBatchAuction) (types.AuctionI, error) {
if ctx.BlockTime().After(msg.EndTime) { // EndTime < CurrentTime
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "end time must be set after the current time")
}
if len(msg.VestingSchedules) > types.MaxNumVestingSchedules {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "exceed maximum number of vesting schedules")
}
if msg.MaxExtendedRound > types.MaxExtendedRound {
return nil, sdkerrors.Wrap(sdkerrors.ErrInvalidRequest, "exceed maximum extended round")
}
nextId := k.GetNextAuctionIdWithUpdate(ctx)
if err := k.PayCreationFee(ctx, msg.GetAuctioneer()); err != nil {
return nil, sdkerrors.Wrap(err, "failed to pay auction creation fee")
}
if err := k.ReserveSellingCoin(ctx, nextId, msg.GetAuctioneer(), msg.SellingCoin); err != nil {
return nil, sdkerrors.Wrap(err, "failed to reserve selling coin")
}
endTimes := []time.Time{msg.EndTime} // it is an array data type to handle BatchAuction
ba := types.NewBaseAuction(
nextId,
types.AuctionTypeBatch,
msg.Auctioneer,
types.SellingReserveAddress(nextId).String(),
types.PayingReserveAddress(nextId).String(),
msg.StartPrice,
msg.SellingCoin,
msg.PayingCoinDenom,
types.VestingReserveAddress(nextId).String(),
msg.VestingSchedules,
msg.StartTime,
endTimes,
types.AuctionStatusStandBy,
)
// Update status if the start time is already passed the current time
if ba.ShouldAuctionStarted(ctx.BlockTime()) {
_ = ba.SetStatus(types.AuctionStatusStarted)
}
auction := types.NewBatchAuction(
ba,
msg.MinBidPrice,
sdk.ZeroDec(),
msg.MaxExtendedRound,
msg.ExtendedRoundRate,
)
// Call hook before storing an auction
k.BeforeBatchAuctionCreated(
ctx,
auction.Auctioneer,
auction.StartPrice,
auction.MinBidPrice,
auction.SellingCoin,
auction.PayingCoinDenom,
auction.VestingSchedules,
auction.MaxExtendedRound,
auction.ExtendedRoundRate,
auction.StartTime,
auction.EndTimes[0],
)
k.SetAuction(ctx, auction)
// Call hook after storing an auction
k.AfterBatchAuctionCreated(
ctx,
auction.Id,
auction.Auctioneer,
auction.StartPrice,
auction.MinBidPrice,
auction.SellingCoin,
auction.PayingCoinDenom,
auction.VestingSchedules,
auction.MaxExtendedRound,
auction.ExtendedRoundRate,
auction.StartTime,
auction.EndTimes[0],
)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCreateBatchAuction,
sdk.NewAttribute(types.AttributeKeyAuctionId, strconv.FormatUint(nextId, 10)),
sdk.NewAttribute(types.AttributeKeyAuctioneerAddress, auction.GetAuctioneer().String()),
sdk.NewAttribute(types.AttributeKeySellingReserveAddress, auction.GetSellingReserveAddress().String()),
sdk.NewAttribute(types.AttributeKeyPayingReserveAddress, auction.GetPayingReserveAddress().String()),
sdk.NewAttribute(types.AttributeKeyStartPrice, auction.GetStartPrice().String()),
sdk.NewAttribute(types.AttributeKeySellingCoin, auction.GetSellingCoin().String()),
sdk.NewAttribute(types.AttributeKeyPayingCoinDenom, auction.GetPayingCoinDenom()),
sdk.NewAttribute(types.AttributeKeyVestingReserveAddress, auction.GetVestingReserveAddress().String()),
sdk.NewAttribute(types.AttributeKeyStartTime, auction.GetStartTime().String()),
sdk.NewAttribute(types.AttributeKeyEndTime, msg.EndTime.String()),
sdk.NewAttribute(types.AttributeKeyAuctionStatus, auction.GetStatus().String()),
sdk.NewAttribute(types.AttributeKeyMinBidPrice, auction.MinBidPrice.String()),
sdk.NewAttribute(types.AttributeKeyMaxExtendedRound, fmt.Sprint(auction.MaxExtendedRound)),
sdk.NewAttribute(types.AttributeKeyExtendedRoundRate, auction.ExtendedRoundRate.String()),
),
})
return auction, nil
}
// CancelAuction handles types.MsgCancelAuction and cancels the auction.
// An auction can only be canceled when it is not started yet.
func (k Keeper) CancelAuction(ctx sdk.Context, msg *types.MsgCancelAuction) error {
auction, found := k.GetAuction(ctx, msg.AuctionId)
if !found {
return sdkerrors.Wrapf(sdkerrors.ErrNotFound, "auction %d not found", msg.AuctionId)
}
if auction.GetAuctioneer().String() != msg.Auctioneer {
return sdkerrors.Wrap(sdkerrors.ErrUnauthorized, "only the auctioneer can cancel the auction")
}
if auction.GetStatus() != types.AuctionStatusStandBy {
return sdkerrors.Wrap(types.ErrInvalidAuctionStatus, "only the stand by auction can be cancelled")
}
sellingReserveAddr := auction.GetSellingReserveAddress()
sellingCoinDenom := auction.GetSellingCoin().Denom
spendableCoins := k.bankKeeper.SpendableCoins(ctx, sellingReserveAddr)
releaseCoin := sdk.NewCoin(sellingCoinDenom, spendableCoins.AmountOf(sellingCoinDenom))
// Release the selling coin back to the auctioneer
if err := k.bankKeeper.SendCoins(ctx, sellingReserveAddr, auction.GetAuctioneer(), sdk.NewCoins(releaseCoin)); err != nil {
return sdkerrors.Wrap(err, "failed to release the selling coin")
}
// Call hook before cancelling the auction
k.BeforeAuctionCanceled(ctx, msg.AuctionId, msg.Auctioneer)
if auction.GetType() == types.AuctionTypeFixedPrice {
fa := auction.(*types.FixedPriceAuction)
fa.RemainingSellingCoin = sdk.NewCoin(sellingCoinDenom, sdk.ZeroInt())
auction = fa
}
_ = auction.SetStatus(types.AuctionStatusCancelled)
k.SetAuction(ctx, auction)
ctx.EventManager().EmitEvents(sdk.Events{
sdk.NewEvent(
types.EventTypeCancelAuction,
sdk.NewAttribute(types.AttributeKeyAuctionId, strconv.FormatUint(auction.GetId(), 10)),
),
})
return nil
}
// AddAllowedBidders is a function that is implemented for an external module.
// An external module uses this function to add allowed bidders in the auction's allowed bidders list.
// It doesn't look up the bidder's previous maximum bid amount. Instead, it overlaps.
// It doesn't have any auctioneer's verification logic because the module is fundamentally designed
// to delegate full authorization to an external module.
// It is up to an external module to freely add necessary verification and operations depending on their use cases.
func (k Keeper) AddAllowedBidders(ctx sdk.Context, auctionId uint64, allowedBidders []types.AllowedBidder) error {
if len(allowedBidders) == 0 {
return types.ErrEmptyAllowedBidders
}
auction, found := k.GetAuction(ctx, auctionId)
if !found {
return sdkerrors.Wrapf(sdkerrors.ErrNotFound, "auction %d is not found", auctionId)
}
// Call hook before adding allowed bidders for the auction
k.BeforeAllowedBiddersAdded(ctx, allowedBidders)
// Store new allowed bidders
for _, ab := range allowedBidders {
if err := ab.Validate(); err != nil {
return err
}
if ab.MaxBidAmount.GT(auction.GetSellingCoin().Amount) {
return types.ErrInsufficientRemainingAmount
}
k.SetAllowedBidder(ctx, auctionId, ab)
}
return nil
}
// UpdateAllowedBidder is a function that is implemented for an external module.
// An external module uses this function to update maximum bid amount of particular allowed bidder in the auction.
// It doesn't have any auctioneer's verification logic because the module is fundamentally designed
// to delegate full authorization to an external module.
// It is up to an external module to freely add necessary verification and operations depending on their use cases.
func (k Keeper) UpdateAllowedBidder(ctx sdk.Context, auctionId uint64, bidder sdk.AccAddress, maxBidAmount math.Int) error {
_, found := k.GetAuction(ctx, auctionId)
if !found {
return sdkerrors.Wrapf(sdkerrors.ErrNotFound, "auction %d is not found", auctionId)
}
_, found = k.GetAllowedBidder(ctx, auctionId, bidder)
if !found {
return sdkerrors.Wrapf(sdkerrors.ErrNotFound, "bidder %s is not found", bidder.String())
}
allowedBidder := types.NewAllowedBidder(bidder, maxBidAmount)
if err := allowedBidder.Validate(); err != nil {
return err
}
// Call hook before updating the allowed bidders for the auction
k.BeforeAllowedBidderUpdated(ctx, auctionId, bidder, maxBidAmount)
k.SetAllowedBidder(ctx, auctionId, allowedBidder)
return nil
}
// AllocateSellingCoin allocates allocated selling coin for all matched bids in MatchingInfo and
// releases them from the selling reserve account.
func (k Keeper) AllocateSellingCoin(ctx sdk.Context, auction types.AuctionI, mInfo MatchingInfo) error {
// Call hook before selling coin allocation
k.BeforeSellingCoinsAllocated(ctx, auction.GetId(), mInfo.AllocationMap, mInfo.RefundMap)
sellingReserveAddr := auction.GetSellingReserveAddress()
sellingCoinDenom := auction.GetSellingCoin().Denom
inputs := []banktypes.Input{}
outputs := []banktypes.Output{}
// Sort bidders to reserve determinism
var bidders []string
for bidder := range mInfo.AllocationMap {
bidders = append(bidders, bidder)
}
sort.Strings(bidders)
// Allocate coins to all matched bidders in AllocationMap and
// set the amounts in transaction inputs and outputs from the selling reserve account
for _, bidder := range bidders {
if mInfo.AllocationMap[bidder].IsZero() {
continue
}
allocateCoins := sdk.NewCoins(sdk.NewCoin(sellingCoinDenom, mInfo.AllocationMap[bidder]))
bidderAddr, _ := sdk.AccAddressFromBech32(bidder)
inputs = append(inputs, banktypes.NewInput(sellingReserveAddr, allocateCoins))
outputs = append(outputs, banktypes.NewOutput(bidderAddr, allocateCoins))
}
// Send all at once
if err := k.bankKeeper.InputOutputCoins(ctx, inputs, outputs); err != nil {
return err
}
return nil
}
// ReleaseVestingPayingCoin releases the vested selling coin to the auctioneer from the vesting reserve account.
func (k Keeper) ReleaseVestingPayingCoin(ctx sdk.Context, auction types.AuctionI) error {
vestingQueues := k.GetVestingQueuesByAuctionId(ctx, auction.GetId())
vestingQueuesLen := len(vestingQueues)
for i, vestingQueue := range vestingQueues {
if vestingQueue.ShouldRelease(ctx.BlockTime()) {
vestingReserveAddr := auction.GetVestingReserveAddress()
auctioneerAddr := auction.GetAuctioneer()
payingCoins := sdk.NewCoins(vestingQueue.PayingCoin)
if err := k.bankKeeper.SendCoins(ctx, vestingReserveAddr, auctioneerAddr, payingCoins); err != nil {
return sdkerrors.Wrap(err, "failed to release paying coin to the auctioneer")
}
vestingQueue.SetReleased(true)
k.SetVestingQueue(ctx, vestingQueue)
// Update status when all the amounts are released
if i == vestingQueuesLen-1 {
_ = auction.SetStatus(types.AuctionStatusFinished)
k.SetAuction(ctx, auction)
}
}
}
return nil
}
// RefundRemainingSellingCoin refunds the remaining selling coin to the auctioneer.
func (k Keeper) RefundRemainingSellingCoin(ctx sdk.Context, auction types.AuctionI) error {
sellingReserveAddr := auction.GetSellingReserveAddress()
sellingCoinDenom := auction.GetSellingCoin().Denom
spendableCoins := k.bankKeeper.SpendableCoins(ctx, sellingReserveAddr)
releaseCoins := sdk.NewCoins(sdk.NewCoin(sellingCoinDenom, spendableCoins.AmountOf(sellingCoinDenom)))
if err := k.bankKeeper.SendCoins(ctx, sellingReserveAddr, auction.GetAuctioneer(), releaseCoins); err != nil {
return err
}
return nil
}
// RefundPayingCoin refunds paying coin to the corresponding bidders.
func (k Keeper) RefundPayingCoin(ctx sdk.Context, auction types.AuctionI, mInfo MatchingInfo) error {
payingReserveAddr := auction.GetPayingReserveAddress()
payingCoinDenom := auction.GetPayingCoinDenom()
inputs := []banktypes.Input{}
outputs := []banktypes.Output{}
// Sort bidders to reserve determinism
var bidders []string
for bidder := range mInfo.RefundMap {
bidders = append(bidders, bidder)
}
sort.Strings(bidders)
// Refund the unmatched bid amount back to the bidder
for _, bidder := range bidders {
if mInfo.RefundMap[bidder].IsZero() {
continue
}
bidderAddr, err := sdk.AccAddressFromBech32(bidder)
if err != nil {
return err
}
refundCoins := sdk.NewCoins(sdk.NewCoin(payingCoinDenom, mInfo.RefundMap[bidder]))
inputs = append(inputs, banktypes.NewInput(payingReserveAddr, refundCoins))
outputs = append(outputs, banktypes.NewOutput(bidderAddr, refundCoins))
}
// Send all at once
if err := k.bankKeeper.InputOutputCoins(ctx, inputs, outputs); err != nil {
return err
}
return nil
}
// ExtendRound extends another round of ExtendedPeriod value for the auction.
func (k Keeper) ExtendRound(ctx sdk.Context, ba *types.BatchAuction) {
params := k.GetParams(ctx)
extendedPeriod := params.ExtendedPeriod
nextEndTime := ba.GetEndTimes()[len(ba.GetEndTimes())-1].AddDate(0, 0, int(extendedPeriod))
endTimes := append(ba.GetEndTimes(), nextEndTime)
_ = ba.SetEndTimes(endTimes)
k.SetAuction(ctx, ba)
}
// CloseFixedPriceAuction closes a fixed price auction.
func (k Keeper) CloseFixedPriceAuction(ctx sdk.Context, auction types.AuctionI) {
mInfo := k.CalculateFixedPriceAllocation(ctx, auction)
if err := k.AllocateSellingCoin(ctx, auction, mInfo); err != nil {
panic(err)
}
if err := k.RefundRemainingSellingCoin(ctx, auction); err != nil {
panic(err)
}
if err := k.ApplyVestingSchedules(ctx, auction); err != nil {
panic(err)
}
}
// CloseBatchAuction closes a batch auction.
func (k Keeper) CloseBatchAuction(ctx sdk.Context, auction types.AuctionI) {
ba, ok := auction.(*types.BatchAuction)
if !ok {
panic(fmt.Errorf("unable to close auction that is not a batch auction: %T", auction))
}
// Extend round since there is no last matched length to compare with
lastMatchedLen := k.GetLastMatchedBidsLen(ctx, ba.GetId())
mInfo := k.CalculateBatchAllocation(ctx, auction)
// Close the auction when maximum extended round + 1 is the same as the length of end times
// If the value of MaxExtendedRound is 0, it means that an auctioneer does not want have an extended round
if ba.MaxExtendedRound+1 == uint32(len(auction.GetEndTimes())) {
if err := k.AllocateSellingCoin(ctx, auction, mInfo); err != nil {
panic(err)
}
if err := k.RefundRemainingSellingCoin(ctx, auction); err != nil {
panic(err)
}
if err := k.RefundPayingCoin(ctx, auction, mInfo); err != nil {
panic(err)
}
if err := k.ApplyVestingSchedules(ctx, auction); err != nil {
panic(err)
}
return
}
if lastMatchedLen == 0 {
k.ExtendRound(ctx, ba)
return
}
currDec := sdk.NewDec(mInfo.MatchedLen)
lastDec := sdk.NewDec(lastMatchedLen)
diff := sdk.OneDec().Sub(currDec.Quo(lastDec)) // 1 - (CurrentMatchedLenDec / LastMatchedLenDec)
// To prevent from auction sniping technique, compare the extended round rate with
// the current and the last length of matched bids to determine
// if the auction needs another extended round
if diff.GTE(ba.ExtendedRoundRate) {
k.ExtendRound(ctx, ba)
return
}
if err := k.AllocateSellingCoin(ctx, auction, mInfo); err != nil {
panic(err)
}
if err := k.RefundRemainingSellingCoin(ctx, auction); err != nil {
panic(err)
}
if err := k.RefundPayingCoin(ctx, auction, mInfo); err != nil {
panic(err)
}
if err := k.ApplyVestingSchedules(ctx, auction); err != nil {
panic(err)
}
}