-
Notifications
You must be signed in to change notification settings - Fork 0
/
batch.go
857 lines (733 loc) · 30.8 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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
package keeper
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
didexported "github.com/furya-official/fury-blockchain/lib/legacydid"
"github.com/furya-official/fury-blockchain/x/bonds/types"
iidtypes "github.com/furya-official/fury-blockchain/x/iid/types"
)
func (k Keeper) MustGetBatch(ctx sdk.Context, bondDid didexported.Did) types.Batch {
store := ctx.KVStore(k.storeKey)
if !k.BatchExists(ctx, bondDid) {
panic(fmt.Sprintf("batch not found for %s\n", bondDid))
}
bz := store.Get(types.GetBatchKey(bondDid))
var batch types.Batch
k.cdc.MustUnmarshal(bz, &batch)
return batch
}
func (k Keeper) MustGetLastBatch(ctx sdk.Context, bondDid didexported.Did) types.Batch {
store := ctx.KVStore(k.storeKey)
if !k.LastBatchExists(ctx, bondDid) {
panic(fmt.Sprintf("last batch not found for %s\n", bondDid))
}
bz := store.Get(types.GetLastBatchKey(bondDid))
var batch types.Batch
k.cdc.MustUnmarshal(bz, &batch)
return batch
}
func (k Keeper) BatchExists(ctx sdk.Context, bondDid didexported.Did) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(types.GetBatchKey(bondDid))
}
func (k Keeper) LastBatchExists(ctx sdk.Context, bondDid didexported.Did) bool {
store := ctx.KVStore(k.storeKey)
return store.Has(types.GetLastBatchKey(bondDid))
}
func (k Keeper) SetBatch(ctx sdk.Context, bondDid didexported.Did, batch types.Batch) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetBatchKey(bondDid), k.cdc.MustMarshal(&batch))
}
func (k Keeper) SetLastBatch(ctx sdk.Context, bondDid didexported.Did, batch types.Batch) {
store := ctx.KVStore(k.storeKey)
store.Set(types.GetLastBatchKey(bondDid), k.cdc.MustMarshal(&batch))
}
func (k Keeper) AddBuyOrder(ctx sdk.Context, bondDid didexported.Did, bo types.BuyOrder, buyPrices, sellPrices sdk.DecCoins) {
batch := k.MustGetBatch(ctx, bondDid)
batch.TotalBuyAmount = batch.TotalBuyAmount.Add(bo.BaseOrder.Amount)
batch.BuyPrices = buyPrices
batch.SellPrices = sellPrices
batch.Buys = append(batch.Buys, bo)
k.SetBatch(ctx, bondDid, batch)
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("added buy order for %s from %s", bo.BaseOrder.Amount.String(), bo.BaseOrder.AccountDid.String()))
}
func (k Keeper) AddSellOrder(ctx sdk.Context, bondDid didexported.Did, so types.SellOrder, buyPrices, sellPrices sdk.DecCoins) {
batch := k.MustGetBatch(ctx, bondDid)
batch.TotalSellAmount = batch.TotalSellAmount.Add(so.BaseOrder.Amount)
batch.BuyPrices = buyPrices
batch.SellPrices = sellPrices
batch.Sells = append(batch.Sells, so)
k.SetBatch(ctx, bondDid, batch)
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("added sell order for %s from %s", so.BaseOrder.Amount.String(), so.BaseOrder.AccountDid.String()))
}
func (k Keeper) AddSwapOrder(ctx sdk.Context, bondDid didexported.Did, so types.SwapOrder) {
batch := k.MustGetBatch(ctx, bondDid)
batch.Swaps = append(batch.Swaps, so)
k.SetBatch(ctx, bondDid, batch)
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("added swap order for %s to %s from %s", so.BaseOrder.Amount.String(), so.ToToken, so.BaseOrder.AccountDid.String()))
}
func (k Keeper) GetBatchBuySellPrices(ctx sdk.Context, bondDid string, batch types.Batch) (buyPricesPT, sellPricesPT sdk.DecCoins, err error) {
bond := k.MustGetBond(ctx, bondDid)
buyAmountDec := batch.TotalBuyAmount.Amount.ToDec()
sellAmountDec := batch.TotalSellAmount.Amount.ToDec()
reserveBalances := k.GetReserveBalances(ctx, bondDid)
currentPricesPT, err := bond.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 = bond.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, err = bond.GetReturnsForBurn(extraSells.Amount, reserveBalances) // sell returns
if err != nil {
return nil, nil, err
}
}
// 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, bondDid didexported.Did, bo types.BuyOrder) (buyPrices, sellPrices sdk.DecCoins, err error) {
bond := k.MustGetBond(ctx, bondDid)
batch := k.MustGetBatch(ctx, bondDid)
// Max supply cannot be less than supply (max supply >= supply)
adjustedSupply := k.GetSupplyAdjustedForBuy(ctx, bondDid)
adjustedSupplyWithBuy := adjustedSupply.Add(bo.BaseOrder.Amount)
if bond.MaxSupply.IsLT(adjustedSupplyWithBuy) {
return nil, nil, types.ErrCannotMintMoreThanMaxSupply
}
// 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 bond.FunctionType == types.AugmentedFunction &&
bond.State == types.HatchState.String() {
args := bond.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.BaseOrder.Amount)
buyPrices, sellPrices, err = k.GetBatchBuySellPrices(ctx, bondDid, batch)
if err != nil {
return nil, nil, err
}
err = k.CheckIfBuyOrderFulfillableAtPrice(ctx, bondDid, bo, buyPrices)
if err != nil {
return nil, nil, err
}
return buyPrices, sellPrices, nil
}
func (k Keeper) GetUpdatedBatchPricesAfterSell(ctx sdk.Context, bondDid didexported.Did, so types.SellOrder) (buyPrices, sellPrices sdk.DecCoins, err error) {
batch := k.MustGetBatch(ctx, bondDid)
// Cannot burn more tokens than what exists
adjustedSupply := k.GetSupplyAdjustedForSell(ctx, bondDid)
if adjustedSupply.IsLT(so.BaseOrder.Amount) {
return nil, nil, types.ErrCannotBurnMoreThanSupply
}
// Simulate sell by bumping up total sell amount
batch.TotalSellAmount = batch.TotalSellAmount.Add(so.BaseOrder.Amount)
buyPrices, sellPrices, err = k.GetBatchBuySellPrices(ctx, bondDid, batch)
if err != nil {
return nil, nil, err
}
return buyPrices, sellPrices, nil
}
func (k Keeper) PerformBuyAtPrice(ctx sdk.Context, bondDid didexported.Did, bo types.BuyOrder, prices sdk.DecCoins) (err error) {
bond := k.MustGetBond(ctx, bondDid)
var extraEventAttributes []sdk.Attribute
// Get buyer address
buyerDidDoc, exists := k.iidKeeper.GetDidDocument(ctx, []byte(bo.BaseOrder.AccountDid.Did()))
if !exists {
return err
}
buyerAddr, err := buyerDidDoc.GetVerificationMethodBlockchainAddress(bo.BaseOrder.AccountDid.String())
if err != nil {
return err
}
feeAddr, err := sdk.AccAddressFromBech32(bond.FeeAddress)
if err != nil {
return err
}
// Mint bond tokens
err = k.BankKeeper.MintCoins(ctx, types.BondsMintBurnAccount,
sdk.Coins{bo.BaseOrder.Amount})
if err != nil {
return err
}
// Send bond tokens bought to buyer
err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx,
types.BondsMintBurnAccount, buyerAddr, sdk.Coins{bo.BaseOrder.Amount})
if err != nil {
return err
}
reservePrices := types.MultiplyDecCoinsByInt(prices, bo.BaseOrder.Amount.Amount)
reservePricesRounded := types.RoundReservePrices(reservePrices)
txFees := bond.GetTxFees(reservePrices)
totalPrices := reservePricesRounded.Add(txFees...)
if totalPrices.IsAnyGT(bo.MaxPrices) {
return sdkerrors.Wrapf(types.ErrMaxPriceExceeded,
"actual prices %s exceed max prices %s",
totalPrices.String(), bo.MaxPrices.String())
}
// Add new reserve to reserve (reservePricesRounded should never be zero)
// TODO: investigate possibility of zero reservePricesRounded
if bond.FunctionType == types.AugmentedFunction &&
bond.State == types.HatchState.String() {
args := bond.FunctionParameters.AsMap()
theta := args["theta"]
// Get current reserve
var currentReserve sdk.Int
if bond.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, bondDid)[0].Amount
}
// Calculate expected new reserve (as fraction 1-theta of new total raise)
newSupply := bond.CurrentSupply.Add(bo.BaseOrder.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 types.ErrInsufficientReserveToBuy
}
coinsToInitialReserve, _ := bond.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, bond.BondDid,
types.BatchesIntermediaryAccount, coinsToInitialReserve)
if err != nil {
return err
}
// Send reserve tokens to funding pool
err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, feeAddr, 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, bond.BondDid, types.BatchesIntermediaryAccount, reservePricesRounded)
if err != nil {
return err
}
}
// Add charged fee to fee address
if !txFees.IsZero() {
err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, feeAddr, txFees)
if err != nil {
return err
}
}
// Add remainder to buyer address
returnToBuyer := bo.MaxPrices.Sub(totalPrices)
if !returnToBuyer.IsZero() {
err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, buyerAddr, returnToBuyer)
if err != nil {
return err
}
}
// Update supply (max supply exceeded check done during MsgBuy)
k.SetCurrentSupply(ctx, bondDid, bond.CurrentSupply.Add(bo.BaseOrder.Amount))
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("performed buy order for %s from %s", bo.BaseOrder.Amount.String(), bo.BaseOrder.AccountDid.String()))
// Get new bond token balance
bondTokenBalance := k.BankKeeper.GetBalance(ctx, buyerAddr, bond.Token).Amount
event := sdk.NewEvent(
types.EventTypeOrderFulfill,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueBuyOrder),
sdk.NewAttribute(types.AttributeKeyAddress, bo.BaseOrder.AccountDid.String()),
sdk.NewAttribute(types.AttributeKeyTokensMinted, bo.BaseOrder.Amount.Amount.String()),
sdk.NewAttribute(types.AttributeKeyChargedPrices, reservePricesRounded.String()),
sdk.NewAttribute(types.AttributeKeyChargedFees, txFees.String()),
sdk.NewAttribute(types.AttributeKeyReturnedToAddress, returnToBuyer.String()),
sdk.NewAttribute(types.AttributeKeyNewBondTokenBalance, bondTokenBalance.String()),
)
if len(extraEventAttributes) > 0 {
event = event.AppendAttributes(extraEventAttributes...)
}
ctx.EventManager().EmitEvent(event)
return nil
}
func (k Keeper) PerformSellAtPrice(ctx sdk.Context, bondDid didexported.Did, so types.SellOrder, prices sdk.DecCoins) (err error) {
bond := k.MustGetBond(ctx, bondDid)
// Get seller address
sellerDidDoc, exists := k.iidKeeper.GetDidDocument(ctx, []byte(so.BaseOrder.AccountDid.Did()))
if !exists {
return sdkerrors.Wrap(iidtypes.ErrDidDocumentNotFound, "Did document not found")
}
sellerAddr, err := sellerDidDoc.GetVerificationMethodBlockchainAddress(so.BaseOrder.AccountDid.String())
if err != nil {
return sdkerrors.Wrap(err, "Address not found")
}
reserveReturns := types.MultiplyDecCoinsByInt(prices, so.BaseOrder.Amount.Amount)
reserveReturnsRounded := types.RoundReserveReturns(reserveReturns)
txFees := bond.GetTxFees(reserveReturns)
exitFees := bond.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.WithdrawFromReserve(ctx, bond.BondDid, sellerAddr, totalReturns)
if err != nil {
return err
}
feeAddr, err := sdk.AccAddressFromBech32(bond.FeeAddress)
if err != nil {
return err
}
// Send total fee to fee address
if !totalFees.IsZero() {
err = k.WithdrawFromReserve(ctx, bond.BondDid, feeAddr, totalFees)
if err != nil {
return err
}
}
// Update supply (burn more than supply check done during MsgSell)
k.SetCurrentSupply(ctx, bondDid, bond.CurrentSupply.Sub(so.BaseOrder.Amount))
logger := k.Logger(ctx)
logger.Info(fmt.Sprintf("performed sell order for %s from %s", so.BaseOrder.Amount.String(), so.BaseOrder.AccountDid.String()))
// Get new bond token balance
bondTokenBalance := k.BankKeeper.GetBalance(ctx, sellerAddr, bond.Token).Amount
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeOrderFulfill,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueSellOrder),
sdk.NewAttribute(types.AttributeKeyAddress, so.BaseOrder.AccountDid.String()),
sdk.NewAttribute(types.AttributeKeyTokensBurned, so.BaseOrder.Amount.Amount.String()),
sdk.NewAttribute(types.AttributeKeyChargedFees, txFees.String()),
sdk.NewAttribute(types.AttributeKeyReturnedToAddress, totalReturns.String()),
sdk.NewAttribute(types.AttributeKeyNewBondTokenBalance, bondTokenBalance.String()),
))
return nil
}
func (k Keeper) PerformSwap(ctx sdk.Context, bondDid didexported.Did, so types.SwapOrder) (err error, ok bool) {
bond := k.MustGetBond(ctx, bondDid)
// WARNING: do not return ok=true if money has already been transferred when error occurs
// Get swapper address
swapperDidDoc, exists := k.iidKeeper.GetDidDocument(ctx, []byte(so.BaseOrder.AccountDid.Did()))
if !exists {
return sdkerrors.Wrap(iidtypes.ErrDidDocumentNotFound, "Did document not found"), true
}
swapperAddr, err := swapperDidDoc.GetVerificationMethodBlockchainAddress(so.BaseOrder.AccountDid.String())
if err != nil {
return sdkerrors.Wrap(err, "Address not found"), true
}
// Get return for swap
reserveBalances := k.GetReserveBalances(ctx, bondDid)
reserveReturns, txFee, err := bond.GetReturnsForSwap(so.BaseOrder.Amount, so.ToToken, reserveBalances)
if err != nil {
return err, true
}
adjustedInput := so.BaseOrder.Amount.Sub(txFee) // same as during GetReturnsForSwap
// Check if new rates violate sanity rate
newReserveBalances := reserveBalances.Add(sdk.Coins{adjustedInput}...).Sub(reserveReturns)
if bond.ReservesViolateSanityRate(newReserveBalances) {
return types.ErrValuesViolateSanityRate, true
}
// Give resultant tokens to swapper (reserveReturns should never be zero)
err = k.WithdrawFromReserve(ctx, bond.BondDid, swapperAddr, 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, bond.BondDid, types.BatchesIntermediaryAccount, sdk.Coins{adjustedInput})
if err != nil {
return err, false
}
feeAddr, err := sdk.AccAddressFromBech32(bond.FeeAddress)
if err != nil {
return err, false
}
// Add fee (taken from swapper) to fee address
if !txFee.IsZero() {
err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, feeAddr, 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.BaseOrder.Amount.String(), reserveReturns, so.BaseOrder.AccountDid))
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeOrderFulfill,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueSwapOrder),
sdk.NewAttribute(types.AttributeKeyAddress, so.BaseOrder.AccountDid.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, bondDid didexported.Did) {
batch := k.MustGetBatch(ctx, bondDid)
// Perform buys or return to buyer
for _, bo := range batch.Buys {
if !bo.BaseOrder.IsCancelled() {
err := k.PerformBuyAtPrice(ctx, bondDid, 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, bondDid, batch)
}
func (k Keeper) PerformSellOrders(ctx sdk.Context, bondDid didexported.Did) {
batch := k.MustGetBatch(ctx, bondDid)
// Perform sells or return to seller
for _, so := range batch.Sells {
if !so.BaseOrder.IsCancelled() {
err := k.PerformSellAtPrice(ctx, bondDid, 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, bondDid, batch)
}
func (k Keeper) PerformSwapOrders(ctx sdk.Context, bondDid didexported.Did) {
logger := ctx.Logger()
batch := k.MustGetBatch(ctx, bondDid)
// Perform swaps
// TODO: implement swaps front-running prevention
for i, so := range batch.Swaps {
if !so.BaseOrder.IsCancelled() {
err, ok := k.PerformSwap(ctx, bondDid, so)
if err != nil {
if ok {
batch.Swaps[i].BaseOrder.Cancelled = true
batch.Swaps[i].BaseOrder.CancelReason = err.Error()
logger.Info(fmt.Sprintf("cancelled swap order for %s to %s from %s", so.BaseOrder.Amount.String(), so.ToToken, so.BaseOrder.AccountDid))
logger.Debug(fmt.Sprintf("cancellation reason: %s", err.Error()))
// Return from amount to swapper
swapperDidDoc, exists := k.iidKeeper.GetDidDocument(ctx, []byte(so.BaseOrder.AccountDid.Did()))
if !exists {
panic(sdkerrors.Wrap(iidtypes.ErrDidDocumentNotFound, "Did document not found"))
}
swapperAddr, err := swapperDidDoc.GetVerificationMethodBlockchainAddress(so.BaseOrder.String())
if err != nil {
panic(sdkerrors.Wrap(err, "Address not found"))
}
err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, swapperAddr, sdk.Coins{so.BaseOrder.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, bondDid, batch)
}
func (k Keeper) PerformOrders(ctx sdk.Context, bondDid didexported.Did) {
k.PerformBuyOrders(ctx, bondDid)
k.PerformSellOrders(ctx, bondDid)
k.PerformSwapOrders(ctx, bondDid)
}
func (k Keeper) CheckIfBuyOrderFulfillableAtPrice(ctx sdk.Context, bondDid didexported.Did, bo types.BuyOrder, prices sdk.DecCoins) error {
bond := k.MustGetBond(ctx, bondDid)
reservePrices := types.MultiplyDecCoinsByInt(prices, bo.BaseOrder.Amount.Amount)
reserveRounded := types.RoundReservePrices(reservePrices)
txFees := bond.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.String(), bo.MaxPrices.String())
}
return nil
}
func (k Keeper) CancelUnfulfillableBuys(ctx sdk.Context, bondDid didexported.Did) (cancelledOrders int) {
logger := k.Logger(ctx)
batch := k.MustGetBatch(ctx, bondDid)
// Cancel unfulfillable buys
for i, bo := range batch.Buys {
if !bo.BaseOrder.IsCancelled() {
err := k.CheckIfBuyOrderFulfillableAtPrice(ctx, bondDid, bo, batch.BuyPrices)
if err != nil {
// Cancel (important to use batch.Buys[i] and not bo!)
batch.Buys[i].BaseOrder.Cancelled = true
batch.Buys[i].BaseOrder.CancelReason = err.Error()
batch.TotalBuyAmount = batch.TotalBuyAmount.Sub(bo.BaseOrder.Amount)
cancelledOrders += 1
logger.Info(fmt.Sprintf("cancelled buy order for %s from %s", bo.BaseOrder.Amount.String(), bo.BaseOrder.AccountDid.String()))
logger.Debug(fmt.Sprintf("cancellation reason: %s", err.Error()))
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeOrderCancel,
sdk.NewAttribute(types.AttributeKeyBondDid, bondDid),
sdk.NewAttribute(types.AttributeKeyOrderType, types.AttributeValueBuyOrder),
sdk.NewAttribute(types.AttributeKeyAddress, bo.BaseOrder.AccountDid.String()),
sdk.NewAttribute(types.AttributeKeyCancelReason, bo.BaseOrder.CancelReason),
))
// Return reserve to buyer
buyerDidDoc, exists := k.iidKeeper.GetDidDocument(ctx, []byte(bo.BaseOrder.AccountDid.Did()))
if !exists {
panic(sdkerrors.Wrap(iidtypes.ErrDidDocumentNotFound, "Did document not found"))
}
buyerAddr, err := buyerDidDoc.GetVerificationMethodBlockchainAddress(bo.BaseOrder.AccountDid.String())
if err != nil {
panic(sdkerrors.Wrap(err, "Address not found"))
}
err = k.BankKeeper.SendCoinsFromModuleToAccount(ctx,
types.BatchesIntermediaryAccount, buyerAddr, bo.MaxPrices)
if err != nil {
panic(err)
}
}
}
}
// Save batch and return number of cancelled orders
k.SetBatch(ctx, bondDid, batch)
return cancelledOrders
}
func (k Keeper) CancelUnfulfillableOrders(ctx sdk.Context, bondDid didexported.Did) (cancelledOrders int) {
batch := k.MustGetBatch(ctx, bondDid)
cancelledOrders = 0
cancelledOrders += k.CancelUnfulfillableBuys(ctx, bondDid)
//cancelledOrders += k.CancelUnfulfillableSells(ctx, bondDid) // Sells always fulfillable
//cancelledOrders += k.CancelUnfulfillableSwaps(ctx, bondDid) // 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, bondDid) // get batch again
buyPrices, sellPrices, err := k.GetBatchBuySellPrices(ctx, bondDid, batch)
if err != nil {
panic(err)
}
batch.BuyPrices = buyPrices
batch.SellPrices = sellPrices
}
// Save batch and return number of cancelled orders
k.SetBatch(ctx, bondDid, batch)
return cancelledOrders
}
func (k Keeper) HandleBondingFunctionAlphaUpdate(ctx sdk.Context, bondDid didexported.Did) {
bond := k.MustGetBond(ctx, bondDid)
batch := k.MustGetBatch(ctx, bondDid)
newPublicAlpha := batch.NextPublicAlpha
nextPublicAlphaDelta := sdk.NewDecFromIntWithPrec(sdk.NewIntFromUint64(5), 1)
var algo types.AugmentedBondRevision1
if err := algo.Init(bond); err != nil {
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaFailed,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyCancelReason, err.Error()),
))
return
}
valueOrError := types.RightFlatMap(types.FromError(newPublicAlpha.Float64()), func(ap float64) types.Either[error, bool] {
return types.RightFlatMap(types.FromError(nextPublicAlphaDelta.Float64()), func(delta float64) types.Either[error, bool] {
algo.UpdateAlpha(ap, delta)
return types.Right[error](true)
})
})
if !valueOrError.IsRight() {
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaFailed,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyCancelReason, valueOrError.Left().Error()),
))
return
}
// Get batch to reset alpha
batch = k.MustGetBatch(ctx, bond.BondDid)
batch.NextPublicAlpha = sdk.OneDec().Neg()
k.SetBatch(ctx, bond.BondDid, batch)
// Set new function parameters
algo.ExportToBond(&bond)
k.SetBond(ctx, bond.BondDid, bond)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaSuccess,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyPublicAlpha, newPublicAlpha.String()),
// sdk.NewAttribute(types.AttributeKeySystemAlpha, newSystemAlpha.String()),
))
}
func (k Keeper) UpdateAlpha(ctx sdk.Context, bondDid didexported.Did) {
bond := k.MustGetBond(ctx, bondDid)
batch := k.MustGetBatch(ctx, bondDid)
newPublicAlpha := batch.NextPublicAlpha
// Get supply, reserve, outcome payment
S := bond.CurrentSupply.Amount.ToDec()
R := bond.CurrentReserve[0].Amount.ToDec()
C := bond.OutcomePayment
// Get current parameters
paramsMap := bond.FunctionParameters.AsMap()
// Calculate scaled delta public alpha, to calculate new system alpha
prevPublicAlpha := paramsMap["publicAlpha"]
//fmt.Println("prevPublicAlpha: ", prevPublicAlpha)
deltaPublicAlpha := newPublicAlpha.Sub(prevPublicAlpha)
//fmt.Println("deltaPublicAlpha: ", deltaPublicAlpha)
temp, err := types.ApproxPower(
prevPublicAlpha.Mul(sdk.OneDec().Sub(types.StartingPublicAlpha)),
sdk.MustNewDecFromStr("2"))
if err != nil {
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaFailed,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyCancelReason, err.Error()),
))
return
}
//fmt.Println("temp: ", temp)
scaledDeltaPublicAlpha := deltaPublicAlpha.Mul(temp)
//fmt.Println("scaledDeltaPublicAlpha: ", scaledDeltaPublicAlpha)
// temp = (prevPublicAlpha * (1 - 0.5)) pow 2
// (new_public_alpha - previous_public_alpha) * temp)
// Calculate new system alpha
prevSystemAlpha := paramsMap["systemAlpha"]
//fmt.Println("prevSystemAlpha: ", prevSystemAlpha)
var newSystemAlpha sdk.Dec
if deltaPublicAlpha.IsPositive() {
//fmt.Println("deltaPublicAlpha is positive")
// 1 - (1 - scaled_delta_public_alpha) * (1 - previous_alpha)
temp1 := sdk.OneDec().Sub(scaledDeltaPublicAlpha)
//fmt.Println("temp1: ", temp1)
temp2 := sdk.OneDec().Sub(prevSystemAlpha)
//fmt.Println("temp2: ", temp2)
newSystemAlpha = sdk.OneDec().Sub(temp1.Mul(temp2))
} else {
//fmt.Println("deltaPublicAlpha is negative")
// (1 - scaled_delta_public_alpha) * (previous_alpha)
temp1 := sdk.OneDec().Sub(scaledDeltaPublicAlpha)
//fmt.Println("temp1: ", temp1)
temp2 := prevSystemAlpha
//fmt.Println("temp2: ", temp2)
newSystemAlpha = temp1.Mul(temp2)
}
//fmt.Println("newSystemAlpha: ", newSystemAlpha)
// Check 1 (newSystemAlpha != prevSystemAlpha)
if newSystemAlpha.Equal(prevSystemAlpha) {
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaFailed,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyCancelReason,
"resultant system alpha based on public alpha is unchanged"),
))
return
}
// Check 2 (I > C * newSystemAlpha)
if paramsMap["I0"].LTE(newSystemAlpha.MulInt(C)) {
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaFailed,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyCancelReason,
"cannot change alpha to that value due to violated restriction [1]"),
))
return
}
// Check 3 (R / C > newSystemAlpha - prevSystemAlpha)
if R.QuoInt(C).LTE(newSystemAlpha.Sub(prevSystemAlpha)) {
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaFailed,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyCancelReason,
"cannot change alpha to that value due to violated restriction [2]"),
))
return
}
// Recalculate kappa and V0 using new alpha
I0 := paramsMap["I0"]
//fmt.Println("I0: ", I0)
newKappa := types.Kappa(I0, C, newSystemAlpha)
//fmt.Println("newKappa: ", newKappa)
newV0, err := types.Invariant(R, S, newKappa)
//fmt.Println("newV0: ", newV0)
if err != nil {
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaFailed,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyCancelReason, err.Error()),
))
return
}
// Get batch to reset alpha
batch = k.MustGetBatch(ctx, bond.BondDid)
batch.NextPublicAlpha = sdk.OneDec().Neg()
k.SetBatch(ctx, bond.BondDid, batch)
// Set new function parameters
bond.FunctionParameters.ReplaceParam("kappa", newKappa)
bond.FunctionParameters.ReplaceParam("V0", newV0)
bond.FunctionParameters.ReplaceParam("publicAlpha", newPublicAlpha)
bond.FunctionParameters.ReplaceParam("systemAlpha", newSystemAlpha)
k.SetBond(ctx, bond.BondDid, bond)
ctx.EventManager().EmitEvent(sdk.NewEvent(
types.EventTypeEditAlphaSuccess,
sdk.NewAttribute(types.AttributeKeyBondDid, bond.BondDid),
sdk.NewAttribute(types.AttributeKeyToken, bond.Token),
sdk.NewAttribute(types.AttributeKeyPublicAlpha, newPublicAlpha.String()),
sdk.NewAttribute(types.AttributeKeySystemAlpha, newSystemAlpha.String()),
))
}