-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathFlowALPv0.cdc
More file actions
2983 lines (2597 loc) · 148 KB
/
Copy pathFlowALPv0.cdc
File metadata and controls
2983 lines (2597 loc) · 148 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"
import "FlowALPInterestRates"
import "FlowALPModels"
import "FlowALPEvents"
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
/* --- CONSTRUCTS & INTERNAL METHODS ---- */
/* --- 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.
*/
///
/// Amount of `withdrawSnap` token that can be withdrawn while staying ≥ targetHealth
access(all) view fun maxWithdraw(
view: FlowALPModels.PositionView,
withdrawSnap: FlowALPModels.TokenSnapshot,
withdrawBal: FlowALPModels.InternalBalance?,
targetHealth: UFix128
): UFix128 {
let preHealth = FlowALPModels.healthFactor(view: view)
if preHealth <= targetHealth {
return 0.0
}
// TODO: this logic partly duplicates FlowALPModels.BalanceSheet construction in _getUpdatedBalanceSheet
// This function differs in that it does not read any data from a Pool resource. Consider consolidating the two implementations.
var effectiveCollateralTotal: UFix128 = 0.0
var effectiveDebtTotal: UFix128 = 0.0
for tokenType in view.balances.keys {
let balance = view.balances[tokenType]!
let snap = view.snapshots[tokenType]!
switch balance.direction {
case FlowALPModels.BalanceDirection.Credit:
let trueBalance = FlowALPMath.scaledBalanceToTrueBalance(
balance.scaledBalance,
interestIndex: snap.getCreditIndex()
)
effectiveCollateralTotal = effectiveCollateralTotal
+ snap.effectiveCollateral(creditBalance: trueBalance)
case FlowALPModels.BalanceDirection.Debit:
let trueBalance = FlowALPMath.scaledBalanceToTrueBalance(
balance.scaledBalance,
interestIndex: snap.getDebitIndex()
)
effectiveDebtTotal = effectiveDebtTotal
+ snap.effectiveDebt(debitBalance: trueBalance)
}
}
let collateralFactor = withdrawSnap.getRisk().getCollateralFactor()
let borrowFactor = withdrawSnap.getRisk().getBorrowFactor()
if withdrawBal == nil || withdrawBal!.direction == FlowALPModels.BalanceDirection.Debit {
// withdrawing increases debt
let numerator = effectiveCollateralTotal
let denominatorTarget = numerator / targetHealth
let deltaDebt = denominatorTarget > effectiveDebtTotal
? denominatorTarget - effectiveDebtTotal
: 0.0 as UFix128
return (deltaDebt * borrowFactor) / withdrawSnap.getPrice()
} else {
// withdrawing reduces collateral
let trueBalance = FlowALPMath.scaledBalanceToTrueBalance(
withdrawBal!.scaledBalance,
interestIndex: withdrawSnap.getCreditIndex()
)
let maxPossible = trueBalance
let requiredCollateral = effectiveDebtTotal * targetHealth
if effectiveCollateralTotal <= requiredCollateral {
return 0.0
}
let deltaCollateralEffective = effectiveCollateralTotal - requiredCollateral
let deltaTokens = (deltaCollateralEffective / collateralFactor) / withdrawSnap.getPrice()
return deltaTokens > maxPossible ? maxPossible : deltaTokens
}
}
/// Pool
///
/// A Pool is the primary logic for protocol operations. It contains the global state of all positions,
/// credit and debit balances for each supported token type, and reserves as they are deposited to positions.
access(all) resource Pool {
/// Pool state (extracted fields)
access(self) var state: @{FlowALPModels.PoolState}
/// Individual user positions (stays on Pool because InternalPosition is FlowALPv0-internal)
access(self) var positions: @{UInt64: {FlowALPModels.InternalPosition}}
/// Pool Config
access(self) var config: {FlowALPModels.PoolConfig}
init(
defaultToken: Type,
priceOracle: {DeFiActions.PriceOracle},
dex: {DeFiActions.SwapperProvider}
) {
pre {
priceOracle.unitOfAccount() == defaultToken:
"Price oracle must return prices in terms of the default token"
}
self.state <- FlowALPModels.createPoolState(
globalLedger: {
defaultToken: FlowALPModels.TokenStateImplv1(
tokenType: defaultToken,
interestCurve: FlowALPInterestRates.FixedCurve(yearlyRate: 0.0),
depositRate: 1_000_000.0, // Default: no rate limiting for default token
depositCapacityCap: 1_000_000.0 // Default: high capacity cap
)
},
reserves: <-{},
insuranceFund: <-MOET.createEmptyVault(vaultType: Type<@MOET.Vault>()),
nextPositionID: 0,
defaultToken: defaultToken,
stabilityFunds: <-{},
positionsNeedingUpdates: [],
positionLock: {}
)
self.positions <- {}
self.config = FlowALPModels.PoolConfigImpl(
priceOracle: priceOracle,
collateralFactor: {defaultToken: 1.0},
borrowFactor: {defaultToken: 1.0},
positionsProcessedPerCallback: 100,
liquidationTargetHF: 1.05,
warmupSec: 300,
lastUnpausedAt: nil,
dex: dex,
dexOracleDeviationBps: 300,
paused: false,
debugLogging: false
)
}
/// Locks a position. Used by Position resources to acquire the position lock.
access(FlowALPModels.EPosition) fun lockPosition(_ pid: UInt64) {
assert(!self.state.isPositionLocked(pid), message: "Reentrancy: position \(pid) is locked")
self.state.setPositionLock(pid, true)
}
/// Unlocks a position. Used by Position resources to release the position lock.
access(FlowALPModels.EPosition) fun unlockPosition(_ pid: UInt64) {
self.state.setPositionLock(pid, false)
}
///////////////
// GETTERS
///////////////
/// Returns whether sensitive pool actions are paused by governance,
/// including withdrawals, deposits, and liquidations
access(all) view fun isPaused(): Bool {
return self.config.isPaused()
}
/// Returns whether withdrawals and liquidations are paused.
/// Both have a warmup period after a global pause is ended, to allow users time to improve position health and avoid liquidation.
/// The warmup period provides an opportunity for users to deposit to unhealthy positions before liquidations start,
/// and also disallows withdrawing while liquidations are disabled, because liquidations can be needed to satisfy withdrawal requests.
access(all) view fun isPausedOrWarmup(): Bool {
if self.isPaused() {
return true
}
if let lastUnpausedAt = self.config.getLastUnpausedAt() {
let now = UInt64(getCurrentBlock().timestamp)
return now < lastUnpausedAt + self.config.getWarmupSec()
}
return false
}
/// Returns an array of the supported token Types
access(all) view fun getSupportedTokens(): [Type] {
return self.config.getSupportedTokens()
}
/// Returns whether a given token Type is supported or not
access(all) view fun isTokenSupported(tokenType: Type): Bool {
return self.config.isTokenSupported(tokenType: tokenType)
}
/// Returns the current balance of the stability fund for a given token type.
/// Returns nil if the token type is not supported.
access(all) view fun getStabilityFundBalance(tokenType: Type): UFix64? {
if self.state.hasStabilityFund(tokenType) {
return self.state.getStabilityFundBalance(tokenType)
}
return nil
}
/// Returns the stability fee rate for a given token type.
/// Returns nil if the token type is not supported.
access(all) view fun getStabilityFeeRate(tokenType: Type): UFix64? {
if let tokenState = self.state.getTokenState(tokenType) {
return tokenState.getStabilityFeeRate()
}
return nil
}
/// Returns the timestamp of the last stability collection for a given token type.
/// Returns nil if the token type is not supported.
access(all) view fun getLastStabilityCollectionTime(tokenType: Type): UFix64? {
if let tokenState = self.state.getTokenState(tokenType) {
return tokenState.getLastStabilityFeeCollectionTime()
}
return nil
}
/// Returns whether an insurance swapper is configured for a given token type
access(all) view fun isInsuranceSwapperConfigured(tokenType: Type): Bool {
if let tokenState = self.state.getTokenState(tokenType) {
return tokenState.getInsuranceSwapper() != nil
}
return false
}
/// Returns the timestamp of the last insurance collection for a given token type
/// Returns nil if the token type is not supported
access(all) view fun getLastInsuranceCollectionTime(tokenType: Type): UFix64? {
if let tokenState = self.state.getTokenState(tokenType) {
return tokenState.getLastInsuranceCollectionTime()
}
return nil
}
/// Returns current pause parameters
access(all) fun getPauseParams(): FlowALPModels.PauseParamsView {
return FlowALPModels.PauseParamsView(
paused: self.config.isPaused(),
warmupSec: self.config.getWarmupSec(),
lastUnpausedAt: self.config.getLastUnpausedAt(),
)
}
/// Returns current liquidation parameters
access(all) fun getLiquidationParams(): FlowALPModels.LiquidationParamsView {
return FlowALPModels.LiquidationParamsView(
targetHF: self.config.getLiquidationTargetHF(),
triggerHF: 1.0,
)
}
/// Returns Oracle-DEX guards and allowlists for frontends/keepers
access(all) fun getDexLiquidationConfig(): {String: AnyStruct} {
return {
"dexOracleDeviationBps": self.config.getDexOracleDeviationBps()
}
}
/// Returns true if the position is under the global liquidation trigger (health < 1.0)
access(all) fun isLiquidatable(pid: UInt64): Bool {
let health = self.positionHealth(pid: pid)
return health < 1.0
}
/// Returns the current reserve balance for the specified token type.
access(all) view fun reserveBalance(type: Type): UFix64 {
return self.state.getReserveBalance(type)
}
/// Returns the balance of the MOET insurance fund
access(all) view fun insuranceFundBalance(): UFix64 {
return self.state.getInsuranceFundBalance()
}
/// Returns the insurance rate for a given token type
access(all) view fun getInsuranceRate(tokenType: Type): UFix64? {
if let tokenState = self.state.getTokenState(tokenType) {
return tokenState.getInsuranceRate()
}
return nil
}
/// Returns a position's balance available for withdrawal of a given Vault type.
/// Phase 0 refactor: compute via pure helpers using a PositionView and TokenSnapshot for the base path.
/// When `pullFromTopUpSource` is true and a topUpSource exists, preserve deposit-assisted semantics.
access(all) fun availableBalance(pid: UInt64, type: Type, pullFromTopUpSource: Bool): UFix64 {
if self.config.isDebugLogging() {
log(" [CONTRACT] availableBalance(pid: \(pid), type: \(type.contractName!), pullFromTopUpSource: \(pullFromTopUpSource))")
}
let position = self._borrowPosition(pid: pid)
if pullFromTopUpSource {
if let topUpSource = position.borrowTopUpSource() {
let sourceType = topUpSource.getSourceType()
let sourceAmount = topUpSource.minimumAvailable()
if self.config.isDebugLogging() {
log(" [CONTRACT] Calling to fundsAvailableAboveTargetHealthAfterDepositing with sourceAmount \(sourceAmount) and targetHealth \(position.getMinHealth())")
}
return self.fundsAvailableAboveTargetHealthAfterDepositing(
pid: pid,
withdrawType: type,
targetHealth: position.getMinHealth(),
depositType: sourceType,
depositAmount: sourceAmount
)
}
}
let view = self.buildPositionView(pid: pid)
// Build a TokenSnapshot for the requested withdraw type (may not exist in view.snapshots)
let tokenState = self._borrowUpdatedTokenState(type: type)
let snap = FlowALPModels.TokenSnapshot(
price: UFix128(self.config.getPriceOracle().price(ofToken: type)!),
credit: tokenState.getCreditInterestIndex(),
debit: tokenState.getDebitInterestIndex(),
risk: FlowALPModels.RiskParamsImplv1(
collateralFactor: UFix128(self.config.getCollateralFactor(tokenType: type)),
borrowFactor: UFix128(self.config.getBorrowFactor(tokenType: type)),
)
)
let withdrawBal = view.balances[type]
let uintMax = FlowALPv0.maxWithdraw(
view: view,
withdrawSnap: snap,
withdrawBal: withdrawBal,
targetHealth: view.minHealth
)
return FlowALPMath.toUFix64Round(uintMax)
}
/// Returns the health of the given position, which is the ratio of the position's effective collateral
/// to its debt as denominated in the Pool's default token.
/// "Effective collateral" means the value of each credit balance times the liquidation threshold
/// for that token, i.e. the maximum borrowable amount
// TODO: make this output enumeration of effective debts/collaterals (or provide option that does)
access(all) fun positionHealth(pid: UInt64): UFix128 {
let position = self._borrowPosition(pid: pid)
// Get the position's collateral and debt values in terms of the default token.
var effectiveCollateral: UFix128 = 0.0
var effectiveDebt: UFix128 = 0.0
for type in position.getBalanceKeys() {
let balance = position.getBalance(type)!
let tokenState = self._borrowUpdatedTokenState(type: type)
let collateralFactor = UFix128(self.config.getCollateralFactor(tokenType: type))
let borrowFactor = UFix128(self.config.getBorrowFactor(tokenType: type))
let price = UFix128(self.config.getPriceOracle().price(ofToken: type)!)
switch balance.direction {
case FlowALPModels.BalanceDirection.Credit:
let trueBalance = FlowALPMath.scaledBalanceToTrueBalance(
balance.scaledBalance,
interestIndex: tokenState.getCreditInterestIndex()
)
let value = price * trueBalance
let effectiveCollateralValue = value * collateralFactor
effectiveCollateral = effectiveCollateral + effectiveCollateralValue
case FlowALPModels.BalanceDirection.Debit:
let trueBalance = FlowALPMath.scaledBalanceToTrueBalance(
balance.scaledBalance,
interestIndex: tokenState.getDebitInterestIndex()
)
let value = price * trueBalance
let effectiveDebtValue = value / borrowFactor
effectiveDebt = effectiveDebt + effectiveDebtValue
}
}
// Calculate the health as the ratio of collateral to debt.
return FlowALPMath.healthComputation(
effectiveCollateral: effectiveCollateral,
effectiveDebt: effectiveDebt
)
}
/// Returns the quantity of funds of a specified token which would need to be deposited
/// to bring the position to the provided target health.
///
/// This function will return 0.0 if the position is already at or over that health value.
access(all) fun fundsRequiredForTargetHealth(pid: UInt64, type: Type, targetHealth: UFix128): UFix64 {
return self.fundsRequiredForTargetHealthAfterWithdrawing(
pid: pid,
depositType: type,
targetHealth: targetHealth,
withdrawType: self.state.getDefaultToken(),
withdrawAmount: 0.0
)
}
/// Returns the details of a given position as a FlowALPModels.PositionDetails external struct
access(all) fun getPositionDetails(pid: UInt64): FlowALPModels.PositionDetails {
if self.config.isDebugLogging() {
log(" [CONTRACT] getPositionDetails(pid: \(pid))")
}
let position = self._borrowPosition(pid: pid)
let balances: [FlowALPModels.PositionBalance] = []
for type in position.getBalanceKeys() {
let balance = position.getBalance(type)!
let tokenState = self._borrowUpdatedTokenState(type: type)
let trueBalance = FlowALPMath.scaledBalanceToTrueBalance(
balance.scaledBalance,
interestIndex: balance.direction == FlowALPModels.BalanceDirection.Credit
? tokenState.getCreditInterestIndex()
: tokenState.getDebitInterestIndex()
)
balances.append(FlowALPModels.PositionBalance(
vaultType: type,
direction: balance.direction,
balance: FlowALPMath.toUFix64Round(trueBalance)
))
}
let health = self.positionHealth(pid: pid)
let defaultTokenAvailable = self.availableBalance(
pid: pid,
type: self.state.getDefaultToken(),
pullFromTopUpSource: false
)
return FlowALPModels.PositionDetails(
balances: balances,
poolDefaultToken: self.state.getDefaultToken(),
defaultTokenAvailableBalance: defaultTokenAvailable,
health: health
)
}
/// Any external party can perform a manual liquidation on a position under the following circumstances:
/// - the position has health < 1
/// - the liquidation price offered is better than what is available on a DEX
/// - the liquidation results in a health <= liquidationTargetHF
///
/// If a liquidation attempt is successful, the balance of the input `repayment` vault is deposited to the pool
/// and a vault containing a balance of `seizeAmount` collateral tokens are returned to the caller.
///
/// Terminology:
/// - N means number of some token: Nc means number of collateral tokens, Nd means number of debt tokens
/// - P means price of some token: Pc means price of collateral, Pd means price of debt
/// - C means collateral: Ce is effective collateral, Ct is true collateral, measured in $
/// - D means debt: De is effective debt, Dt is true debt, measured in $
/// - Fc, Fd are collateral and debt factors
access(all) fun manualLiquidation(
pid: UInt64,
debtType: Type,
seizeType: Type,
seizeAmount: UFix64,
repayment: @{FungibleToken.Vault}
): @{FungibleToken.Vault} {
pre {
!self.isPausedOrWarmup(): "Liquidations are paused by governance"
self.isTokenSupported(tokenType: debtType): "Debt token type unsupported: \(debtType.identifier)"
self.isTokenSupported(tokenType: seizeType): "Collateral token type unsupported: \(seizeType.identifier)"
debtType == repayment.getType(): "Repayment vault does not match debt type: \(debtType.identifier)!=\(repayment.getType().identifier)"
// TODO(jord): liquidation paused / post-pause warm
}
post {
!self.state.isPositionLocked(pid): "Position is not unlocked"
}
self.lockPosition(pid)
let positionView = self.buildPositionView(pid: pid)
let balanceSheet = self._getUpdatedBalanceSheet(pid: pid)
let initialHealth = balanceSheet.health
assert(initialHealth < 1.0, message: "Cannot liquidate healthy position: \(initialHealth)>=1")
// Ensure liquidation amounts don't exceed position amounts
let repayAmount = repayment.balance
let Nc = positionView.trueBalance(ofToken: seizeType) // number of collateral tokens (true balance)
let Nd = positionView.trueBalance(ofToken: debtType) // number of debt tokens (true balance)
assert(UFix128(seizeAmount) <= Nc, message: "Cannot seize more collateral than is in position: collateral balance (\(Nc)) is less than seize amount (\(seizeAmount))")
assert(UFix128(repayAmount) <= Nd, message: "Cannot repay more debt than is in position: debt balance (\(Nd)) is less than repay amount (\(repayAmount))")
// Oracle prices
let Pd_oracle = self.config.getPriceOracle().price(ofToken: debtType)! // debt price given by oracle ($/D)
let Pc_oracle = self.config.getPriceOracle().price(ofToken: seizeType)! // collateral price given by oracle ($/C)
// Price of collateral, denominated in debt token, implied by oracle (D/C)
// Oracle says: "1 unit of collateral is worth `Pcd_oracle` units of debt"
let Pcd_oracle = Pc_oracle / Pd_oracle
// Compute the health factor which would result if we were to accept this liquidation
let Ce_pre = balanceSheet.effectiveCollateral // effective collateral pre-liquidation
let De_pre = balanceSheet.effectiveDebt // effective debt pre-liquidation
let Fc = positionView.snapshots[seizeType]!.getRisk().getCollateralFactor()
let Fd = positionView.snapshots[debtType]!.getRisk().getBorrowFactor()
// Ce_seize = effective value of seized collateral ($)
let Ce_seize = FlowALPMath.effectiveCollateral(credit: UFix128(seizeAmount), price: UFix128(Pc_oracle), collateralFactor: Fc)
// De_seize = effective value of repaid debt ($)
let De_seize = FlowALPMath.effectiveDebt(debit: UFix128(repayAmount), price: UFix128(Pd_oracle), borrowFactor: Fd)
let Ce_post = Ce_pre - Ce_seize // position's total effective collateral after liquidation ($)
let De_post = De_pre - De_seize // position's total effective debt after liquidation ($)
let postHealth = FlowALPMath.healthComputation(effectiveCollateral: Ce_post, effectiveDebt: De_post)
assert(postHealth <= self.config.getLiquidationTargetHF(), message: "Liquidation must not exceed target health: post-liquidation health (\(postHealth)) is greater than target health (\(self.config.getLiquidationTargetHF()))")
// Compare the liquidation offer to liquidation via DEX. If the DEX would provide a better price, reject the offer.
let swapper = self.config.getSwapperForLiquidation(seizeType: seizeType, debtType: debtType)
// Get a quote: "how much collateral do I need to give you to get `repayAmount` debt tokens"
let quote = swapper.quoteIn(forDesired: repayAmount, reverse: false)
assert(seizeAmount < quote.inAmount, message: "Liquidation offer must be better than that offered by DEX")
// Compare the DEX price to the oracle price and revert if they diverge beyond configured threshold.
let Pcd_dex = quote.outAmount / quote.inAmount // price of collateral, denominated in debt token, implied by dex quote (D/C)
assert(
FlowALPMath.dexOraclePriceDeviationInRange(dexPrice: Pcd_dex, oraclePrice: Pcd_oracle, maxDeviationBps: self.config.getDexOracleDeviationBps()),
message: "DEX/oracle price deviation too large. Dex price: \(Pcd_dex), Oracle price: \(Pcd_oracle)")
// Execute the liquidation
let seizedCollateral <- self._doLiquidation(pid: pid, repayment: <-repayment, debtType: debtType, seizeType: seizeType, seizeAmount: seizeAmount)
self.unlockPosition(pid)
return <- seizedCollateral
}
/// Internal liquidation function which performs a liquidation.
/// The balance of `repayment` is deposited to the debt token reserve, and `seizeAmount` units of collateral are returned.
/// Callers are responsible for checking preconditions.
access(self) fun _doLiquidation(pid: UInt64, repayment: @{FungibleToken.Vault}, debtType: Type, seizeType: Type, seizeAmount: UFix64): @{FungibleToken.Vault} {
pre {
!self.isPausedOrWarmup(): "Liquidations are paused by governance"
// position must have debt and collateral balance
}
let repayAmount = repayment.balance
assert(repayment.getType() == debtType, message: "Vault type mismatch for repay. Repayment type is \(repayment.getType().identifier) but debt type is \(debtType.identifier)")
// Use reserve handler to deposit repayment (burns MOET, deposits to reserves for other tokens)
let repayReserveOps = self.state.getTokenState(debtType)!.getReserveOperations()
let repayStateRef = &self.state as auth(FlowALPModels.EImplementation) &{FlowALPModels.PoolState}
repayReserveOps.depositRepayment(state: repayStateRef, from: <-repayment)
// Reduce borrower's debt position by repayAmount
let position = self._borrowPosition(pid: pid)
let debtState = self._borrowUpdatedTokenState(type: debtType)
position.borrowBalance(debtType)!.recordDeposit(amount: UFix128(repayAmount), tokenState: debtState)
// Withdraw seized collateral from position and send to liquidator
let seizeState = self._borrowUpdatedTokenState(type: seizeType)
let positionBalance = position.getBalance(seizeType)
if positionBalance == nil {
// Liquidation is seizing collateral - validate single collateral type
position.validateCollateralType(seizeType)
position.setBalance(seizeType, FlowALPModels.InternalBalance(direction: FlowALPModels.BalanceDirection.Credit, scaledBalance: 0.0))
}
position.borrowBalance(seizeType)!.recordWithdrawal(amount: UFix128(seizeAmount), tokenState: seizeState)
let seizeReserveRef = self.state.borrowReserve(seizeType)!
let seizedCollateral <- seizeReserveRef.withdraw(amount: seizeAmount)
let newHealth = self.positionHealth(pid: pid)
// TODO: sanity check health here? for auto-liquidating, we may need to perform a bounded search which could result in unbounded error in the final health
FlowALPEvents.emitLiquidationExecuted(
pid: pid,
poolUUID: self.uuid,
debtType: debtType.identifier,
repayAmount: repayAmount,
seizeType: seizeType.identifier,
seizeAmount: seizeAmount,
newHF: newHealth
)
return <-seizedCollateral
}
/// Returns the quantity of funds of a specified token which would need to be deposited
/// in order to bring the position to the target health
/// assuming we also withdraw a specified amount of another token.
///
/// This function will return 0.0 if the position would already be at or over the target health value
/// after the proposed withdrawal.
access(all) fun fundsRequiredForTargetHealthAfterWithdrawing(
pid: UInt64,
depositType: Type,
targetHealth: UFix128,
withdrawType: Type,
withdrawAmount: UFix64
): UFix64 {
pre {
targetHealth >= 1.0: "Target health (\(targetHealth)) must be >=1 after any withdrawal"
}
if self.config.isDebugLogging() {
log(" [CONTRACT] fundsRequiredForTargetHealthAfterWithdrawing(pid: \(pid), depositType: \(depositType.contractName!), targetHealth: \(targetHealth), withdrawType: \(withdrawType.contractName!), withdrawAmount: \(withdrawAmount))")
}
let balanceSheet = self._getUpdatedBalanceSheet(pid: pid)
let position = self._borrowPosition(pid: pid)
let adjusted = self.computeAdjustedBalancesAfterWithdrawal(
balanceSheet: balanceSheet,
position: position,
withdrawType: withdrawType,
withdrawAmount: withdrawAmount
)
return self.computeRequiredDepositForHealth(
position: position,
depositType: depositType,
withdrawType: withdrawType,
effectiveCollateral: adjusted.effectiveCollateral,
effectiveDebt: adjusted.effectiveDebt,
targetHealth: targetHealth
)
}
// TODO: documentation
access(self) fun computeAdjustedBalancesAfterWithdrawal(
balanceSheet: FlowALPModels.BalanceSheet,
position: &{FlowALPModels.InternalPosition},
withdrawType: Type,
withdrawAmount: UFix64
): FlowALPModels.BalanceSheet {
var effectiveCollateralAfterWithdrawal = balanceSheet.effectiveCollateral
var effectiveDebtAfterWithdrawal = balanceSheet.effectiveDebt
if withdrawAmount == 0.0 {
return FlowALPModels.BalanceSheet(effectiveCollateral: effectiveCollateralAfterWithdrawal, effectiveDebt: effectiveDebtAfterWithdrawal)
}
if self.config.isDebugLogging() {
log(" [CONTRACT] effectiveCollateralAfterWithdrawal: \(effectiveCollateralAfterWithdrawal)")
log(" [CONTRACT] effectiveDebtAfterWithdrawal: \(effectiveDebtAfterWithdrawal)")
}
let withdrawAmountU = UFix128(withdrawAmount)
let withdrawPrice2 = UFix128(self.config.getPriceOracle().price(ofToken: withdrawType)!)
let withdrawBorrowFactor2 = UFix128(self.config.getBorrowFactor(tokenType: withdrawType))
let balance = position.getBalance(withdrawType)
let direction = balance?.direction ?? FlowALPModels.BalanceDirection.Debit
let scaledBalance = balance?.scaledBalance ?? 0.0
switch direction {
case FlowALPModels.BalanceDirection.Debit:
// If the position doesn't have any collateral for the withdrawn token,
// we can just compute how much additional effective debt the withdrawal will create.
effectiveDebtAfterWithdrawal = balanceSheet.effectiveDebt +
(withdrawAmountU * withdrawPrice2) / withdrawBorrowFactor2
case FlowALPModels.BalanceDirection.Credit:
let withdrawTokenState = self._borrowUpdatedTokenState(type: withdrawType)
// The user has a collateral position in the given token, we need to figure out if this withdrawal
// will flip over into debt, or just draw down the collateral.
let trueCollateral = FlowALPMath.scaledBalanceToTrueBalance(
scaledBalance,
interestIndex: withdrawTokenState.getCreditInterestIndex()
)
let collateralFactor = UFix128(self.config.getCollateralFactor(tokenType: withdrawType))
if trueCollateral >= withdrawAmountU {
// This withdrawal will draw down collateral, but won't create debt, we just need to account
// for the collateral decrease.
effectiveCollateralAfterWithdrawal = balanceSheet.effectiveCollateral -
(withdrawAmountU * withdrawPrice2) * collateralFactor
} else {
// The withdrawal will wipe out all of the collateral, and create some debt.
effectiveDebtAfterWithdrawal = balanceSheet.effectiveDebt +
((withdrawAmountU - trueCollateral) * withdrawPrice2) / withdrawBorrowFactor2
effectiveCollateralAfterWithdrawal = balanceSheet.effectiveCollateral -
(trueCollateral * withdrawPrice2) * collateralFactor
}
}
return FlowALPModels.BalanceSheet(
effectiveCollateral: effectiveCollateralAfterWithdrawal,
effectiveDebt: effectiveDebtAfterWithdrawal
)
}
// TODO(jord): ~100-line function - consider refactoring
// TODO: documentation
access(self) fun computeRequiredDepositForHealth(
position: &{FlowALPModels.InternalPosition},
depositType: Type,
withdrawType: Type,
effectiveCollateral: UFix128,
effectiveDebt: UFix128,
targetHealth: UFix128
): UFix64 {
let effectiveCollateralAfterWithdrawal = effectiveCollateral
var effectiveDebtAfterWithdrawal = effectiveDebt
if self.config.isDebugLogging() {
log(" [CONTRACT] effectiveCollateralAfterWithdrawal: \(effectiveCollateralAfterWithdrawal)")
log(" [CONTRACT] effectiveDebtAfterWithdrawal: \(effectiveDebtAfterWithdrawal)")
}
// We now have new effective collateral and debt values that reflect the proposed withdrawal (if any!)
// Now we can figure out how many of the given token would need to be deposited to bring the position
// to the target health value.
var healthAfterWithdrawal = FlowALPMath.healthComputation(
effectiveCollateral: effectiveCollateralAfterWithdrawal,
effectiveDebt: effectiveDebtAfterWithdrawal
)
if self.config.isDebugLogging() {
log(" [CONTRACT] healthAfterWithdrawal: \(healthAfterWithdrawal)")
}
if healthAfterWithdrawal >= targetHealth {
// The position is already at or above the target health, so we don't need to deposit anything.
return 0.0
}
// For situations where the required deposit will BOTH pay off debt and accumulate collateral, we keep
// track of the number of tokens that went towards paying off debt.
var debtTokenCount: UFix128 = 0.0
let depositPrice = UFix128(self.config.getPriceOracle().price(ofToken: depositType)!)
let depositBorrowFactor = UFix128(self.config.getBorrowFactor(tokenType: depositType))
let withdrawBorrowFactor = UFix128(self.config.getBorrowFactor(tokenType: withdrawType))
let maybeBalance = position.getBalance(depositType)
if maybeBalance?.direction == FlowALPModels.BalanceDirection.Debit {
// The user has a debt position in the given token, we start by looking at the health impact of paying off
// the entire debt.
let depositTokenState = self._borrowUpdatedTokenState(type: depositType)
let debtBalance = maybeBalance!.scaledBalance
let trueDebtTokenCount = FlowALPMath.scaledBalanceToTrueBalance(
debtBalance,
interestIndex: depositTokenState.getDebitInterestIndex()
)
let debtEffectiveValue = (depositPrice * trueDebtTokenCount) / depositBorrowFactor
// Ensure we don't underflow - if debtEffectiveValue is greater than effectiveDebtAfterWithdrawal,
// it means we can pay off all debt
var effectiveDebtAfterPayment: UFix128 = 0.0
if debtEffectiveValue <= effectiveDebtAfterWithdrawal {
effectiveDebtAfterPayment = effectiveDebtAfterWithdrawal - debtEffectiveValue
}
// Check what the new health would be if we paid off all of this debt
let potentialHealth = FlowALPMath.healthComputation(
effectiveCollateral: effectiveCollateralAfterWithdrawal,
effectiveDebt: effectiveDebtAfterPayment
)
// Does paying off all of the debt reach the target health? Then we're done.
if potentialHealth >= targetHealth {
// We can reach the target health by paying off some or all of the debt. We can easily
// compute how many units of the token would be needed to reach the target health.
let healthChange = targetHealth - healthAfterWithdrawal
let requiredEffectiveDebt = effectiveDebtAfterWithdrawal
- (effectiveCollateralAfterWithdrawal / targetHealth)
// The amount of the token to pay back, in units of the token.
let paybackAmount = (requiredEffectiveDebt * depositBorrowFactor) / depositPrice
if self.config.isDebugLogging() {
log(" [CONTRACT] paybackAmount: \(paybackAmount)")
}
return FlowALPMath.toUFix64RoundUp(paybackAmount)
} else {
// We can pay off the entire debt, but we still need to deposit more to reach the target health.
// We have logic below that can determine the collateral deposition required to reach the target health
// from this new health position. Rather than copy that logic here, we fall through into it. But first
// we have to record the amount of tokens that went towards debt payback and adjust the effective
// debt to reflect that it has been paid off.
debtTokenCount = trueDebtTokenCount
// Ensure we don't underflow
if debtEffectiveValue <= effectiveDebtAfterWithdrawal {
effectiveDebtAfterWithdrawal = effectiveDebtAfterWithdrawal - debtEffectiveValue
} else {
effectiveDebtAfterWithdrawal = 0.0
}
healthAfterWithdrawal = potentialHealth
}
}
// At this point, we're either dealing with a position that didn't have a debt position in the deposit
// token, or we've accounted for the debt payoff and adjusted the effective debt above.
// Now we need to figure out how many tokens would need to be deposited (as collateral) to reach the
// target health. We can rearrange the health equation to solve for the required collateral:
// We need to increase the effective collateral from its current value to the required value, so we
// multiply the required health change by the effective debt, and turn that into a token amount.
let healthChangeU = targetHealth - healthAfterWithdrawal
// TODO: apply the same logic as below to the early return blocks above
let depositCollateralFactor = UFix128(self.config.getCollateralFactor(tokenType: depositType))
let requiredEffectiveCollateral = (healthChangeU * effectiveDebtAfterWithdrawal) / depositCollateralFactor
// The amount of the token to deposit, in units of the token.
let collateralTokenCount = requiredEffectiveCollateral / depositPrice
if self.config.isDebugLogging() {
log(" [CONTRACT] requiredEffectiveCollateral: \(requiredEffectiveCollateral)")
log(" [CONTRACT] collateralTokenCount: \(collateralTokenCount)")
log(" [CONTRACT] debtTokenCount: \(debtTokenCount)")
log(" [CONTRACT] collateralTokenCount + debtTokenCount: \(collateralTokenCount) + \(debtTokenCount) = \(collateralTokenCount + debtTokenCount)")
}
// debtTokenCount is the number of tokens that went towards debt, zero if there was no debt.
return FlowALPMath.toUFix64Round(collateralTokenCount + debtTokenCount)
}
/// Returns the quantity of the specified token that could be withdrawn
/// while still keeping the position's health at or above the provided target.
access(all) fun fundsAvailableAboveTargetHealth(pid: UInt64, type: Type, targetHealth: UFix128): UFix64 {
return self.fundsAvailableAboveTargetHealthAfterDepositing(
pid: pid,
withdrawType: type,
targetHealth: targetHealth,
depositType: self.state.getDefaultToken(),
depositAmount: 0.0
)
}
/// Returns the quantity of the specified token that could be withdrawn
/// while still keeping the position's health at or above the provided target,
/// assuming we also deposit a specified amount of another token.
access(all) fun fundsAvailableAboveTargetHealthAfterDepositing(
pid: UInt64,
withdrawType: Type,
targetHealth: UFix128,
depositType: Type,
depositAmount: UFix64
): UFix64 {
if self.config.isDebugLogging() {
log(" [CONTRACT] fundsAvailableAboveTargetHealthAfterDepositing(pid: \(pid), withdrawType: \(withdrawType.contractName!), targetHealth: \(targetHealth), depositType: \(depositType.contractName!), depositAmount: \(depositAmount))")
}
if depositType == withdrawType && depositAmount > 0.0 {
// If the deposit and withdrawal types are the same, we compute the available funds assuming
// no deposit (which is less work) and increase that by the deposit amount at the end
let fundsAvailable = self.fundsAvailableAboveTargetHealth(
pid: pid,
type: withdrawType,
targetHealth: targetHealth
)
return fundsAvailable + depositAmount
}
let balanceSheet = self._getUpdatedBalanceSheet(pid: pid)
let position = self._borrowPosition(pid: pid)
let adjusted = self.computeAdjustedBalancesAfterDeposit(
balanceSheet: balanceSheet,
position: position,
depositType: depositType,
depositAmount: depositAmount
)
return self.computeAvailableWithdrawal(
position: position,
withdrawType: withdrawType,
effectiveCollateral: adjusted.effectiveCollateral,
effectiveDebt: adjusted.effectiveDebt,
targetHealth: targetHealth
)
}
// Helper function to compute balances after deposit
access(self) fun computeAdjustedBalancesAfterDeposit(
balanceSheet: FlowALPModels.BalanceSheet,
position: &{FlowALPModels.InternalPosition},
depositType: Type,
depositAmount: UFix64
): FlowALPModels.BalanceSheet {
var effectiveCollateralAfterDeposit = balanceSheet.effectiveCollateral
var effectiveDebtAfterDeposit = balanceSheet.effectiveDebt
if self.config.isDebugLogging() {
log(" [CONTRACT] effectiveCollateralAfterDeposit: \(effectiveCollateralAfterDeposit)")
log(" [CONTRACT] effectiveDebtAfterDeposit: \(effectiveDebtAfterDeposit)")
}
if depositAmount == 0.0 {
return FlowALPModels.BalanceSheet(
effectiveCollateral: effectiveCollateralAfterDeposit,
effectiveDebt: effectiveDebtAfterDeposit
)
}
let depositAmountCasted = UFix128(depositAmount)
let depositPriceCasted = UFix128(self.config.getPriceOracle().price(ofToken: depositType)!)
let depositBorrowFactorCasted = UFix128(self.config.getBorrowFactor(tokenType: depositType))
let depositCollateralFactorCasted = UFix128(self.config.getCollateralFactor(tokenType: depositType))
let balance = position.getBalance(depositType)
let direction = balance?.direction ?? FlowALPModels.BalanceDirection.Credit
let scaledBalance = balance?.scaledBalance ?? 0.0
switch direction {
case FlowALPModels.BalanceDirection.Credit:
// If there's no debt for the deposit token,
// we can just compute how much additional effective collateral the deposit will create.
effectiveCollateralAfterDeposit = balanceSheet.effectiveCollateral +
(depositAmountCasted * depositPriceCasted) * depositCollateralFactorCasted
case FlowALPModels.BalanceDirection.Debit:
let depositTokenState = self._borrowUpdatedTokenState(type: depositType)
// The user has a debt position in the given token, we need to figure out if this deposit
// will result in net collateral, or just bring down the debt.
let trueDebt = FlowALPMath.scaledBalanceToTrueBalance(
scaledBalance,
interestIndex: depositTokenState.getDebitInterestIndex()
)
if self.config.isDebugLogging() {
log(" [CONTRACT] trueDebt: \(trueDebt)")
}
if trueDebt >= depositAmountCasted {
// This deposit will pay down some debt, but won't result in net collateral, we
// just need to account for the debt decrease.
// TODO - validate if this should deal with withdrawType or depositType
effectiveDebtAfterDeposit = balanceSheet.effectiveDebt -
(depositAmountCasted * depositPriceCasted) / depositBorrowFactorCasted
} else {
// The deposit will wipe out all of the debt, and create some collateral.
// TODO - validate if this should deal with withdrawType or depositType
effectiveDebtAfterDeposit = balanceSheet.effectiveDebt -
(trueDebt * depositPriceCasted) / depositBorrowFactorCasted
effectiveCollateralAfterDeposit = balanceSheet.effectiveCollateral +
(depositAmountCasted - trueDebt) * depositPriceCasted * depositCollateralFactorCasted
}
}
if self.config.isDebugLogging() {
log(" [CONTRACT] effectiveCollateralAfterDeposit: \(effectiveCollateralAfterDeposit)")
log(" [CONTRACT] effectiveDebtAfterDeposit: \(effectiveDebtAfterDeposit)")
}
// We now have new effective collateral and debt values that reflect the proposed deposit (if any!).
// Now we can figure out how many of the withdrawal token are available while keeping the position
// at or above the target health value.
return FlowALPModels.BalanceSheet(
effectiveCollateral: effectiveCollateralAfterDeposit,
effectiveDebt: effectiveDebtAfterDeposit
)
}
// Helper function to compute available withdrawal
// TODO(jord): ~100-line function - consider refactoring
access(self) fun computeAvailableWithdrawal(
position: &{FlowALPModels.InternalPosition},
withdrawType: Type,
effectiveCollateral: UFix128,
effectiveDebt: UFix128,
targetHealth: UFix128
): UFix64 {
var effectiveCollateralAfterDeposit = effectiveCollateral
let effectiveDebtAfterDeposit = effectiveDebt
let healthAfterDeposit = FlowALPMath.healthComputation(
effectiveCollateral: effectiveCollateralAfterDeposit,
effectiveDebt: effectiveDebtAfterDeposit
)
if self.config.isDebugLogging() {
log(" [CONTRACT] healthAfterDeposit: \(healthAfterDeposit)")
}
if healthAfterDeposit <= targetHealth {
// The position is already at or below the provided target health, so we can't withdraw anything.
return 0.0
}
// For situations where the available withdrawal will BOTH draw down collateral and create debt, we keep
// track of the number of tokens that are available from collateral
var collateralTokenCount: UFix128 = 0.0