forked from DeFiCh/ain
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfeature_loan_priceupdate.py
executable file
·350 lines (295 loc) · 14.3 KB
/
feature_loan_priceupdate.py
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
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Copyright (c) DeFi Blockchain Developers
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
"""Test Active/Next price update."""
from test_framework.authproxy import JSONRPCException
from test_framework.test_framework import DefiTestFramework
from decimal import Decimal
from test_framework.util import assert_equal
import calendar
import time
class PriceUpdateTest (DefiTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
self.extra_args = [
['-txnotokens=0', '-amkheight=1', '-bayfrontheight=1', '-eunosheight=1', '-txindex=1', '-fortcanningheight=1']
]
def run_test(self):
self.nodes[0].generate(300)
self.nodes[0].createtoken({
"symbol": "BTC",
"name": "BTC token",
"isDAT": True,
"collateralAddress": self.nodes[0].get_genesis_keys().ownerAuthAddress
})
self.nodes[0].createtoken({
"symbol": "USD",
"name": "USD token",
"isDAT": True,
"collateralAddress": self.nodes[0].get_genesis_keys().ownerAuthAddress
})
self.nodes[0].generate(1)
# mint BTC
self.nodes[0].minttokens("2000@BTC")
self.nodes[0].generate(1)
account = self.nodes[0].get_genesis_keys().ownerAuthAddress
# transfer DFI
self.nodes[0].utxostoaccount({account: "2000@DFI"})
self.nodes[0].generate(1)
# setup oracles
oracle_address1 = self.nodes[0].getnewaddress("", "legacy")
price_feeds = [
{"currency": "USD", "token": "TSLA"},
{"currency": "USD", "token": "DFI"},
{"currency": "USD", "token": "BTC"}]
oracle_id1 = self.nodes[0].appointoracle(oracle_address1, price_feeds, 10)
self.nodes[0].generate(1)
oracle_address2 = self.nodes[0].getnewaddress("", "legacy")
oracle_id2 = self.nodes[0].appointoracle(oracle_address2, price_feeds, 10)
self.nodes[0].generate(1)
collTokenDFI_USD = {
'token': "DFI",
'factor': 1,
'fixedIntervalPriceId': "DFI/USD"}
try:
self.nodes[0].setcollateraltoken(collTokenDFI_USD)
except JSONRPCException as e:
errorString = e.error['message']
assert("no live oracles for specified request" in errorString)
# feed oracle
oracle1_prices = [
{"currency": "USD", "tokenAmount": "10@DFI"},
{"currency": "USD", "tokenAmount": "10@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id1, timestamp, oracle1_prices)
self.nodes[0].generate(1)
oracle2_prices = [
{"currency": "USD", "tokenAmount": "20@DFI"},
{"currency": "USD", "tokenAmount": "20@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id2, timestamp, oracle2_prices)
self.nodes[0].generate(1)
self.nodes[0].setcollateraltoken(collTokenDFI_USD)
self.nodes[0].generate(1)
collTokenBTC_USD = {
'token': "BTC",
'factor': 1,
'fixedIntervalPriceId': "BTC/USD"}
self.nodes[0].setcollateraltoken(collTokenBTC_USD)
self.nodes[0].generate(1)
# Create loan schemes
self.nodes[0].createloanscheme(200, 1, 'LOAN1')
self.nodes[0].generate(1)
# Create vault
vaultId1 = self.nodes[0].createvault(account, 'LOAN1') # default loan scheme
self.nodes[0].generate(6)
self.nodes[0].deposittovault(vaultId1, account, '1000@DFI')
self.nodes[0].generate(1)
self.nodes[0].deposittovault(vaultId1, account, '1000@BTC')
self.nodes[0].generate(1)
# set TSLA as loan token
loanTokenTSLA_USD = {
'symbol': "TSLA",
'name': "Tesla Token",
'fixedIntervalPriceId': "TSLA/USD",
'mintable': True,
'interest': 1
}
try:
self.nodes[0].setloantoken(loanTokenTSLA_USD)
except JSONRPCException as e:
errorString = e.error['message']
assert("no live oracles for specified request" in errorString)
oracle1_prices = [
{"currency": "USD", "tokenAmount": "20@TSLA"},
{"currency": "USD", "tokenAmount": "20@DFI"},
{"currency": "USD", "tokenAmount": "20@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id1, timestamp, oracle1_prices)
self.nodes[0].generate(1)
oracle2_prices = [
{"currency": "USD", "tokenAmount": "10@TSLA"},
{"currency": "USD", "tokenAmount": "10@DFI"},
{"currency": "USD", "tokenAmount": "10@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id2, timestamp, oracle2_prices)
self.nodes[0].generate(1)
self.nodes[0].setloantoken(loanTokenTSLA_USD)
self.nodes[0].generate(1)
try:
self.nodes[0].takeloan({
'vaultId': vaultId1,
'amounts': "10@TSLA"})
except JSONRPCException as e:
errorString = e.error['message']
assert("No live fixed prices for TSLA/USD" in errorString)
self.nodes[0].generate(5) # let price update
loanAmount = 40
self.nodes[0].takeloan({
'vaultId': vaultId1,
'amounts': str(loanAmount)+"@TSLA"})
self.nodes[0].generate(1)
takenLoanAmount = loanAmount
try:
fixedPrice = self.nodes[0].getfixedintervalprice("AAA/USD")
except JSONRPCException as e:
errorString = e.error['message']
assert("fixedIntervalPrice with id <AAA/USD> not found" in errorString)
fixedPrice = self.nodes[0].getfixedintervalprice("TSLA/USD")
assert_equal(fixedPrice['activePrice'], Decimal(15.00000000))
assert_equal(fixedPrice['nextPrice'], Decimal(15.00000000))
assert_equal(fixedPrice['activePriceBlock'], 324)
assert_equal(fixedPrice['nextPriceBlock'], 330)
oracle2_prices = [
{"currency": "USD", "tokenAmount": "15@TSLA"},
{"currency": "USD", "tokenAmount": "15@DFI"},
{"currency": "USD", "tokenAmount": "15@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id2, timestamp, oracle2_prices)
self.nodes[0].generate(1)
# Change price over deviation threshold to invalidate price
oracle1_prices = [
{"currency": "USD", "tokenAmount": "30@TSLA"},
{"currency": "USD", "tokenAmount": "30@DFI"},
{"currency": "USD", "tokenAmount": "30@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id1, timestamp, oracle1_prices)
self.nodes[0].generate(1)
# price is valid because it hasn't been updated yet
loanAmount = 10
self.nodes[0].takeloan({
'vaultId': vaultId1,
'amounts': str(loanAmount)+"@TSLA"})
self.nodes[0].generate(2) # let price update to invalid state
takenLoanAmount += loanAmount
vault = self.nodes[0].getvault(vaultId1)
assert_equal(vault["state"], "frozen")
try:
self.nodes[0].takeloan({
'vaultId': vaultId1,
'amounts': "10@TSLA"})
except JSONRPCException as e:
errorString = e.error['message']
assert("Cannot take loan while any of the asset's price in the vault is not live" in errorString)
try:
self.nodes[0].withdrawfromvault(vaultId1, account, "100@DFI")
except JSONRPCException as e:
errorString = e.error['message']
assert("Cannot withdraw from vault while any of the asset's price is invalid" in errorString)
try:
self.nodes[0].paybackloan({
'vaultId': vaultId1,
'from': account,
'amounts': ["0.5@TSLA"]})
except JSONRPCException as e:
errorString = e.error['message']
assert("Cannot payback loan while any of the asset's price is invalid" in errorString)
account2 = self.nodes[0].getnewaddress("", "legacy")
self.nodes[0].generate(1)
params = {'ownerAddress': account2}
try:
self.nodes[0].updatevault(vaultId1, params)
except JSONRPCException as e:
errorString = e.error['message']
assert("Cannot update vault while any of the asset's price is invalid" in errorString)
fixedPrice = self.nodes[0].getfixedintervalprice("TSLA/USD")
assert_equal(fixedPrice['isLive'], False)
assert_equal(fixedPrice['activePrice'], Decimal('15.00000000'))
assert_equal(fixedPrice['nextPrice'], Decimal('22.50000000'))
self.nodes[0].generate(5) # let price update to valid state
self.nodes[0].updatevault(vaultId1, params)
self.nodes[0].generate(1)
vault = self.nodes[0].getvault(vaultId1)
assert_equal(vault["ownerAddress"], account2)
loanAmount = 30
self.nodes[0].takeloan({
'vaultId': vaultId1,
'amounts': str(loanAmount)+ "@TSLA"})
self.nodes[0].generate(1)
takenLoanAmount += loanAmount
try:
self.nodes[0].withdrawfromvault(vaultId1, account, "900@DFI")
except JSONRPCException as e:
errorString = e.error['message']
assert("At least 50% of the collateral must be in DFI" in errorString)
vault = self.nodes[0].getvault(vaultId1)
self.nodes[0].withdrawfromvault(vaultId1, account, "100@BTC")
self.nodes[0].generate(1)
fixedPrice = self.nodes[0].getfixedintervalprice("TSLA/USD")
assert_equal(fixedPrice['isLive'], True)
assert_equal(fixedPrice['activePrice'], Decimal('22.50000000'))
assert_equal(fixedPrice['nextPrice'], Decimal('22.50000000'))
vault = self.nodes[0].getvault(vaultId1)
assert_equal(vault["collateralAmounts"][1], '900.00000000@BTC')
interest_TSLA = self.nodes[0].getinterest('LOAN1')[0]["totalInterest"]
totalLoanAmount = takenLoanAmount + interest_TSLA
assert_equal(vault["loanAmounts"][0], str(totalLoanAmount)+"@TSLA")
height = self.nodes[0].getblockcount()
assert_equal(height, 340)
oracle1_prices = [
{"currency": "USD", "tokenAmount": "100@TSLA"},
{"currency": "USD", "tokenAmount": "100@DFI"},
{"currency": "USD", "tokenAmount": "100@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id1, timestamp, oracle1_prices)
self.nodes[0].generate(3)
fixedPrice = self.nodes[0].getfixedintervalprice("TSLA/USD")
assert_equal(fixedPrice['isLive'], False)
assert_equal(fixedPrice['activePrice'], Decimal('22.50000000'))
assert_equal(fixedPrice['nextPrice'], Decimal('57.50000000'))
assert_equal(fixedPrice['nextPriceBlock'], 348)
assert_equal(fixedPrice['activePriceBlock'], 342)
self.nodes[0].generate(6)
fixedPrice = self.nodes[0].getfixedintervalprice("TSLA/USD")
assert_equal(fixedPrice['isLive'], True)
assert_equal(fixedPrice['activePrice'], Decimal('57.50000000'))
assert_equal(fixedPrice['nextPrice'], Decimal('57.50000000'))
assert_equal(fixedPrice['nextPriceBlock'], 354)
assert_equal(fixedPrice['activePriceBlock'], 348)
fixedPriceList = self.nodes[0].listfixedintervalprices()
assert_equal(len(fixedPriceList), 3)
pagination = {"start": "DFI/USD"}
fixedPriceList = self.nodes[0].listfixedintervalprices(pagination)
assert_equal(len(fixedPriceList), 2)
# Test verbose parameter in getvault to retrieve nextCollateralRatio
# Update price
oracle1_prices = [
{"currency": "USD", "tokenAmount": "70@TSLA"},
{"currency": "USD", "tokenAmount": "100@DFI"},
{"currency": "USD", "tokenAmount": "100@BTC"}]
timestamp = calendar.timegm(time.gmtime())
self.nodes[0].setoracledata(oracle_id1, timestamp, oracle1_prices)
self.nodes[0].generate(6)
# Check nextPrice and active price are correct
fixedPrice = self.nodes[0].getfixedintervalprice("TSLA/USD")
assert_equal(fixedPrice['isLive'], True)
assert_equal(fixedPrice['activePrice'], Decimal('57.50000000'))
assert_equal(fixedPrice['nextPrice'], Decimal('42.50000000'))
# Check vault nextCollateralRatio and collateralRatio
vaultBeforeUpdate = self.nodes[0].getvault(vaultId1, True)
assert_equal(vaultBeforeUpdate["collateralRatio"], 2375)
assert_equal(vaultBeforeUpdate["nextCollateralRatio"], 3213)
interestPerBlockTSLA = vaultBeforeUpdate["interestsPerBlock"][0].split('@')[0]
amountInterestTSLA = vaultBeforeUpdate["interestAmounts"][0].split('@')[0]
self.nodes[0].generate(1)
vaultBeforeUpdate = self.nodes[0].getvault(vaultId1, True)
expectedInterestAfterOneBlock = Decimal(amountInterestTSLA) + Decimal(interestPerBlockTSLA)
realInteresAfterOneBlock = Decimal(vaultBeforeUpdate["interestAmounts"][0].split('@')[0])
assert_equal(realInteresAfterOneBlock, expectedInterestAfterOneBlock)
# Let price update and check vault again
self.nodes[0].generate(5)
vaultAfterUpdate = self.nodes[0].getvault(vaultId1, True)
assert_equal(vaultAfterUpdate["collateralRatio"], vaultBeforeUpdate["nextCollateralRatio"])
assert_equal(vaultAfterUpdate["nextCollateralRatio"], 3213)
interestPerBlockTSLA = vaultAfterUpdate["interestsPerBlock"][0].split('@')[0]
amountInterestTSLA = vaultAfterUpdate["interestAmounts"][0].split('@')[0]
self.nodes[0].generate(1)
vaultAfterUpdate = self.nodes[0].getvault(vaultId1, True)
expectedInterestAfterOneBlock = Decimal(amountInterestTSLA) + Decimal(interestPerBlockTSLA)
realInteresAfterOneBlock = Decimal(vaultAfterUpdate["interestAmounts"][0].split('@')[0])
assert_equal(realInteresAfterOneBlock, expectedInterestAfterOneBlock)
if __name__ == '__main__':
PriceUpdateTest().main()