-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFlowALPv0.cdc
More file actions
4916 lines (4262 loc) · 233 KB
/
FlowALPv0.cdc
File metadata and controls
4916 lines (4262 loc) · 233 KB
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
import "Burner"
import "FungibleToken"
import "ViewResolver"
import "DeFiActionsUtils"
import "DeFiActions"
import "MOET"
import "FlowALPMath"
access(all) contract FlowALPv0 {
// Design notes: Fixed-point and 128-bit usage:
// - Interest indices and rates are maintained in 128-bit fixed-point to avoid precision loss during compounding.
// - External-facing amounts remain UFix64.
// Promotions to 128-bit occur only for internal math that multiplies by indices/rates.
// This strikes a balance between precision and ergonomics while keeping on-chain math safe.
/// The canonical StoragePath where the primary FlowALPv0 Pool is stored
access(all) let PoolStoragePath: StoragePath
/// The canonical StoragePath where the PoolFactory resource is stored
access(all) let PoolFactoryPath: StoragePath
/// The canonical PublicPath where the primary FlowALPv0 Pool can be accessed publicly
access(all) let PoolPublicPath: PublicPath
access(all) let PoolCapStoragePath: StoragePath
/// The canonical StoragePath where PositionManager resources are stored
access(all) let PositionStoragePath: StoragePath
/// The canonical PublicPath where PositionManager can be accessed publicly
access(all) let PositionPublicPath: PublicPath
/* --- EVENTS ---- */
// Prefer Type in events for stronger typing; off-chain can stringify via .identifier
access(all) event Opened(
pid: UInt64,
poolUUID: UInt64
)
access(all) event Deposited(
pid: UInt64,
poolUUID: UInt64,
vaultType: Type,
amount: UFix64,
depositedUUID: UInt64
)
access(all) event Withdrawn(
pid: UInt64,
poolUUID: UInt64,
vaultType: Type,
amount: UFix64,
withdrawnUUID: UInt64
)
/// Emitted when a position is closed via the closePosition() method.
/// This indicates a full position closure with debt repayment and collateral extraction.
///
/// Uses dictionaries instead of parallel arrays for deterministic, unambiguous data.
/// Keys are token type identifiers (e.g., "A.xxx.FlowToken.Vault").
access(all) event PositionClosed(
pid: UInt64,
poolUUID: UInt64,
repaymentsByType: {String: UFix64}, // Map of debt token type → amount repaid
withdrawalsByType: {String: UFix64} // Map of token type → amount withdrawn (collateral + overpayment dust)
)
access(all) event Rebalanced(
pid: UInt64,
poolUUID: UInt64,
atHealth: UFix128,
amount: UFix64,
fromUnder: Bool
)
/// Consolidated liquidation params update event including all updated values
access(all) event LiquidationParamsUpdated(
poolUUID: UInt64,
targetHF: UFix128,
)
access(all) event PauseParamsUpdated(
poolUUID: UInt64,
warmupSec: UInt64,
)
/// Emitted when the pool is paused, which temporarily prevents liquidations, withdrawals, and deposits.
access(all) event PoolPaused(
poolUUID: UInt64
)
/// Emitted when the pool is unpaused, which re-enables all functionality when the Pool was previously paused.
access(all) event PoolUnpaused(
poolUUID: UInt64,
warmupEndsAt: UInt64
)
access(all) event LiquidationExecuted(
pid: UInt64,
poolUUID: UInt64,
debtType: String,
repayAmount: UFix64,
seizeType: String,
seizeAmount: UFix64,
newHF: UFix128
)
access(all) event LiquidationExecutedViaDex(
pid: UInt64,
poolUUID: UInt64,
seizeType: String,
seized: UFix64,
debtType: String,
repaid: UFix64,
slippageBps: UInt16,
newHF: UFix128
)
access(all) event PriceOracleUpdated(
poolUUID: UInt64,
newOracleType: String
)
access(all) event InterestCurveUpdated(
poolUUID: UInt64,
tokenType: String,
curveType: String
)
access(all) event DepositCapacityRegenerated(
tokenType: Type,
oldCapacityCap: UFix64,
newCapacityCap: UFix64
)
access(all) event DepositCapacityConsumed(
tokenType: Type,
pid: UInt64,
amount: UFix64,
remainingCapacity: UFix64
)
//// Emitted each time the insurance rate is updated for a specific token in a specific pool.
//// The insurance rate is an annual percentage; for example a value of 0.001 indicates 0.1%.
access(all) event InsuranceRateUpdated(
poolUUID: UInt64,
tokenType: String,
insuranceRate: UFix64,
)
/// Emitted each time an insurance fee is collected for a specific token in a specific pool.
/// The insurance amount is the amount of insurance collected, denominated in MOET.
access(all) event InsuranceFeeCollected(
poolUUID: UInt64,
tokenType: String,
insuranceAmount: UFix64,
collectionTime: UFix64,
)
//// Emitted each time the stability rate is updated for a specific token in a specific pool.
//// The stability rate is an annual percentage; the default value is 0.05 (5%).
access(all) event StabilityFeeRateUpdated(
poolUUID: UInt64,
tokenType: String,
stabilityFeeRate: UFix64,
)
/// Emitted each time an stability fee is collected for a specific token in a specific pool.
/// The stability amount is the amount of stability collected, denominated in token type.
access(all) event StabilityFeeCollected(
poolUUID: UInt64,
tokenType: String,
stabilityAmount: UFix64,
collectionTime: UFix64,
)
/// Emitted each time funds are withdrawn from the stability fund for a specific token in a specific pool.
/// The amount is the quantity withdrawn, denominated in the token type.
access(all) event StabilityFundWithdrawn(
poolUUID: UInt64,
tokenType: String,
amount: UFix64,
)
/* --- CONSTRUCTS & INTERNAL METHODS ---- */
/// EPosition
///
/// Entitlement for managing positions within the pool.
/// This entitlement grants access to position-specific operations including deposits, withdrawals,
/// rebalancing, and health parameter management for any position in the pool.
///
/// Note that this entitlement provides access to all positions in the pool,
/// not just individual position owners' positions.
access(all) entitlement EPosition
/// ERebalance
///
/// Entitlement for rebalancing positions.
access(all) entitlement ERebalance
/// EGovernance
///
/// Entitlement for governance operations that control pool-wide parameters and configuration.
/// This entitlement grants access to administrative functions that affect the entire pool,
/// including liquidation settings, token support, interest rates, and protocol parameters.
///
/// This entitlement should be granted only to trusted governance entities that manage
/// the protocol's risk parameters and operational settings.
access(all) entitlement EGovernance
/// EImplementation
///
/// Entitlement for internal implementation operations that maintain the pool's state
/// and process asynchronous updates. This entitlement grants access to low-level state
/// management functions used by the protocol's internal mechanisms.
///
/// This entitlement is used internally by the protocol to maintain state consistency
/// and process queued operations. It should not be granted to external users.
access(all) entitlement EImplementation
/// EParticipant
///
/// Entitlement for general participant operations that allow users to interact with the pool
/// at a basic level. This entitlement grants access to position creation and basic deposit
/// operations without requiring full position ownership.
///
/// This entitlement is more permissive than EPosition and allows anyone to create positions
/// and make deposits, enabling public participation in the protocol while maintaining
/// separation between position creation and position management.
access(all) entitlement EParticipant
/// Grants access to configure drawdown sinks, top-up sources, and other position settings, for the Position resource.
/// Withdrawal access is provided using FungibleToken.Withdraw.
access(all) entitlement EPositionAdmin
/* --- NUMERIC TYPES POLICY ---
- External/public APIs (Vault amounts, deposits/withdrawals, events) use UFix64.
- Internal accounting and risk math use UFix128: scaled/true balances, interest indices/rates,
health factor, and prices once converted.
Rationale:
- Interest indices and rates are modeled as 18-decimal fixed-point in FlowALPMath and stored as UFix128.
- Operating in the UFix128 domain minimizes rounding error in true↔scaled conversions and
health/price computations.
- We convert at boundaries via type casting to UFix128 or FlowALPMath.toUFix64.
*/
/// InternalBalance
///
/// A structure used internally to track a position's balance for a particular token
access(all) struct InternalBalance {
/// The current direction of the balance - Credit (owed to borrower) or Debit (owed to protocol)
access(all) var direction: BalanceDirection
/// Internally, position balances are tracked using a "scaled balance".
/// The "scaled balance" is the actual balance divided by the current interest index for the associated token.
/// This means we don't need to update the balance of a position as time passes, even as interest rates change.
/// We only need to update the scaled balance when the user deposits or withdraws funds.
/// The interest index is a number relatively close to 1.0,
/// so the scaled balance will be roughly of the same order of magnitude as the actual balance.
/// We store the scaled balance as UFix128 to align with UFix128 interest indices
// and to reduce rounding during true ↔ scaled conversions.
access(all) var scaledBalance: UFix128
// Single initializer that can handle both cases
init(
direction: BalanceDirection,
scaledBalance: UFix128
) {
self.direction = direction
self.scaledBalance = scaledBalance
}
/// Records a deposit of the defined amount, updating the inner scaledBalance as well as relevant values
/// in the provided TokenState.
///
/// It's assumed the TokenState and InternalBalance relate to the same token Type,
/// but since neither struct have values defining the associated token,
/// callers should be sure to make the arguments do in fact relate to the same token Type.
///
/// amount is expressed in UFix128 (true token units) to operate in the internal UFix128 domain;
/// public deposit APIs accept UFix64 and are converted at the boundary.
///
access(contract) fun recordDeposit(amount: UFix128, tokenState: auth(EImplementation) &TokenState) {
switch self.direction {
case BalanceDirection.Credit:
// Depositing into a credit position just increases the balance.
//
// To maximize precision, we could convert the scaled balance to a true balance,
// add the deposit amount, and then convert the result back to a scaled balance.
//
// However, this will only cause problems for very small deposits (fractions of a cent),
// so we save computational cycles by just scaling the deposit amount
// and adding it directly to the scaled balance.
let scaledDeposit = FlowALPv0.trueBalanceToScaledBalance(
amount,
interestIndex: tokenState.creditInterestIndex
)
self.scaledBalance = self.scaledBalance + scaledDeposit
// Increase the total credit balance for the token
tokenState.increaseCreditBalance(by: amount)
case BalanceDirection.Debit:
// When depositing into a debit position, we first need to compute the true balance
// to see if this deposit will flip the position from debit to credit.
let trueBalance = FlowALPv0.scaledBalanceToTrueBalance(
self.scaledBalance,
interestIndex: tokenState.debitInterestIndex
)
// Use >= comparison to match withdrawal pattern (both use >= for consistency).
// When deposit exactly equals debt, we enter this branch and check if balance reaches zero.
if trueBalance >= amount {
// The deposit isn't big enough to clear the debt,
// so we just decrement the debt.
let updatedBalance = trueBalance - amount
// Special case: If debt is fully repaid (exact match), flip to Credit with zero balance.
// This ensures a position with zero debt is always represented as Credit, not Debit.
if updatedBalance == 0.0 {
self.direction = BalanceDirection.Credit
self.scaledBalance = 0.0
} else {
self.scaledBalance = FlowALPv0.trueBalanceToScaledBalance(
updatedBalance,
interestIndex: tokenState.debitInterestIndex
)
}
// Decrease the total debit balance for the token
tokenState.decreaseDebitBalance(by: amount)
} else {
// The deposit is enough to clear the debt,
// so we switch to a credit position.
let updatedBalance = amount - trueBalance
self.direction = BalanceDirection.Credit
self.scaledBalance = FlowALPv0.trueBalanceToScaledBalance(
updatedBalance,
interestIndex: tokenState.creditInterestIndex
)
// Increase the credit balance AND decrease the debit balance
tokenState.increaseCreditBalance(by: updatedBalance)
tokenState.decreaseDebitBalance(by: trueBalance)
}
}
}
/// Records a withdrawal of the defined amount, updating the inner scaledBalance
/// as well as relevant values in the provided TokenState.
///
/// It's assumed the TokenState and InternalBalance relate to the same token Type,
/// but since neither struct have values defining the associated token,
/// callers should be sure to make the arguments do in fact relate to the same token Type.
///
/// amount is expressed in UFix128 for the same rationale as deposits;
/// public withdraw APIs are UFix64 and are converted at the boundary.
///
access(contract) fun recordWithdrawal(amount: UFix128, tokenState: auth(EImplementation) &TokenState) {
switch self.direction {
case BalanceDirection.Debit:
// Withdrawing from a debit position just increases the debt amount.
//
// To maximize precision, we could convert the scaled balance to a true balance,
// subtract the withdrawal amount, and then convert the result back to a scaled balance.
//
// However, this will only cause problems for very small withdrawals (fractions of a cent),
// so we save computational cycles by just scaling the withdrawal amount
// and subtracting it directly from the scaled balance.
let scaledWithdrawal = FlowALPv0.trueBalanceToScaledBalance(
amount,
interestIndex: tokenState.debitInterestIndex
)
self.scaledBalance = self.scaledBalance + scaledWithdrawal
// Increase the total debit balance for the token
tokenState.increaseDebitBalance(by: amount)
case BalanceDirection.Credit:
// When withdrawing from a credit position,
// we first need to compute the true balance
// to see if this withdrawal will flip the position from credit to debit.
let trueBalance = FlowALPv0.scaledBalanceToTrueBalance(
self.scaledBalance,
interestIndex: tokenState.creditInterestIndex
)
if trueBalance >= amount {
// The withdrawal isn't big enough to push the position into debt,
// so we just decrement the credit balance.
let updatedBalance = trueBalance - amount
self.scaledBalance = FlowALPv0.trueBalanceToScaledBalance(
updatedBalance,
interestIndex: tokenState.creditInterestIndex
)
// Decrease the total credit balance for the token
tokenState.decreaseCreditBalance(by: amount)
} else {
// The withdrawal is enough to push the position into debt,
// so we switch to a debit position.
let updatedBalance = amount - trueBalance
self.direction = BalanceDirection.Debit
self.scaledBalance = FlowALPv0.trueBalanceToScaledBalance(
updatedBalance,
interestIndex: tokenState.debitInterestIndex
)
// Decrease the credit balance AND increase the debit balance
tokenState.decreaseCreditBalance(by: trueBalance)
tokenState.increaseDebitBalance(by: updatedBalance)
}
}
}
}
/// BalanceSheet
///
/// An struct containing a position's overview in terms of its effective collateral and debt
/// as well as its current health.
access(all) struct BalanceSheet {
/// Effective collateral is a normalized valuation of collateral deposited into this position, denominated in $.
/// In combination with effective debt, this determines how much additional debt can be taken out by this position.
access(all) let effectiveCollateral: UFix128
/// Effective debt is a normalized valuation of debt withdrawn against this position, denominated in $.
/// In combination with effective collateral, this determines how much additional debt can be taken out by this position.
access(all) let effectiveDebt: UFix128
/// The health of the related position
access(all) let health: UFix128
init(
effectiveCollateral: UFix128,
effectiveDebt: UFix128
) {
self.effectiveCollateral = effectiveCollateral
self.effectiveDebt = effectiveDebt
self.health = FlowALPv0.healthComputation(
effectiveCollateral: effectiveCollateral,
effectiveDebt: effectiveDebt
)
}
}
access(all) struct PauseParamsView {
access(all) let paused: Bool
access(all) let warmupSec: UInt64
access(all) let lastUnpausedAt: UInt64?
init(
paused: Bool,
warmupSec: UInt64,
lastUnpausedAt: UInt64?,
) {
self.paused = paused
self.warmupSec = warmupSec
self.lastUnpausedAt = lastUnpausedAt
}
}
/// Liquidation parameters view (global)
access(all) struct LiquidationParamsView {
access(all) let targetHF: UFix128
access(all) let triggerHF: UFix128
init(
targetHF: UFix128,
triggerHF: UFix128,
) {
self.targetHF = targetHF
self.triggerHF = triggerHF
}
}
/// ImplementationUpdates
///
/// Entitlement mapping that enables authorized references on nested resources within InternalPosition.
/// This mapping translates EImplementation entitlement into Mutate and FungibleToken.Withdraw
/// capabilities, allowing the protocol's internal implementation to modify position state and
/// interact with fungible token vaults.
///
/// This mapping is used internally to process queued deposits and manage position state
/// without requiring direct access to the nested resources.
access(all) entitlement mapping ImplementationUpdates {
EImplementation -> Mutate
EImplementation -> FungibleToken.Withdraw
}
/// InternalPosition
///
/// An internal resource used to track deposits, withdrawals, balances, and queued deposits to an open position.
access(all) resource InternalPosition {
/// The position-specific target health, for auto-balancing purposes.
/// When the position health moves outside the range [minHealth, maxHealth], the balancing operation
/// should result in a position health of targetHealth.
access(EImplementation) var targetHealth: UFix128
/// The position-specific minimum health threshold, below which a position is considered undercollateralized.
/// When a position is under-collateralized, it is eligible for rebalancing.
/// NOTE: An under-collateralized position is distinct from an unhealthy position, and cannot be liquidated
access(EImplementation) var minHealth: UFix128
/// The position-specific maximum health threshold, above which a position is considered overcollateralized.
/// When a position is over-collateralized, it is eligible for rebalancing.
access(EImplementation) var maxHealth: UFix128
/// The balances of deposited and withdrawn token types
access(mapping ImplementationUpdates) var balances: {Type: InternalBalance}
/// Funds that have been deposited but must be asynchronously added to the Pool's reserves and recorded
access(mapping ImplementationUpdates) var queuedDeposits: @{Type: {FungibleToken.Vault}}
/// A DeFiActions Sink that if non-nil will enable the Pool to push overflown value automatically when the
/// position exceeds its maximum health based on the value of deposited collateral versus withdrawals
access(mapping ImplementationUpdates) var drawDownSink: {DeFiActions.Sink}?
/// A DeFiActions Source that if non-nil will enable the Pool to pull underflown value automatically when the
/// position falls below its minimum health based on the value of deposited collateral versus withdrawals.
///
/// If this value is not set, liquidation may occur in the event of undercollateralization.
access(mapping ImplementationUpdates) var topUpSource: {DeFiActions.Source}?
init() {
self.balances = {}
self.queuedDeposits <- {}
self.targetHealth = 1.3
self.minHealth = 1.1
self.maxHealth = 1.5
self.drawDownSink = nil
self.topUpSource = nil
}
/// Sets the Position's target health. See InternalPosition.targetHealth for details.
access(EImplementation) fun setTargetHealth(_ targetHealth: UFix128) {
pre {
targetHealth > self.minHealth: "Target health (\(targetHealth)) must be greater than min health (\(self.minHealth))"
targetHealth < self.maxHealth: "Target health (\(targetHealth)) must be less than max health (\(self.maxHealth))"
}
self.targetHealth = targetHealth
}
/// Sets the Position's minimum health. See InternalPosition.minHealth for details.
access(EImplementation) fun setMinHealth(_ minHealth: UFix128) {
pre {
minHealth > 1.0: "Min health (\(minHealth)) must be >1"
minHealth < self.targetHealth: "Min health (\(minHealth)) must be greater than target health (\(self.targetHealth))"
}
self.minHealth = minHealth
}
/// Sets the Position's maximum health. See InternalPosition.maxHealth for details.
access(EImplementation) fun setMaxHealth(_ maxHealth: UFix128) {
pre {
maxHealth > self.targetHealth: "Max health (\(maxHealth)) must be greater than target health (\(self.targetHealth))"
}
self.maxHealth = maxHealth
}
/// Returns a value-copy of `balances` suitable for constructing a `PositionView`.
access(all) fun copyBalances(): {Type: InternalBalance} {
return self.balances
}
/// Sets the InternalPosition's drawDownSink. If `nil`, the Pool will not be able to push overflown value when
/// the position exceeds its maximum health.
///
/// The Sink MUST accept a token type that is supported by the pool (i.e. present in the pool's globalLedger).
/// Validated against the caller-supplied `supportedTypes` set (pass `globalLedger.keys` from Pool).
access(EImplementation) fun setDrawDownSink(_ sink: {DeFiActions.Sink}?, supportedTypes: {Type: Bool}) {
pre {
sink == nil || supportedTypes[sink!.getSinkType()] == true:
"Invalid Sink provided - Sink must accept a pool-supported token type"
}
self.drawDownSink = sink
}
/// Sets the InternalPosition's topUpSource. If `nil`, the Pool will not be able to pull underflown value when
/// the position falls below its minimum health which may result in liquidation.
access(EImplementation) fun setTopUpSource(_ source: {DeFiActions.Source}?) {
/// TODO(jord): User can provide top-up source containing unsupported token type. Then later rebalances will revert.
/// Possibly an attack vector on automated rebalancing, if multiple positions are rebalanced in the same transaction.
self.topUpSource = source
}
}
/// InterestCurve
///
/// A simple interface to calculate interest rate for a token type.
access(all) struct interface InterestCurve {
/// Returns the annual interest rate for the given credit and debit balance, for some token T.
/// @param creditBalance The credit (deposit) balance of token T
/// @param debitBalance The debit (withdrawal) balance of token T
access(all) fun interestRate(creditBalance: UFix128, debitBalance: UFix128): UFix128 {
post {
// Max rate is 400% (4.0) to accommodate high-utilization scenarios
// with kink-based curves like Aave v3's interest rate strategy
result <= 4.0:
"Interest rate can't exceed 400%"
}
}
}
/// FixedRateInterestCurve
///
/// A fixed-rate interest curve implementation that returns a constant yearly interest rate
/// regardless of utilization. This is suitable for stable assets like MOET where predictable
/// rates are desired.
/// @param yearlyRate The fixed yearly interest rate as a UFix128 (e.g., 0.05 for 5% APY)
access(all) struct FixedRateInterestCurve: InterestCurve {
access(all) let yearlyRate: UFix128
init(yearlyRate: UFix128) {
pre {
yearlyRate <= 1.0: "Yearly rate cannot exceed 100%, got \(yearlyRate)"
}
self.yearlyRate = yearlyRate
}
access(all) fun interestRate(creditBalance: UFix128, debitBalance: UFix128): UFix128 {
return self.yearlyRate
}
}
/// KinkInterestCurve
///
/// A kink-based interest rate curve implementation. The curve has two linear segments:
/// - Before the optimal utilization ratio (the "kink"): a gentle slope
/// - After the optimal utilization ratio: a steep slope to discourage over-utilization
///
/// This creates a "kinked" curve that incentivizes maintaining utilization near the
/// optimal point while heavily penalizing over-utilization to protect protocol liquidity.
///
/// Formula:
/// - utilization = debitBalance / (creditBalance + debitBalance)
/// - Before kink (utilization <= optimalUtilization):
/// rate = baseRate + (slope1 × utilization / optimalUtilization)
/// - After kink (utilization > optimalUtilization):
/// rate = baseRate + slope1 + (slope2 × excessUtilization)
/// where excessUtilization = (utilization - optimalUtilization) / (1 - optimalUtilization)
///
/// @param optimalUtilization The target utilization ratio (e.g., 0.80 for 80%)
/// @param baseRate The minimum yearly interest rate (e.g., 0.01 for 1% APY)
/// @param slope1 The total rate increase from 0% to optimal utilization (e.g., 0.04 for 4%)
/// @param slope2 The total rate increase from optimal to 100% utilization (e.g., 0.60 for 60%)
access(all) struct KinkInterestCurve: InterestCurve {
/// The optimal utilization ratio (the "kink" point), e.g., 0.80 = 80%
access(all) let optimalUtilization: UFix128
/// The base yearly interest rate applied at 0% utilization
access(all) let baseRate: UFix128
/// The slope of the interest curve before the optimal point (gentle slope)
access(all) let slope1: UFix128
/// The slope of the interest curve after the optimal point (steep slope)
access(all) let slope2: UFix128
init(
optimalUtilization: UFix128,
baseRate: UFix128,
slope1: UFix128,
slope2: UFix128
) {
pre {
optimalUtilization >= 0.01:
"Optimal utilization must be at least 1%, got \(optimalUtilization)"
optimalUtilization <= 0.99:
"Optimal utilization must be at most 99%, got \(optimalUtilization)"
slope2 >= slope1:
"Slope2 (\(slope2)) must be >= slope1 (\(slope1))"
baseRate + slope1 + slope2 <= 4.0:
"Maximum rate cannot exceed 400%, got \(baseRate + slope1 + slope2)"
}
self.optimalUtilization = optimalUtilization
self.baseRate = baseRate
self.slope1 = slope1
self.slope2 = slope2
}
access(all) fun interestRate(creditBalance: UFix128, debitBalance: UFix128): UFix128 {
// If no debt, return base rate
if debitBalance == 0.0 {
return self.baseRate
}
// Calculate utilization ratio: debitBalance / (creditBalance + debitBalance)
// Note: totalBalance > 0 is guaranteed since debitBalance > 0 and creditBalance >= 0
let totalBalance = creditBalance + debitBalance
let utilization = debitBalance / totalBalance
// If utilization is below or at the optimal point, use slope1
if utilization <= self.optimalUtilization {
// rate = baseRate + (slope1 × utilization / optimalUtilization)
let utilizationFactor = utilization / self.optimalUtilization
let slope1Component = self.slope1 * utilizationFactor
return self.baseRate + slope1Component
} else {
// If utilization is above the optimal point, use slope2 for excess
// excessUtilization = (utilization - optimalUtilization) / (1 - optimalUtilization)
let excessUtilization = utilization - self.optimalUtilization
let maxExcess = FlowALPMath.one - self.optimalUtilization
let excessFactor = excessUtilization / maxExcess
// rate = baseRate + slope1 + (slope2 × excessFactor)
let slope2Component = self.slope2 * excessFactor
return self.baseRate + self.slope1 + slope2Component
}
}
}
/// TokenState
///
/// The TokenState struct tracks values related to a single token Type within the Pool.
access(all) struct TokenState {
access(EImplementation) var tokenType : Type
/// The timestamp at which the TokenState was last updated
access(EImplementation) var lastUpdate: UFix64
/// The total credit balance for this token, in a specific Pool.
/// The total credit balance is the sum of balances of all positions with a credit balance (ie. they have lent this token).
/// In other words, it is the the sum of net deposits among positions which are net creditors in this token.
access(EImplementation) var totalCreditBalance: UFix128
/// The total debit balance for this token, in a specific Pool.
/// The total debit balance is the sum of balances of all positions with a debit balance (ie. they have borrowed this token).
/// In other words, it is the the sum of net withdrawals among positions which are net debtors in this token.
access(EImplementation) var totalDebitBalance: UFix128
/// The index of the credit interest for the related token.
///
/// Interest indices are 18-decimal fixed-point values (see FlowALPMath) and are stored as UFix128
/// to maintain precision when converting between scaled and true balances and when compounding.
access(EImplementation) var creditInterestIndex: UFix128
/// The index of the debit interest for the related token.
///
/// Interest indices are 18-decimal fixed-point values (see FlowALPMath) and are stored as UFix128
/// to maintain precision when converting between scaled and true balances and when compounding.
access(EImplementation) var debitInterestIndex: UFix128
/// The per-second interest rate for credit of the associated token.
///
/// For example, if the per-second rate is 1%, this value is 0.01.
/// Stored as UFix128 to match index precision and avoid cumulative rounding during compounding.
access(EImplementation) var currentCreditRate: UFix128
/// The per-second interest rate for debit of the associated token.
///
/// For example, if the per-second rate is 1%, this value is 0.01.
/// Stored as UFix128 for consistency with indices/rates math.
access(EImplementation) var currentDebitRate: UFix128
/// The interest curve implementation used to calculate interest rate
access(EImplementation) var interestCurve: {InterestCurve}
/// The annual insurance rate applied to total debit when computing credit interest (default 0.1%)
access(EImplementation) var insuranceRate: UFix64
/// Timestamp of the last insurance collection for this token.
access(EImplementation) var lastInsuranceCollectionTime: UFix64
/// Swapper used to convert this token to MOET for insurance collection.
access(EImplementation) var insuranceSwapper: {DeFiActions.Swapper}?
/// The stability fee rate to calculate stability (default 0.05, 5%).
access(EImplementation) var stabilityFeeRate: UFix64
/// Timestamp of the last stability collection for this token.
access(EImplementation) var lastStabilityFeeCollectionTime: UFix64
/// Per-position limit fraction of capacity (default 0.05 i.e., 5%)
access(EImplementation) var depositLimitFraction: UFix64
/// The rate at which depositCapacity can increase over time. This is a tokens per hour rate,
/// and should be applied to the depositCapacityCap once an hour.
access(EImplementation) var depositRate: UFix64
/// The timestamp of the last deposit capacity update
access(EImplementation) var lastDepositCapacityUpdate: UFix64
/// The limit on deposits of the related token
access(EImplementation) var depositCapacity: UFix64
/// The upper bound on total deposits of the related token,
/// limiting how much depositCapacity can reach
access(EImplementation) var depositCapacityCap: UFix64
/// Tracks per-user deposit usage for enforcing user deposit limits
/// Maps position ID -> usage amount (how much of each user's limit has been consumed for this token type)
access(EImplementation) var depositUsage: {UInt64: UFix64}
/// The minimum balance size for the related token T per position.
/// This minimum balance is denominated in units of token T.
/// Let this minimum balance be M. Then each position must have either:
/// - A balance of 0
/// - A credit balance greater than or equal to M
/// - A debit balance greater than or equal to M
access(EImplementation) var minimumTokenBalancePerPosition: UFix64
init(
tokenType: Type,
interestCurve: {InterestCurve},
depositRate: UFix64,
depositCapacityCap: UFix64
) {
self.tokenType = tokenType
self.lastUpdate = getCurrentBlock().timestamp
self.totalCreditBalance = 0.0
self.totalDebitBalance = 0.0
self.creditInterestIndex = 1.0
self.debitInterestIndex = 1.0
self.currentCreditRate = 1.0
self.currentDebitRate = 1.0
self.interestCurve = interestCurve
self.insuranceRate = 0.0
self.lastInsuranceCollectionTime = getCurrentBlock().timestamp
self.insuranceSwapper = nil
self.stabilityFeeRate = 0.05
self.lastStabilityFeeCollectionTime = getCurrentBlock().timestamp
self.depositLimitFraction = 0.05
self.depositRate = depositRate
self.depositCapacity = depositCapacityCap
self.depositCapacityCap = depositCapacityCap
self.depositUsage = {}
self.lastDepositCapacityUpdate = getCurrentBlock().timestamp
self.minimumTokenBalancePerPosition = 1.0
}
/// Sets the insurance rate for this token state
access(EImplementation) fun setInsuranceRate(_ rate: UFix64) {
self.insuranceRate = rate
}
/// Sets the last insurance collection timestamp
access(EImplementation) fun setLastInsuranceCollectionTime(_ lastInsuranceCollectionTime: UFix64) {
self.lastInsuranceCollectionTime = lastInsuranceCollectionTime
}
/// Sets the swapper used for insurance collection (must swap from this token type to MOET)
access(EImplementation) fun setInsuranceSwapper(_ swapper: {DeFiActions.Swapper}?) {
if let swapper = swapper {
assert(swapper.inType() == self.tokenType, message: "Insurance swapper must accept \(self.tokenType.identifier), not \(swapper.inType().identifier)")
assert(swapper.outType() == Type<@MOET.Vault>(), message: "Insurance swapper must output MOET")
}
self.insuranceSwapper = swapper
}
/// Sets the per-deposit limit fraction for this token state
access(EImplementation) fun setDepositLimitFraction(_ frac: UFix64) {
self.depositLimitFraction = frac
}
/// Sets the deposit rate for this token state after settling the old rate
/// Argument expressed astokens per hour
access(EImplementation) fun setDepositRate(_ hourlyRate: UFix64) {
// settle using old rate if for some reason too much time has passed without regeneration
self.regenerateDepositCapacity()
self.depositRate = hourlyRate
}
/// Sets the deposit capacity cap for this token state
access(EImplementation) fun setDepositCapacityCap(_ cap: UFix64) {
self.depositCapacityCap = cap
// If current capacity exceeds the new cap, clamp it to the cap
if self.depositCapacity > cap {
self.depositCapacity = cap
}
// Reset the last update timestamp to prevent regeneration based on old timestamp
self.lastDepositCapacityUpdate = getCurrentBlock().timestamp
}
/// Sets the minimum token balance per position for this token state
access(EImplementation) fun setMinimumTokenBalancePerPosition(_ minimum: UFix64) {
self.minimumTokenBalancePerPosition = minimum
}
/// Sets the stability fee rate for this token state.
access(EImplementation) fun setStabilityFeeRate(_ rate: UFix64) {
self.stabilityFeeRate = rate
}
/// Sets the last stability fee collection timestamp for this token state.
access(EImplementation) fun setLastStabilityFeeCollectionTime(_ lastStabilityFeeCollectionTime: UFix64) {
self.lastStabilityFeeCollectionTime = lastStabilityFeeCollectionTime
}
/// Calculates the per-user deposit limit cap based on depositLimitFraction * depositCapacityCap
access(EImplementation) fun getUserDepositLimitCap(): UFix64 {
return self.depositLimitFraction * self.depositCapacityCap
}
/// Decreases deposit capacity by the specified amount and tracks per-user deposit usage
/// (used when deposits are made)
access(EImplementation) fun consumeDepositCapacity(_ amount: UFix64, pid: UInt64) {
assert(
amount <= self.depositCapacity,
message: "cannot consume more than available deposit capacity"
)
self.depositCapacity = self.depositCapacity - amount
// Track per-user deposit usage for the accepted amount
let currentUserUsage = self.depositUsage[pid] ?? 0.0
self.depositUsage[pid] = currentUserUsage + amount
emit DepositCapacityConsumed(
tokenType: self.tokenType,
pid: pid,
amount: amount,
remainingCapacity: self.depositCapacity
)
}
/// Sets deposit capacity (used for time-based regeneration)
access(EImplementation) fun setDepositCapacity(_ capacity: UFix64) {
self.depositCapacity = capacity
}
/// Sets the interest curve for this token state
/// After updating the curve, also update the interest rates to reflect the new curve
access(EImplementation) fun setInterestCurve(_ curve: {InterestCurve}) {
self.interestCurve = curve
// Update rates immediately to reflect the new curve
self.updateInterestRates()
}
/// Balance update helpers used by core accounting.
/// All balance changes automatically trigger updateForUtilizationChange()
/// which recalculates interest rates based on the new utilization ratio.
/// This ensures rates always reflect the current state of the pool
/// without requiring manual rate update calls.
access(EImplementation) fun increaseCreditBalance(by amount: UFix128) {
self.totalCreditBalance = self.totalCreditBalance + amount
self.updateForUtilizationChange()
}
access(EImplementation) fun decreaseCreditBalance(by amount: UFix128) {
if amount >= self.totalCreditBalance {
self.totalCreditBalance = 0.0
} else {
self.totalCreditBalance = self.totalCreditBalance - amount
}
self.updateForUtilizationChange()
}
access(EImplementation) fun increaseDebitBalance(by amount: UFix128) {
self.totalDebitBalance = self.totalDebitBalance + amount
self.updateForUtilizationChange()
}
access(EImplementation) fun decreaseDebitBalance(by amount: UFix128) {
if amount >= self.totalDebitBalance {
self.totalDebitBalance = 0.0
} else {
self.totalDebitBalance = self.totalDebitBalance - amount
}
self.updateForUtilizationChange()
}
// Updates the credit and debit interest index for this token, accounting for time since the last update.
access(EImplementation) fun updateInterestIndices() {
let currentTime = getCurrentBlock().timestamp
let dt = currentTime - self.lastUpdate
// No time elapsed or already at cap → nothing to do
if dt <= 0.0 {
return
}
// Update interest indices (dt > 0 ensures sensible compounding)
self.creditInterestIndex = FlowALPv0.compoundInterestIndex(
oldIndex: self.creditInterestIndex,
perSecondRate: self.currentCreditRate,
elapsedSeconds: dt
)
self.debitInterestIndex = FlowALPv0.compoundInterestIndex(
oldIndex: self.debitInterestIndex,
perSecondRate: self.currentDebitRate,
elapsedSeconds: dt