This repository has been archived by the owner on Mar 28, 2023. It is now read-only.
/
DepositLiquidationTest.js
449 lines (354 loc) · 16.8 KB
/
DepositLiquidationTest.js
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
const { deployAndLinkAll } = require('../testHelpers/testDeployer.js')
const { states } = require('../testHelpers/utils.js')
const { createSnapshot, restoreSnapshot } = require('../testHelpers/helpers/snapshot.js')
const { accounts, web3 } = require('@openzeppelin/test-environment')
const [owner] = accounts
const { BN, expectRevert } = require('@openzeppelin/test-helpers')
const { expect } = require('chai')
// spare signature:
// signing with privkey '11' * 32
// const preimage = '0x' + '33'.repeat(32)
// const digest = '0xdeb0e38ced1e41de6f92e70e80c418d2d356afaaa99e26f5939dbc7d3ef4772a'
// const pubkey = '0x4f355bdcb7cc0af728ef3cceb9615d90684bb5b2ca5f859ab0f0b704075871aa385b6b1b8ead809ca67454d9683fcf2ba03456d6fe2c4abe2b07f0fbdbb2f1c1'
// const v = 28
// const r = '0x9a40a074721355f427762f5e6d5cb16a0a9ada06011984e49fc81b3ce89cab6d'
// const s = '0xs234e909713e74a9a49bf9484a69968dabcb1953bf091fa3e31d48531695cf293'
describe('DepositLiquidation', async function() {
let tbtcConstants
let tbtcSystemStub
let tbtcToken
let tbtcDepositToken
let feeRebateToken
let testDeposit
let ecdsaKeepStub
let beneficiary
before(async () => {
await createSnapshot()
})
after(async () => {
await restoreSnapshot()
})
before(async () => {
({
tbtcConstants,
tbtcSystemStub,
tbtcToken,
tbtcDepositToken,
feeRebateToken,
testDeposit,
ecdsaKeepStub,
} = await deployAndLinkAll())
beneficiary = accounts[4]
const underThreshold = await tbtcSystemStub.getUndercollateralizedThresholdPercent()
const severeThreshold = await tbtcSystemStub.getSeverelyUndercollateralizedThresholdPercent()
await testDeposit.setUndercollateralizedThresholdPercent(new BN(underThreshold))
await testDeposit.setSeverelyUndercollateralizedThresholdPercent(new BN(severeThreshold))
await testDeposit.setSignerFeeDivisor(new BN('200'))
await tbtcDepositToken.forceMint(beneficiary, web3.utils.toBN(testDeposit.address))
await feeRebateToken.forceMint(beneficiary, web3.utils.toBN(testDeposit.address))
await testDeposit.reset()
await testDeposit.setKeepAddress(ecdsaKeepStub.address)
})
beforeEach(async () => {
await createSnapshot()
})
afterEach(async () => {
await restoreSnapshot()
})
describe('purchaseSignerBondsAtAuction', async () => {
let lotSize
let buyer
before(async () => {
lotSize = await testDeposit.lotSizeTbtc.call()
buyer = accounts[1]
})
beforeEach(async () => {
await testDeposit.setState(states.LIQUIDATION_IN_PROGRESS)
for (let i = 0; i < 2; i++) {
await tbtcToken.resetBalance(lotSize, { from: accounts[i] })
await tbtcToken.resetAllowance(testDeposit.address, lotSize, { from: accounts[i] })
}
})
it('sets state to liquidated, logs Liquidated, ', async () => {
const blockNumber = await web3.eth.getBlock('latest').number
await testDeposit.purchaseSignerBondsAtAuction({ from: owner })
const depositState = await testDeposit.getState.call()
expect(depositState).to.eq.BN(states.LIQUIDATED)
const eventList = await tbtcSystemStub.getPastEvents('Liquidated', { fromBlock: blockNumber, toBlock: 'latest' })
expect(eventList.length).to.equal(1)
})
it('reverts if not in a liquidation auction', async () => {
await testDeposit.setState(states.START)
await expectRevert(
testDeposit.purchaseSignerBondsAtAuction(),
'No active auction'
)
})
it('reverts if TBTC balance is insufficient', async () => {
// burn 1 from buyer to make balance insufficient
await tbtcToken.forceBurn(owner, 1)
await expectRevert(
testDeposit.purchaseSignerBondsAtAuction(),
'Not enough TBTC to cover outstanding debt'
)
})
it(`burns msg.sender's tokens`, async () => {
const initialTokenBalance = await tbtcToken.balanceOf(buyer)
await testDeposit.purchaseSignerBondsAtAuction({ from: buyer })
const finalTokenBalance = await tbtcToken.balanceOf(buyer)
const tokenCheck = new BN(finalTokenBalance).add(new BN(lotSize))
expect(tokenCheck, 'tokens not burned correctly').to.eq.BN(initialTokenBalance)
})
it('distributes reward to FRT holder', async () => {
// Make sure Deposit has enough to cover beneficiary reward
const beneficiaryReward = await testDeposit.signerFee.call()
await tbtcToken.forceMint(testDeposit.address, beneficiaryReward)
const initialTokenBalance = await tbtcToken.balanceOf(beneficiary)
await testDeposit.purchaseSignerBondsAtAuction({ from: buyer })
const finalTokenBalance = await tbtcToken.balanceOf(beneficiary)
const tokenCheck = new BN(initialTokenBalance).add(new BN(beneficiaryReward).add(lotSize))
expect(finalTokenBalance, 'tokens not returned to beneficiary correctly').to.eq.BN(tokenCheck)
})
it('distributes value to the buyer', async () => {
const value = 10000000000000000
const block = await web3.eth.getBlock('latest')
const notifiedTime = block.timestamp
const initialBalance = await web3.eth.getBalance(buyer)
await testDeposit.send(value, { from: owner })
await testDeposit.setLiquidationAndCourtesyInitated(notifiedTime, 0)
await testDeposit.purchaseSignerBondsAtAuction({ from: buyer })
const finalBalance = await web3.eth.getBalance(buyer)
expect(new BN(finalBalance), 'buyer balance should increase').to.be.gte.BN(initialBalance)
})
it('splits funds between liquidation triggerer and signers if not fraud', async () => {
const liquidationInitiator = accounts[4]
const block = await web3.eth.getBlock('latest')
const notifiedTime = block.timestamp
const value = 1000000000000
const basePercentage = await tbtcConstants.getAuctionBasePercentage.call()
await testDeposit.send(value)
const initialInitiatorBalance = await web3.eth.getBalance(liquidationInitiator)
const initialSignerBalance = await web3.eth.getBalance(ecdsaKeepStub.address)
await testDeposit.setLiquidationInitiator(liquidationInitiator)
await testDeposit.setLiquidationAndCourtesyInitated(notifiedTime, 0)
// Buy auction immediately. No scaling taken place. Auction value is base percentage of signer bond.
await testDeposit.purchaseSignerBondsAtAuction({ from: buyer })
const finalInitiatorBalance = await web3.eth.getBalance(liquidationInitiator)
const finalSignerBalance = await web3.eth.getBalance(ecdsaKeepStub.address)
const initiatorBalanceDiff = new BN(finalInitiatorBalance).sub(new BN(initialInitiatorBalance))
const signerBalanceDiff = new BN(finalSignerBalance).sub(new BN(initialSignerBalance))
const totalReward = value * (100 - basePercentage) / 100
const split = totalReward / 2
expect(new BN(split)).to.eq.BN(initiatorBalanceDiff)
expect(new BN(split)).to.eq.BN(signerBalanceDiff)
})
it('transfers full ETH balance to liquidation triggerer if fraud', async () => {
const block = await web3.eth.getBlock('latest')
const notifiedTime = block.timestamp
const liquidationInitiator = accounts[2]
const value = 1000000000000
const basePercentage = await tbtcConstants.getAuctionBasePercentage.call()
await testDeposit.send(value)
const initialInitiatorBalance = await web3.eth.getBalance(liquidationInitiator)
const initialSignerBalance = await web3.eth.getBalance(ecdsaKeepStub.address)
await testDeposit.setState(states.FRAUD_LIQUIDATION_IN_PROGRESS)
await testDeposit.setLiquidationAndCourtesyInitated(notifiedTime, 0)
await testDeposit.setLiquidationInitiator(liquidationInitiator)
// Buy auction immediately. No scaling taken place. Auction value is base percentage of signer bond.
await testDeposit.purchaseSignerBondsAtAuction({ from: buyer })
const finalInitiatorBalance = await web3.eth.getBalance(liquidationInitiator)
const finalSignerBalance = await web3.eth.getBalance(ecdsaKeepStub.address)
const initiatorBalanceDiff = new BN(finalInitiatorBalance).sub(new BN(initialInitiatorBalance))
const signerBalanceDiff = new BN(finalSignerBalance).sub(new BN(initialSignerBalance))
const totalReward = value * (100 - basePercentage) / 100
expect(new BN(signerBalanceDiff)).to.eq.BN(0)
expect(new BN(initiatorBalanceDiff)).to.eq.BN(totalReward)
})
})
describe('notifyCourtesyCall', async () => {
let oraclePrice
let lotSize
let lotValue
let undercollateralizedPercent
before(async () => {
await tbtcSystemStub.setOraclePrice(new BN('1000000000000', 10))
oraclePrice = await tbtcSystemStub.fetchBitcoinPrice.call()
lotSize = await testDeposit.lotSizeSatoshis.call()
lotValue = lotSize.mul(oraclePrice)
undercollateralizedPercent = await testDeposit.getUndercollateralizedThresholdPercent.call()
})
beforeEach(async () => {
await testDeposit.setState(states.ACTIVE)
await ecdsaKeepStub.setBondAmount(0)
})
it('sets courtesy call state, sets the timestamp, and logs CourtesyCalled', async () => {
const blockNumber = await web3.eth.getBlock('latest').number
// Bond value is calculated as:
// `bondValue = collateralization * (lotSize * oraclePrice) / 100`
// Here we subtract `1` to test collateralization less than undercollateralized
// threshold (140%).
const bondValue = undercollateralizedPercent.mul(lotValue).div(new BN(100)).sub(new BN(1))
await ecdsaKeepStub.setBondAmount(bondValue)
await testDeposit.notifyCourtesyCall()
const depositState = await testDeposit.getState.call()
expect(depositState).to.eq.BN(states.COURTESY_CALL)
const liquidationTime = await testDeposit.getLiquidationAndCourtesyInitiated.call()
expect(liquidationTime[1]).not.to.eq.BN(0)
const eventList = await tbtcSystemStub.getPastEvents('CourtesyCalled', { fromBlock: blockNumber, toBlock: 'latest' })
expect(eventList.length).to.equal(1)
})
it('reverts if not in active state', async () => {
await testDeposit.setState(states.START)
await expectRevert(
testDeposit.notifyCourtesyCall(),
'Can only courtesy call from active state'
)
})
it('reverts if sufficiently collateralized', async () => {
// Bond value is calculated as:
// `bondValue = collateralization * (lotSize * oraclePrice) / 100`
// Here we test collateralization equal undercollateralized threshold (140%).
const bondValue = undercollateralizedPercent.mul(lotValue).div(new BN(100))
await ecdsaKeepStub.setBondAmount(bondValue)
await expectRevert(
testDeposit.notifyCourtesyCall(),
'Signers have sufficient collateral'
)
})
})
describe('exitCourtesyCall', async () => {
beforeEach(async () => {
const block = await web3.eth.getBlock('latest')
const blockTimestamp = block.timestamp
const notifiedTime = blockTimestamp // not expired
const fundedTime = blockTimestamp // not expired
await ecdsaKeepStub.setBondAmount(new BN('1000000000000000000000000', 10))
await tbtcSystemStub.setOraclePrice(new BN('1', 10))
await testDeposit.setState(states.COURTESY_CALL)
await testDeposit.setUTXOInfo('0x' + '00'.repeat(8), fundedTime, '0x' + '00'.repeat(36))
await testDeposit.setLiquidationAndCourtesyInitated(0, notifiedTime)
})
afterEach(async () => {
await ecdsaKeepStub.setBondAmount(1000)
await tbtcSystemStub.setOraclePrice(new BN('1000000000000', 10))
})
it('transitions to active, and logs ExitedCourtesyCall', async () => {
const blockNumber = await web3.eth.getBlock('latest').number
await testDeposit.exitCourtesyCall()
const depositState = await testDeposit.getState.call()
expect(depositState).to.eq.BN(states.ACTIVE)
const eventList = await tbtcSystemStub.getPastEvents('ExitedCourtesyCall', { fromBlock: blockNumber, toBlock: 'latest' })
expect(eventList.length).to.equal(1)
})
it('reverts if not in courtesy call state', async () => {
await testDeposit.setState(states.START)
await expectRevert(
testDeposit.exitCourtesyCall(),
'Not currently in courtesy call'
)
})
it('reverts if the deposit is still undercollateralized', async () => {
await tbtcSystemStub.setOraclePrice(new BN('1000000000000', 10))
await ecdsaKeepStub.setBondAmount(0)
await expectRevert(
testDeposit.exitCourtesyCall(),
'Deposit is still undercollateralized'
)
})
})
describe('notifyUndercollateralizedLiquidation', async () => {
let oraclePrice
let lotSize
let lotValue
let severelyUndercollateralizedPercent
before(async () => {
await tbtcSystemStub.setOraclePrice(new BN('1000000000000', 10))
oraclePrice = await tbtcSystemStub.fetchBitcoinPrice.call()
lotSize = await testDeposit.lotSizeSatoshis.call()
lotValue = lotSize.mul(oraclePrice)
severelyUndercollateralizedPercent = await tbtcSystemStub.getSeverelyUndercollateralizedThresholdPercent.call()
})
beforeEach(async () => {
await testDeposit.setState(states.ACTIVE)
await ecdsaKeepStub.setBondAmount(0)
await ecdsaKeepStub.send(1000000, { from: owner })
})
it('executes', async () => {
// Bond value is calculated as:
// `bondValue = collateralization * (lotSize * oraclePrice) / 100`
// Here we test collateralization less than severely undercollateralized
// threshold (120%).
const bondValue = severelyUndercollateralizedPercent.mul(lotValue).div(new BN(100)).sub(new BN(1))
await ecdsaKeepStub.setBondAmount(bondValue)
await testDeposit.notifyUndercollateralizedLiquidation()
// TODO: Add validations or cover with `reverts if the deposit is not
// severely undercollateralized` test case.
})
it('reverts if not in active or courtesy call', async () => {
await testDeposit.setState(states.START)
await expectRevert(
testDeposit.notifyUndercollateralizedLiquidation(),
'Deposit not in active or courtesy call'
)
})
it('reverts if the deposit is not severely undercollateralized', async () => {
// Bond value is calculated as:
// `bondValue = collateralization * (lotSize * oraclePrice) / 100`
// Here we test collateralization equal severely undercollateralized threshold (120%).
const bondValue = severelyUndercollateralizedPercent.mul(lotValue).div(new BN(100))
await ecdsaKeepStub.setBondAmount(bondValue)
await expectRevert(
testDeposit.notifyUndercollateralizedLiquidation(),
'Deposit has sufficient collateral'
)
})
it('assert starts signer abort liquidation', async () => {
await ecdsaKeepStub.send(1000000, { from: owner })
await testDeposit.notifyUndercollateralizedLiquidation()
const bond = await web3.eth.getBalance(ecdsaKeepStub.address)
expect(new BN(bond), 'Bond not seized as expected').to.eq.BN('0')
const liquidationTime = await testDeposit.getLiquidationAndCourtesyInitiated.call()
expect(liquidationTime[0], 'liquidation timestamp not recorded').not.to.eq.BN(0)
})
})
describe('notifyCourtesyTimeout', async () => {
let courtesyTime
let timer
before(async () => {
timer = await tbtcConstants.getCourtesyCallTimeout.call()
})
beforeEach(async () => {
const block = await web3.eth.getBlock('latest')
const blockTimestamp = block.timestamp
courtesyTime = blockTimestamp - timer.toNumber() // has not expired
await testDeposit.setState(states.COURTESY_CALL)
await testDeposit.setLiquidationAndCourtesyInitated(0, courtesyTime)
await ecdsaKeepStub.send(1000000, { from: owner })
})
it('executes', async () => {
await testDeposit.notifyCourtesyTimeout()
})
it('reverts if not in a courtesy call period', async () => {
await testDeposit.setState(states.START)
await expectRevert(
testDeposit.notifyCourtesyTimeout(),
'Not in a courtesy call period'
)
})
it('reverts if the period has not elapsed', async () => {
await testDeposit.setLiquidationAndCourtesyInitated(0, courtesyTime * 5)
await expectRevert(
testDeposit.notifyCourtesyTimeout(),
'Courtesy period has not elapsed'
)
})
it('assert starts signer abort liquidation', async () => {
await ecdsaKeepStub.send(1000000, { from: owner })
await testDeposit.notifyCourtesyTimeout()
const bond = await web3.eth.getBalance(ecdsaKeepStub.address)
expect(new BN(bond), 'Bond not seized as expected').to.eq.BN('0')
const liquidationTime = await testDeposit.getLiquidationAndCourtesyInitiated.call()
expect(liquidationTime[0], 'liquidation timestamp not recorded').not.to.eq.BN(0)
})
})
})