/
perpetual.go
1508 lines (1325 loc) · 43.7 KB
/
perpetual.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
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package keeper
import (
"fmt"
"math/big"
"math/rand"
"sort"
"time"
"github.com/furyanprotocol/v4-chain/protocol/daemons/pricefeed/client/constants"
errorsmod "cosmossdk.io/errors"
"github.com/furyanprotocol/v4-chain/protocol/indexer/indexer_manager"
gometrics "github.com/armon/go-metrics"
"github.com/cosmos/cosmos-sdk/store/prefix"
"github.com/cosmos/cosmos-sdk/telemetry"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/furyanprotocol/v4-chain/protocol/dtypes"
indexerevents "github.com/furyanprotocol/v4-chain/protocol/indexer/events"
"github.com/furyanprotocol/v4-chain/protocol/lib"
"github.com/furyanprotocol/v4-chain/protocol/lib/metrics"
epochstypes "github.com/furyanprotocol/v4-chain/protocol/x/epochs/types"
"github.com/furyanprotocol/v4-chain/protocol/x/perpetuals/types"
pricestypes "github.com/furyanprotocol/v4-chain/protocol/x/prices/types"
)
// CreatePerpetual creates a new perpetual in the store.
// Returns an error if any of the perpetual fields fail validation,
// or if the `marketId` does not exist.
func (k Keeper) CreatePerpetual(
ctx sdk.Context,
id uint32,
ticker string,
marketId uint32,
atomicResolution int32,
defaultFundingPpm int32,
liquidityTier uint32,
) (types.Perpetual, error) {
// Check if perpetual exists.
if k.HasPerpetual(ctx, id) {
return types.Perpetual{}, errorsmod.Wrap(
types.ErrPerpetualAlreadyExists,
lib.UintToString(id),
)
}
// Create the perpetual.
perpetual := types.Perpetual{
Params: types.PerpetualParams{
Id: id,
Ticker: ticker,
MarketId: marketId,
AtomicResolution: atomicResolution,
DefaultFundingPpm: defaultFundingPpm,
LiquidityTier: liquidityTier,
},
FundingIndex: dtypes.ZeroInt(),
}
if err := k.validatePerpetual(
ctx,
&perpetual,
); err != nil {
return perpetual, err
}
// Store the new perpetual.
k.setPerpetual(ctx, perpetual)
k.SetEmptyPremiumSamples(ctx)
k.SetEmptyPremiumVotes(ctx)
return perpetual, nil
}
// HasPerpetual checks if a perpetual exists in the store.
func (k Keeper) HasPerpetual(
ctx sdk.Context,
id uint32,
) (found bool) {
perpetualStore := prefix.NewStore(ctx.KVStore(k.storeKey), []byte(types.PerpetualKeyPrefix))
return perpetualStore.Has(lib.Uint32ToKey(id))
}
func (k Keeper) HasAuthority(authority string) bool {
_, ok := k.authorities[authority]
return ok
}
// ModifyPerpetual modifies an existing perpetual in the store.
// The new perpetual object must pass stateful and stateless validations.
// Upon successful modification, send an indexer event.
func (k Keeper) ModifyPerpetual(
ctx sdk.Context,
id uint32,
ticker string,
marketId uint32,
defaultFundingPpm int32,
liquidityTier uint32,
) (types.Perpetual, error) {
// Get perpetual.
perpetual, err := k.GetPerpetual(ctx, id)
if err != nil {
return perpetual, err
}
// Modify perpetual.
perpetual.Params.Ticker = ticker
perpetual.Params.MarketId = marketId
perpetual.Params.DefaultFundingPpm = defaultFundingPpm
perpetual.Params.LiquidityTier = liquidityTier
// Validate updates to perpetual.
if err = k.validatePerpetual(
ctx,
&perpetual,
); err != nil {
return perpetual, err
}
// Store the modified perpetual.
k.setPerpetual(ctx, perpetual)
// Emit indexer event.
k.GetIndexerEventManager().AddTxnEvent(
ctx,
indexerevents.SubtypeUpdatePerpetual,
indexerevents.UpdatePerpetualEventVersion,
indexer_manager.GetBytes(
indexerevents.NewUpdatePerpetualEventV1(
perpetual.Params.Id,
perpetual.Params.Ticker,
perpetual.Params.MarketId,
perpetual.Params.AtomicResolution,
perpetual.Params.LiquidityTier,
),
),
)
return perpetual, nil
}
// GetPerpetual returns a perpetual from its id.
func (k Keeper) GetPerpetual(
ctx sdk.Context,
id uint32,
) (val types.Perpetual, err error) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte(types.PerpetualKeyPrefix))
b := store.Get(lib.Uint32ToKey(id))
if b == nil {
return val, errorsmod.Wrap(types.ErrPerpetualDoesNotExist, lib.UintToString(id))
}
k.cdc.MustUnmarshal(b, &val)
return val, nil
}
// GetAllPerpetuals returns all perpetuals, sorted by perpetual Id.
func (k Keeper) GetAllPerpetuals(ctx sdk.Context) (list []types.Perpetual) {
store := prefix.NewStore(ctx.KVStore(k.storeKey), []byte(types.PerpetualKeyPrefix))
iterator := sdk.KVStorePrefixIterator(store, []byte{})
defer iterator.Close()
for ; iterator.Valid(); iterator.Next() {
var val types.Perpetual
k.cdc.MustUnmarshal(iterator.Value(), &val)
list = append(list, val)
}
sort.Slice(list, func(i, j int) bool {
return list[i].Params.Id < list[j].Params.Id
})
return list
}
// processStoredPremiums combines all stored premiums into a single premium value
// for each `MarketPremiums` in the premium storage.
// Returns a mapping from perpetual Id to summarized premium value.
// Arguments:
// - `premiumKey`: indicates whether the function is processing `PremiumSamples`
// or `PremiumVotes`.
// - `combineFunc`: a function that converts a list of premium values into one
// premium value (e.g. average or median)
// - `filterFunc`: a function that takes in a list of premium values and filter
// out some values.
// - `minNumPremiumsRequired`: minimum number of premium values required for each
// market. Padding will be added if `NumPremiums < minNumPremiumsRequired`.
func (k Keeper) processStoredPremiums(
ctx sdk.Context,
newEpochInfo epochstypes.EpochInfo,
premiumKey string,
minNumPremiumsRequired uint32,
combineFunc func([]int32) int32,
filterFunc func([]int32) []int32,
) (
perpIdToPremium map[uint32]int32,
) {
perpIdToPremium = make(map[uint32]int32)
premiumStore := k.getPremiumStore(ctx, premiumKey)
telemetry.SetGaugeWithLabels(
[]string{
types.ModuleName,
metrics.NumPremiumsFromEpoch,
metrics.Count,
},
float32(premiumStore.NumPremiums),
[]gometrics.Label{
metrics.GetLabelForStringValue(
metrics.PremiumType,
premiumKey,
),
metrics.GetLabelForStringValue(
metrics.EpochInfoName,
newEpochInfo.Name,
),
metrics.GetLabelForBoolValue(
metrics.IsEpochOne,
newEpochInfo.CurrentEpoch == 1,
),
},
)
for _, marketPremiums := range premiumStore.AllMarketPremiums {
// Invariant: `len(marketPremiums.Premiums) <= NumPremiums`
if uint32(len(marketPremiums.Premiums)) > premiumStore.NumPremiums {
panic(fmt.Errorf(
"marketPremiums (%+v) has more non-zero premiums than total number of premiums (%d)",
marketPremiums,
premiumStore.NumPremiums,
))
}
// Use minimum number of premiums as final length of array, if it's greater than NumPremiums.
// For `PremiumSamples`, this may happen in the event of a chain halt where there were
// fewer than expected `funding-sample` epochs. For `PremiumVotes`, this may happen
// if block times are longer than expected and hence there were not enough blocks to
// collect votes.
// Note `NumPremiums >= len(marketPremiums.Premiums)`, so `lenPadding >= 0`.
lenPadding := int64(lib.Max(premiumStore.NumPremiums, minNumPremiumsRequired)) -
int64(len(marketPremiums.Premiums))
padding := make([]int32, lenPadding)
paddedPremiums := append(marketPremiums.Premiums, padding...)
perpIdToPremium[marketPremiums.PerpetualId] = combineFunc(filterFunc(paddedPremiums))
}
return perpIdToPremium
}
// processPremiumVotesIntoSamples summarizes premium votes from proposers into premium samples.
// For each perpetual market:
// 1. Get the median of `PremiumVotes` collected during the past `funding-sample` epoch.
// This median value is referred to as a "sample".
// 2. Append the new "sample" to the `PremiumSamples` in state.
// 3. Clear `PremiumVotes` to an empty slice.
func (k Keeper) processPremiumVotesIntoSamples(
ctx sdk.Context,
newFundingSampleEpoch epochstypes.EpochInfo,
) {
// For premium votes, we take the median of all votes without modifying the list
// (using identify function as `filterFunc`)
perpIdToSummarizedPremium := k.processStoredPremiums(
ctx,
newFundingSampleEpoch,
types.PremiumVotesKey,
k.GetParams(ctx).MinNumVotesPerSample,
// `MustGetMedian` panics when the padded list is empty, which breaks the invariant that
// Max(premiumStore.NumPremiums, minNumPremiumsRequired) > 0.
// See details in implementation of `processStoredPremiums`.
lib.MustGetMedian[int32], // combineFunc
func(input []int32) []int32 { return input }, // filterFunc
)
newSamples := []types.FundingPremium{}
newSamplesForEvent := []indexerevents.FundingUpdateV1{}
allPerps := k.GetAllPerpetuals(ctx)
for _, perp := range allPerps {
summarizedPremium, found := perpIdToSummarizedPremium[perp.GetId()]
if !found {
summarizedPremium = 0
}
telemetry.SetGaugeWithLabels(
[]string{
types.ModuleName,
metrics.PremiumSampleValue,
},
float32(summarizedPremium),
[]gometrics.Label{
metrics.GetLabelForIntValue(
metrics.PerpetualId,
int(perp.GetId()),
),
},
)
// Append all samples (including zeros) to `newSamplesForEvent`, since
// the indexer should forward all sample values to users.
newSamplesForEvent = append(newSamplesForEvent, indexerevents.FundingUpdateV1{
PerpetualId: perp.GetId(),
FundingValuePpm: summarizedPremium,
})
if summarizedPremium != 0 {
// Append non-zero sample to `PremiumSample` storage.
newSamples = append(newSamples, types.FundingPremium{
PerpetualId: perp.GetId(),
PremiumPpm: summarizedPremium,
})
}
}
if err := k.AddPremiumSamples(ctx, newSamples); err != nil {
panic(err)
}
k.indexerEventManager.AddBlockEvent(
ctx,
indexerevents.SubtypeFundingValues,
indexer_manager.IndexerTendermintEvent_BLOCK_EVENT_END_BLOCK,
indexerevents.FundingValuesEventVersion,
indexer_manager.GetBytes(
indexerevents.NewPremiumSamplesEvent(newSamplesForEvent),
),
)
k.SetEmptyPremiumVotes(ctx)
}
// MaybeProcessNewFundingSampleEpoch summarizes premium votes stored in application
// states into new funding samples, if the current block is the start of a new
// `funding-sample` epoch. Otherwise, does nothing.
func (k Keeper) MaybeProcessNewFundingSampleEpoch(
ctx sdk.Context,
) {
numBlocks, err := k.epochsKeeper.NumBlocksSinceEpochStart(
ctx,
epochstypes.FundingSampleEpochInfoName,
)
// Invariant broken: `FundingSample` epoch must exist in epochs store.
if err != nil {
panic(err)
}
// If the current block is not the start of a new funding-sample epoch, do nothing.
if numBlocks != 0 {
return
}
newFundingSampleEpoch := k.epochsKeeper.MustGetFundingSampleEpochInfo(ctx)
k.processPremiumVotesIntoSamples(ctx, newFundingSampleEpoch)
}
// getFundingIndexDelta returns fundingIndexDelta which represents the change of FundingIndex since
// the last time `funding-tick` was processed.
// TODO(DEC-1536): Make the 8-hour funding rate period configurable.
func (k Keeper) getFundingIndexDelta(
ctx sdk.Context,
perp types.Perpetual,
big8hrFundingRatePpm *big.Int,
timeSinceLastFunding uint32,
) (
fundingIndexDelta *big.Int,
err error,
) {
marketPrice, err := k.pricesKeeper.GetMarketPrice(ctx, perp.Params.MarketId)
if err != nil {
return nil, fmt.Errorf("failed to get market price for perpetual %v, err = %w", perp.Params.Id, err)
}
// Get pro-rated funding rate adjusted by time delta.
proratedFundingRate := new(big.Rat).SetInt(big8hrFundingRatePpm)
proratedFundingRate.Mul(
proratedFundingRate,
new(big.Rat).SetUint64(uint64(timeSinceLastFunding)),
)
proratedFundingRate.Quo(
proratedFundingRate,
// TODO(DEC-1536): Make the 8-hour funding rate period configurable.
new(big.Rat).SetUint64(3600*8),
)
bigFundingIndexDelta := lib.FundingRateToIndex(
proratedFundingRate,
perp.Params.AtomicResolution,
marketPrice.Price,
marketPrice.Exponent,
)
return bigFundingIndexDelta, nil
}
// GetAddPremiumVotes returns the newest premiums for all perpetuals,
// if the current block is the start of a new funding-sample epoch.
// Otherwise, does nothing and returns an empty message.
// Does not make any changes to state.
func (k Keeper) GetAddPremiumVotes(
ctx sdk.Context,
) (
msgAddPremiumVotes *types.MsgAddPremiumVotes,
) {
newPremiumVotes, err := k.sampleAllPerpetuals(ctx)
if err != nil {
k.Logger(ctx).Error(fmt.Sprintf(
"failed to sample perpetuals, err = %v",
err,
))
}
telemetry.SetGauge(
float32(len(newPremiumVotes)),
types.ModuleName,
metrics.NewPremiumVotes,
metrics.Count,
metrics.Proposer,
)
return types.NewMsgAddPremiumVotes(newPremiumVotes)
}
// sampleAllPerpetuals takes premium samples for each perpetual market,
// and returns as a list of samples sorted by perpetual Id.
// Markets with zero premium samples are skipped in return value.
func (k Keeper) sampleAllPerpetuals(ctx sdk.Context) (
samples []types.FundingPremium,
err error,
) {
allPerpetuals := k.GetAllPerpetuals(ctx)
// Calculate `maxAbsPremiumVotePpm` of each liquidity tier.
liquidityTierToMaxAbsPremiumVotePpm := k.getLiquidityTiertoMaxAbsPremiumVotePpm(ctx)
// Measure latency of calling `GetPricePremiumForPerpetual` for all perpetuals.
defer telemetry.ModuleMeasureSince(
types.ModuleName,
time.Now(),
metrics.GetAllPerpetualPricePremiums,
metrics.Latency,
)
marketIdToIndexPrice := k.pricesKeeper.GetMarketIdToValidIndexPrice(ctx)
for _, perp := range allPerpetuals {
indexPrice, exists := marketIdToIndexPrice[perp.Params.MarketId]
// Valid index price is missing
if !exists {
// Only log and increment stats if height is passed initialization period.
if ctx.BlockHeight() > pricestypes.PriceDaemonInitializationBlocks {
k.Logger(ctx).Error(
"Perpetual does not have valid index price. Skipping premium",
constants.MarketIdLogKey,
perp.Params.MarketId,
)
telemetry.IncrCounterWithLabels(
[]string{
types.ModuleName,
metrics.MissingIndexPriceForFunding,
metrics.Count,
},
1,
[]gometrics.Label{
metrics.GetLabelForIntValue(
metrics.MarketId,
int(perp.Params.MarketId),
),
},
)
}
// Skip this market, effectively emitting a zero premium.
continue
}
// Get impact notional corresponding to this perpetual market (panic if its liquidity tier doesn't exist).
liquidityTier, err := k.GetLiquidityTier(ctx, perp.Params.LiquidityTier)
if err != nil {
panic(err)
}
bigImpactNotionalQuoteQuantums := new(big.Int).SetUint64(liquidityTier.ImpactNotional)
// Get `maxAbsPremiumVotePpm` for this perpetual's liquidity tier (panic if not found).
maxAbsPremiumVotePpm, exists := liquidityTierToMaxAbsPremiumVotePpm[perp.Params.LiquidityTier]
if !exists {
panic(types.ErrLiquidityTierDoesNotExist)
}
premiumPpm, err := k.clobKeeper.GetPricePremiumForPerpetual(
ctx,
perp.Params.Id,
types.GetPricePremiumParams{
IndexPrice: indexPrice,
BaseAtomicResolution: perp.Params.AtomicResolution,
QuoteAtomicResolution: lib.QuoteCurrencyAtomicResolution,
ImpactNotionalQuoteQuantums: bigImpactNotionalQuoteQuantums,
MaxAbsPremiumVotePpm: maxAbsPremiumVotePpm,
},
)
if err != nil {
return nil, err
}
if premiumPpm == 0 {
// Do not include zero premiums in message.
k.Logger(ctx).Debug(
fmt.Sprintf(
"Perpetual (%d) has zero sampled premium. Not including in AddPremiumVotes message",
perp.Params.Id,
))
continue
}
samples = append(
samples,
*types.NewFundingPremium(
perp.Params.Id,
premiumPpm,
),
)
}
return samples, nil
}
// GetRemoveSampleTailsFunc returns a function that sorts the input samples (in place) and returns
// the sub-slice from the original slice, which removes `tailRemovalRatePpm` from top and bottom from the samples.
// Note the returned sub-slice is not a copy but references a sub-sequence of the original slice.
func (k Keeper) GetRemoveSampleTailsFunc(
ctx sdk.Context,
tailRemovalRatePpm uint32,
) func(input []int32) (output []int32) {
return func(premiums []int32) []int32 {
totalRemoval := lib.Int64MulPpm(
int64(len(premiums)),
tailRemovalRatePpm*2,
)
// Return early if no tail to remove.
if totalRemoval == 0 {
return premiums
} else if totalRemoval >= int64(len(premiums)) {
k.Logger(ctx).Error(fmt.Sprintf(
"GetRemoveSampleTailsFunc: totalRemoval(%d) > length of premium samples (%d); skip removing",
totalRemoval,
len(premiums),
))
return premiums
}
bottomRemoval := totalRemoval / 2
topRemoval := totalRemoval - bottomRemoval
end := int64(len(premiums)) - topRemoval
sort.Slice(premiums, func(i, j int) bool { return premiums[i] < premiums[j] })
return premiums[bottomRemoval:end]
}
}
// MaybeProcessNewFundingTickEpoch processes funding ticks if the current block
// is the start of a new funding-tick epoch. Otherwise, do nothing.
func (k Keeper) MaybeProcessNewFundingTickEpoch(ctx sdk.Context) {
numBlocks, err := k.epochsKeeper.NumBlocksSinceEpochStart(
ctx,
epochstypes.FundingTickEpochInfoName,
)
if err != nil {
panic(err)
}
// If the current block is not the start of a new funding-tick epoch, do nothing.
if numBlocks != 0 {
return
}
allPerps := k.GetAllPerpetuals(ctx)
params := k.GetParams(ctx)
fundingTickEpochInfo := k.epochsKeeper.MustGetFundingTickEpochInfo(ctx)
fundingSampleEpochInfo := k.epochsKeeper.MustGetFundingSampleEpochInfo(ctx)
// Use the ratio between funding-tick and funding-sample durations
// as minimum number of samples required to get a premium rate.
minSampleRequiredForPremiumRate := lib.MustDivideUint32RoundUp(
fundingTickEpochInfo.Duration,
fundingSampleEpochInfo.Duration,
)
// TODO(DEC-1449): Read `RemovedTailSampleRatioPpm` from state. Determine initial value.
// This value should be 0% or some low value like 5%, since we already has a layer of
// filtering we compute samples as median of premium votes.
tailRemovalRatePpm := types.RemovedTailSampleRatioPpm
// Get `sampleTailsRemovalFunc` which removes a percentage of top and bottom samples
// from the input after sorting.
sampleTailsRemovalFunc := k.GetRemoveSampleTailsFunc(ctx, tailRemovalRatePpm)
// Process stored samples from last `funding-tick` epoch, and retrieve
// a mapping from `perpetualId` to summarized premium rate for this epoch.
// For premiums, we first remove a fixed amount of bottom/top samples, then
// take the average of the remaining samples.
perpIdToPremiumPpm := k.processStoredPremiums(
ctx,
fundingTickEpochInfo,
types.PremiumSamplesKey,
minSampleRequiredForPremiumRate,
lib.AvgInt32, // combineFunc
sampleTailsRemovalFunc, // filterFunc
)
newFundingRatesAndIndicesForEvent := []indexerevents.FundingUpdateV1{}
for _, perp := range allPerps {
premiumPpm, found := perpIdToPremiumPpm[perp.Params.Id]
if !found {
k.Logger(ctx).Info(
fmt.Sprintf(
"MaybeProcessNewFundingTickEpoch: No samples found for perpetual (%v) during `funding-tick` epoch\n",
perp.Params.Id,
),
)
premiumPpm = 0
}
bigFundingRatePpm := new(big.Int).SetInt64(int64(premiumPpm))
// funding rate = premium + default funding
bigFundingRatePpm.Add(
bigFundingRatePpm,
new(big.Int).SetInt64(int64(perp.Params.DefaultFundingPpm)),
)
liquidityTier, err := k.GetLiquidityTier(ctx, perp.Params.LiquidityTier)
if err != nil {
panic(err)
}
// Panic if maintenance fraction ppm is larger than its maximum value.
if liquidityTier.MaintenanceFractionPpm > types.MaxMaintenanceFractionPpm {
panic(errorsmod.Wrapf(
types.ErrMaintenanceFractionPpmExceedsMax,
"perpetual Id = (%d), liquidity tier Id = (%d), maintenance fraction ppm = (%v)",
perp.Params.Id, perp.Params.LiquidityTier, liquidityTier.MaintenanceFractionPpm,
))
}
// Clamp funding rate according to equation:
// |R| <= clamp_factor * (initial margin - maintenance margin)
fundingRateUpperBoundPpm := liquidityTier.GetMaxAbsFundingClampPpm(params.FundingRateClampFactorPpm)
bigFundingRatePpm = lib.BigIntClamp(
bigFundingRatePpm,
new(big.Int).Neg(fundingRateUpperBoundPpm),
fundingRateUpperBoundPpm,
)
// Emit clamped funding rate.
telemetry.SetGaugeWithLabels(
[]string{
types.ModuleName,
metrics.PremiumRate,
},
float32(bigFundingRatePpm.Int64()),
[]gometrics.Label{
metrics.GetLabelForIntValue(
metrics.PerpetualId,
int(perp.Params.Id),
),
},
)
if bigFundingRatePpm.Cmp(lib.BigMaxInt32()) > 0 {
panic(errorsmod.Wrapf(
types.ErrFundingRateInt32Overflow,
"perpetual Id = (%d), funding rate = (%v)",
perp.Params.Id, bigFundingRatePpm,
))
}
if bigFundingRatePpm.Sign() != 0 {
fundingIndexDelta, err := k.getFundingIndexDelta(
ctx,
perp,
bigFundingRatePpm,
// use funding-tick duration as `timeSinceLastFunding`
// TODO(DEC-1483): Handle the case when duration value is updated
// during the epoch.
fundingTickEpochInfo.Duration,
)
if err != nil {
panic(err)
}
if err := k.ModifyFundingIndex(ctx, perp.Params.Id, fundingIndexDelta); err != nil {
panic(err)
}
}
// Get perpetual object with updated funding index.
perp, err = k.GetPerpetual(ctx, perp.Params.Id)
if err != nil {
panic(err)
}
newFundingRatesAndIndicesForEvent = append(newFundingRatesAndIndicesForEvent, indexerevents.FundingUpdateV1{
PerpetualId: perp.Params.Id,
FundingValuePpm: int32(bigFundingRatePpm.Int64()),
FundingIndex: perp.FundingIndex,
})
}
k.indexerEventManager.AddBlockEvent(
ctx,
indexerevents.SubtypeFundingValues,
indexer_manager.IndexerTendermintEvent_BLOCK_EVENT_END_BLOCK,
indexerevents.FundingValuesEventVersion,
indexer_manager.GetBytes(
indexerevents.NewFundingRatesAndIndicesEvent(newFundingRatesAndIndicesForEvent),
),
)
// Clear premium samples.
k.SetEmptyPremiumSamples(ctx)
}
// GetNetNotional returns the net notional in quote quantums, which can be represented by the following equation:
// `quantums / 10^baseAtomicResolution * marketPrice * 10^marketExponent * 10^quoteAtomicResolution`.
// Note that longs are positive, and shorts are negative.
// Returns an error if a perpetual with `id` does not exist or if the `perpetual.Params.MarketId` does
// not exist.
//
// Note that this function is getting called very frequently; metrics in this function
// should be sampled to reduce CPU time.
func (k Keeper) GetNetNotional(
ctx sdk.Context,
id uint32,
bigQuantums *big.Int,
) (
bigNetNotionalQuoteQuantums *big.Int,
err error,
) {
if rand.Float64() < metrics.LatencyMetricSampleRate {
defer metrics.ModuleMeasureSinceWithLabels(
types.ModuleName,
[]string{metrics.GetNetNotional, metrics.Latency},
time.Now(),
[]gometrics.Label{
metrics.GetLabelForStringValue(
metrics.SampleRate,
fmt.Sprintf("%f", metrics.LatencyMetricSampleRate),
),
},
)
}
perpetual, marketPrice, err := k.GetPerpetualAndMarketPrice(ctx, id)
if err != nil {
return new(big.Int), err
}
return GetNetNotionalInQuoteQuantums(perpetual, marketPrice, bigQuantums), nil
}
// GetNetNotionalInQuoteQuantums returns the net notional in quote quantums, which can be
// represented by the following equation:
//
// `quantums / 10^baseAtomicResolution * marketPrice * 10^marketExponent * 10^quoteAtomicResolution`.
// Note that longs are positive, and shorts are negative.
//
// Also note that this is a stateless function.
func GetNetNotionalInQuoteQuantums(
perpetual types.Perpetual,
marketPrice pricestypes.MarketPrice,
bigQuantums *big.Int,
) (
bigNetNotionalQuoteQuantums *big.Int,
) {
bigQuoteQuantums := lib.BaseToQuoteQuantums(
bigQuantums,
perpetual.Params.AtomicResolution,
marketPrice.Price,
marketPrice.Exponent,
)
return bigQuoteQuantums
}
// GetNotionalInBaseQuantums returns the net notional in base quantums, which can be represented
// by the following equation:
// `quoteQuantums * 10^baseAtomicResolution / (marketPrice * 10^marketExponent * 10^quoteAtomicResolution)`.
// Note that longs are positive, and shorts are negative.
// Returns an error if a perpetual with `id` does not exist or if the `perpetual.Params.MarketId` does
// not exist.
func (k Keeper) GetNotionalInBaseQuantums(
ctx sdk.Context,
id uint32,
bigQuoteQuantums *big.Int,
) (
bigBaseQuantums *big.Int,
err error,
) {
defer telemetry.ModuleMeasureSince(
types.ModuleName,
time.Now(),
metrics.GetNotionalInBaseQuantums,
metrics.Latency,
)
perpetual, marketPrice, err := k.GetPerpetualAndMarketPrice(ctx, id)
if err != nil {
return new(big.Int), err
}
bigBaseQuantums = lib.QuoteToBaseQuantums(
bigQuoteQuantums,
perpetual.Params.AtomicResolution,
marketPrice.Price,
marketPrice.Exponent,
)
return bigBaseQuantums, nil
}
// GetNetCollateral returns the net collateral in quote quantums. The net collateral is equal to
// the net open notional, which can be represented by the following equation:
// `quantums / 10^baseAtomicResolution * marketPrice * 10^marketExponent * 10^quoteAtomicResolution`.
// Note that longs are positive, and shorts are negative.
// Returns an error if a perpetual with `id` does not exist or if the `perpetual.Params.MarketId` does
// not exist.
func (k Keeper) GetNetCollateral(
ctx sdk.Context,
id uint32,
bigQuantums *big.Int,
) (
bigNetCollateralQuoteQuantums *big.Int,
err error,
) {
// The net collateral is equal to the net open notional.
return k.GetNetNotional(ctx, id, bigQuantums)
}
// GetMarginRequirements returns initial and maintenance margin requirements in quote quantums, given the position
// size in base quantums.
//
// Margin requirements are a function of the absolute value of the open notional of the position as well as
// the parameters of the relevant `LiquidityTier` of the perpetual.
// Initial margin requirement is determined by multiplying `InitialMarginPpm` and `notionalValue`.
// `notionalValue` is determined by multiplying the size of the position by the oracle price of the position.
// Maintenance margin requirement is then simply a fraction (`maintenanceFractionPpm`) of initial margin requirement.
//
// Returns an error if a perpetual with `id`, `perpetual.Params.MarketId`, or
// `perpetual.Params.LiquidityTier` does not exist.
//
// Note that this function is getting called very frequently; metrics in this function
// should be sampled to reduce CPU time.
func (k Keeper) GetMarginRequirements(
ctx sdk.Context,
id uint32,
bigQuantums *big.Int,
) (
bigInitialMarginQuoteQuantums *big.Int,
bigMaintenanceMarginQuoteQuantums *big.Int,
err error,
) {
if rand.Float64() < metrics.LatencyMetricSampleRate {
defer metrics.ModuleMeasureSinceWithLabels(
types.ModuleName,
[]string{metrics.GetMarginRequirements, metrics.Latency},
time.Now(),
[]gometrics.Label{
metrics.GetLabelForStringValue(
metrics.SampleRate,
fmt.Sprintf("%f", metrics.LatencyMetricSampleRate),
),
},
)
}
// Get perpetual and market price.
perpetual, marketPrice, err := k.GetPerpetualAndMarketPrice(ctx, id)
if err != nil {
return nil, nil, err
}
// Get perpetual's liquidity tier.
liquidityTier, err := k.GetLiquidityTier(ctx, perpetual.Params.LiquidityTier)
if err != nil {
return nil, nil, err
}
bigInitialMarginQuoteQuantums,
bigMaintenanceMarginQuoteQuantums = GetMarginRequirementsInQuoteQuantums(
perpetual,
marketPrice,
liquidityTier,
bigQuantums,
)
return bigInitialMarginQuoteQuantums, bigMaintenanceMarginQuoteQuantums, nil
}
// GetMarginRequirementsInQuoteQuantums returns initial and maintenance margin requirements
// in quote quantums, given the position size in base quantums.
//
// Note that this is a stateless function.
func GetMarginRequirementsInQuoteQuantums(
perpetual types.Perpetual,
marketPrice pricestypes.MarketPrice,
liquidityTier types.LiquidityTier,
bigQuantums *big.Int,
) (
bigInitialMarginQuoteQuantums *big.Int,
bigMaintenanceMarginQuoteQuantums *big.Int,
) {
// Always consider the magnitude of the position regardless of whether it is long/short.
bigAbsQuantums := new(big.Int).Set(bigQuantums).Abs(bigQuantums)
bigQuoteQuantums := lib.BaseToQuoteQuantums(
bigAbsQuantums,
perpetual.Params.AtomicResolution,
marketPrice.Price,
marketPrice.Exponent,
)
// Initial margin requirement quote quantums = size in quote quantums * initial margin PPM.
bigInitialMarginQuoteQuantums = liquidityTier.GetInitialMarginQuoteQuantums(bigQuoteQuantums)
// Maintenance margin requirement quote quantums = IM in quote quantums * maintenance fraction PPM.
bigMaintenanceMarginQuoteQuantums = lib.BigRatRound(
lib.BigRatMulPpm(
new(big.Rat).SetInt(bigInitialMarginQuoteQuantums),
liquidityTier.MaintenanceFractionPpm,
),
true,
)
return bigInitialMarginQuoteQuantums, bigMaintenanceMarginQuoteQuantums
}
// GetSettlementPpm returns the net settlement amount ppm (in quote quantums) given
// the perpetual Id and position size (in base quantums).
// When handling rounding, always round positive settlement amount to zero, and
// negative amount to negative infinity. This ensures total amount of value does
// not increase after settlement.
// Example:
// For a round of funding payments, accounts A, B are to receive 102.5 quote quantums;
// account C is to pay 205 quote quantums.
// After settlement, accounts A, B are credited 102 quote quantum each; account C
// is debited 205 quote quantums.
func (k Keeper) GetSettlementPpm(
ctx sdk.Context,
perpetualId uint32,
quantums *big.Int,
index *big.Int,
) (
bigNetSettlementPpm *big.Int,
newFundingIndex *big.Int,
err error,
) {
// Get the perpetual for newest FundingIndex.
perpetual, err := k.GetPerpetual(ctx, perpetualId)
if err != nil {
return big.NewInt(0), big.NewInt(0), err
}
bigNetSettlementPpm, newFundingIndex = GetSettlementPpmWithPerpetual(
perpetual,
quantums,
index,
)
return bigNetSettlementPpm, newFundingIndex, nil
}
// GetSettlementPpm returns the net settlement amount ppm (in quote quantums) given
// the perpetual and position size (in base quantums).
//
// Note that this function is a stateless utility function.
func GetSettlementPpmWithPerpetual(
perpetual types.Perpetual,
quantums *big.Int,
index *big.Int,
) (
bigNetSettlementPpm *big.Int,
newFundingIndex *big.Int,
) {
indexDelta := new(big.Int).Sub(perpetual.FundingIndex.BigInt(), index)
// if indexDelta is zero, then net settlement is zero.
if indexDelta.Sign() == 0 {
return big.NewInt(0), perpetual.FundingIndex.BigInt()
}
bigNetSettlementPpm = new(big.Int).Mul(indexDelta, quantums)