/
batch.go
610 lines (509 loc) · 21.4 KB
/
batch.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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
package keeper
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/mage-war/wars/x/wars/internal/types"
)
func (k Keeper) MustGetBatch(ctx sdk.Context, token string) types.Batch {
store := ctx.KVStore(k.storeKey)
if !k.BatchExists(ctx, token) {
panic(fmt.Sprintf("batch not found for %s\n", token))
}
bz := store.Get(types.GetBatchKey(token))
var batch types.Batch
k.cdc.MustUnmarshalBinaryBare(bz, &batch)
return batch
}
func (k Keeper) MustGetLastBatch(ctx sdk.Context, token string) types.Batch {
store := ctx.KVStore(k.storeKey)
if !k.LastBatchExists(ctx, token) {
panic(fmt.Sprintf("last batch not found for %s\n", token))
}
bz := store.Get(types.GetLastBatchKey(token))
var batch types.Batch
k.cdc.MustUnmarshalBinaryBare(bz, &batch)
return batch
}
func (k Keeper) BatchExists(ctx sdk.Context, token string) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(types.GetBatchKey(token))
}
func (k Keeper) LastBatchExists(ctx sdk.Context, token string) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(types.GetLastBatchKey(token))
}
func (k Keeper) SetBatch(ctx sdk.Context, token string, batch types.Batch) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetBatchKey(token), k.cdc.MustMarshalBinaryBare(batch))
}
func (k Keeper) SetLastBatch(ctx sdk.Context, token string, batch types.Batch) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetLastBatchKey(token), k.cdc.MustMarshalBinaryBare(batch))
}
func (k Keeper) AddBuyOrder(ctx sdk.Context, token string, bo types.BuyOrder, buyPrices, sellPrices sdk.DecCoins) {
batch := k.MustGetBatch(ctx, token)
batch.TotalBuyAmount = batch.TotalBuyAmount.Add(bo.Amount)
batch.BuyPrices = buyPrices
batch.SellPrices = sellPrices
batch.Buys = append(batch.Buys, bo)
k.SetBatch(ctx, token, batch)
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("added buy order for %s from %s", bo.Amount.String(), bo.Address.String()))
}
func (k Keeper) AddSellOrder(ctx sdk.Context, token string, so types.SellOrder, buyPrices, sellPrices sdk.DecCoins) {
batch := k.MustGetBatch(ctx, token)
batch.TotalSellAmount = batch.TotalSellAmount.Add(so.Amount)
batch.BuyPrices = buyPrices
batch.SellPrices = sellPrices
batch.Sells = append(batch.Sells, so)
k.SetBatch(ctx, token, batch)
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("added sell order for %s from %s", so.Amount.String(), so.Address.String()))
}
func (k Keeper) AddSwapOrder(ctx sdk.Context, token string, so types.SwapOrder) {
batch := k.MustGetBatch(ctx, token)
batch.Swaps = append(batch.Swaps, so)
k.SetBatch(ctx, token, batch)
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("added swap order for %s to %s from %s", so.Amount.String(), so.ToToken, so.Address.String()))
}
func (k Keeper) GetBatchBuySellPrices(ctx sdk.Context, token string, batch types.Batch) (buyPricesPT, sellPricesPT sdk.DecCoins, err error) {
war := k.MustGetWar(ctx, token)
buyAmountDec := batch.TotalBuyAmount.Amount.ToDec()
sellAmountDec := batch.TotalSellAmount.Amount.ToDec()
reserveBalances := k.GetReserveBalances(ctx, token)
currentPricesPT, err := war.GetCurrentPricesPT(reserveBalances)
if err != nil {
return nil, nil, err
}
// Get (amount of) matched and (actual) curve-calculated value for the remaining amount
// - The matched amount is the least of the buys and sells (i.e. greatest common amount)
// - The curved values are the prices/returns for the extra unmatched buys/sells
var matchedAmount sdk.Dec
var curvedValues sdk.DecCoins
if batch.EqualBuysAndSells() {
// Since equal, both prices are current prices
return currentPricesPT, currentPricesPT, nil
} else if batch.MoreBuysThanSells() {
matchedAmount = sellAmountDec // since sells < buys, greatest common amount is sells
extraBuys := batch.TotalBuyAmount.Sub(batch.TotalSellAmount)
curvedValues, err = war.GetPricesToMint(extraBuys.Amount, reserveBalances) // buy prices
if err != nil {
return nil, nil, err
}
} else {
matchedAmount = buyAmountDec // since buys < sells, greatest common amount is buys
extraSells := batch.TotalSellAmount.Sub(batch.TotalBuyAmount)
curvedValues = war.GetReturnsForBurn(extraSells.Amount, reserveBalances) // sell returns
}
// Get (actual) matched values
matchedValues := types.MultiplyDecCoinsByDec(currentPricesPT, matchedAmount)
// If buys > sells, totalValues is the total buy prices
// If sells > buys, totalValues is the total sell returns
totalValues := matchedValues.Add(curvedValues...)
// Calculate buy and sell prices per token
if batch.MoreBuysThanSells() {
buyPricesPT = types.DivideDecCoinsByDec(totalValues, buyAmountDec)
sellPricesPT = currentPricesPT
} else {
buyPricesPT = currentPricesPT
sellPricesPT = types.DivideDecCoinsByDec(totalValues, sellAmountDec)
}
return buyPricesPT, sellPricesPT, nil
}
func (k Keeper) GetUpdatedBatchPricesAfterBuy(ctx sdk.Context, token string, bo types.BuyOrder) (buyPrices, sellPrices sdk.DecCoins, err error) {
war := k.MustGetWar(ctx, token)
batch := k.MustGetBatch(ctx, token)
// Max supply cannot be less than supply (max supply >= supply)
adjustedSupply := k.GetSupplyAdjustedForBuy(ctx, token)
adjustedSupplyWithBuy := adjustedSupply.Add(bo.Amount)
if war.MaxSupply.IsLT(adjustedSupplyWithBuy) {
return nil, nil, sdkerrors.Wrap(types.ErrCannotMintMoreThanMaxSupply, war.MaxSupply.String())
}
// If augmented in hatch phase and adjusted supply exceeds S0, disallow buy
// since it is not allowed for a batch to cross over to the open phase.
//
// S0 is rounded to ceil for the case that it has a decimal, otherwise it
// cannot be reached without being exceeded, when using integer buy amounts
// (e.g. if supply is 100 and S0=100.5, we cannot reach S0 by performing
// the minimum buy of 1 token [101>100.5], so S0 is rounded to ceil; S0=101)
if war.FunctionType == types.AugmentedFunction &&
war.State == types.HatchState {
args := war.FunctionParameters.AsMap()
if adjustedSupplyWithBuy.Amount.ToDec().GT(args["S0"].Ceil()) {
return nil, nil, sdkerrors.Wrap(sdkerrors.ErrInvalidCoins, "Buy exceeds initial supply S0. Consider buying less tokens.")
}
}
// Simulate buy by bumping up total buy amount
batch.TotalBuyAmount = batch.TotalBuyAmount.Add(bo.Amount)
buyPrices, sellPrices, err = k.GetBatchBuySellPrices(ctx, token, batch)
if err != nil {
return nil, nil, err
}
err = k.CheckIfBuyOrderFulfillableAtPrice(ctx, token, bo, buyPrices)
if err != nil {
return nil, nil, err
}
return buyPrices, sellPrices, nil
}
func (k Keeper) GetUpdatedBatchPricesAfterSell(ctx sdk.Context, token string, so types.SellOrder) (buyPrices, sellPrices sdk.DecCoins, err error) {
batch := k.MustGetBatch(ctx, token)
// Cannot burn more tokens than what exists
adjustedSupply := k.GetSupplyAdjustedForSell(ctx, token)
if adjustedSupply.IsLT(so.Amount) {
return nil, nil, sdkerrors.Wrap(types.ErrCannotBurnMoreThanSupply, so.Amount.String())
}
// Simulate sell by bumping up total sell amount
batch.TotalSellAmount = batch.TotalSellAmount.Add(so.Amount)
buyPrices, sellPrices, err = k.GetBatchBuySellPrices(ctx, token, batch)
if err != nil {
return nil, nil, err
}
return buyPrices, sellPrices, nil
}
func (k Keeper) PerformBuyAtPrice(ctx sdk.Context, token string, bo types.BuyOrder, prices sdk.DecCoins) (err error) {
war := k.MustGetWar(ctx, token)
var extraEventAttributes []sdk.Attribute
// Mint war tokens
err = k.SupplyKeeper.MintCoins(ctx, types.WarsMintBurnAccount,
sdk.Coins{bo.Amount})
if err != nil {
return err
}
// Send war tokens bought to buyer
err = k.SupplyKeeper.SendCoinsFromModuleToAccount(ctx,
types.WarsMintBurnAccount, bo.Address, sdk.Coins{bo.Amount})
if err != nil {
return err
}
reservePrices := types.MultiplyDecCoinsByInt(prices, bo.Amount.Amount)
reservePricesRounded := types.RoundReservePrices(reservePrices)
txFees := war.GetTxFees(reservePrices)
totalPrices := reservePricesRounded.Add(txFees...)
if totalPrices.IsAnyGT(bo.MaxPrices) {
sdkerrors.Wrapf(types.ErrMaxPriceExceeded, "Actual prices %s exceed max prices %s", totalPrices, bo.MaxPrices)
}
// Add new reserve to reserve (reservePricesRounded should never be zero)
// TODO: investigate possibility of zero reservePricesRounded
if war.FunctionType == types.AugmentedFunction &&
war.State == types.HatchState {
args := war.FunctionParameters.AsMap()
theta := args["theta"]
// Get current reserve
var currentReserve sdk.Int
if war.CurrentReserve.Empty() {
currentReserve = sdk.ZeroInt()
} else {
// Reserve balances should all be equal given that we are always
// applying the same additions/subtractions to all reserve balances.
// Thus we can pick the first reserve balance as the global balance.
currentReserve = k.GetReserveBalances(ctx, token)[0].Amount
}
// Calculate expected new reserve (as fraction 1-theta of new total raise)
newSupply := war.CurrentSupply.Add(bo.Amount).Amount
newTotalRaise := args["p0"].Mul(newSupply.ToDec())
newReserve := newTotalRaise.Mul(
sdk.OneDec().Sub(theta)).Ceil().TruncateInt()
// Calculate amount that should go into initial reserve
toInitialReserve := newReserve.Sub(currentReserve)
if reservePricesRounded[0].Amount.LT(toInitialReserve) {
// Reserve supplied by buyer is insufficient
return sdkerrors.Wrap(types.ErrInsufficientReserveToBuy, toInitialReserve.String())
}
coinsToInitialReserve, _ := war.GetNewReserveDecCoins(
toInitialReserve.ToDec()).TruncateDecimal()
// Calculate amount that should go into funding pool
coinsToFundingPool := reservePricesRounded.Sub(coinsToInitialReserve)
// Send reserve tokens to initial reserve
err = k.DepositReserveFromModule(ctx, war.Token,
types.BatchesIntermediaryAccount, coinsToInitialReserve)
if err != nil {
return err
}
// Send reserve tokens to funding pool
err = k.SupplyKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, war.FeeAddress, coinsToFundingPool)
if err != nil {
return err
}
extraEventAttributes = append(extraEventAttributes,
sdk.NewAttribute(types.AttributeKeyChargedPricesReserve, toInitialReserve.String()),
sdk.NewAttribute(types.AttributeKeyChargedPricesFunding, coinsToFundingPool.String()),
)
} else {
err = k.DepositReserveFromModule(
ctx, war.Token, types.BatchesIntermediaryAccount, reservePricesRounded)
if err != nil {
return err
}
}
// Add charged fee to fee address
if !txFees.IsZero() {
err = k.SupplyKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, war.FeeAddress, txFees)
if err != nil {
return err
}
}
// Add remainder to buyer address
returnToBuyer := bo.MaxPrices.Sub(totalPrices)
if !returnToBuyer.IsZero() {
err = k.SupplyKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, bo.Address, returnToBuyer)
if err != nil {
return err
}
}
// Update supply (max supply exceeded check done during MsgBuy)
k.SetCurrentSupply(ctx, token, war.CurrentSupply.Add(bo.Amount))
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("performed buy order for %s from %s", bo.Amount.String(), bo.Address.String()))
// Get new war token balance
warTokenBalance := k.BankKeeper.GetCoins(ctx, bo.Address).AmountOf(war.Token)
event := sdk.NewEvent(
types.EventTypeOrderFulfill,
sdk.NewAttribute(types.AttributeKeyWar, war.Token),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueBuyOrder),
sdk.NewAttribute(types.AttributeKeyAddress, bo.Address.String()),
sdk.NewAttribute(types.AttributeKeyTokensMinted, bo.Amount.Amount.String()),
sdk.NewAttribute(types.AttributeKeyChargedPrices, reservePricesRounded.String()),
sdk.NewAttribute(types.AttributeKeyChargedFees, txFees.String()),
sdk.NewAttribute(types.AttributeKeyReturnedToAddress, returnToBuyer.String()),
sdk.NewAttribute(types.AttributeKeyNewWarTokenBalance, warTokenBalance.String()),
)
if len(extraEventAttributes) > 0 {
event = event.AppendAttributes(extraEventAttributes...)
}
ctx.EventManager().EmitEvent(event)
return nil
}
func (k Keeper) PerformSellAtPrice(ctx sdk.Context, token string, so types.SellOrder, prices sdk.DecCoins) (err error) {
war := k.MustGetWar(ctx, token)
reserveReturns := types.MultiplyDecCoinsByInt(prices, so.Amount.Amount)
reserveReturnsRounded := types.RoundReserveReturns(reserveReturns)
txFees := war.GetTxFees(reserveReturns)
exitFees := war.GetExitFees(reserveReturns)
totalFees := types.AdjustFees(txFees.Add(exitFees...), reserveReturnsRounded) // calculate actual total fees
totalReturns := reserveReturnsRounded.Sub(totalFees) // calculate actual reserveReturns
// Send total returns to seller (totalReturns should never be zero)
// TODO: investigate possibility of zero totalReturns
err = k.WithdrawReserve(ctx, war.Token, so.Address, totalReturns)
if err != nil {
return err
}
// Send total fee to fee address
if !totalFees.IsZero() {
err = k.WithdrawReserve(ctx, war.Token, war.FeeAddress, totalFees)
if err != nil {
return err
}
}
// Update supply (burn more than supply check done during MsgSell)
k.SetCurrentSupply(ctx, token, war.CurrentSupply.Sub(so.Amount))
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("performed sell order for %s from %s", so.Amount.String(), so.Address.String()))
// Get new war token balance
warTokenBalance := k.BankKeeper.GetCoins(ctx, so.Address).AmountOf(war.Token)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeOrderFulfill,
sdk.NewAttribute(types.AttributeKeyWar, war.Token),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueSellOrder),
sdk.NewAttribute(types.AttributeKeyAddress, so.Address.String()),
sdk.NewAttribute(types.AttributeKeyTokensBurned, so.Amount.Amount.String()),
sdk.NewAttribute(types.AttributeKeyChargedFees, txFees.String()),
sdk.NewAttribute(types.AttributeKeyReturnedToAddress, totalReturns.String()),
sdk.NewAttribute(types.AttributeKeyNewWarTokenBalance, warTokenBalance.String()),
))
return nil
}
func (k Keeper) PerformSwap(ctx sdk.Context, token string, so types.SwapOrder) (err error, ok bool) {
war := k.MustGetWar(ctx, token)
// WARNING: do not return ok=true if money has already been transferred when error occurs
// Get return for swap
reserveBalances := k.GetReserveBalances(ctx, token)
reserveReturns, txFee, err := war.GetReturnsForSwap(so.Amount, so.ToToken, reserveBalances)
if err != nil {
return err, true
}
adjustedInput := so.Amount.Sub(txFee) // same as during GetReturnsForSwap
// Check if new rates violate sanity rate
newReserveBalances := reserveBalances.Add(adjustedInput).Sub(reserveReturns)
if war.ReservesViolateSanityRate(newReserveBalances) {
return sdkerrors.Wrap(types.ErrValuesViolateSanityRate, newReserveBalances.String()), true
}
// Give resultant tokens to swapper (reserveReturns should never be zero)
err = k.WithdrawReserve(ctx, war.Token, so.Address, reserveReturns)
if err != nil {
return err, false
}
// Add fee-reduced coins to be swapped to reserve (adjustedInput should never be zero)
err = k.DepositReserveFromModule(
ctx, war.Token, types.BatchesIntermediaryAccount, sdk.Coins{adjustedInput})
if err != nil {
return err, false
}
// Add fee (taken from swapper) to fee address
if !txFee.IsZero() {
err = k.SupplyKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, war.FeeAddress, sdk.Coins{txFee})
if err != nil {
return err, false
}
}
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("performed swap order for %s to %s from %s",
so.Amount.String(), reserveReturns, so.Address.String()))
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeOrderFulfill,
sdk.NewAttribute(types.AttributeKeyWar, war.Token),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueSwapOrder),
sdk.NewAttribute(types.AttributeKeyAddress, so.Address.String()),
sdk.NewAttribute(types.AttributeKeyTokensSwapped, adjustedInput.String()),
sdk.NewAttribute(types.AttributeKeyChargedFees, txFee.String()),
sdk.NewAttribute(types.AttributeKeyReturnedToAddress, reserveReturns.String()),
))
return nil, true
}
func (k Keeper) PerformBuyOrders(ctx sdk.Context, token string) {
batch := k.MustGetBatch(ctx, token)
// Perform buys or return to buyer
for _, bo := range batch.Buys {
if !bo.IsCancelled() {
err := k.PerformBuyAtPrice(ctx, token, bo, batch.BuyPrices)
if err != nil {
// Panic here since all calculations should have been done
// correctly to prevent any errors during the buy
panic(err)
}
}
}
// Update batch with any new changes (shouldn't be any)
k.SetBatch(ctx, token, batch)
}
func (k Keeper) PerformSellOrders(ctx sdk.Context, token string) {
batch := k.MustGetBatch(ctx, token)
// Perform sells or return to seller
for _, so := range batch.Sells {
if !so.IsCancelled() {
err := k.PerformSellAtPrice(ctx, token, so, batch.SellPrices)
if err != nil {
// Panic here since all calculations should have been done
// correctly to prevent any errors during the sell
panic(err)
}
}
}
// Update batch with any new changes (shouldn't be any)
k.SetBatch(ctx, token, batch)
}
func (k Keeper) PerformSwapOrders(ctx sdk.Context, token string) {
logger := ctx.Logger()
batch := k.MustGetBatch(ctx, token)
// Perform swaps
// TODO: implement swaps front-running prevention
for i, so := range batch.Swaps {
if !so.IsCancelled() {
err, ok := k.PerformSwap(ctx, token, so)
if err != nil {
if ok {
batch.Swaps[i].Cancelled = true
batch.Swaps[i].CancelReason = err.Error()
logger.Info(fmt.Sprintf("cancelled swap order for %s to %s from %s", so.Amount.String(), so.ToToken, so.Address.String()))
logger.Debug(fmt.Sprintf("cancellation reason: %s", err.Error()))
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeOrderCancel,
sdk.NewAttribute(types.AttributeKeyWar, token),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueSwapOrder),
sdk.NewAttribute(types.AttributeKeyAddress, so.Address.String()),
sdk.NewAttribute(types.AttributeKeyCancelReason, batch.Swaps[i].CancelReason),
))
// Return from amount to swapper
err := k.SupplyKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, so.Address, sdk.Coins{so.Amount})
if err != nil {
panic(err)
}
} else {
// Panic here since all calculations should have been done
// correctly to prevent any errors during the swap
panic(err)
}
}
}
}
// Update batch with any new cancellations
k.SetBatch(ctx, token, batch)
}
func (k Keeper) PerformOrders(ctx sdk.Context, token string) {
k.PerformBuyOrders(ctx, token)
k.PerformSellOrders(ctx, token)
k.PerformSwapOrders(ctx, token)
}
func (k Keeper) CheckIfBuyOrderFulfillableAtPrice(ctx sdk.Context, token string, bo types.BuyOrder, prices sdk.DecCoins) error {
war := k.MustGetWar(ctx, token)
reservePrices := types.MultiplyDecCoinsByInt(prices, bo.Amount.Amount)
reserveRounded := types.RoundReservePrices(reservePrices)
txFees := war.GetTxFees(reservePrices)
totalPrices := reserveRounded.Add(txFees...)
// Check that max prices not exceeded
if totalPrices.IsAnyGT(bo.MaxPrices) {
return sdkerrors.Wrapf(types.ErrMaxPriceExceeded, "Actual prices %s exceed max prices %s", totalPrices, bo.MaxPrices)
}
return nil
}
func (k Keeper) CancelUnfulfillableBuys(ctx sdk.Context, token string) (cancelledOrders int) {
logger := k.Logger(ctx)
batch := k.MustGetBatch(ctx, token)
// Cancel unfulfillable buys
for i, bo := range batch.Buys {
if !bo.IsCancelled() {
err := k.CheckIfBuyOrderFulfillableAtPrice(ctx, token, bo, batch.BuyPrices)
if err != nil {
// Cancel (important to use batch.Buys[i] and not bo!)
batch.Buys[i].Cancelled = true
batch.Buys[i].CancelReason = err.Error()
batch.TotalBuyAmount = batch.TotalBuyAmount.Sub(bo.Amount)
cancelledOrders += 1
logger.Info(fmt.Sprintf("cancelled buy order for %s from %s", bo.Amount.String(), bo.Address.String()))
logger.Debug(fmt.Sprintf("cancellation reason: %s", err.Error()))
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeOrderCancel,
sdk.NewAttribute(types.AttributeKeyWar, token),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueBuyOrder),
sdk.NewAttribute(types.AttributeKeyAddress, bo.Address.String()),
sdk.NewAttribute(types.AttributeKeyCancelReason, batch.Buys[i].CancelReason),
))
// Return reserve to buyer
err := k.SupplyKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, bo.Address, bo.MaxPrices)
if err != nil {
panic(err)
}
}
}
}
// Save batch and return number of cancelled orders
k.SetBatch(ctx, token, batch)
return cancelledOrders
}
func (k Keeper) CancelUnfulfillableOrders(ctx sdk.Context, token string) (cancelledOrders int) {
batch := k.MustGetBatch(ctx, token)
cancelledOrders = 0
cancelledOrders += k.CancelUnfulfillableBuys(ctx, token)
//cancelledOrders += k.CancelUnfulfillableSells(ctx, token) // Sells always fulfillable
//cancelledOrders += k.CancelUnfulfillableSwaps(ctx, token) // Swaps only cancelled while they are being performed
// Update buy and sell prices if any cancellation took place
if cancelledOrders > 0 {
batch = k.MustGetBatch(ctx, token) // get batch again
buyPrices, sellPrices, err := k.GetBatchBuySellPrices(ctx, token, batch)
if err != nil {
panic(err)
}
batch.BuyPrices = buyPrices
batch.SellPrices = sellPrices
}
// Save batch and return number of cancelled orders
k.SetBatch(ctx, token, batch)
return cancelledOrders
}