-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtest_fuzz.py
2687 lines (2349 loc) · 105 KB
/
test_fuzz.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 logging
import math
from collections import defaultdict
from dataclasses import dataclass
from typing import Callable, Dict, Union, Tuple, Optional, NamedTuple
from ordered_set import OrderedSet
from wake.testing import *
from wake.testing.fuzzing import *
from pytypes.core.src.hub.PWNHub import PWNHub
from pytypes.core.src.config.PWNConfig import PWNConfig
from pytypes.core.src.loan.token.PWNLOAN import PWNLOAN
from pytypes.core.src.nonce.PWNRevokedNonce import PWNRevokedNonce
from pytypes.core.lib.MultiToken.src.MultiToken import MultiToken
from pytypes.core.lib.MultiToken.src.MultiTokenCategoryRegistry import (
MultiTokenCategoryRegistry,
)
from pytypes.core.src.loan.terms.simple.loan.PWNSimpleLoan import PWNSimpleLoan
from pytypes.core.src.utilizedcredit.PWNUtilizedCredit import PWNUtilizedCredit
from pytypes.core.src.loan.terms.simple.proposal.PWNSimpleLoanProposal import (
PWNSimpleLoanProposal,
)
from pytypes.core.src.loan.terms.simple.proposal.PWNSimpleLoanElasticProposal import (
PWNSimpleLoanElasticProposal,
)
from pytypes.core.src.loan.terms.simple.proposal.PWNSimpleLoanDutchAuctionProposal import (
PWNSimpleLoanDutchAuctionProposal,
)
from pytypes.core.src.loan.terms.simple.proposal.PWNSimpleLoanSimpleProposal import (
PWNSimpleLoanSimpleProposal,
)
from pytypes.core.src.loan.terms.simple.proposal.PWNSimpleLoanElasticChainlinkProposal import (
PWNSimpleLoanElasticChainlinkProposal,
)
from pytypes.core.src.loan.terms.simple.proposal.PWNSimpleLoanListProposal import (
PWNSimpleLoanListProposal,
)
from pytypes.core.src.loan.vault.Permit import Permit as PWNPermit
from pytypes.core.src.PWNErrors import Expired
from pytypes.core.src.loan.lib.Chainlink import Chainlink
from pytypes.periphery.src.pooladapter.ERC4626Adapter import ERC4626Adapter
from pytypes.periphery.src.pooladapter.AaveAdapter import AaveAdapter, IAavePoolLike
from pytypes.periphery.src.pooladapter.CompoundAdapter import CompoundAdapter, ICometLike
from pytypes.tests.AggregatorV2V3Interface import AggregatorV2V3Interface
from pytypes.wake.interfaces.IERC1155 import IERC1155
from pytypes.wake.interfaces.IERC721 import IERC721
from pytypes.wake.interfaces.IERC20 import IERC20
from pytypes.wake.ERC1967Factory import ERC1967Factory
from pytypes.tests.ERC721Mock import ERC721Mock
from pytypes.tests.FeedRegistryInterface import FeedRegistryInterface
from pytypes.tests.MockERC4626 import MockERC4626
from .keyed_default_dict import KeyedDefaultDict
from .merkle_tree import MerkleTree
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
ACTIVE_LOAN_TAG = keccak256(b"PWN_ACTIVE_LOAN")
LOAN_PROPOSAL_TAG = keccak256(b"PWN_LOAN_PROPOSAL")
NONCE_MANAGER_TAG = keccak256(b"NONCE_MANAGER")
MAX_APR = 160_000
MIN_DURATION = 10 * 60 # 10 minutes
TOKENS: Dict[int, Dict[str, Union[IERC20, IERC721, IERC1155]]] = {
0: {
"USDC": IERC20("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"),
"USDT": IERC20("0xdac17f958d2ee523a2206206994597c13d831ec7"),
"BNB": IERC20("0xB8c77482e45F1F44dE1745F52C74426C631bDD52"),
"DAI": IERC20("0x6b175474e89094c44da98b954eedeac495271d0f"),
"WETH": IERC20("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2"),
# "STA": IERC20("0xa7DE087329BFcda5639247F96140f9DAbe3DeED1"), fee-on-transfer not supported
"LEND": IERC20("0x80fB784B7eD66730e8b1DBd9820aFD29931aab03"),
"YAMV2": IERC20("0xaba8cac6866b83ae4eec97dd07ed254282f6ad8a"),
"MKR": IERC20("0x9f8f72aa9304c8b593d555f12ef6589cc3a579a2"),
"EURS": IERC20("0xdb25f211ab05b1c97d595516f45794528a807ad8"),
"UNI": IERC20("0x1f9840a85d5af5bf1d1762f925bdaddc4201f984"),
"SHIB": IERC20("0x95ad61b0a150d79219dcf64e1e6cc01f0b64c4ce"),
"WBTC": IERC20("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599"),
"FTM": IERC20("0x4E15361FD6b4BB609Fa63C81A2be19d873717870"),
},
2: {
"BARFLIES": IERC1155("0x503AC85cFAB61a1E33DF33c8B26aE81E3c6e3ef2"),
},
}
MAX_TOKENS: Dict[Account, int] = {
TOKENS[0]["USDC"]: 5_000,
TOKENS[0]["USDT"]: 5_000,
TOKENS[0]["BNB"]: 8,
TOKENS[0]["DAI"]: 5_000,
TOKENS[0]["WETH"]: 2,
TOKENS[0]["LEND"]: 100_000,
TOKENS[0]["YAMV2"]: 100_000,
TOKENS[0]["MKR"]: 4,
TOKENS[0]["EURS"]: 5_000,
TOKENS[0]["UNI"]: 50,
TOKENS[0]["SHIB"]: 100_000_000,
TOKENS[0]["WBTC"]: 1,
TOKENS[0]["FTM"]: 7_000,
TOKENS[2]["BARFLIES"]: 100_000,
}
AAVE_POOLS: Dict[Account, IAavePoolLike] = {
TOKENS[0]["USDC"]: IAavePoolLike("0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"),
TOKENS[0]["USDT"]: IAavePoolLike("0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"),
TOKENS[0]["DAI"]: IAavePoolLike("0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"),
TOKENS[0]["WETH"]: IAavePoolLike("0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"),
TOKENS[0]["UNI"]: IAavePoolLike("0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"),
TOKENS[0]["WBTC"]: IAavePoolLike("0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2"),
}
AAVE_EXTRA_DEPOSIT = 2
COMP_POOLS: Dict[Account, ICometLike] = {
TOKENS[0]["USDC"]: ICometLike("0xc3d688B66703497DAA19211EEdff47f25384cdc3"),
TOKENS[0]["USDT"]: ICometLike("0x3Afdc9BCA9213A35503b077a6072F3D0d5AB0840"),
TOKENS[0]["WETH"]: ICometLike("0xA17581A9E3356d9A858b789D68B4d866e593aE94"),
}
COMP_EXTRA_DEPOSIT = 2
HAS_CHAINLINK_FEED: Dict[Account, bool] = defaultdict(lambda: False)
HAS_CHAINLINK_FEED[TOKENS[0]["USDC"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["USDT"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["DAI"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["WETH"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["MKR"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["UNI"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["SHIB"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["WBTC"]] = True
HAS_CHAINLINK_FEED[TOKENS[0]["FTM"]] = True
PermitInfo = NamedTuple("PermitInfo", [("name", str), ("version", Optional[str])])
PERMIT: Dict[Account, PermitInfo] = {}
PERMIT[TOKENS[0]["USDC"]] = PermitInfo(name="USD Coin", version="2")
PERMIT[TOKENS[0]["UNI"]] = PermitInfo(name="Uniswap", version=None)
FEED_REGISTRY = FeedRegistryInterface("0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf")
MAX_CHAINLINK_FEED_PRICE_AGE = 24 * 60 * 60 # 1 day
def get_decimals(token: Account):
with may_revert():
return abi.decode(token.call(abi.encode_with_signature("decimals()")), [uint])
return 0
DECIMALS: Dict[Account, int] = KeyedDefaultDict(get_decimals)
class AggregatorData(NamedTuple):
round_id: int
price: int
timestamp: int
@dataclass
class Permit:
owner: Address
spender: Address
value: uint256
nonce: uint256
deadline: uint256
def random_duration_or_date():
# min duration is 10 minutes
if random_bool():
# duration
return random_int(MIN_DURATION, 1000)
else:
return chain.blocks["pending"].timestamp + random_int(MIN_DURATION, 1000)
def random_nonce():
# small enough to introduce collisions, large enough to prevent complete exhaustion
return random_int(0, 2**12 - 1)
def random_expiration():
return chain.blocks["pending"].timestamp + random_int(0, 1000)
@dataclass
class Loan:
id: uint
credit: IERC20
collateral: Account
lender: Account
borrower: Account
fixed_interest_amount: uint
credit_amount: uint
collateral_amount: uint
collateral_category: MultiToken.Category
collateral_id: uint
interest_apr: uint
start_timestamp: uint
duration: uint
repaid: bool
source_of_funds: Account
extension_proposals: List[PWNSimpleLoan.ExtensionProposal]
proposal: Union[
PWNSimpleLoanElasticProposal.Proposal,
PWNSimpleLoanDutchAuctionProposal.Proposal,
PWNSimpleLoanSimpleProposal.Proposal,
PWNSimpleLoanElasticChainlinkProposal.Proposal,
PWNSimpleLoanListProposal.Proposal,
]
class PWNFuzzTest(FuzzTest):
hub: PWNHub
vault: PWNSimpleLoan
config: PWNConfig
utilized_credit: PWNUtilizedCredit
revoked_nonce: PWNRevokedNonce
multi_token_registry: MultiTokenCategoryRegistry
erc4626_adapter: ERC4626Adapter
aave_adapter: AaveAdapter
compound_adapter: CompoundAdapter
loan_token: PWNLOAN
fee: int
fee_collector: Account
elastic_proposal: PWNSimpleLoanElasticProposal
dutch_auction_proposal: PWNSimpleLoanDutchAuctionProposal
simple_proposal: PWNSimpleLoanSimpleProposal
elastic_chainlink_proposal: PWNSimpleLoanElasticChainlinkProposal
list_proposal: PWNSimpleLoanListProposal
simple_proposals: Dict[
bytes32,
Tuple[PWNSimpleLoanSimpleProposal.Proposal, Optional[PWNSimpleLoan.LenderSpec]],
]
dutch_auction_proposals: Dict[
bytes32,
Tuple[
PWNSimpleLoanDutchAuctionProposal.Proposal,
Optional[PWNSimpleLoan.LenderSpec],
],
]
elastic_proposals: Dict[
bytes32,
Tuple[
PWNSimpleLoanElasticProposal.Proposal, Optional[PWNSimpleLoan.LenderSpec]
],
]
elastic_chainlink_proposals: Dict[
bytes32,
Tuple[
PWNSimpleLoanElasticChainlinkProposal.Proposal,
Optional[PWNSimpleLoan.LenderSpec],
],
]
list_proposals: Dict[
bytes32,
Tuple[PWNSimpleLoanListProposal.Proposal, Optional[PWNSimpleLoan.LenderSpec]],
]
whitelisted_collateral_ids: Dict[bytes32, OrderedSet[int]]
nonce_spaces: Dict[Account, int]
revoked_nonces: Dict[Account, OrderedSet[int]]
loans: Dict[int, Loan]
utilized_credit_ids: Dict[Account, Dict[bytes32, int]]
utilized_ids: List[bytes32]
erc20_balances: Dict[IERC20, Dict[Account, int]]
erc721_owners: Dict[IERC721, Dict[int, Account]]
erc1155_balances: Dict[IERC1155, Dict[Account, Dict[int, int]]]
aggregator_data: Dict[Account, AggregatorData]
erc4626_vaults: Dict[Account, MockERC4626]
def pre_sequence(self) -> None:
self.hub = PWNHub.deploy()
self.utilized_credit = PWNUtilizedCredit.deploy(self.hub, LOAN_PROPOSAL_TAG)
self.revoked_nonce = PWNRevokedNonce.deploy(self.hub, NONCE_MANAGER_TAG)
self.multi_token_registry = MultiTokenCategoryRegistry.deploy()
self.erc4626_adapter = ERC4626Adapter.deploy(self.hub)
self.aave_adapter = AaveAdapter.deploy(self.hub)
self.compound_adapter = CompoundAdapter.deploy(self.hub)
proxy_factory = ERC1967Factory.deploy()
config = PWNConfig.deploy()
self.config = PWNConfig(
proxy_factory.deploy_(config, chain.accounts[0]).return_value
)
self.fee = random_int(0, 1_000)
self.fee_collector = Account(
random_address()
) # random_account() breaks logic due to fee collector vs lender/borrower collision
self.config.initialize(chain.accounts[0], self.fee, self.fee_collector)
self.loan_token = PWNLOAN.deploy(self.hub)
self.vault = PWNSimpleLoan.deploy(
self.hub,
self.loan_token,
self.config,
self.revoked_nonce,
self.multi_token_registry,
)
self.elastic_proposal = PWNSimpleLoanElasticProposal.deploy(
self.hub, self.revoked_nonce, self.config, self.utilized_credit
)
self.dutch_auction_proposal = PWNSimpleLoanDutchAuctionProposal.deploy(
self.hub, self.revoked_nonce, self.config, self.utilized_credit
)
self.simple_proposal = PWNSimpleLoanSimpleProposal.deploy(
self.hub, self.revoked_nonce, self.config, self.utilized_credit
)
self.elastic_chainlink_proposal = PWNSimpleLoanElasticChainlinkProposal.deploy(
self.hub,
self.revoked_nonce,
self.config,
self.utilized_credit,
FEED_REGISTRY,
Address.ZERO,
TOKENS[0]["WETH"],
)
self.list_proposal = PWNSimpleLoanListProposal.deploy(
self.hub, self.revoked_nonce, self.config, self.utilized_credit
)
self.hub.setTags(
[
self.elastic_proposal,
self.dutch_auction_proposal,
self.simple_proposal,
self.elastic_chainlink_proposal,
self.list_proposal,
],
[LOAN_PROPOSAL_TAG] * 5,
True,
)
self.hub.setTags(
[
self.elastic_proposal,
self.dutch_auction_proposal,
self.simple_proposal,
self.elastic_chainlink_proposal,
self.list_proposal,
],
[NONCE_MANAGER_TAG] * 5,
True,
)
self.hub.setTag(self.vault, NONCE_MANAGER_TAG, True)
self.hub.setTag(self.vault, ACTIVE_LOAN_TAG, True)
self.simple_proposals = {}
self.dutch_auction_proposals = {}
self.elastic_proposals = {}
self.elastic_chainlink_proposals = {}
self.list_proposals = {}
self.whitelisted_collateral_ids = {}
self.nonce_spaces = defaultdict(int)
self.revoked_nonces = defaultdict(lambda: OrderedSet([]))
self.loans = {}
self.aggregator_data = {}
self.erc4626_vaults = KeyedDefaultDict(
lambda token: self._register_erc4626_vault(token)
)
self.utilized_credit_ids = defaultdict(lambda: defaultdict(int))
self.utilized_ids = [bytes32(random_bytes(32)) for _ in range(100)]
TOKENS[1] = {
"MOCK": ERC721Mock.deploy("Mock", "MOCK"),
self.loan_token.symbol(): self.loan_token,
}
self.erc20_balances = defaultdict(lambda: defaultdict(int))
for acc in chain.accounts:
for token in TOKENS[0].values():
self.erc20_balances[token][acc] = token.balanceOf(acc)
self.erc721_owners = defaultdict(lambda: {})
self.erc1155_balances = defaultdict(lambda: defaultdict(lambda: defaultdict(int)))
self._register_tokens()
for pool in AAVE_POOLS.values():
self.config.registerPoolAdapter(pool, self.aave_adapter)
for pool in COMP_POOLS.values():
self.config.registerPoolAdapter(pool, self.compound_adapter)
def _register_tokens(self):
for category, tokens in TOKENS.items():
for token, token_address in tokens.items():
self.multi_token_registry.registerCategoryValue(token_address, category)
def _register_erc4626_vault(self, token: Account):
vault = MockERC4626.deploy(token)
self.config.registerPoolAdapter(vault, self.erc4626_adapter)
return vault
def _get_aggregator_data(self, aggregator: Account) -> AggregatorData:
if aggregator not in self.aggregator_data:
round_id, price, _, updated_at, _ = AggregatorV2V3Interface(
aggregator
).latestRoundData()
self.aggregator_data[aggregator] = AggregatorData(
round_id, price, updated_at
)
return self.aggregator_data[aggregator]
def _random_lender_spec(
self,
lender: Account,
credit_token: Account,
):
options = [
lender.address,
self.erc4626_vaults[credit_token].address,
]
if credit_token in AAVE_POOLS:
options.append(AAVE_POOLS[credit_token].address)
if credit_token in COMP_POOLS:
options.append(COMP_POOLS[credit_token].address)
return PWNSimpleLoan.LenderSpec(random.choice(options))
def _random_credit_limit(self, owner: Account, utilized_credit_id: bytes32, credit_amount: int) -> int:
p = random.random()
if p < 0.45:
return 0
elif p < 0.5:
return random_int(
int(self.utilized_credit_ids[owner][utilized_credit_id] * 0.9) + credit_amount,
int(self.utilized_credit_ids[owner][utilized_credit_id] * 1.1) + credit_amount + 100,
edge_values_prob=0.01
)
else:
return random_int(
self.utilized_credit_ids[owner][utilized_credit_id] + credit_amount,
self.utilized_credit_ids[owner][utilized_credit_id] * 2 + credit_amount + 100,
edge_values_prob=0.01,
)
def _update_aggregator_price(self, aggregator: Account, new_price: int):
if aggregator not in self.aggregator_data:
round_id = AggregatorV2V3Interface(aggregator).latestRound()
else:
round_id = self.aggregator_data[aggregator].round_id + 1
timestamp = chain.blocks["latest"].timestamp
self.aggregator_data[aggregator] = AggregatorData(
round_id, new_price, timestamp
)
write_storage_variable(
aggregator, "s_hotVars", round_id, keys=["latestAggregatorRoundId"]
)
try:
write_storage_variable(
aggregator,
"s_transmissions",
{"answer": new_price, "timestamp": timestamp},
keys=[round_id],
)
except ValueError:
# some aggregators have 3-member structs in s_transmissions
write_storage_variable(
aggregator,
"s_transmissions",
{
"answer": new_price,
"observationsTimestamp": timestamp,
"transmissionTimestamp": timestamp,
},
keys=[round_id],
)
_, price, _, updated_at, _ = AggregatorV2V3Interface(
aggregator
).latestRoundData()
assert price == new_price
assert updated_at == timestamp
def post_invariants(self) -> None:
chain.mine(lambda t: t + 50)
@flow()
def flow_set_fee(self):
self.fee = random_int(0, 1_000)
self.config.setFee(self.fee)
logger.info(f"Fee set to {self.fee}")
@flow()
def flow_set_fee_collector(self):
self.fee_collector = Account(
random_address()
) # random_account() breaks logic due to fee collector vs lender/borrower collision
self.config.setFeeCollector(self.fee_collector)
logger.info(f"Fee collector set to {self.fee_collector}")
def _new_simple_proposal(
self,
) -> Tuple[
PWNSimpleLoanSimpleProposal.Proposal, Optional[PWNSimpleLoan.LenderSpec]
]:
if random_bool() and len(self.loans) > 0:
refinance_id = random.choice(list(self.loans.keys()))
else:
refinance_id = 0
is_offer = random_bool()
if refinance_id != 0:
refinance_loan = self.loans[refinance_id]
collateral_category = refinance_loan.collateral_category
collateral_token = refinance_loan.collateral
collateral_id = refinance_loan.collateral_id
collateral_amount = refinance_loan.collateral_amount
credit_token = refinance_loan.credit
state_fingerprint = refinance_loan.proposal.collateralStateFingerprint
if is_offer:
allowed_acceptor = refinance_loan.borrower
proposer = random_account()
else:
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = refinance_loan.borrower
else:
collateral_category = random.choice(
[MultiToken.Category.ERC20, MultiToken.Category.ERC721, MultiToken.Category.ERC1155]
)
if collateral_category == MultiToken.Category.ERC721:
pwn_tokens = [
id
for id in self.erc721_owners[IERC721(self.loan_token)].keys()
if self.erc721_owners[IERC721(self.loan_token)][id] != self.vault
]
if len(pwn_tokens) > 0 and random_bool(true_prob=0.77):
collateral_token = self.loan_token
collateral_id = random.choice(pwn_tokens)
state_fingerprint = self.loan_token.getStateFingerprint(collateral_id)
if is_offer:
allowed_acceptor = self.erc721_owners[IERC721(self.loan_token)][
collateral_id
]
proposer = random_account()
else:
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = self.erc721_owners[IERC721(self.loan_token)][
collateral_id
]
else:
collateral_token = TOKENS[1]["MOCK"]
collateral_id = random_int(0, 2**256 - 1)
state_fingerprint = keccak256(abi.encode(uint8(0)))
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = random_account()
elif collateral_category == MultiToken.Category.ERC1155:
collateral_token = random.choice(list(TOKENS[collateral_category.value].values()))
collateral_id = random_int(0, 2**256 - 1)
state_fingerprint = bytes32(0)
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = random_account()
else:
collateral_token = random.choice(
list(TOKENS[collateral_category.value].values())
)
collateral_id = 0
state_fingerprint = bytes(0)
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = random_account()
collateral_amount = (
random_int(0, MAX_TOKENS[collateral_token]) * 10 ** DECIMALS[collateral_token]
if collateral_category != MultiToken.Category.ERC721
else 0
)
credit_token = random.choice(list(TOKENS[0].values()))
credit_decimals = DECIMALS[credit_token]
credit_amount = random_int(0, MAX_TOKENS[credit_token]) * 10 ** credit_decimals
utilized_credit_id = random.choice(self.utilized_ids)
available_credit_limit = self._random_credit_limit(proposer, utilized_credit_id, credit_amount)
fixed_interest_amount = random_int(0, MAX_TOKENS[credit_token]) * 10 ** credit_decimals
interest_apr = random_int(0, MAX_APR)
duration_or_date = random_duration_or_date()
expiration = random_expiration()
lender_spec = (
self._random_lender_spec(proposer, credit_token) if is_offer else None
)
nonce_space = self.nonce_spaces[proposer]
nonce = random_nonce()
return (
PWNSimpleLoanSimpleProposal.Proposal(
collateralCategory=collateral_category,
collateralAddress=collateral_token.address,
collateralId=collateral_id,
collateralAmount=collateral_amount,
checkCollateralStateFingerprint=collateral_category
== MultiToken.Category.ERC721,
collateralStateFingerprint=state_fingerprint,
creditAddress=credit_token.address,
creditAmount=credit_amount,
availableCreditLimit=available_credit_limit,
utilizedCreditId=utilized_credit_id,
fixedInterestAmount=fixed_interest_amount,
accruingInterestAPR=interest_apr,
durationOrDate=duration_or_date,
expiration=expiration,
allowedAcceptor=allowed_acceptor.address,
proposer=proposer.address,
proposerSpecHash=(
keccak256(abi.encode(lender_spec)) if lender_spec else bytes32(0)
),
isOffer=is_offer,
refinancingLoanId=refinance_id,
nonceSpace=nonce_space,
nonce=nonce,
loanContract=self.vault.address,
),
lender_spec,
)
@flow()
def flow_make_simple_proposal(self):
proposal, lender_spec = self._new_simple_proposal()
tx = self.simple_proposal.makeProposal(proposal, from_=proposal.proposer)
proposal_hash = next(
e
for e in tx.events
if isinstance(e, PWNSimpleLoanSimpleProposal.ProposalMade)
).proposalHash
self.simple_proposals[proposal_hash] = (proposal, lender_spec)
logger.info(f"Proposal made: {proposal}")
@flow()
def flow_accept_simple_proposal(self):
if len(self.simple_proposals) == 0:
return
onchain_proposal = random_bool()
if onchain_proposal:
proposal_hash = random.choice(list(self.simple_proposals.keys()))
proposal, lender_spec = self.simple_proposals[proposal_hash]
signature = b""
inclusion_proof = []
else:
proposal, lender_spec = self._new_simple_proposal()
proposal_hash = self.simple_proposal.getProposalHash(proposal)
if random_bool():
signature = Account(proposal.proposer).sign_structured(
proposal,
Eip712Domain(
name="PWNSimpleLoanSimpleProposal",
version="1.3",
chainId=chain.chain_id,
verifyingContract=self.simple_proposal,
),
)
inclusion_proof = []
else:
tree = MerkleTree(hash_leaves=False)
leaves = [random_bytes(32) for _ in range(random_int(1, 10))]
leaves.append(proposal_hash)
random.shuffle(leaves)
for leaf in leaves:
tree.add_leaf(leaf)
multiproposal = PWNSimpleLoanProposal.Multiproposal(tree.root)
signature = Account(proposal.proposer).sign_structured(
multiproposal,
Eip712Domain(
name="PWNMultiproposal",
),
)
inclusion_proof = tree.get_proof(tree.leaves.index(proposal_hash))
tx = self._accept_proposal(
proposal,
abi.encode(proposal),
self.simple_proposal,
proposal.collateralAmount,
proposal.creditAmount,
proposal.collateralId,
proposal.expiration,
signature,
inclusion_proof,
chain.blocks["latest"].timestamp + 10,
lender_spec,
)
if tx is None or tx.error is not None:
self.simple_proposals.pop(proposal_hash, None)
elif (
tx.error is None
and proposal.collateralCategory == MultiToken.Category.ERC721
):
# ERC-721 with given collateral id cannot be minted again
self.simple_proposals.pop(proposal_hash, None)
def _new_dutch_auction_proposal(
self,
) -> Tuple[
PWNSimpleLoanDutchAuctionProposal.Proposal, Optional[PWNSimpleLoan.LenderSpec]
]:
if random_bool() and len(self.loans) > 0:
refinance_id = random.choice(list(self.loans.keys()))
else:
refinance_id = 0
is_offer = random_bool()
if refinance_id != 0:
refinance_loan = self.loans[refinance_id]
collateral_category = refinance_loan.collateral_category
collateral_token = refinance_loan.collateral
collateral_id = refinance_loan.collateral_id
collateral_amount = refinance_loan.collateral_amount
credit_token = refinance_loan.credit
state_fingerprint = refinance_loan.proposal.collateralStateFingerprint
if is_offer:
allowed_acceptor = refinance_loan.borrower
proposer = random_account()
else:
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = refinance_loan.borrower
else:
collateral_category = random.choice(
[MultiToken.Category.ERC20, MultiToken.Category.ERC721, MultiToken.Category.ERC1155]
)
if collateral_category == MultiToken.Category.ERC721:
pwn_tokens = [
id
for id in self.erc721_owners[IERC721(self.loan_token)].keys()
if self.erc721_owners[IERC721(self.loan_token)][id] != self.vault
]
if len(pwn_tokens) > 0 and random_bool(true_prob=0.77):
collateral_token = self.loan_token
collateral_id = random.choice(pwn_tokens)
state_fingerprint = self.loan_token.getStateFingerprint(collateral_id)
if is_offer:
allowed_acceptor = self.erc721_owners[IERC721(self.loan_token)][
collateral_id
]
proposer = random_account()
else:
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = self.erc721_owners[IERC721(self.loan_token)][
collateral_id
]
else:
collateral_token = TOKENS[1]["MOCK"]
collateral_id = random_int(0, 2**256 - 1)
state_fingerprint = keccak256(abi.encode(uint8(0)))
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = random_account()
elif collateral_category == MultiToken.Category.ERC1155:
collateral_token = random.choice(list(TOKENS[2].values()))
collateral_id = random_int(0, 2**256 - 1)
state_fingerprint = bytes(0)
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = random_account()
else:
collateral_token = random.choice(
list(TOKENS[collateral_category.value].values())
)
collateral_id = 0
state_fingerprint = bytes(0)
allowed_acceptor = random_account() if random_bool() else Account(0)
proposer = random_account()
collateral_amount = (
random_int(0, MAX_TOKENS[collateral_token]) * 10 ** DECIMALS[collateral_token]
if collateral_category != MultiToken.Category.ERC721
else 0
)
credit_token = random.choice(list(TOKENS[0].values()))
credit_decimals = DECIMALS[credit_token]
min_credit_amount = random_int(0, MAX_TOKENS[credit_token]) * 10**credit_decimals
max_credit_amount = random_int(min_credit_amount, MAX_TOKENS[credit_token] * 10**credit_decimals)
utilized_credit_id = random.choice(self.utilized_ids)
available_credit_limit = self._random_credit_limit(proposer, utilized_credit_id, max_credit_amount)
fixed_interest_amount = random_int(0, MAX_TOKENS[credit_token]) * 10**credit_decimals
interest_apr = random_int(0, MAX_APR)
duration_or_date = random_duration_or_date()
auction_start = chain.blocks["pending"].timestamp + random_int(-5, 30)
auction_duration = random_int(1, 60) * 60 + random_int(0, 1, zero_prob=0.1)
lender_spec = (
self._random_lender_spec(proposer, credit_token) if is_offer else None
)
nonce_space = self.nonce_spaces[proposer]
nonce = random_nonce()
return (
PWNSimpleLoanDutchAuctionProposal.Proposal(
collateralCategory=collateral_category,
collateralAddress=collateral_token.address,
collateralId=collateral_id,
collateralAmount=collateral_amount,
checkCollateralStateFingerprint=collateral_category
== MultiToken.Category.ERC721,
collateralStateFingerprint=state_fingerprint,
creditAddress=credit_token.address,
minCreditAmount=min_credit_amount,
maxCreditAmount=max_credit_amount,
availableCreditLimit=available_credit_limit,
utilizedCreditId=utilized_credit_id,
fixedInterestAmount=fixed_interest_amount,
accruingInterestAPR=interest_apr,
durationOrDate=duration_or_date,
auctionStart=auction_start,
auctionDuration=auction_duration,
allowedAcceptor=allowed_acceptor.address,
proposer=proposer.address,
proposerSpecHash=(
keccak256(abi.encode(lender_spec)) if lender_spec else bytes32(0)
),
isOffer=is_offer,
refinancingLoanId=refinance_id,
nonceSpace=nonce_space,
nonce=nonce,
loanContract=self.vault.address,
),
lender_spec,
)
@flow()
def flow_make_dutch_auction_proposal(self):
proposal, lender_spec = self._new_dutch_auction_proposal()
tx = self.dutch_auction_proposal.makeProposal(proposal, from_=proposal.proposer)
proposal_hash = next(
e
for e in tx.events
if isinstance(e, PWNSimpleLoanDutchAuctionProposal.ProposalMade)
).proposalHash
self.dutch_auction_proposals[proposal_hash] = (proposal, lender_spec)
logger.info(f"Proposal made: {proposal}")
@flow()
def flow_accept_dutch_auction_proposal(self):
if len(self.dutch_auction_proposals) == 0:
return
onchain_proposal = random_bool()
if onchain_proposal:
proposal_hash = random.choice(list(self.dutch_auction_proposals.keys()))
proposal, lender_spec = self.dutch_auction_proposals[proposal_hash]
signature = b""
inclusion_proof = []
else:
proposal, lender_spec = self._new_dutch_auction_proposal()
proposal_hash = self.dutch_auction_proposal.getProposalHash(proposal)
if random_bool():
signature = Account(proposal.proposer).sign_structured(
proposal,
Eip712Domain(
name="PWNSimpleLoanDutchAuctionProposal",
version="1.1",
chainId=chain.chain_id,
verifyingContract=self.dutch_auction_proposal,
),
)
inclusion_proof = []
else:
tree = MerkleTree(hash_leaves=False)
leaves = [random_bytes(32) for _ in range(random_int(1, 10))]
leaves.append(proposal_hash)
random.shuffle(leaves)
for leaf in leaves:
tree.add_leaf(leaf)
multiproposal = PWNSimpleLoanProposal.Multiproposal(tree.root)
signature = Account(proposal.proposer).sign_structured(
multiproposal,
Eip712Domain(
name="PWNMultiproposal",
),
)
inclusion_proof = tree.get_proof(tree.leaves.index(proposal_hash))
credit_decimals = DECIMALS[IERC20(proposal.creditAddress)]
target_time = chain.blocks["latest"].timestamp + 10
credit_change = max(
0,
(proposal.maxCreditAmount - proposal.minCreditAmount)
* ((target_time - proposal.auctionStart) // 60)
// (proposal.auctionDuration // 60),
)
current_credit_amount = max(
0,
(
proposal.minCreditAmount + credit_change
if proposal.isOffer
else proposal.maxCreditAmount - credit_change
),
)
slippage = random_int(0, 1_000) * 10**credit_decimals
if proposal.isOffer:
credit_amount = random_int(
current_credit_amount - slippage, current_credit_amount
)
else:
if slippage >= current_credit_amount:
slippage = random_int(0, current_credit_amount)
credit_amount = random_int(
current_credit_amount, current_credit_amount + slippage
)
proposal_values = PWNSimpleLoanDutchAuctionProposal.ProposalValues(
current_credit_amount, slippage
)
def revert_handler(tx: TransactionAbc) -> bool:
if proposal.auctionDuration < 60:
assert (
tx.error
== PWNSimpleLoanDutchAuctionProposal.InvalidAuctionDuration(
proposal.auctionDuration, 60
)
)
return True
elif proposal.auctionDuration % 60 != 0:
assert (
tx.error
== PWNSimpleLoanDutchAuctionProposal.AuctionDurationNotInFullMinutes(
proposal.auctionDuration
)
)
return True
elif proposal.minCreditAmount >= proposal.maxCreditAmount:
assert (
tx.error
== PWNSimpleLoanDutchAuctionProposal.InvalidCreditAmountRange(
proposal.minCreditAmount, proposal.maxCreditAmount
)
)
return True
elif tx.block.timestamp < proposal.auctionStart:
assert (
tx.error
== PWNSimpleLoanDutchAuctionProposal.AuctionNotInProgress(
tx.block.timestamp, proposal.auctionStart
)
)
return True
elif (
tx.block.timestamp
>= proposal.auctionStart + proposal.auctionDuration + 60
):
assert tx.error == Expired(
tx.block.timestamp,
proposal.auctionStart + proposal.auctionDuration + 60,
)
return True
elif proposal.isOffer and credit_amount + slippage < current_credit_amount:
assert (
tx.error
== PWNSimpleLoanDutchAuctionProposal.InvalidCreditAmount(
credit_amount, current_credit_amount, slippage
)
)
return True
elif (
not proposal.isOffer
and credit_amount - slippage > current_credit_amount
):
assert (
tx.error
== PWNSimpleLoanDutchAuctionProposal.InvalidCreditAmount(