-
Notifications
You must be signed in to change notification settings - Fork 0
/
pool.py
4316 lines (3653 loc) · 126 KB
/
pool.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
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 smartpy as sp
Constants = sp.import_script_from_url("file:common/constants.py")
Token = sp.import_script_from_url("file:token.py")
################################################################
################################################################
# STATE MACHINE STATES
################################################################
################################################################
IDLE = 0
WAITING_UPDATE_BALANCE = 1
WAITING_REDEEM = 2
WAITING_DEPOSIT = 3
################################################################
################################################################
# CONTRACT
################################################################
################################################################
Addresses = sp.import_script_from_url("file:./test-helpers/addresses.py")
class PoolContract(Token.FA12):
def __init__(
self,
# The address of the token contract which will be deposited.
tokenAddress = Addresses.TOKEN_ADDRESS,
# The governor of the pool.
governorAddress = Addresses.GOVERNOR_ADDRESS,
# The address of the stability fund.
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
# The interest rate.
interestRate = sp.nat(0),
# The last time the interest rate was updated.
lastInterestCompoundTime = sp.timestamp(0),
# The initial token balance.
underlyingBalance = sp.nat(0),
# The initial state of the state machine.
state = IDLE,
# State machine states - exposed for testing.
savedState_tokensToRedeem = sp.none,
savedState_redeemer = sp.none,
savedState_tokensToDeposit = sp.none,
savedState_depositor = sp.none,
):
token_id = sp.nat(0)
token_metadata = sp.map(
l = {
"name": sp.bytes('0x496e7465726573742042656172696e67206b555344'), # Interest Bearing kUSD
"decimals": sp.bytes('0x3138'), # 18
"symbol": sp.bytes('0x69626b555344'), # ibkUSD
"icon": sp.bytes('0x2068747470733a2f2f6b6f6c696272692d646174612e73332e616d617a6f6e6177732e636f6d2f6c6f676f2e706e67') # https://kolibri-data.s3.amazonaws.com/logo.png
},
tkey = sp.TString,
tvalue = sp.TBytes
)
token_entry = (token_id, token_metadata)
token_metadata = sp.big_map(
l = {
token_id: token_entry,
},
tkey = sp.TNat,
tvalue = sp.TPair(sp.TNat, sp.TMap(sp.TString, sp.TBytes))
)
metadata_data = sp.bytes_of_string('{ "name": "Interest Bearing kUSD", "description": "Interest Bearing kUSD", "authors": ["Hover Labs <[email protected]>"], "homepage": "https://kolibri.finance", "interfaces": [ "TZIP-007-2021-01-29"] }')
metadata = sp.big_map(
l = {
"": sp.bytes('0x74657a6f732d73746f726167653a64617461'), # "tezos-storage:data"
"data": metadata_data
},
tkey = sp.TString,
tvalue = sp.TBytes
)
self.exception_optimization_level = "debug-message"
self.init(
# Parent class fields
balances = sp.big_map(tvalue = sp.TRecord(approvals = sp.TMap(sp.TAddress, sp.TNat), balance = sp.TNat)),
totalSupply = 0,
# Metadata
metadata = metadata,
token_metadata = token_metadata,
# Addresses
governorAddress = governorAddress,
stabilityFundAddress = stabilityFundAddress,
tokenAddress = tokenAddress,
# Configuration
interestRate = interestRate,
# Internal State
underlyingBalance = underlyingBalance,
lastInterestCompoundTime = lastInterestCompoundTime,
# State machinge
state = state,
savedState_tokensToRedeem = savedState_tokensToRedeem, # Amount of tokens to redeem, populated when state = WAITING_REDEEM
savedState_redeemer = savedState_redeemer, # Account redeeming tokens, populated when state = WAITING_REDEEM
savedState_tokensToDeposit = savedState_tokensToDeposit, # Amount of tokens to deposit, populated when state = WAITING_DEPOSIT
savedState_depositor = savedState_depositor, # Account depositing the tokens, populated when state = WAITING_DEPOSIT
)
################################################################
# Liquidity Provider Tokens
################################################################
# Deposit a number of tokens and receive LP tokens.
@sp.entry_point
def deposit(self, tokensToDeposit):
sp.set_type(tokensToDeposit, sp.TNat)
# Validate state
sp.verify(self.data.state == IDLE, "bad state")
# Save state
self.data.state = WAITING_DEPOSIT
self.data.savedState_tokensToDeposit = sp.some(tokensToDeposit)
self.data.savedState_depositor = sp.some(sp.sender)
# Call token contract to update balance.
param = (sp.self_address, sp.self_entry_point(entry_point = 'deposit_callback'))
contractHandle = sp.contract(
sp.TPair(sp.TAddress, sp.TContract(sp.TNat)),
self.data.tokenAddress,
"getBalance",
).open_some()
sp.transfer(param, sp.mutez(0), contractHandle)
# Private callback for redeem.
@sp.entry_point
def deposit_callback(self, updatedBalance):
sp.set_type(updatedBalance, sp.TNat)
# Validate sender
sp.verify(sp.sender == self.data.tokenAddress, "bad sender")
# Validate state
sp.verify(self.data.state == WAITING_DEPOSIT, "bad state")
# Calculate the newly accrued interest.
accruedInterest = self.accrueInterest(sp.unit)
# Calculate the tokens to issue.
tokensToDeposit = sp.local('tokensToDeposit', self.data.savedState_tokensToDeposit.open_some())
newTokens = sp.local('newTokens', tokensToDeposit.value * Constants.PRECISION)
sp.if self.data.totalSupply != sp.nat(0):
newUnderlyingBalance = sp.local('newUnderlyingBalance', updatedBalance + accruedInterest + tokensToDeposit.value)
fractionOfPoolOwnership = sp.local('fractionOfPoolOwnership', (tokensToDeposit.value * Constants.PRECISION) / newUnderlyingBalance.value)
newTokens.value = ((fractionOfPoolOwnership.value * self.data.totalSupply) / (sp.as_nat(Constants.PRECISION - fractionOfPoolOwnership.value)))
# Debit underlying balance by the amount of tokens that will be sent
self.data.underlyingBalance = updatedBalance + accruedInterest + tokensToDeposit.value
# Transfer tokens to this contract.
depositor = sp.local('depositor', self.data.savedState_depositor.open_some())
tokenTransferParam = sp.record(
from_ = depositor.value,
to_ = sp.self_address,
value = tokensToDeposit.value
)
transferHandle = sp.contract(
sp.TRecord(from_ = sp.TAddress, to_ = sp.TAddress, value = sp.TNat).layout(("from_ as from", ("to_ as to", "value"))),
self.data.tokenAddress,
"transfer"
).open_some()
sp.transfer(tokenTransferParam, sp.mutez(0), transferHandle)
# Mint tokens to the depositor
tokenMintParam = sp.record(
address = depositor.value,
value = newTokens.value
)
mintHandle = sp.contract(
sp.TRecord(address = sp.TAddress, value = sp.TNat).layout(("address", "value")),
sp.self_address,
entry_point = 'mint',
).open_some()
sp.transfer(tokenMintParam, sp.mutez(0), mintHandle)
# Reset state
self.data.state = IDLE
self.data.savedState_tokensToDeposit = sp.none
self.data.savedState_depositor = sp.none
# Redeem a number of LP tokens for the underlying asset.
@sp.entry_point
def redeem(self, tokensToRedeem):
sp.set_type(tokensToRedeem, sp.TNat)
# Validate state
sp.verify(self.data.state == IDLE, "bad state")
# Save state
self.data.state = WAITING_REDEEM
self.data.savedState_tokensToRedeem = sp.some(tokensToRedeem)
self.data.savedState_redeemer = sp.some(sp.sender)
# Call token contract to update balance.
param = (sp.self_address, sp.self_entry_point(entry_point = 'redeem_callback'))
contractHandle = sp.contract(
sp.TPair(sp.TAddress, sp.TContract(sp.TNat)),
self.data.tokenAddress,
"getBalance",
).open_some()
sp.transfer(param, sp.mutez(0), contractHandle)
# Private callback for redeem.
@sp.entry_point
def redeem_callback(self, updatedBalance):
sp.set_type(updatedBalance, sp.TNat)
# Validate sender
sp.verify(sp.sender == self.data.tokenAddress, "bad sender")
# Validate state
sp.verify(self.data.state == WAITING_REDEEM, "bad state")
# Calculate the newly accrued interest.
accruedInterest = self.accrueInterest(sp.unit)
# Calculate tokens to receive.
tokensToRedeem = sp.local('tokensToRedeem', self.data.savedState_tokensToRedeem.open_some())
fractionOfPoolOwnership = sp.local('fractionOfPoolOwnership', (tokensToRedeem.value * Constants.PRECISION) // self.data.totalSupply)
tokensToReceive = sp.local('tokensToReceive', (fractionOfPoolOwnership.value * (updatedBalance + accruedInterest)) / Constants.PRECISION)
# Debit underlying balance by the amount of tokens that will be sent
# TODO(keefertaylor): Test.
self.data.underlyingBalance = sp.as_nat(updatedBalance + accruedInterest - tokensToReceive.value)
# Burn the tokens being redeemed.
redeemer = sp.local('redeemer', self.data.savedState_redeemer.open_some())
tokenBurnParam = sp.record(
address = redeemer.value,
value = tokensToRedeem.value
)
burnHandle = sp.contract(
sp.TRecord(address = sp.TAddress, value = sp.TNat).layout(("address", "value")),
sp.self_address,
entry_point = 'burn',
).open_some()
sp.transfer(tokenBurnParam, sp.mutez(0), burnHandle)
# Transfer tokens to the owner.
tokenTransferParam = sp.record(
from_ = sp.self_address,
to_ = redeemer.value,
value = tokensToReceive.value
)
transferHandle = sp.contract(
sp.TRecord(from_ = sp.TAddress, to_ = sp.TAddress, value = sp.TNat).layout(("from_ as from", ("to_ as to", "value"))),
self.data.tokenAddress,
"transfer"
).open_some()
sp.transfer(tokenTransferParam, sp.mutez(0), transferHandle)
# Reset state
self.data.state = IDLE
self.data.savedState_tokensToRedeem = sp.none
self.data.savedState_redeemer = sp.none
# Unsafe way to redeem a number of LP tokens for the underlying asset.
#
# Users should prefer to call redeem.
#
# This entry point does *not* accrue interest for the underlying balance. Using this entrypoint
# means that the calling LP will forego some of their rewards. This entry point is useful in the
# case that the stability fund will not or cannot pay rewards and LPs want to extract their collateral.
@sp.entry_point
def UNSAFE_redeem(self, tokensToRedeem):
sp.set_type(tokensToRedeem, sp.TNat)
# Validate state
sp.verify(self.data.state == IDLE, "bad state")
# Calculate tokens to receive.
fractionOfPoolOwnership = sp.local('fractionOfPoolOwnership', (tokensToRedeem * Constants.PRECISION) / self.data.totalSupply)
tokensToReceive = sp.local('tokensToReceive', (fractionOfPoolOwnership.value * self.data.underlyingBalance) / Constants.PRECISION)
# Debit underlying balance by the amount of tokens that will be sent
self.data.underlyingBalance = sp.as_nat(self.data.underlyingBalance - tokensToReceive.value)
# Burn the tokens being redeemed.
tokenBurnParam = sp.record(
address = sp.sender,
value = tokensToRedeem
)
burnHandle = sp.contract(
sp.TRecord(address = sp.TAddress, value = sp.TNat).layout(("address", "value")),
sp.self_address,
entry_point = 'burn',
).open_some()
sp.transfer(tokenBurnParam, sp.mutez(0), burnHandle)
# Transfer tokens to the owner.
tokenTransferParam = sp.record(
from_ = sp.self_address,
to_ = sp.sender,
value = tokensToReceive.value
)
transferHandle = sp.contract(
sp.TRecord(from_ = sp.TAddress, to_ = sp.TAddress, value = sp.TNat).layout(("from_ as from", ("to_ as to", "value"))),
self.data.tokenAddress,
"transfer"
).open_some()
sp.transfer(tokenTransferParam, sp.mutez(0), transferHandle)
################################################################
# State Management
################################################################
# Accrue interest.
# This entrypoint is only useful if you require interest to be pulled from
# the stability fund before you can redeem LP tokens.
#
# Because of BFS call ordering, when `redeem` is called, transaction will occur
# in the following order:
# 1) tokens that are redeemed for are transferred to redeemer
# 2) tokens accrued in interest are transferred to the pool from the stability fund
#
#
# If the tokens transferred to the redeemer are greater that the tokens currently in the pool,
# the call will fail. Users should call `manuallyAccrueInterest` first, then `redeem` in this case.
#
# If / when DFS call orders are adopted, this method is no longer needed.
@sp.entry_point
def manuallyAccrueInterest(self, unit):
sp.set_type(unit, sp.TUnit)
self.data.underlyingBalance = self.data.underlyingBalance + self.accrueInterest(sp.unit)
################################################################
# Governance
################################################################
# Update the governor address.
@sp.entry_point
def updateGovernorAddress(self, newGovernorAddress):
sp.set_type(newGovernorAddress, sp.TAddress)
sp.verify(sp.sender == self.data.governorAddress, "not governor")
self.data.governorAddress = newGovernorAddress
# Update the stability fund address.
@sp.entry_point
def updateStabilityFundAddress(self, newStabilityFundAddress):
sp.set_type(newStabilityFundAddress, sp.TAddress)
sp.verify(sp.sender == self.data.governorAddress, "not governor")
self.data.stabilityFundAddress = newStabilityFundAddress
# Update the interest rate.
@sp.entry_point
def updateInterestRate(self, newInterestRate):
sp.set_type(newInterestRate, sp.TNat)
sp.verify(sp.sender == self.data.governorAddress, "not governor")
# Accrue interest.
accruedInterest = self.accrueInterest(sp.unit)
self.data.underlyingBalance = self.data.underlyingBalance + accruedInterest
# Adjust rate
self.data.interestRate = newInterestRate
# Update contract metadata
@sp.entry_point
def updateContractMetadata(self, params):
sp.set_type(params, sp.TPair(sp.TString, sp.TBytes))
sp.verify(sp.sender == self.data.governorAddress, "not governor")
key = sp.fst(params)
value = sp.snd(params)
self.data.metadata[key] = value
# Update token metadata
@sp.entry_point
def updateTokenMetadata(self, params):
sp.set_type(params, sp.TPair(sp.TNat, sp.TMap(sp.TString, sp.TBytes)))
sp.verify(sp.sender == self.data.governorAddress, "not governor")
self.data.token_metadata[0] = params
# Rescue any XTZ that may have been sent to the contract.
@sp.entry_point
def rescueXTZ(self, params):
sp.set_type(params, sp.TRecord(destinationAddress = sp.TAddress).layout("destinationAddress"))
# Verify the requester is the governor.
sp.verify(sp.sender == self.data.governorAddress, "NOT_GOVERNOR")
sp.send(params.destinationAddress, sp.balance)
################################################################
# Helpers
################################################################
# Helper function to:
# - Calculate elapsed periods
# - Accrue interest using linear approximation
# - Request funds
#
# This functionality is split out for re-use and for testing.
#
# Param: unit
# Return: The newly accrued interest
@sp.sub_entry_point
def accrueInterest(self, unit):
sp.set_type(unit, sp.TUnit)
# Calculate the number of periods that elapsed.
timeDeltaSeconds = sp.as_nat(sp.now - self.data.lastInterestCompoundTime)
numPeriods = sp.local('numPeriods', timeDeltaSeconds // Constants.SECONDS_PER_COMPOUND)
# Update the last updated time.
self.data.lastInterestCompoundTime = self.data.lastInterestCompoundTime.add_seconds(sp.to_int(numPeriods.value * Constants.SECONDS_PER_COMPOUND))
# Determine the new amount of interest accrued.
newUnderlyingBalance = sp.local(
'newTotalUnderlying',
self.data.underlyingBalance * (Constants.PRECISION + (numPeriods.value * self.data.interestRate)) // Constants.PRECISION
)
accruedInterest = sp.local('accruedInterest', sp.as_nat(newUnderlyingBalance.value - self.data.underlyingBalance))
# Transfer in accrued tokens
stabilityFundHandle = sp.contract(
sp.TNat,
self.data.stabilityFundAddress,
'accrueInterest'
).open_some()
sp.transfer(accruedInterest.value, sp.mutez(0), stabilityFundHandle)
# Return the number of newly accrued tokens.
sp.result(accruedInterest.value)
################################################################
################################################################
# TESTS
################################################################
################################################################
# Only run tests if this file is main.
if __name__ == "__main__":
Dummy = sp.import_script_from_url("file:./test-helpers/dummy.py")
FA12 = sp.import_script_from_url("file:./test-helpers/fa12.py")
FakeDexter = sp.import_script_from_url("file:./test-helpers/fake-dexter-pool.py")
FakeOven = sp.import_script_from_url("file:./test-helpers/fake-oven.py")
FakeOvenRegistry = sp.import_script_from_url("file:./test-helpers/fake-oven-registry.py")
StabilityFund = sp.import_script_from_url("file:./stability-fund.py")
################################################################
# Test Helpers
################################################################
# Tests sub_entry_points
# See: https://t.me/SmartPy_io/9155
class Tester(sp.Contract):
def __init__(
self,
contractEntrypoint,
interestRate,
lastInterestCompoundTime,
stabilityFundAddress,
underlyingBalance
):
self.contractEntrypoint = contractEntrypoint
self.init(
result = sp.none,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = stabilityFundAddress,
underlyingBalance = underlyingBalance,
)
@sp.entry_point
def testContractEntryPoint(self, params):
self.data.result = sp.some(self.contractEntrypoint(params))
################################################################
# accrueInterest
################################################################
@sp.add_test(name="accrueInterest - updates lastInterestCompoundTime for one period")
def test():
# GIVEN a Pool contract
scenario = sp.test_scenario()
interestRate = sp.nat(0)
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = sp.nat(0)
)
scenario += tester
# WHEN interest is accrued after 1 compound period.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(Constants.SECONDS_PER_COMPOUND)
)
# THEN the last interest update time is updated.
scenario.verify(tester.data.lastInterestCompoundTime == sp.timestamp(Constants.SECONDS_PER_COMPOUND))
@sp.add_test(name="accrueInterest - updates lastInterestCompoundTime for two periods")
def test():
# GIVEN a Pool contract
scenario = sp.test_scenario()
interestRate = sp.nat(0)
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = sp.nat(0)
)
scenario += tester
# WHEN interest is accrued after 2 compound periods.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(Constants.SECONDS_PER_COMPOUND * 2)
)
# THEN the last interest update time is updated.
scenario.verify(tester.data.lastInterestCompoundTime == sp.timestamp(Constants.SECONDS_PER_COMPOUND * 2))
@sp.add_test(name="accrueInterest - updates lastInterestCompoundTime for one period with nonzero start")
def test():
# GIVEN a Pool contract with a previous interest update time.
scenario = sp.test_scenario()
interestRate = sp.nat(0)
lastInterestCompoundTime = sp.timestamp(Constants.SECONDS_PER_COMPOUND)
pool = PoolContract(
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = sp.nat(0)
)
scenario += tester
# WHEN interest is accrued after 1 compound period.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(Constants.SECONDS_PER_COMPOUND * 2)
)
# THEN the last interest update time is updated.
scenario.verify(tester.data.lastInterestCompoundTime == sp.timestamp(Constants.SECONDS_PER_COMPOUND * 2))
@sp.add_test(name="accrueInterest - updates lastInterestCompoundTime by flooring partial periods")
def test():
# GIVEN a Pool contract
scenario = sp.test_scenario()
interestRate = sp.nat(0)
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = sp.nat(0)
)
scenario += tester
# WHEN interest is accrued after 2.5 periods
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(150) # 2.5 periods
)
# THEN the last interest update time is floored.
scenario.verify(tester.data.lastInterestCompoundTime == sp.timestamp(Constants.SECONDS_PER_COMPOUND * 2))
@sp.add_test(name="accrueInterest - calculates accrued interest for one period")
def test():
# GIVEN a Pool contract
scenario = sp.test_scenario()
interestRate = sp.nat(100000000000000000)
initialValue = Constants.PRECISION
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = initialValue
)
scenario += tester
# WHEN interest is accrued after 1 compound period.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(Constants.SECONDS_PER_COMPOUND)
)
# THEN the the accrued interest is calculated correctly.
scenario.verify(tester.data.result.open_some() == sp.as_nat(1100000000000000000 - initialValue))
@sp.add_test(name="accrueInterest - calculates accrued interest for two periods")
def test():
# GIVEN a Pool contract
scenario = sp.test_scenario()
interestRate = sp.nat(100000000000000000)
initialValue = Constants.PRECISION
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = initialValue
)
scenario += tester
# WHEN interest is accrued after 2 compound periods.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(Constants.SECONDS_PER_COMPOUND * 2)
)
# THEN the the accrued interest is calculated correctly.
scenario.verify(tester.data.result.open_some() == sp.as_nat(1200000000000000000 - initialValue))
@sp.add_test(name="accrueInterest - calculates accrued interest for one period with nonzero start")
def test():
# GIVEN a Pool contract with a previous interest update time.
scenario = sp.test_scenario()
interestRate = sp.nat(100000000000000000)
initialValue = 1100000000000000000
lastInterestCompoundTime = sp.timestamp(Constants.SECONDS_PER_COMPOUND)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = initialValue
)
scenario += tester
# WHEN interest is accrued after 1 compound period.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(Constants.SECONDS_PER_COMPOUND * 2)
)
# THEN the the accrued interest is calculated correctly.
scenario.verify(tester.data.result.open_some() == sp.as_nat(1210000000000000000 - initialValue))
@sp.add_test(name="accrueInterest - calculates accrued interest by flooring partial periods")
def test():
# GIVEN a Pool contract
scenario = sp.test_scenario()
interestRate = sp.nat(100000000000000000)
initialValue = Constants.PRECISION
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = Addresses.STABILITY_FUND_ADDRESS,
underlyingBalance = initialValue
)
scenario += tester
# WHEN interest is accrued after 2.5 periods
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(150) # 2.5 periods
)
# THEN the the accrued interest is calculated correctly.
scenario.verify(tester.data.result.open_some() == sp.as_nat(1200000000000000000 - initialValue))
@sp.add_test(name="accrueInterest - retrieves stability fees for one period")
def test():
scenario = sp.test_scenario()
# GIVEN a token contract.
token = FA12.FA12(
admin = Addresses.ADMIN_ADDRESS
)
scenario += token
# AND a Pool contract
interestRate = sp.nat(100000000000000000)
initialValue = Constants.PRECISION
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a stability fund contract.
stabilityFund = StabilityFund.StabilityFundContract(
savingsAccountContractAddress = pool.address,
tokenContractAddress = token.address,
)
scenario += stabilityFund
# AND the stability fund has many tokens
scenario += token.mint(
sp.record(
address = stabilityFund.address,
value = 1000000 * Constants.PRECISION
)
).run(
sender = Addresses.ADMIN_ADDRESS
)
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = stabilityFund.address,
underlyingBalance = initialValue
)
scenario += tester
# AND the tester has the initial underlying balance.
scenario += token.mint(
sp.record(
address = tester.address,
value = initialValue
)
).run(
sender = Addresses.ADMIN_ADDRESS
)
# AND the stability fund is wired to the tester.
scenario += stabilityFund.setSavingsAccountContract(
tester.address
).run(
sender = Addresses.GOVERNOR_ADDRESS
)
# WHEN interest is accrued after 1 compound period.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(Constants.SECONDS_PER_COMPOUND)
)
# THEN the contract has the right number of tokens.
scenario.verify(token.data.balances[tester.address].balance == 1100000000000000000)
@sp.add_test(name="accrueInterest - retrieves stability fees for two periods")
def test():
scenario = sp.test_scenario()
# GIVEN a token contract.
token = FA12.FA12(
admin = Addresses.ADMIN_ADDRESS
)
scenario += token
# AND a Pool contract
interestRate = sp.nat(100000000000000000)
initialValue = Constants.PRECISION
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a stability fund contract.
stabilityFund = StabilityFund.StabilityFundContract(
savingsAccountContractAddress = pool.address,
tokenContractAddress = token.address,
)
scenario += stabilityFund
# AND the stability fund has many tokens
scenario += token.mint(
sp.record(
address = stabilityFund.address,
value = 1000000 * Constants.PRECISION
)
).run(
sender = Addresses.ADMIN_ADDRESS
)
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = stabilityFund.address,
underlyingBalance = initialValue
)
scenario += tester
# AND the tester has the initial underlying balance.
scenario += token.mint(
sp.record(
address = tester.address,
value = initialValue
)
).run(
sender = Addresses.ADMIN_ADDRESS
)
# AND the stability fund is wired to the tester.
scenario += stabilityFund.setSavingsAccountContract(
tester.address
).run(
sender = Addresses.GOVERNOR_ADDRESS
)
# WHEN interest is accrued after 2 compound periods.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(2 * Constants.SECONDS_PER_COMPOUND)
)
# THEN the contract has the right number of tokens.
scenario.verify(token.data.balances[tester.address].balance == 1200000000000000000)
@sp.add_test(name="accrueInterest - retrieves stability fees for one periods starting at nonzero")
def test():
scenario = sp.test_scenario()
# GIVEN a token contract.
token = FA12.FA12(
admin = Addresses.ADMIN_ADDRESS
)
scenario += token
# AND a Pool contract
interestRate = sp.nat(100000000000000000)
initialValue = sp.nat(1100000000000000000)
lastInterestCompoundTime = sp.timestamp(Constants.SECONDS_PER_COMPOUND)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a stability fund contract.
stabilityFund = StabilityFund.StabilityFundContract(
savingsAccountContractAddress = pool.address,
tokenContractAddress = token.address,
)
scenario += stabilityFund
# AND the stability fund has many tokens
scenario += token.mint(
sp.record(
address = stabilityFund.address,
value = 1000000 * Constants.PRECISION
)
).run(
sender = Addresses.ADMIN_ADDRESS
)
# AND a tester.
tester = Tester(
pool.accrueInterest,
interestRate = interestRate,
lastInterestCompoundTime = lastInterestCompoundTime,
stabilityFundAddress = stabilityFund.address,
underlyingBalance = initialValue
)
scenario += tester
# AND the tester has the initial underlying balance.
scenario += token.mint(
sp.record(
address = tester.address,
value = initialValue
)
).run(
sender = Addresses.ADMIN_ADDRESS
)
# AND the stability fund is wired to the tester.
scenario += stabilityFund.setSavingsAccountContract(
tester.address
).run(
sender = Addresses.GOVERNOR_ADDRESS
)
# WHEN interest is accrued after the second compound period.
scenario += tester.testContractEntryPoint(sp.unit).run(
now = sp.timestamp(2 * Constants.SECONDS_PER_COMPOUND)
)
# THEN the contract has the right number of tokens.
scenario.verify(token.data.balances[tester.address].balance == 1210000000000000000)
@sp.add_test(name="accrueInterest - correctly floors partial periods")
def test():
scenario = sp.test_scenario()
# GIVEN a token contract.
token = FA12.FA12(
admin = Addresses.ADMIN_ADDRESS
)
scenario += token
# AND a Pool contract
interestRate = sp.nat(100000000000000000)
initialValue = Constants.PRECISION
lastInterestCompoundTime = sp.timestamp(0)
pool = PoolContract(
interestRate = interestRate,
underlyingBalance = initialValue,
lastInterestCompoundTime = lastInterestCompoundTime
)
scenario += pool
# AND a stability fund contract.
stabilityFund = StabilityFund.StabilityFundContract(
savingsAccountContractAddress = pool.address,
tokenContractAddress = token.address,
)
scenario += stabilityFund