generated from opentensor/bittensor-subnet-template
-
Notifications
You must be signed in to change notification settings - Fork 16
/
pools.py
1255 lines (993 loc) · 53.1 KB
/
pools.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
# The MIT License (MIT)
# Copyright © 2023 Syeam Bin Abdullah
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
# documentation files (the “Software”), to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of
# the Software.
# THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
import json
import math
from decimal import Decimal
from enum import IntEnum
from pathlib import Path
from typing import Any, ClassVar, Literal
import bittensor as bt
import numpy as np
from eth_account import Account
from pydantic import BaseModel, Field, PrivateAttr, field_validator, model_validator
from web3 import Web3
from web3.constants import ADDRESS_ZERO
from web3.contract.contract import Contract
from web3.types import BlockData
from sturdy.constants import *
from sturdy.pool_registry.pool_registry import POOL_REGISTRY
from sturdy.utils.ethmath import wei_div
from sturdy.utils.misc import (
getReserveFactor,
rayMul,
retry_with_backoff,
ttl_cache,
)
class POOL_TYPES(IntEnum):
STURDY_SILO = 1
AAVE_DEFAULT = 2
DAI_SAVINGS = 3
COMPOUND_V3 = 4
MORPHO = 5
YEARN_V3 = 6
AAVE_TARGET = 7
def get_minimum_allocation(pool: "ChainBasedPoolModel") -> int:
borrow_amount = 0
our_supply = 0
assets_available = 0
match pool.pool_type:
case POOL_TYPES.STURDY_SILO:
borrow_amount = pool._totalBorrow
our_supply = pool._user_deposits
assets_available = max(0, pool._total_supplied_assets - borrow_amount)
case T if T in (POOL_TYPES.AAVE_DEFAULT, POOL_TYPES.AAVE_TARGET):
# borrow amount for aave pools is total_stable_debt + total_variable_debt
borrow_amount = ((pool._nextTotalStableDebt * int(1e18)) // int(10**pool._decimals)) + (
(pool._totalVariableDebt * int(1e18)) // int(10**pool._decimals)
)
our_supply = pool._user_deposits
assets_available = max(0, ((pool._total_supplied_assets * int(1e18)) // int(10**pool._decimals)) - borrow_amount)
case POOL_TYPES.COMPOUND_V3:
borrow_amount = pool._total_borrow
our_supply = pool._user_deposits
assets_available = max(0, pool._total_supplied_assets - borrow_amount)
case POOL_TYPES.MORPHO:
borrow_amount = pool._curr_borrows
our_supply = pool._user_deposits
assets_available = max(0, pool._total_supplied_assets - borrow_amount)
case POOL_TYPES.YEARN_V3:
return max(0, pool._user_deposits - pool._max_withdraw)
case POOL_TYPES.DAI_SAVINGS:
pass # TODO: is there a more appropriate way to go about this?
case _: # not a valid pool type
return 1
return 0 if borrow_amount <= assets_available else assets_available if our_supply >= assets_available else 0
def check_allocations(
assets_and_pools: dict, allocations: dict[str, int], alloc_threshold: float = TOTAL_ALLOC_THRESHOLD
) -> bool:
"""
Checks allocations from miner.
Args:
- assets_and_pools (dict[str, Union[dict[str, int], int]]): The assets and pools which the allocations are for.
- allocations (dict[str, int]): The allocations to validate.
Returns:
- bool: Represents if allocations are valid.
"""
# Ensure the allocations are provided and valid
if not allocations or not isinstance(allocations, dict):
return False
# Ensure the 'total_assets' key exists in assets_and_pools and is a valid number
to_allocate = assets_and_pools.get("total_assets")
if to_allocate is None or not isinstance(to_allocate, int):
return False
to_allocate = Decimal(str(to_allocate))
total_allocated = Decimal(0)
total_assets = assets_and_pools["total_assets"]
# Check allocations
for allocation in allocations.values():
try:
allocation_value = Decimal(str(allocation))
except (ValueError, TypeError):
return False
if allocation_value < 0:
return False
total_allocated += allocation_value
if total_allocated > to_allocate:
return False
# Ensure total allocated does not exceed the total assets, and that most assets have been allocated
if total_allocated > to_allocate or total_allocated < int(alloc_threshold * total_assets):
return False
pools = assets_and_pools["pools"]
# check if allocations are above the borrow amounts
for pool_uid, pool in pools.items():
allocation = allocations.get(pool_uid, 0)
min_alloc = get_minimum_allocation(pool)
if allocation < min_alloc:
return False
return True
class ChainBasedPoolModel(BaseModel):
"""This serves as the base model of pools which need to pull data from on-chain
Args:
contract_address: (str),
"""
class Config:
use_enum_values = True # This will use the enum's value instead of the enum itself
pool_type: POOL_TYPES | int | str = Field(..., description="type of pool")
user_address: str = Field(
default=ADDRESS_ZERO,
description="address of the 'user' - used for various on-chain calls",
)
contract_address: str = Field(default=ADDRESS_ZERO, description="address of contract to call")
_initted: bool = PrivateAttr(False) # noqa: FBT003
@field_validator("pool_type", mode="before")
def validator_pool_type(cls, value) -> POOL_TYPES | int | str:
if isinstance(value, POOL_TYPES):
return value
if isinstance(value, int):
return POOL_TYPES(value)
if isinstance(value, str):
try:
return POOL_TYPES[value]
except KeyError:
raise ValueError(f"Invalid enum name: {value}") # noqa: B904
raise ValueError(f"Invalid value: {value}")
@model_validator(mode="after")
def check_params(cls, values): # noqa: ANN201
if not Web3.is_address(values.contract_address):
raise ValueError("pool address is invalid!")
if not Web3.is_address(values.user_address):
raise ValueError("user address is invalid!")
return values
def pool_init(self, **args: Any) -> None:
raise NotImplementedError("pool_init() has not been implemented!")
def sync(self, **args: Any) -> None:
raise NotImplementedError("sync() has not been implemented!")
def supply_rate(self, **args: Any) -> int:
raise NotImplementedError("supply_rate() has not been implemented!")
class PoolFactory:
@staticmethod
def create_pool(pool_type: POOL_TYPES, **kwargs: Any) -> ChainBasedPoolModel:
match pool_type:
case POOL_TYPES.AAVE_DEFAULT:
return AaveV3DefaultInterestRateV2Pool(**kwargs)
case POOL_TYPES.STURDY_SILO:
return VariableInterestSturdySiloStrategy(**kwargs)
case POOL_TYPES.DAI_SAVINGS:
return DaiSavingsRate(**kwargs)
case POOL_TYPES.COMPOUND_V3:
return CompoundV3Pool(**kwargs)
case POOL_TYPES.MORPHO:
return MorphoVault(**kwargs)
case POOL_TYPES.YEARN_V3:
return YearnV3Vault(**kwargs)
case POOL_TYPES.AAVE_TARGET:
return AaveV3RateTargetBaseInterestRatePool(**kwargs)
case _:
raise ValueError(f"Unknown pool type: {pool_type}")
class AaveV3DefaultInterestRateV2Pool(ChainBasedPoolModel):
"""This class defines the default pool type for Aave"""
pool_type: Literal[POOL_TYPES.AAVE_DEFAULT] = POOL_TYPES.AAVE_DEFAULT
_atoken_contract: Contract = PrivateAttr()
_pool_contract: Contract = PrivateAttr()
_underlying_asset_contract: Contract = PrivateAttr()
_underlying_asset_address: str = PrivateAttr()
_reserve_data = PrivateAttr()
_strategy_contract = PrivateAttr()
_nextTotalStableDebt = PrivateAttr()
_nextAvgStableBorrowRate = PrivateAttr()
_variable_debt_token_contract = PrivateAttr()
_totalVariableDebt = PrivateAttr()
_reserveFactor = PrivateAttr()
_user_deposits: int = PrivateAttr()
_total_supplied_assets: int = PrivateAttr()
_decimals: int = PrivateAttr()
_user_asset_balance: int = PrivateAttr()
_yield_index: int = PrivateAttr()
class Config:
arbitrary_types_allowed = True
def __hash__(self) -> int:
return hash((self._atoken_contract.address, self._underlying_asset_address))
def __eq__(self, other) -> bool:
if not isinstance(other, AaveV3DefaultInterestRateV2Pool):
return NotImplemented
# Compare the attributes for equality
return (self._atoken_contract.address, self._underlying_asset_address) == (
other._atoken_contract.address,
other._underlying_asset_address,
)
def pool_init(self, web3_provider: Web3) -> None:
try:
assert web3_provider.is_connected()
except Exception as err:
bt.logging.error("Failed to connect to Web3 instance!")
bt.logging.error(err) # type: ignore[]
try:
atoken_abi_file_path = Path(__file__).parent / "abi/AToken.json"
atoken_abi_file = atoken_abi_file_path.open()
atoken_abi = json.load(atoken_abi_file)
atoken_abi_file.close()
atoken_contract = web3_provider.eth.contract(abi=atoken_abi, decode_tuples=True)
self._atoken_contract = retry_with_backoff(
atoken_contract,
address=self.contract_address,
)
pool_abi_file_path = Path(__file__).parent / "abi/Pool.json"
pool_abi_file = pool_abi_file_path.open()
pool_abi = json.load(pool_abi_file)
pool_abi_file.close()
atoken_contract = self._atoken_contract
pool_address = retry_with_backoff(atoken_contract.functions.POOL().call)
pool_contract = web3_provider.eth.contract(abi=pool_abi, decode_tuples=True)
self._pool_contract = retry_with_backoff(pool_contract, address=pool_address)
self._underlying_asset_address = retry_with_backoff(
self._atoken_contract.functions.UNDERLYING_ASSET_ADDRESS().call,
)
erc20_abi_file_path = Path(__file__).parent / "abi/IERC20.json"
erc20_abi_file = erc20_abi_file_path.open()
erc20_abi = json.load(erc20_abi_file)
erc20_abi_file.close()
underlying_asset_contract = web3_provider.eth.contract(abi=erc20_abi, decode_tuples=True)
self._underlying_asset_contract = retry_with_backoff(
underlying_asset_contract,
address=self._underlying_asset_address,
)
self._total_supplied_assets = retry_with_backoff(self._atoken_contract.functions.totalSupply().call)
self._initted = True
except Exception as err:
bt.logging.error("Failed to load contract!")
bt.logging.error(err) # type: ignore[]
def sync(self, web3_provider: Web3) -> None:
"""Syncs with chain"""
if not self._initted:
self.pool_init(web3_provider)
try:
pool_abi_file_path = Path(__file__).parent / "abi/Pool.json"
pool_abi_file = pool_abi_file_path.open()
pool_abi = json.load(pool_abi_file)
pool_abi_file.close()
atoken_contract_onchain = self._atoken_contract
pool_address = retry_with_backoff(atoken_contract_onchain.functions.POOL().call)
pool_contract = web3_provider.eth.contract(abi=pool_abi, decode_tuples=True)
self._pool_contract = retry_with_backoff(pool_contract, address=pool_address)
self._underlying_asset_address = retry_with_backoff(
self._atoken_contract.functions.UNDERLYING_ASSET_ADDRESS().call,
)
self._reserve_data = retry_with_backoff(
self._pool_contract.functions.getReserveData(self._underlying_asset_address).call,
)
reserve_strat_abi_file_path = Path(__file__).parent / "abi/IReserveInterestRateStrategy.json"
reserve_strat_abi_file = reserve_strat_abi_file_path.open()
reserve_strat_abi = json.load(reserve_strat_abi_file)
reserve_strat_abi_file.close()
strategy_contract = web3_provider.eth.contract(abi=reserve_strat_abi)
self._strategy_contract = retry_with_backoff(
strategy_contract,
address=self._reserve_data.interestRateStrategyAddress,
)
stable_debt_token_abi_file_path = Path(__file__).parent / "abi/IStableDebtToken.json"
stable_debt_token_abi_file = stable_debt_token_abi_file_path.open()
stable_debt_token_abi = json.load(stable_debt_token_abi_file)
stable_debt_token_abi_file.close()
stable_debt_token_contract = web3_provider.eth.contract(abi=stable_debt_token_abi)
stable_debt_token_contract = retry_with_backoff(
stable_debt_token_contract,
address=self._reserve_data.stableDebtTokenAddress,
)
(
_,
self._nextTotalStableDebt,
self._nextAvgStableBorrowRate,
_,
) = retry_with_backoff(stable_debt_token_contract.functions.getSupplyData().call)
variable_debt_token_abi_file_path = Path(__file__).parent / "abi/IVariableDebtToken.json"
variable_debt_token_abi_file = variable_debt_token_abi_file_path.open()
variable_debt_token_abi = json.load(variable_debt_token_abi_file)
variable_debt_token_abi_file.close()
variable_debt_token_contract = web3_provider.eth.contract(abi=variable_debt_token_abi)
self._variable_debt_token_contract = retry_with_backoff(
variable_debt_token_contract,
address=self._reserve_data.variableDebtTokenAddress,
)
nextVariableBorrowIndex = self._reserve_data.variableBorrowIndex
nextScaledVariableDebt = retry_with_backoff(self._variable_debt_token_contract.functions.scaledTotalSupply().call)
self._totalVariableDebt = rayMul(nextScaledVariableDebt, nextVariableBorrowIndex)
reserveConfiguration = self._reserve_data.configuration
self._reserveFactor = getReserveFactor(reserveConfiguration)
self._decimals = retry_with_backoff(self._underlying_asset_contract.functions.decimals().call)
self._user_deposits = retry_with_backoff(
self._atoken_contract.functions.balanceOf(Web3.to_checksum_address(self.user_address)).call
)
self._user_asset_balance = retry_with_backoff(
self._underlying_asset_contract.functions.balanceOf(Web3.to_checksum_address(self.user_address)).call
)
self._yield_index = retry_with_backoff(
self._pool_contract.functions.getReserveNormalizedIncome(self._underlying_asset_address).call
)
except Exception as err:
bt.logging.error("Failed to sync to chain!")
bt.logging.error(err) # type: ignore[]
# last 256 unique calls to this will be cached for the next 60 seconds
@ttl_cache(maxsize=256, ttl=60)
def supply_rate(self, amount: int) -> int:
"""Returns supply rate given new deposit amount"""
try:
already_deposited = self._user_deposits
delta = amount - already_deposited
to_deposit = max(0, delta)
to_remove = abs(delta) if delta < 0 else 0
(nextLiquidityRate, _) = retry_with_backoff(
self._strategy_contract.functions.calculateInterestRates(
(
self._reserve_data.unbacked,
int(to_deposit),
int(to_remove),
self._nextTotalStableDebt + self._totalVariableDebt,
self._reserveFactor,
self._underlying_asset_address,
True,
already_deposited,
),
).call,
)
return Web3.to_wei(nextLiquidityRate / 1e27, "ether")
except Exception as e:
bt.logging.error("Failed to retrieve supply apy!")
bt.logging.error(e) # type: ignore[]
return 0
class AaveV3RateTargetBaseInterestRatePool(ChainBasedPoolModel):
"""This class defines the default pool type for Aave"""
pool_type: Literal[POOL_TYPES.AAVE_TARGET] = POOL_TYPES.AAVE_TARGET
_atoken_contract: Contract = PrivateAttr()
_pool_contract: Contract = PrivateAttr()
_underlying_asset_contract: Contract = PrivateAttr()
_underlying_asset_address: str = PrivateAttr()
_reserve_data = PrivateAttr()
_strategy_contract = PrivateAttr()
_nextTotalStableDebt = PrivateAttr()
_nextAvgStableBorrowRate = PrivateAttr()
_variable_debt_token_contract = PrivateAttr()
_totalVariableDebt = PrivateAttr()
_reserveFactor = PrivateAttr()
_user_deposits: int = PrivateAttr()
_total_supplied_assets: int = PrivateAttr()
_decimals: int = PrivateAttr()
_user_asset_balance: int = PrivateAttr()
_yield_index: int = PrivateAttr()
class Config:
arbitrary_types_allowed = True
def __hash__(self) -> int:
return hash((self._atoken_contract.address, self._underlying_asset_address))
def __eq__(self, other) -> bool:
if not isinstance(other, AaveV3DefaultInterestRateV2Pool):
return NotImplemented
# Compare the attributes for equality
return (self._atoken_contract.address, self._underlying_asset_address) == (
other._atoken_contract.address,
other._underlying_asset_address,
)
def pool_init(self, web3_provider: Web3) -> None:
try:
assert web3_provider.is_connected()
except Exception as err:
bt.logging.error("Failed to connect to Web3 instance!")
bt.logging.error(err) # type: ignore[]
try:
atoken_abi_file_path = Path(__file__).parent / "abi/AToken.json"
atoken_abi_file = atoken_abi_file_path.open()
atoken_abi = json.load(atoken_abi_file)
atoken_abi_file.close()
atoken_contract = web3_provider.eth.contract(abi=atoken_abi, decode_tuples=True)
self._atoken_contract = retry_with_backoff(
atoken_contract,
address=self.contract_address,
)
pool_abi_file_path = Path(__file__).parent / "abi/Pool.json"
pool_abi_file = pool_abi_file_path.open()
pool_abi = json.load(pool_abi_file)
pool_abi_file.close()
atoken_contract = self._atoken_contract
pool_address = retry_with_backoff(atoken_contract.functions.POOL().call)
pool_contract = web3_provider.eth.contract(abi=pool_abi, decode_tuples=True)
self._pool_contract = retry_with_backoff(pool_contract, address=pool_address)
self._underlying_asset_address = retry_with_backoff(
self._atoken_contract.functions.UNDERLYING_ASSET_ADDRESS().call,
)
erc20_abi_file_path = Path(__file__).parent / "abi/IERC20.json"
erc20_abi_file = erc20_abi_file_path.open()
erc20_abi = json.load(erc20_abi_file)
erc20_abi_file.close()
underlying_asset_contract = web3_provider.eth.contract(abi=erc20_abi, decode_tuples=True)
self._underlying_asset_contract = retry_with_backoff(
underlying_asset_contract,
address=self._underlying_asset_address,
)
self._total_supplied_assets = retry_with_backoff(self._atoken_contract.functions.totalSupply().call)
self._initted = True
except Exception as err:
bt.logging.error("Failed to load contract!")
bt.logging.error(err) # type: ignore[]
def sync(self, web3_provider: Web3) -> None:
"""Syncs with chain"""
if not self._initted:
self.pool_init(web3_provider)
try:
pool_abi_file_path = Path(__file__).parent / "abi/Pool.json"
pool_abi_file = pool_abi_file_path.open()
pool_abi = json.load(pool_abi_file)
pool_abi_file.close()
atoken_contract_onchain = self._atoken_contract
pool_address = retry_with_backoff(atoken_contract_onchain.functions.POOL().call)
pool_contract = web3_provider.eth.contract(abi=pool_abi, decode_tuples=True)
self._pool_contract = retry_with_backoff(pool_contract, address=pool_address)
self._underlying_asset_address = retry_with_backoff(
self._atoken_contract.functions.UNDERLYING_ASSET_ADDRESS().call,
)
self._reserve_data = retry_with_backoff(
self._pool_contract.functions.getReserveData(self._underlying_asset_address).call,
)
reserve_strat_abi_file_path = Path(__file__).parent / "abi/RateTargetBaseInterestRateStrategy.json"
reserve_strat_abi_file = reserve_strat_abi_file_path.open()
reserve_strat_abi = json.load(reserve_strat_abi_file)
reserve_strat_abi_file.close()
strategy_contract = web3_provider.eth.contract(abi=reserve_strat_abi)
self._strategy_contract = retry_with_backoff(
strategy_contract,
address=self._reserve_data.interestRateStrategyAddress,
)
stable_debt_token_abi_file_path = Path(__file__).parent / "abi/IStableDebtToken.json"
stable_debt_token_abi_file = stable_debt_token_abi_file_path.open()
stable_debt_token_abi = json.load(stable_debt_token_abi_file)
stable_debt_token_abi_file.close()
stable_debt_token_contract = web3_provider.eth.contract(abi=stable_debt_token_abi)
stable_debt_token_contract = retry_with_backoff(
stable_debt_token_contract,
address=self._reserve_data.stableDebtTokenAddress,
)
(
_,
self._nextTotalStableDebt,
self._nextAvgStableBorrowRate,
_,
) = retry_with_backoff(stable_debt_token_contract.functions.getSupplyData().call)
variable_debt_token_abi_file_path = Path(__file__).parent / "abi/IVariableDebtToken.json"
variable_debt_token_abi_file = variable_debt_token_abi_file_path.open()
variable_debt_token_abi = json.load(variable_debt_token_abi_file)
variable_debt_token_abi_file.close()
variable_debt_token_contract = web3_provider.eth.contract(abi=variable_debt_token_abi)
self._variable_debt_token_contract = retry_with_backoff(
variable_debt_token_contract,
address=self._reserve_data.variableDebtTokenAddress,
)
nextVariableBorrowIndex = self._reserve_data.variableBorrowIndex
nextScaledVariableDebt = retry_with_backoff(self._variable_debt_token_contract.functions.scaledTotalSupply().call)
self._totalVariableDebt = rayMul(nextScaledVariableDebt, nextVariableBorrowIndex)
reserveConfiguration = self._reserve_data.configuration
self._reserveFactor = getReserveFactor(reserveConfiguration)
self._decimals = retry_with_backoff(self._underlying_asset_contract.functions.decimals().call)
self._user_deposits = retry_with_backoff(
self._atoken_contract.functions.balanceOf(Web3.to_checksum_address(self.user_address)).call
)
self._user_asset_balance = retry_with_backoff(
self._underlying_asset_contract.functions.balanceOf(Web3.to_checksum_address(self.user_address)).call
)
self._yield_index = retry_with_backoff(
self._pool_contract.functions.getReserveNormalizedIncome(self._underlying_asset_address).call
)
except Exception as err:
bt.logging.error("Failed to sync to chain!")
bt.logging.error(err) # type: ignore[]
# last 256 unique calls to this will be cached for the next 60 seconds
@ttl_cache(maxsize=256, ttl=60)
def supply_rate(self, amount: int) -> int:
"""Returns supply rate given new deposit amount"""
try:
already_deposited = self._user_deposits
delta = amount - already_deposited
to_deposit = max(0, delta)
to_remove = abs(delta) if delta < 0 else 0
(nextLiquidityRate, _, _) = retry_with_backoff(
self._strategy_contract.functions.calculateInterestRates(
(
self._reserve_data.unbacked,
int(to_deposit),
int(to_remove),
self._nextTotalStableDebt,
self._totalVariableDebt,
self._nextAvgStableBorrowRate,
self._reserveFactor,
self._underlying_asset_address,
self._atoken_contract.address,
),
).call,
)
return Web3.to_wei(nextLiquidityRate / 1e27, "ether")
except Exception as e:
bt.logging.error("Failed to retrieve supply apy!")
bt.logging.error(e) # type: ignore[]
return 0
class VariableInterestSturdySiloStrategy(ChainBasedPoolModel):
pool_type: Literal[POOL_TYPES.STURDY_SILO] = POOL_TYPES.STURDY_SILO
_silo_strategy_contract: Contract = PrivateAttr()
_pair_contract: Contract = PrivateAttr()
_rate_model_contract: Contract = PrivateAttr()
_user_deposits: int = PrivateAttr()
_util_prec: int = PrivateAttr()
_fee_prec: int = PrivateAttr()
_total_supplied_assets: Any = PrivateAttr()
_totalBorrow: Any = PrivateAttr()
_current_rate_info = PrivateAttr()
_rate_prec: int = PrivateAttr()
_block: BlockData = PrivateAttr()
_decimals: int = PrivateAttr()
_asset: Contract = PrivateAttr()
_user_asset_balance: int = PrivateAttr()
_user_total_assets: int = PrivateAttr()
_yield_index: Contract = PrivateAttr()
def __hash__(self) -> int:
return hash((self._silo_strategy_contract.address, self._pair_contract))
def __eq__(self, other) -> bool:
if not isinstance(other, VariableInterestSturdySiloStrategy):
return NotImplemented
# Compare the attributes for equality
return (self._silo_strategy_contract.address, self._pair_contract) == (
other._silo_strategy_contract.address,
other._pair_contract.address,
)
def pool_init(self, web3_provider: Web3) -> None:
try:
assert web3_provider.is_connected()
except Exception as err:
bt.logging.error("Failed to connect to Web3 instance!")
bt.logging.error(err) # type: ignore[]
try:
silo_strategy_abi_file_path = Path(__file__).parent / "abi/SturdySiloStrategy.json"
silo_strategy_abi_file = silo_strategy_abi_file_path.open()
silo_strategy_abi = json.load(silo_strategy_abi_file)
silo_strategy_abi_file.close()
silo_strategy_contract = web3_provider.eth.contract(abi=silo_strategy_abi, decode_tuples=True)
self._silo_strategy_contract = retry_with_backoff(silo_strategy_contract, address=self.contract_address)
pair_abi_file_path = Path(__file__).parent / "abi/SturdyPair.json"
pair_abi_file = pair_abi_file_path.open()
pair_abi = json.load(pair_abi_file)
pair_abi_file.close()
pair_contract_address = retry_with_backoff(self._silo_strategy_contract.functions.pair().call)
pair_contract = web3_provider.eth.contract(abi=pair_abi, decode_tuples=True)
self._pair_contract = retry_with_backoff(pair_contract, address=pair_contract_address)
rate_model_abi_file_path = Path(__file__).parent / "abi/VariableInterestRate.json"
rate_model_abi_file = rate_model_abi_file_path.open()
rate_model_abi = json.load(rate_model_abi_file)
rate_model_abi_file.close()
rate_model_contract_address = retry_with_backoff(self._pair_contract.functions.rateContract().call)
rate_model_contract = web3_provider.eth.contract(abi=rate_model_abi, decode_tuples=True)
self._rate_model_contract = retry_with_backoff(rate_model_contract, address=rate_model_contract_address)
self._decimals = retry_with_backoff(self._pair_contract.functions.decimals().call)
erc20_abi_file_path = Path(__file__).parent / "abi/IERC20.json"
erc20_abi_file = erc20_abi_file_path.open()
erc20_abi = json.load(erc20_abi_file)
erc20_abi_file.close()
asset_address = retry_with_backoff(self._pair_contract.functions.asset().call)
asset_contract = web3_provider.eth.contract(abi=erc20_abi, decode_tuples=True)
self._asset = retry_with_backoff(asset_contract, address=asset_address)
self._initted = True
except Exception as e:
bt.logging.error(e) # type: ignore[]
def sync(self, web3_provider: Web3) -> None:
"""Syncs with chain"""
if not self._initted:
self.pool_init(web3_provider)
user_shares = retry_with_backoff(self._pair_contract.functions.balanceOf(self.contract_address).call)
self._user_deposits = retry_with_backoff(self._pair_contract.functions.convertToAssets(user_shares).call)
constants = retry_with_backoff(self._pair_contract.functions.getConstants().call)
self._util_prec = constants[2]
self._fee_prec = constants[3]
self._total_supplied_assets: Any = retry_with_backoff(self._pair_contract.functions.totalAssets().call)
self._totalBorrow: Any = retry_with_backoff(self._pair_contract.functions.totalBorrow().call).amount
self._block = web3_provider.eth.get_block("latest")
self._current_rate_info = retry_with_backoff(self._pair_contract.functions.currentRateInfo().call)
self._rate_prec = retry_with_backoff(self._rate_model_contract.functions.RATE_PREC().call)
self._user_asset_balance = retry_with_backoff(self._asset.functions.balanceOf(self.user_address).call)
# get current price per share
self._yield_index = retry_with_backoff(self._pair_contract.functions.pricePerShare().call)
# last 256 unique calls to this will be cached for the next 60 seconds
@ttl_cache(maxsize=256, ttl=60)
def supply_rate(self, amount: int) -> int:
# amount scaled down to the asset's decimals from 18 decimals (wei)
delta = amount - self._user_deposits
"""Returns supply rate given new deposit amount"""
util_rate = int((self._util_prec * self._totalBorrow) // (self._total_supplied_assets + delta))
last_update_timestamp = self._current_rate_info.lastTimestamp
current_timestamp = self._block["timestamp"]
delta_time = int(current_timestamp - last_update_timestamp)
protocol_fee = self._current_rate_info.feeToProtocolRate
(new_rate_per_sec, _) = retry_with_backoff(
self._rate_model_contract.functions.getNewRate(
delta_time,
util_rate,
int(self._current_rate_info.fullUtilizationRate),
).call,
)
return int(
new_rate_per_sec
* 31536000
* 1e18
* util_rate
// self._rate_prec
// self._util_prec
* (1 - (protocol_fee / self._fee_prec)),
) # (rate_per_sec_pct * seconds_in_year * util_rate_pct) * 1e18
class CompoundV3Pool(ChainBasedPoolModel):
"""Model for Compound V3 Pools"""
pool_type: Literal[POOL_TYPES.COMPOUND_V3] = POOL_TYPES.COMPOUND_V3
_ctoken_contract: Contract = PrivateAttr()
_base_oracle_contract: Contract = PrivateAttr()
_reward_oracle_contract: Contract = PrivateAttr()
_base_token_contract: Contract = PrivateAttr()
_reward_token_contract: Contract = PrivateAttr()
_base_token_price: float = PrivateAttr()
_reward_token_price: float = PrivateAttr()
_base_decimals: int = PrivateAttr()
_total_borrow: int = PrivateAttr()
_user_deposits: int = PrivateAttr()
_total_supplied_assets: int = PrivateAttr()
_CompoundTokenMap: dict = {
"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2": "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", # WETH -> ETH
}
def pool_init(self, web3_provider: Web3) -> None:
comet_abi_file_path = Path(__file__).parent / "abi/Comet.json"
comet_abi_file = comet_abi_file_path.open()
comet_abi = json.load(comet_abi_file)
comet_abi_file.close()
# ctoken contract
ctoken_contract = web3_provider.eth.contract(abi=comet_abi, decode_tuples=True)
self._ctoken_contract = retry_with_backoff(ctoken_contract, address=self.contract_address)
oracle_abi_file_path = Path(__file__).parent / "abi/EACAggregatorProxy.json"
oracle_abi_file = oracle_abi_file_path.open()
oracle_abi = json.load(oracle_abi_file)
oracle_abi_file.close()
feed_registry_abi_file_path = Path(__file__).parent / "abi/FeedRegistry.json"
feed_registry_abi_file = feed_registry_abi_file_path.open()
feed_registry_abi = json.load(feed_registry_abi_file)
feed_registry_abi_file.close()
chainlink_registry_address = "0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf" # chainlink registry address on eth mainnet
usd_address = "0x0000000000000000000000000000000000000348" # follows: https://en.wikipedia.org/wiki/ISO_4217
chainlink_registry = web3_provider.eth.contract(abi=feed_registry_abi, decode_tuples=True)
chainlink_registry_contract = retry_with_backoff(chainlink_registry, address=chainlink_registry_address)
base_token_address = retry_with_backoff(self._ctoken_contract.functions.baseToken().call)
asset_address = self._CompoundTokenMap.get(base_token_address, base_token_address)
base_oracle_address = retry_with_backoff(
chainlink_registry_contract.functions.getFeed(asset_address, usd_address).call,
)
base_oracle_contract = web3_provider.eth.contract(abi=oracle_abi, decode_tuples=True)
self._base_oracle_contract = retry_with_backoff(base_oracle_contract, address=base_oracle_address)
reward_oracle_address = "0xdbd020CAeF83eFd542f4De03e3cF0C28A4428bd5" # TODO: COMP price feed address
reward_oracle_contract = web3_provider.eth.contract(abi=oracle_abi, decode_tuples=True)
self._reward_oracle_contract = retry_with_backoff(reward_oracle_contract, address=reward_oracle_address)
self._initted = True
def sync(self, web3_provider: Web3) -> None:
if not self._initted:
self.pool_init(web3_provider)
# get token prices - in wei
base_decimals = retry_with_backoff(self._base_oracle_contract.functions.decimals().call)
self._base_decimals = base_decimals
reward_decimals = retry_with_backoff(self._reward_oracle_contract.functions.decimals().call)
self._total_borrow = retry_with_backoff(self._ctoken_contract.functions.totalBorrow().call)
self._base_token_price = (
retry_with_backoff(self._base_oracle_contract.functions.latestAnswer().call) / 10**base_decimals
)
self._reward_token_price = (
retry_with_backoff(self._reward_oracle_contract.functions.latestAnswer().call) / 10**reward_decimals
)
self._user_deposits = retry_with_backoff(self._ctoken_contract.functions.balanceOf(self.user_address).call)
self._total_supplied_assets = retry_with_backoff(self._ctoken_contract.functions.totalSupply().call)
def supply_rate(self, amount: int) -> int:
# amount scaled down to the asset's decimals from 18 decimals (wei)
# get pool supply rate (base token)
already_in_pool = self._user_deposits
delta = amount - already_in_pool
new_supply = self._total_supplied_assets + delta
current_borrows = self._total_borrow
utilization = wei_div(current_borrows, new_supply)
seconds_per_year = 31536000
seconds_per_day = 86400
pool_rate = retry_with_backoff(self._ctoken_contract.functions.getSupplyRate(utilization).call) * seconds_per_year
base_scale = retry_with_backoff(self._ctoken_contract.functions.baseScale().call)
conv_total_supply = new_supply / base_scale
base_index_scale = retry_with_backoff(self._ctoken_contract.functions.baseIndexScale().call)
base_tracking_supply_speed = retry_with_backoff(self._ctoken_contract.functions.baseTrackingSupplySpeed().call)
reward_per_day = base_tracking_supply_speed / base_index_scale * seconds_per_day
comp_rate = 0
if conv_total_supply * self._base_token_price > 0:
comp_rate = Web3.to_wei(
self._reward_token_price * reward_per_day / (conv_total_supply * self._base_token_price) * 365,
"ether",
)
return int(pool_rate + comp_rate)
class DaiSavingsRate(ChainBasedPoolModel):
"""Model for DAI Savings Rate"""
pool_type: Literal[POOL_TYPES.DAI_SAVINGS] = POOL_TYPES.DAI_SAVINGS
_sdai_contract: Contract = PrivateAttr()
_pot_contract: Contract = PrivateAttr()
def __hash__(self) -> int:
return hash(self._sdai_contract.address)
def __eq__(self, other) -> bool:
if not isinstance(other, VariableInterestSturdySiloStrategy):
return NotImplemented
# Compare the attributes for equality
return self._sdai_contract.address == other._sdai_contract.address # type: ignore[]
def pool_init(self, web3_provider: Web3) -> None:
sdai_abi_file_path = Path(__file__).parent / "abi/SavingsDai.json"
sdai_abi_file = sdai_abi_file_path.open()
sdai_abi = json.load(sdai_abi_file)
sdai_abi_file.close()
sdai_contract = web3_provider.eth.contract(abi=sdai_abi, decode_tuples=True)
self._sdai_contract = retry_with_backoff(sdai_contract, address=self.contract_address)
pot_abi_file_path = Path(__file__).parent / "abi/Pot.json"
pot_abi_file = pot_abi_file_path.open()
pot_abi = json.load(pot_abi_file)
pot_abi_file.close()
pot_address = retry_with_backoff(self._sdai_contract.functions.pot().call)
pot_contract = web3_provider.eth.contract(abi=pot_abi, decode_tuples=True)
self._pot_contract = retry_with_backoff(pot_contract, address=pot_address)
self._initted = True
def sync(self, web3_provider: Web3) -> None:
if not self._initted:
self.pool_init(web3_provider)
# last 256 unique calls to this will be cached for the next 60 seconds
@ttl_cache(maxsize=256, ttl=60)
def supply_rate(self) -> int:
RAY = 1e27
dsr = retry_with_backoff(self._pot_contract.functions.dsr().call)
seconds_per_year = 31536000
x = (dsr / RAY) ** seconds_per_year
return int(math.floor((x - 1) * 1e18))
class MorphoVault(ChainBasedPoolModel):
"""Model for Morpho Vaults"""
pool_type: Literal[POOL_TYPES.MORPHO] = POOL_TYPES.MORPHO
_vault_contract: Contract = PrivateAttr()
_morpho_contract: Contract = PrivateAttr()
_irm_abi: str = PrivateAttr()
_decimals: int = PrivateAttr()
_DECIMALS_OFFSET: int = PrivateAttr()
# TODO: update unit tests to check these :^)
_irm_contracts: dict = PrivateAttr(default={})
_total_supplied_assets: int = PrivateAttr()
_user_deposits: int = PrivateAttr()
_curr_borrows: int = PrivateAttr()
_asset_decimals: int = PrivateAttr()
_underlying_asset_contract: Contract = PrivateAttr()
_user_asset_balance: int = PrivateAttr()
_yield_index: int = PrivateAttr()
_VIRTUAL_SHARES: ClassVar[int] = 1e6
_VIRTUAL_ASSETS: ClassVar[int] = 1
def __hash__(self) -> int:
return hash(self._vault_contract.address)
def __eq__(self, other) -> bool:
if not isinstance(other, MorphoVault):
return NotImplemented
# Compare the attributes for equality
return self._vault_contract.address == other._vault_contract.address # type: ignore[]
def pool_init(self, web3_provider: Web3) -> None:
vault_abi_file_path = Path(__file__).parent / "abi/MetaMorpho.json"
vault_abi_file = vault_abi_file_path.open()
vault_abi = json.load(vault_abi_file)
vault_abi_file.close()
vault_contract = web3_provider.eth.contract(abi=vault_abi, decode_tuples=True)
self._vault_contract = retry_with_backoff(vault_contract, address=self.contract_address)
morpho_abi_file_path = Path(__file__).parent / "abi/Morpho.json"
morpho_abi_file = morpho_abi_file_path.open()
morpho_abi = json.load(morpho_abi_file)
morpho_abi_file.close()
morpho_address = retry_with_backoff(self._vault_contract.functions.MORPHO().call)
morpho_contract = web3_provider.eth.contract(abi=morpho_abi, decode_tuples=True)
self._morpho_contract = retry_with_backoff(morpho_contract, address=morpho_address)