-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathfunds_available_above_target_health_test.cdc
More file actions
355 lines (290 loc) · 15.1 KB
/
Copy pathfunds_available_above_target_health_test.cdc
File metadata and controls
355 lines (290 loc) · 15.1 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
import Test
import BlockchainHelpers
import "test_helpers.cdc"
import "MOET"
import "TidalProtocol"
import "TidalProtocolUtils"
access(all) let protocolAccount = Test.getAccount(0x0000000000000007)
access(all) let userAccount = Test.createAccount()
access(all) let flowTokenIdentifier = "A.0000000000000003.FlowToken.Vault"
access(all) var moetTokenIdentifier = "A.0000000000000007.MOET.Vault"
access(all) let flowVaultStoragePath = /storage/flowTokenVault
access(all) let wrapperStoragePath = /storage/tidalProtocolPositionWrapper
access(all) let flowCollateralFactor = 0.8
access(all) let flowBorrowFactor = 1.0
access(all) let flowStartPrice = 1.0 // denominated in MOET
access(all) let positionFundingAmount = 100.0 // FLOW
access(all) var positionID: UInt64 = 0
access(all) var snapshot: UInt64 = 0
/**
REFERENCE MATHS
---------------
NOTE: These methods do not yet account for true balance (i.e. deposited/withdrawn + interest)
Effective Collateral Value (MOET)
effectiveCollateralValue = collateralBalance * collateralPrice * collateralFactor
Borrowable Value (MOET)
borrowLimit = (effectiveCollateralValue / targetHealth) * borrowFactor
borrowLimit = collateralBalance * collateralPrice * collateralFactor / targetHealth * borrowFactor
Current Health
borrowedValue = collateralBalance * collateralPrice * collateralFactor / targetHealth * borrowFactor
borrowedValue * targetHealth = collateralBalance * collateralPrice * collateralFactor * borrowFactor
health = collateralBalance * collateralPrice * collateralFactor * borrowFactor / borrowedValue
health = effectiveCollateralValue * borrowFactor / borrowedValue
*/
access(all) let startCollateralValue = flowStartPrice * positionFundingAmount
access(all) let startEffectiveCollateralValue = startCollateralValue * flowCollateralFactor
access(all) let startBorrowLimitAtTarget = startEffectiveCollateralValue / targetHealth
access(all)
fun setup() {
log("----- SETTING UP funds_available_above_target_health_test.cdc -----")
deployContracts()
// price setup
setMockOraclePrice(signer: protocolAccount, forTokenIdentifier: flowTokenIdentifier, price: flowStartPrice)
// create the Pool & add FLOW as suppoorted token
createAndStorePool(signer: protocolAccount, defaultTokenIdentifier: defaultTokenIdentifier, beFailed: false)
addSupportedTokenSimpleInterestCurve(
signer: protocolAccount,
tokenTypeIdentifier: flowTokenIdentifier,
collateralFactor: flowCollateralFactor,
borrowFactor: flowBorrowFactor,
depositRate: 1_000_000.0,
depositCapacityCap: 1_000_000.0
)
// prep user's account
setupMoetVault(userAccount, beFailed: false)
mintFlow(to: userAccount, amount: positionFundingAmount)
snapshot = getCurrentBlockHeight()
log("----- funds_available_above_target_health_test.cdc SETUP COMPLETE -----")
}
access(all)
fun testFundsAvailableAboveTargetHealthAfterDepositingWithPushFromHealthy() {
log("==============================")
log("[TEST] Executing testFundsAvailableAboveTargetHealthAfterDepositingWithPushFromHealthy()")
if snapshot < getCurrentBlockHeight() {
Test.reset(to: snapshot)
}
let openRes = executeTransaction(
"./transactions/mock-tidal-protocol-consumer/create_wrapped_position.cdc",
[positionFundingAmount, flowVaultStoragePath, true],
userAccount
)
Test.expect(openRes, Test.beSucceeded())
// assert expected starting point
let balanceAfterBorrow = getBalance(address: userAccount.address, vaultPublicPath: MOET.VaultPublicPath)!
let expectedBorrowAmount = (positionFundingAmount * flowCollateralFactor * flowStartPrice) / targetHealth
Test.assert(balanceAfterBorrow >= expectedBorrowAmount - 0.01 && balanceAfterBorrow <= expectedBorrowAmount + 0.01,
message: "Expected MOET balance to be ~\(expectedBorrowAmount), but got \(balanceAfterBorrow)")
let evts = Test.eventsOfType(Type<TidalProtocol.Opened>())
let openedEvt = evts[evts.length - 1] as! TidalProtocol.Opened
positionID = openedEvt.pid
let positionDetails = getPositionDetails(pid: positionID, beFailed: false)
let health = positionDetails.health
let moetBalance = positionDetails.balances[0]
let flowPositionBalance = positionDetails.balances[1]
Test.assertEqual(positionFundingAmount, flowPositionBalance.balance)
Test.assertEqual(expectedBorrowAmount, moetBalance.balance)
Test.assertEqual(TidalProtocol.BalanceDirection.Credit, flowPositionBalance.direction)
Test.assertEqual(TidalProtocol.BalanceDirection.Debit, moetBalance.direction)
Test.assert(equalWithinVariance(intTargetHealth, health),
message: "Expected health to be \(intTargetHealth), but got \(health)")
log("[TEST] FLOW price set to \(flowStartPrice)")
let amounts: [UFix64] = [0.0, 10.0, 100.0, 1_000.0, 10_000.0, 100_000.0, 1_000_000.0]
let expectedExcess = 0.0 // none available above target from healthy state
let internalSnapshot = getCurrentBlockHeight()
for i, amount in amounts {
runFundsAvailableAboveTargetHealthAfterDepositing(
pid: positionID,
existingBorrowed: expectedBorrowAmount,
existingFlowCollateral: positionFundingAmount,
currentFlowPrice: flowStartPrice,
depositAmount: amount,
withdrawIdentifier: moetTokenIdentifier,
depositIdentifier: flowTokenIdentifier
)
// minting to topUpSource Vault which should *not* affect calculation
let mintToSource = amount < 100.0 ? 100.0 : amount * 10.0
log("[TEST] Minting \(mintToSource) to position topUpSource and running again")
mintMoet(signer: protocolAccount, to: userAccount.address, amount: mintToSource, beFailed: false)
runFundsAvailableAboveTargetHealthAfterDepositing(
pid: positionID,
existingBorrowed: expectedBorrowAmount,
existingFlowCollateral: positionFundingAmount,
currentFlowPrice: flowStartPrice,
depositAmount: amount,
withdrawIdentifier: moetTokenIdentifier,
depositIdentifier: flowTokenIdentifier
)
Test.reset(to: internalSnapshot)
}
log("==============================")
}
access(all)
fun testFundsAvailableAboveTargetHealthAfterDepositingWithoutPushFromHealthy() {
log("==============================")
log("[TEST] Executing testFundsAvailableAboveTargetHealthAfterDepositingWithoutPushFromHealthy()")
if snapshot < getCurrentBlockHeight() {
Test.reset(to: snapshot)
}
let openRes = executeTransaction(
"./transactions/mock-tidal-protocol-consumer/create_wrapped_position.cdc",
[positionFundingAmount, flowVaultStoragePath, false],
userAccount
)
Test.expect(openRes, Test.beSucceeded())
// assert expected starting point
let balanceAfterBorrow = getBalance(address: userAccount.address, vaultPublicPath: MOET.VaultPublicPath)!
let expectedBorrowAmount = 0.0
Test.assertEqual(expectedBorrowAmount, balanceAfterBorrow)
let evts = Test.eventsOfType(Type<TidalProtocol.Opened>())
let openedEvt = evts[evts.length - 1] as! TidalProtocol.Opened
positionID = openedEvt.pid
let positionDetails = getPositionDetails(pid: positionID, beFailed: false)
let health = positionDetails.health
let flowPositionBalance = positionDetails.balances[0]
Test.assertEqual(positionFundingAmount, flowPositionBalance.balance)
Test.assertEqual(TidalProtocol.BalanceDirection.Credit, flowPositionBalance.direction)
Test.assertEqual(ceilingHealth, health)
log("[TEST] FLOW price set to \(flowStartPrice)")
let amounts: [UFix64] = [0.0, 10.0, 100.0, 1_000.0, 10_000.0, 100_000.0, 1_000_000.0]
var expectedExcess = 0.0 // none available above target from healthy state
var expectedDeficit = ((positionFundingAmount * flowCollateralFactor) / targetHealth * flowBorrowFactor) * flowStartPrice
let internalSnapshot = getCurrentBlockHeight()
for i, amount in amounts {
runFundsAvailableAboveTargetHealthAfterDepositing(
pid: positionID,
existingBorrowed: expectedBorrowAmount,
existingFlowCollateral: positionFundingAmount,
currentFlowPrice: flowStartPrice,
depositAmount: amount,
withdrawIdentifier: moetTokenIdentifier,
depositIdentifier: flowTokenIdentifier
)
// minting to topUpSource Vault which should *not* affect calculation
let mintToSource = amount < 100.0 ? 100.0 : amount * 10.0
log("[TEST] Minting \(mintToSource) to position topUpSource and running again")
mintMoet(signer: protocolAccount, to: userAccount.address, amount: mintToSource, beFailed: false)
runFundsAvailableAboveTargetHealthAfterDepositing(
pid: positionID,
existingBorrowed: expectedBorrowAmount,
existingFlowCollateral: positionFundingAmount,
currentFlowPrice: flowStartPrice,
depositAmount: amount,
withdrawIdentifier: moetTokenIdentifier,
depositIdentifier: flowTokenIdentifier
)
Test.reset(to: internalSnapshot)
}
log("==============================")
}
access(all)
fun testFundsAvailableAboveTargetHealthAfterDepositingWithoutPushFromOvercollateralized() {
log("==============================")
log("[TEST] Executing testFundsAvailableAboveTargetHealthAfterDepositingWithoutPushFromOvercollateralized()")
if snapshot < getCurrentBlockHeight() {
Test.reset(to: snapshot)
}
let openRes = executeTransaction(
"./transactions/mock-tidal-protocol-consumer/create_wrapped_position.cdc",
[positionFundingAmount, flowVaultStoragePath, false],
userAccount
)
Test.expect(openRes, Test.beSucceeded())
// assert expected starting point
let balanceAfterBorrow = getBalance(address: userAccount.address, vaultPublicPath: MOET.VaultPublicPath)!
let expectedBorrowAmount = 0.0
Test.assertEqual(expectedBorrowAmount, balanceAfterBorrow)
let evts = Test.eventsOfType(Type<TidalProtocol.Opened>())
let openedEvt = evts[evts.length - 1] as! TidalProtocol.Opened
positionID = openedEvt.pid
let positionDetails = getPositionDetails(pid: positionID, beFailed: false)
let health = positionDetails.health
let flowPositionBalance = positionDetails.balances[0]
Test.assertEqual(positionFundingAmount, flowPositionBalance.balance)
Test.assertEqual(TidalProtocol.BalanceDirection.Credit, flowPositionBalance.direction)
let priceIncrease = 0.25
let newPrice = flowStartPrice * (1.0 + priceIncrease)
let newCollateralValue = positionFundingAmount * newPrice
let newEffectiveCollateralValue = newCollateralValue * flowCollateralFactor
let expectedAvailableAboveTarget = newEffectiveCollateralValue / targetHealth * flowBorrowFactor
setMockOraclePrice(signer: protocolAccount,
forTokenIdentifier: flowTokenIdentifier,
price: newPrice
)
let actualHealth = getPositionHealth(pid: positionID, beFailed: false)
Test.assertEqual(ceilingHealth, actualHealth) // no debt should virtually infinite health, capped by UFix64 type
log("[TEST] FLOW price set to \(newPrice) from \(flowStartPrice)")
log("[TEST] Position health after price increase: \(actualHealth)")
log("[TEST] Expected available above target health: \(expectedAvailableAboveTarget) MOET")
log("..............................")
// minting to topUpSource Vault which should *not* affect calculation here
let mintToSource = 1_000.0
log("[TEST] Minting \(mintToSource) to position topUpSource")
mintMoet(signer: protocolAccount, to: userAccount.address, amount: mintToSource, beFailed: false)
log("..............................")
var depositAmount = 0.0
// var expectedAvailable = expectedAvailableAboveTarget + (depositAmount * flowCollateralFactor / targetHealth * flowBorrowFactor) * newPrice
var expectedAvailable = (positionFundingAmount + depositAmount) * newPrice * flowCollateralFactor / targetHealth * flowBorrowFactor
var actualAvailable = fundsAvailableAboveTargetHealthAfterDepositing(
pid: positionID,
withdrawType: moetTokenIdentifier,
targetHealth: intTargetHealth,
depositType: flowTokenIdentifier,
depositAmount: depositAmount,
beFailed: false
)
log("[TEST] Depositing: \(depositAmount)")
log("[TEST] Expected Available: \(expectedAvailable)")
log("[TEST] Actual Available: \(actualAvailable)")
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable),
message: "Values are not equal within variance - expected: \(expectedAvailable), actual: \(actualAvailable)")
log("..............................")
depositAmount = 100.0
expectedAvailable = expectedAvailableAboveTarget + (depositAmount * flowCollateralFactor / targetHealth * flowBorrowFactor) * newPrice
actualAvailable = fundsAvailableAboveTargetHealthAfterDepositing(
pid: positionID,
withdrawType: moetTokenIdentifier,
targetHealth: intTargetHealth,
depositType: flowTokenIdentifier,
depositAmount: depositAmount,
beFailed: false
)
log("[TEST] Depositing: \(depositAmount)")
log("[TEST] Expected Available: \(expectedAvailable)")
log("[TEST] Actual Available: \(actualAvailable)")
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable),
message: "Values are not equal within variance - expected: \(expectedAvailable), actual: \(actualAvailable)")
log("==============================")
}
// TODO
// - Test deposit & withdraw same type
// - Test depositing withdraw type without pushing to sink, creating a Credit balance before testing
/* --- Parameterized runner --- */
access(all)
fun runFundsAvailableAboveTargetHealthAfterDepositing(
pid: UInt64,
existingBorrowed: UFix64,
existingFlowCollateral: UFix64,
currentFlowPrice: UFix64,
depositAmount: UFix64,
withdrawIdentifier: String,
depositIdentifier: String
) {
log("..............................")
let expectedTotalBorrowCapacity = (existingFlowCollateral + depositAmount) * currentFlowPrice * flowCollateralFactor / targetHealth * flowBorrowFactor
let expectedAvailable = expectedTotalBorrowCapacity - existingBorrowed
let actualAvailable = fundsAvailableAboveTargetHealthAfterDepositing(
pid: pid,
withdrawType: withdrawIdentifier,
targetHealth: intTargetHealth,
depositType: depositIdentifier,
depositAmount: depositAmount,
beFailed: false
)
log("[TEST] Withdraw type: \(withdrawIdentifier)")
log("[TEST] Deposit type: \(depositIdentifier)")
log("[TEST] Depositing: \(depositAmount)")
log("[TEST] Expected Available: \(expectedAvailable)")
log("[TEST] Actual Available: \(actualAvailable)")
Test.assert(equalWithinVariance(expectedAvailable, actualAvailable),
message: "Values are not equal within variance - expected: \(expectedAvailable), actual: \(actualAvailable)")
}