-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathZZStRSR.test.ts
3555 lines (2861 loc) · 143 KB
/
ZZStRSR.test.ts
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 { loadFixture } from '@nomicfoundation/hardhat-network-helpers'
import { SignerWithAddress } from '@nomiclabs/hardhat-ethers/signers'
import { anyValue } from '@nomicfoundation/hardhat-chai-matchers/withArgs'
import { expect } from 'chai'
import { signERC2612Permit } from 'eth-permit'
import { BigNumber, ContractFactory } from 'ethers'
import hre, { ethers, upgrades } from 'hardhat'
import { getChainId } from '../common/blockchain-utils'
import { setOraclePrice } from './utils/oracles'
import { bn, fp, near, shortString } from '../common/numbers'
import { expectEvents } from '../common/events'
import {
ERC20Mock,
ERC1271Mock,
StRSRP0,
StRSRP1Votes,
StaticATokenMock,
IAssetRegistry,
TestIBackingManager,
TestIBasketHandler,
TestIFacade,
TestIMain,
TestIRToken,
TestIStRSR,
CTokenMock,
} from '../typechain'
import { IConfig, MAX_RATIO, MAX_UNSTAKING_DELAY } from '../common/configuration'
import { CollateralStatus, MAX_UINT256, ONE_PERIOD, ZERO_ADDRESS } from '../common/constants'
import {
advanceBlocks,
advanceTime,
advanceToTimestamp,
getLatestBlockNumber,
getLatestBlockTimestamp,
setNextBlockTimestamp,
} from './utils/time'
import { whileImpersonating } from './utils/impersonation'
import {
Collateral,
defaultFixture,
Implementation,
IMPLEMENTATION,
SLOW,
VERSION,
} from './fixtures'
import { makeDecayFn, calcErr } from './utils/rewards'
import snapshotGasCost from './utils/snapshotGasCost'
import { cartesianProduct } from './utils/cases'
import { useEnv } from '#/utils/env'
const describeP1 = IMPLEMENTATION == Implementation.P1 ? describe : describe.skip
const describeGas =
IMPLEMENTATION == Implementation.P1 && useEnv('REPORT_GAS') ? describe.only : describe.skip
const describeExtreme =
IMPLEMENTATION == Implementation.P1 && useEnv('EXTREME') ? describe.only : describe.skip
describe(`StRSRP${IMPLEMENTATION} contract`, () => {
let owner: SignerWithAddress
let addr1: SignerWithAddress
let addr2: SignerWithAddress
let addr3: SignerWithAddress
let other: SignerWithAddress
// RSR
let rsr: ERC20Mock
// Main
let main: TestIMain
let backingManager: TestIBackingManager
let basketHandler: TestIBasketHandler
let rToken: TestIRToken
let facade: TestIFacade
let assetRegistry: IAssetRegistry
// StRSR
let stRSR: TestIStRSR
// Tokens/Assets
let token0: ERC20Mock
let token1: ERC20Mock
let token2: StaticATokenMock
let token3: CTokenMock
let collateral0: Collateral
let collateral1: Collateral
let collateral2: Collateral
let collateral3: Collateral
// Config
let config: IConfig
// Basket
let basket: Collateral[]
let basketsNeededAmts: BigNumber[]
// Quantities
let initialBal: BigNumber
let stkWithdrawalDelay: number
interface IWithdrawal {
rsrAmount: BigNumber
availableAt: BigNumber
}
// Implementation-agnostic testing interface for withdrawals
// The P1 implementation differs enough that this method of testing is highly constrained
const expectWithdrawal = async (
address: string,
index: number,
withdrawal: Partial<IWithdrawal>
) => {
if (IMPLEMENTATION == Implementation.P0) {
const stRSRP0 = <StRSRP0>await ethers.getContractAt('StRSRP0', stRSR.address)
const [account, rsrAmount, , availableAt] = await stRSRP0.withdrawals(address, index)
expect(account).to.eql(address)
if (withdrawal.rsrAmount) expect(rsrAmount.toString()).to.eql(withdrawal.rsrAmount.toString())
if (withdrawal.availableAt) {
expect(availableAt.toString()).to.eql(withdrawal.availableAt.toString())
}
} else if (IMPLEMENTATION == Implementation.P1) {
const stRSRP1 = <StRSRP1Votes>await ethers.getContractAt('StRSRP1Votes', stRSR.address)
const [draftsCurr, availableAt] = await stRSRP1.draftQueues(1, address, index)
const [draftsPrev] = index == 0 ? [0] : await stRSRP1.draftQueues(1, address, index - 1)
const drafts = draftsCurr.sub(draftsPrev)
if (withdrawal.rsrAmount) {
const rsrAmount = fp(drafts).div(await stRSRP1.draftRate())
expect(rsrAmount.toString()).to.eql(withdrawal.rsrAmount.toString())
}
if (withdrawal.availableAt) {
expect(availableAt.toString()).to.eql(withdrawal.availableAt.toString())
}
} else {
throw new Error('PROTO_IMPL must be set to either `0` or `1`')
}
}
// Only used for P1, checks the length of the draft queue
const expectDraftQueue = async (era: number, account: string, expectedValue: number) => {
if (IMPLEMENTATION == Implementation.P1) {
const stRSRP1 = <StRSRP1Votes>await ethers.getContractAt('StRSRP1Votes', stRSR.address)
expect(await stRSRP1.draftQueueLen(era, account)).to.equal(expectedValue)
} else return
}
beforeEach(async () => {
;[owner, addr1, addr2, addr3, other] = await ethers.getSigners()
// Deploy fixture
;({
rsr,
stRSR,
basket,
basketsNeededAmts,
config,
main,
backingManager,
basketHandler,
rToken,
facade,
assetRegistry,
} = await loadFixture(defaultFixture))
// Mint initial amounts of RSR
initialBal = bn('10000e18')
await rsr.connect(owner).mint(addr1.address, initialBal)
await rsr.connect(owner).mint(addr2.address, initialBal)
await rsr.connect(owner).mint(addr3.address, initialBal)
await rsr.connect(owner).mint(owner.address, initialBal)
// Get assets and tokens
;[collateral0, collateral1, collateral2, collateral3] = basket
token0 = <ERC20Mock>await ethers.getContractAt('ERC20Mock', await collateral0.erc20())
token1 = <ERC20Mock>await ethers.getContractAt('ERC20Mock', await collateral1.erc20())
token2 = <StaticATokenMock>(
await ethers.getContractAt('StaticATokenMock', await collateral2.erc20())
)
token3 = <CTokenMock>await ethers.getContractAt('CTokenMock', await collateral3.erc20())
})
describe('Deployment #fast', () => {
it('Should setup initial addresses and values correctly', async () => {
expect(await rsr.balanceOf(stRSR.address)).to.equal(0)
expect(await stRSR.balanceOf(owner.address)).to.equal(0)
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
expect(await stRSR.balanceOf(addr2.address)).to.equal(0)
// ERC20
expect(await stRSR.name()).to.equal('rtknRSR Token')
expect(await stRSR.symbol()).to.equal('rtknRSR')
expect(await stRSR.decimals()).to.equal(18)
expect(await stRSR.totalSupply()).to.equal(0)
expect(await stRSR.exchangeRate()).to.equal(fp('1'))
expect(await stRSR.unstakingDelay()).to.equal(config.unstakingDelay)
expect(await stRSR.rewardRatio()).to.equal(config.rewardRatio)
})
it('Should setup the DomainSeparator for Permit correctly', async () => {
const chainId = await getChainId(hre)
const _name = await stRSR.name()
const verifyingContract = stRSR.address
expect(await stRSR.DOMAIN_SEPARATOR()).to.equal(
await ethers.utils._TypedDataEncoder.hashDomain({
name: _name,
version: VERSION,
chainId,
verifyingContract,
})
)
})
it('Should perform validations on init', async () => {
let StRSRFactory: ContractFactory = await ethers.getContractFactory('StRSRP0')
let newStRSR: TestIStRSR = <TestIStRSR>await StRSRFactory.deploy()
if (IMPLEMENTATION == Implementation.P1) {
// Create a new StRSR
StRSRFactory = await ethers.getContractFactory('StRSRP1Votes')
newStRSR = <TestIStRSR>await StRSRFactory.deploy()
newStRSR = <TestIStRSR>await upgrades.deployProxy(StRSRFactory, [], {
kind: 'uups',
})
}
await expect(
newStRSR.init(
main.address,
'',
'rtknRSR',
config.unstakingDelay,
config.rewardRatio,
config.withdrawalLeak
)
).to.be.reverted
await expect(
newStRSR.init(
main.address,
'rtknRSR Token',
'',
config.unstakingDelay,
config.rewardRatio,
config.withdrawalLeak
)
).to.be.reverted
})
})
describe('Configuration / State #fast', () => {
it('Should allow to update unstakingDelay if Owner and perform validations', async () => {
// Setup a new value
const newUnstakingDelay: BigNumber = ONE_PERIOD.mul(2).add(1000)
await expect(stRSR.connect(owner).setUnstakingDelay(newUnstakingDelay))
.to.emit(stRSR, 'UnstakingDelaySet')
.withArgs(config.unstakingDelay, newUnstakingDelay)
expect(await stRSR.unstakingDelay()).to.equal(newUnstakingDelay)
// Try to update again if not owner
await expect(stRSR.connect(addr1).setUnstakingDelay(bn('500'))).to.be.revertedWith(
'governance only'
)
// Cannot update with invalid unstaking delay
await expect(
stRSR.connect(owner).setUnstakingDelay(ONE_PERIOD.mul(2).sub(1))
).to.be.revertedWith('invalid unstakingDelay')
// Cannot update with zero unstaking delay
await expect(stRSR.connect(owner).setUnstakingDelay(bn(0))).to.be.revertedWith(
'invalid unstakingDelay'
)
// Cannot update with unstaking delay > max
await expect(
stRSR.connect(owner).setUnstakingDelay(MAX_UNSTAKING_DELAY + 1)
).to.be.revertedWith('invalid unstakingDelay')
})
it('Should allow to update rewardRatio if Owner and perform validations', async () => {
// Setup a new value
const newRatio: BigNumber = bn('100000')
await expect(stRSR.connect(owner).setRewardRatio(newRatio))
.to.emit(stRSR, 'RewardRatioSet')
.withArgs(config.rewardRatio, newRatio)
expect(await stRSR.rewardRatio()).to.equal(newRatio)
// Try to update again if not owner
await expect(stRSR.connect(addr1).setRewardRatio(bn('0'))).to.be.revertedWith(
'governance only'
)
// Cannot update with rewardRatio > max
await expect(stRSR.connect(owner).setRewardRatio(MAX_RATIO.add(1))).to.be.revertedWith(
'invalid rewardRatio'
)
})
it('Should allow to update withdrawalLeak if Owner and perform validations', async () => {
// Setup a new value
const newLeak: BigNumber = fp('0.1') // 10%
await expect(stRSR.connect(owner).setWithdrawalLeak(newLeak))
.to.emit(stRSR, 'WithdrawalLeakSet')
.withArgs(config.withdrawalLeak, newLeak)
expect(await stRSR.withdrawalLeak()).to.equal(newLeak)
// Try to update again if not owner
await expect(stRSR.connect(addr1).setWithdrawalLeak(bn('0'))).to.be.revertedWith(
'governance only'
)
// Cannot update with withdrawalLeak > max
await expect(stRSR.connect(owner).setWithdrawalLeak(fp('0.3').add(1))).to.be.revertedWith(
'invalid withdrawalLeak'
)
})
it('Should payout rewards before updating the reward ratio', async () => {
const startBal = await rsr.balanceOf(addr1.address)
const stakeAmt = bn('100e18')
await rsr.connect(addr1).approve(stRSR.address, stakeAmt)
await stRSR.connect(addr1).stake(stakeAmt)
// send some rewards
await rsr.connect(addr2).transfer(stRSR.address, bn('10e18'))
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1200)
await stRSR.setRewardRatio(bn('1e13'))
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1200)
await stRSR.connect(addr1).unstake(stakeAmt)
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1209600)
await stRSR.connect(addr1).withdraw(addr1.address, 1)
const endingBal = await rsr.balanceOf(addr1.address)
expect(endingBal.sub(startBal)).gt(0)
})
it('Should payout rewards when updating the reward ratio, even if frozen', async () => {
const startBal = await rsr.balanceOf(addr1.address)
const stakeAmt = bn('100e18')
await rsr.connect(addr1).approve(stRSR.address, stakeAmt)
await stRSR.connect(addr1).stake(stakeAmt)
// send some rewards
await rsr.connect(addr2).transfer(stRSR.address, bn('10e18'))
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1200)
// Freeze Main
await main.connect(owner).freezeShort()
// Set reward ratio - rewards payout
await expectEvents(stRSR.setRewardRatio(bn('1e13')), [
{
contract: stRSR,
name: 'ExchangeRateSet',
emitted: true,
},
{
contract: stRSR,
name: 'RewardsPaid',
emitted: true,
},
])
// Unfreeze Main
await main.connect(owner).unfreeze()
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1200)
await stRSR.connect(addr1).unstake(stakeAmt)
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1209600)
await stRSR.connect(addr1).withdraw(addr1.address, 1)
// Rewards paid
const endingBal = await rsr.balanceOf(addr1.address)
expect(endingBal.sub(startBal)).gt(0)
})
})
describe('Deposits/Staking', () => {
it('Should not allow to stake amount = 0', async () => {
// Perform stake
const amount: BigNumber = bn('1000e18')
const zero: BigNumber = bn(0)
// Approve transfer and stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await expect(stRSR.connect(addr1).stake(zero)).to.be.revertedWith('zero amount')
// Check deposit not registered
expect(await rsr.balanceOf(stRSR.address)).to.equal(0)
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal)
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
})
it('Should not allow to stake from the zero address', async () => {
// Perform stake
const amount: BigNumber = bn('1000e18')
if (IMPLEMENTATION == Implementation.P0) {
await whileImpersonating(ZERO_ADDRESS, async (signer) => {
await expect(stRSR.connect(signer).stake(amount)).to.be.revertedWith(
'ERC20: insufficient allowance'
)
})
} else if (IMPLEMENTATION == Implementation.P1) {
await whileImpersonating(ZERO_ADDRESS, async (signer) => {
await expect(stRSR.connect(signer).stake(amount)).to.be.revertedWith('zero address')
})
}
})
it('Should allow to stake if Main is Paused', async () => {
// Perform stake
const amount: BigNumber = bn('1000e18')
// Pause Main
await main.connect(owner).pauseTrading()
await main.connect(owner).pauseIssuance()
// Approve transfer and stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await stRSR.connect(addr1).stake(amount)
// Check deposit registered
expect(await rsr.balanceOf(stRSR.address)).to.equal(amount)
expect(await rsr.balanceOf(stRSR.address)).to.equal(amount)
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount))
expect(await stRSR.balanceOf(addr1.address)).to.equal(amount)
})
it('Should still allow to stake if frozen', async () => {
// This is crucial for governace to function
// Perform stake
const amount: BigNumber = bn('1000e18')
// Freeze Main
await main.connect(owner).freezeShort()
// Approve transfer and stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await stRSR.connect(addr1).stake(amount)
expect(await stRSR.balanceOf(addr1.address)).to.equal(amount)
})
it('Should allow to stake/deposit in RSR', async () => {
// Perform stake
const amount: BigNumber = bn('1000e18')
// Approve transfer and stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await expect(stRSR.connect(addr1).stake(amount))
.to.emit(stRSR, 'Staked')
.withArgs(1, addr1.address, amount, amount)
// Check balances and stakes
expect(await rsr.balanceOf(stRSR.address)).to.equal(amount)
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount))
expect(await stRSR.balanceOf(addr1.address)).to.equal(amount)
// Exchange rate remains steady
expect(await stRSR.exchangeRate()).to.equal(fp('1'))
})
it('Should allow multiple stakes/deposits in RSR', async () => {
// Perform stake
const amount1: BigNumber = bn('1000e18')
const amount2: BigNumber = bn('200e18')
const amount3: BigNumber = bn('3000e18')
// Approve transfer and stake twice
await rsr.connect(addr1).approve(stRSR.address, amount1.add(amount2))
await expect(stRSR.connect(addr1).stake(amount1))
.to.emit(stRSR, 'Staked')
.withArgs(1, addr1.address, amount1, amount1)
await expect(stRSR.connect(addr1).stake(amount2))
.to.emit(stRSR, 'Staked')
.withArgs(1, addr1.address, amount2, amount2)
// New stake from different account
await rsr.connect(addr2).approve(stRSR.address, amount3)
await expect(stRSR.connect(addr2).stake(amount3))
.to.emit(stRSR, 'Staked')
.withArgs(1, addr2.address, amount3, amount3)
// Check balances and stakes
expect(await rsr.balanceOf(stRSR.address)).to.equal(amount1.add(amount2).add(amount3))
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount1).sub(amount2))
expect(await stRSR.balanceOf(addr1.address)).to.equal(amount1.add(amount2))
expect(await rsr.balanceOf(addr2.address)).to.equal(initialBal.sub(amount3))
expect(await stRSR.balanceOf(addr2.address)).to.equal(amount3)
// Exchange rate remains steady
expect(await stRSR.exchangeRate()).to.equal(fp('1'))
})
})
describe('Withdrawals/Unstaking', () => {
it('Should not allow to unstake amount = 0', async () => {
const zero: BigNumber = bn(0)
// Unstake
await expect(stRSR.connect(addr1).unstake(zero)).to.be.revertedWith('zero amount')
})
it('Should not allow to unstake if not enough balance', async () => {
const amount: BigNumber = bn('1000e18')
// Unstake with no stakes/balance
await expect(stRSR.connect(addr1).unstake(amount)).to.be.revertedWith('insufficient balance')
})
it('Should not unstake if paused', async () => {
await main.connect(owner).pauseTrading()
await expect(stRSR.connect(addr1).unstake(0)).to.be.revertedWith('frozen or trading paused')
})
it('Should not unstake if frozen', async () => {
await main.connect(owner).freezeShort()
await expect(stRSR.connect(addr1).unstake(0)).to.be.revertedWith('frozen or trading paused')
})
it('Should emit UnstakingStarted event with draftEra -- regression test 01/18/2024', async () => {
const amount: BigNumber = bn('1000e18')
// Stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await stRSR.connect(addr1).stake(amount)
// Seize half the RSR, bumping the draftEra because the withdrawal queue is empty
await whileImpersonating(backingManager.address, async (signer) => {
await stRSR.connect(signer).seizeRSR(amount.div(2))
})
// Unstake
await expect(stRSR.connect(addr1).unstake(amount))
.emit(stRSR, 'UnstakingStarted')
.withArgs(0, 2, addr1.address, amount.div(2), amount, anyValue)
})
it('Should create Pending withdrawal when unstaking', async () => {
const amount: BigNumber = bn('1000e18')
// Stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await stRSR.connect(addr1).stake(amount)
const availableAt = (await getLatestBlockTimestamp()) + config.unstakingDelay.toNumber() + 1
// Set next block timestamp - for deterministic result
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1)
// Unstake
await expect(stRSR.connect(addr1).unstake(amount))
.emit(stRSR, 'UnstakingStarted')
.withArgs(0, 1, addr1.address, amount, amount, availableAt)
// Check withdrawal properly registered
await expectWithdrawal(addr1.address, 0, { rsrAmount: amount })
// Check balances and stakes
expect(await rsr.balanceOf(stRSR.address)).to.equal(amount)
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount))
// All staked funds withdrawn upfront
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
expect(await stRSR.totalSupply()).to.equal(0)
// Exchange rate remains steady
expect(await stRSR.exchangeRate()).to.equal(fp('1'))
})
it('Should allow multiple unstakes/withdrawals in RSR', async () => {
// Perform stake
const amount1: BigNumber = bn('1e18')
const amount2: BigNumber = bn('2e18')
const amount3: BigNumber = bn('3e18')
// Approve transfers
await rsr.connect(addr1).approve(stRSR.address, amount1.add(amount2))
await rsr.connect(addr2).approve(stRSR.address, amount3)
// Stake
await stRSR.connect(addr1).stake(amount1)
await stRSR.connect(addr1).stake(amount2)
await stRSR.connect(addr2).stake(amount3)
let availableAt = (await getLatestBlockTimestamp()) + config.unstakingDelay.toNumber() + 1
// Set next block timestamp - for deterministic result
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1)
// Unstake - Create withdrawal
await expect(stRSR.connect(addr1).unstake(amount1))
.emit(stRSR, 'UnstakingStarted')
.withArgs(0, 1, addr1.address, amount1, amount1, availableAt)
await expectWithdrawal(addr1.address, 0, { rsrAmount: amount1 })
// Check draftQueueLen
await expectDraftQueue(1, addr1.address, 1)
// All staked funds withdrawn upfront
expect(await stRSR.balanceOf(addr1.address)).to.equal(amount2)
availableAt = (await getLatestBlockTimestamp()) + config.unstakingDelay.toNumber() + 1
// Set next block timestamp - for deterministic result
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1)
// Unstake again
await expect(stRSR.connect(addr1).unstake(amount2))
.emit(stRSR, 'UnstakingStarted')
.withArgs(1, 1, addr1.address, amount2, amount2, availableAt)
await expectWithdrawal(addr1.address, 1, { rsrAmount: amount2 })
await expectDraftQueue(1, addr1.address, 2)
// All staked funds withdrawn upfront
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
availableAt = (await getLatestBlockTimestamp()) + config.unstakingDelay.toNumber() + 1
// Set next block timestamp - for deterministic result
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1)
// Unstake again with different user
await expect(stRSR.connect(addr2).unstake(amount3))
.emit(stRSR, 'UnstakingStarted')
.withArgs(0, 1, addr2.address, amount3, amount3, availableAt)
await expectWithdrawal(addr2.address, 0, { rsrAmount: amount3 })
await expectDraftQueue(1, addr1.address, 2)
await expectDraftQueue(1, addr2.address, 1)
// All staked funds withdrawn upfront
expect(await stRSR.balanceOf(addr2.address)).to.equal(0)
// Exchange rate remains steady
expect(await stRSR.exchangeRate()).to.equal(fp('1'))
})
it('Should allow cancelling unstaking', async () => {
const amount: BigNumber = bn('1000e18')
// Stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await stRSR.connect(addr1).stake(amount)
const availableAt = (await getLatestBlockTimestamp()) + config.unstakingDelay.toNumber() + 1
// Set next block timestamp - for deterministic result
await setNextBlockTimestamp((await getLatestBlockTimestamp()) + 1)
// Unstake
await expect(stRSR.connect(addr1).unstake(amount))
.emit(stRSR, 'UnstakingStarted')
.withArgs(0, 1, addr1.address, amount, amount, availableAt)
// Check withdrawal properly registered
await expectWithdrawal(addr1.address, 0, { rsrAmount: amount })
// Check balances and stakes
expect(await rsr.balanceOf(stRSR.address)).to.equal(amount)
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount))
// All staked funds withdrawn upfront
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
expect(await stRSR.totalSupply()).to.equal(0)
// Exchange rate remains steady
expect(await stRSR.exchangeRate()).to.equal(fp('1'))
// Cancelling the unstake with invalid index does nothing
await expect(stRSR.connect(addr1).cancelUnstake(0)).to.not.emit(stRSR, 'UnstakingCancelled')
await expect(stRSR.connect(addr1).cancelUnstake(2)).to.be.revertedWith('index out-of-bounds')
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
expect(await stRSR.totalSupply()).to.equal(0)
// Let's cancel the unstake
await expect(stRSR.connect(addr1).cancelUnstake(1)).to.emit(stRSR, 'UnstakingCancelled')
// Check balances and stakes
expect(await stRSR.balanceOf(addr1.address)).to.equal(amount)
expect(await stRSR.totalSupply()).to.equal(amount)
expect(await rsr.balanceOf(stRSR.address)).to.equal(amount) // RSR is still in the contract
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount)) // RSR wasn't returned
})
it('Should not allow to cancel unstake if frozen', async () => {
const amount: BigNumber = bn('1000e18')
// Stake
await rsr.connect(addr1).approve(stRSR.address, amount)
await stRSR.connect(addr1).stake(amount)
// Unstake
await stRSR.connect(addr1).unstake(amount)
// Freeze Main
await main.connect(owner).freezeShort()
// Attempt to cancel unstake
await expect(stRSR.connect(addr1).cancelUnstake(1)).to.be.revertedWith('frozen')
})
describe('Withdrawal Leak', () => {
const withdrawalLeak = fp('0.1') // 10%
const stake = bn('1000e18')
beforeEach(async () => {
stkWithdrawalDelay = bn(await stRSR.unstakingDelay()).toNumber()
// Stake
await rsr.connect(addr1).approve(stRSR.address, stake)
await stRSR.connect(addr1).stake(stake)
// Set Withdrawal Leak
await expect(stRSR.connect(owner).setWithdrawalLeak(withdrawalLeak))
.to.emit(stRSR, 'WithdrawalLeakSet')
.withArgs(config.withdrawalLeak, withdrawalLeak)
})
it('Should refresh above withdrawal leak only', async () => {
const withdrawal = stake.mul(withdrawalLeak).div(fp('1'))
await stRSR.connect(addr1).unstake(withdrawal)
await stRSR.connect(addr1).unstake(1)
await stRSR.connect(addr1).unstake(1)
// Move forward past stakingWithdrawalDelaylay
await advanceToTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)
let lastRefresh = await assetRegistry.lastRefresh()
// Should not refresh
await stRSR.withdraw(addr1.address, 1)
expect(await assetRegistry.lastRefresh()).to.eq(lastRefresh)
// Should refresh
await stRSR.withdraw(addr1.address, 2)
expect(await assetRegistry.lastRefresh()).to.be.gt(lastRefresh)
lastRefresh = await assetRegistry.lastRefresh()
// Should not refresh
await stRSR.withdraw(addr1.address, 3)
expect(await assetRegistry.lastRefresh()).to.eq(lastRefresh)
})
it('Should prevent unstaking', async () => {
const withdrawal = stake.mul(withdrawalLeak).div(fp('1')).add(1)
await stRSR.connect(addr1).unstake(withdrawal)
// Move forward past stakingWithdrawalDelaylay
await advanceToTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)
// Depeg collateral
await setOraclePrice(collateral1.address, bn('0.5e8'))
await expect(stRSR.withdraw(addr1.address, 1)).to.be.revertedWith('RToken readying')
})
})
context('With deposits and withdrawals', () => {
let amount1: BigNumber
let amount2: BigNumber
let amount3: BigNumber
beforeEach(async () => {
stkWithdrawalDelay = bn(await stRSR.unstakingDelay()).toNumber()
// Perform stake
amount1 = bn('1e18')
amount2 = bn('2e18')
amount3 = bn('3e18')
// Approve transfers
await rsr.connect(addr1).approve(stRSR.address, amount1)
await rsr.connect(addr2).approve(stRSR.address, amount2.add(amount3))
// Stake
await stRSR.connect(addr1).stake(amount1)
await stRSR.connect(addr2).stake(amount2)
await stRSR.connect(addr2).stake(amount3)
// Unstake - Create withdrawal
await stRSR.connect(addr1).unstake(amount1)
})
it('Should revert withdraw if Main is paused', async () => {
// Get current balance for user
const prevAddr1Balance = await rsr.balanceOf(addr1.address)
// Move forward past stakingWithdrawalDelay
await setNextBlockTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)
// Pause Main
await main.connect(owner).pauseTrading()
// Withdraw
await expect(stRSR.connect(addr1).withdraw(addr1.address, 1)).to.be.revertedWith(
'frozen or trading paused'
)
// If unpaused should withdraw OK
await main.connect(owner).unpauseTrading()
// Withdraw
await stRSR.connect(addr1).withdraw(addr1.address, 1)
// Withdrawal was completed
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(prevAddr1Balance.add(amount1))
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
})
it('Should revert withdraw if Main is frozen', async () => {
// Get current balance for user
const prevAddr1Balance = await rsr.balanceOf(addr1.address)
// Move forward past stakingWithdrawalDelay
await setNextBlockTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)
// Freeze Main
await main.connect(owner).freezeShort()
// Withdraw
await expect(stRSR.connect(addr1).withdraw(addr1.address, 1)).to.be.revertedWith(
'frozen or trading paused'
)
// If unpaused should withdraw OK
await main.connect(owner).unfreeze()
// Withdraw
await stRSR.connect(addr1).withdraw(addr1.address, 1)
// Withdrawal was completed
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(prevAddr1Balance.add(amount1))
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
})
it('Should not complete withdrawal if not fully collateralized', async () => {
// Need to issue some RTokens to handle fully/not fully collateralized
await token0.connect(owner).mint(addr1.address, initialBal)
await token1.connect(owner).mint(addr1.address, initialBal)
await token2.connect(owner).mint(addr1.address, initialBal)
await token3.connect(owner).mint(addr1.address, initialBal)
// Approvals
await token0.connect(addr1).approve(rToken.address, initialBal)
await token1.connect(addr1).approve(rToken.address, initialBal)
await token2.connect(addr1).approve(rToken.address, initialBal)
await token3.connect(addr1).approve(rToken.address, initialBal)
// Issue tokens
const issueAmount: BigNumber = bn('100e18')
await rToken.connect(addr1).issue(issueAmount)
// Get current balance for user
const prevAddr1Balance = await rsr.balanceOf(addr1.address)
// Move forward past stakingWithdrawalDelay
await setNextBlockTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)
const erc20s = await facade.basketTokens(rToken.address)
// Set not fully collateralized by changing basket
await basketHandler.connect(owner).setPrimeBasket([token0.address], [fp('1')])
await basketHandler.connect(owner).refreshBasket()
expect(await basketHandler.fullyCollateralized()).to.equal(false)
// Withdraw
await expect(stRSR.connect(addr1).withdraw(addr1.address, 1)).to.be.revertedWith(
'RToken readying'
)
// If fully collateralized should withdraw OK - Set back original basket
await basketHandler.connect(owner).setPrimeBasket(erc20s, basketsNeededAmts)
await basketHandler.connect(owner).refreshBasket()
expect(await basketHandler.fullyCollateralized()).to.equal(true)
// Withdraw
await stRSR.connect(addr1).withdraw(addr1.address, 1)
// Withdrawal completed
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(prevAddr1Balance.add(amount1))
// All staked funds withdrawn upfront
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
})
it('Should not complete withdrawal if IFFY or DISABLED', async () => {
// Move forward past stakingWithdrawalDelay
await setNextBlockTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)
// Set Token1 to default - 50% price reduction and mark default as probable
await setOraclePrice(collateral1.address, bn('0.5e8'))
await collateral1.refresh()
expect(await basketHandler.status()).to.equal(CollateralStatus.IFFY)
expect(await basketHandler.fullyCollateralized()).to.equal(true)
// Attempt to Withdraw
await expect(stRSR.connect(addr1).withdraw(addr1.address, 1)).to.be.revertedWith(
'RToken readying'
)
// Nothing completed
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount1))
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
// Move past DELAY_UNTIL_DEFAULT
await setNextBlockTimestamp(
(await collateral1.delayUntilDefault()) + (await getLatestBlockTimestamp())
)
// Still can't withdraw
await collateral1.refresh()
expect(await basketHandler.status()).to.equal(CollateralStatus.DISABLED)
expect(await basketHandler.fullyCollateralized()).to.equal(true)
// Attempt to Withdraw
await expect(stRSR.connect(addr1).withdraw(addr1.address, 1)).to.be.revertedWith(
'RToken readying'
)
})
it('Should not withdraw before stakingWithdrawalDelay', async () => {
// Withdraw
await expect(stRSR.connect(addr1).withdraw(addr1.address, 1)).to.be.revertedWith(
'withdrawal unavailable'
)
// Nothing completed so far
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount1))
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
// Withdraw after certain time (still before stakingWithdrawalDelay)
await setNextBlockTimestamp(
Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay / 2
)
await expect(stRSR.connect(addr1).withdraw(addr1.address, 1)).to.be.revertedWith(
'withdrawal unavailable'
)
// Nothing completed still
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(addr1.address)).to.equal(initialBal.sub(amount1))
expect(await stRSR.balanceOf(addr1.address)).to.equal(0)
})
it('Should not withdraw if firstId >= endId', async () => {
const prevAddr1Balance = await rsr.balanceOf(addr1.address)
await setNextBlockTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)
// Withdraw
await stRSR.connect(addr1).withdraw(addr1.address, 1)
// Withdrawal was completed
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(prevAddr1Balance.add(amount1))
// withdraw with same ID, nothing happens
await stRSR.connect(addr1).withdraw(addr1.address, 1)
// Nothing changed since second withdrawal
expect(await stRSR.totalSupply()).to.equal(amount2.add(amount3))
expect(await rsr.balanceOf(stRSR.address)).to.equal(await stRSR.totalSupply())
expect(await rsr.balanceOf(addr1.address)).to.equal(prevAddr1Balance.add(amount1))
})
it('Should withdraw after stakingWithdrawalDelay', async () => {
// Get current balance for user
const prevAddr1Balance = await rsr.balanceOf(addr1.address)
// Move forward past stakingWithdrawalDelay
await setNextBlockTimestamp(Number(await getLatestBlockTimestamp()) + stkWithdrawalDelay)