@gearbox-protocol/sdk 3.0.0-vfourabi.1 → 3.0.0-vfourabi.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (275) hide show
  1. package/.eslintignore +3 -0
  2. package/.github/workflows/lint_pr.yml +18 -0
  3. package/.github/workflows/pr.yml +39 -0
  4. package/.github/workflows/release.yml +47 -0
  5. package/.gitignore +19 -0
  6. package/.husky/commit-msg +1 -0
  7. package/.husky/pre-commit +1 -0
  8. package/.nvmrc +1 -0
  9. package/.releaserc.json +34 -0
  10. package/.vscode/extensions.json +7 -0
  11. package/.vscode/settings.json +16 -0
  12. package/.yarn/install-state.gz +0 -0
  13. package/.yarnrc.yml +1 -0
  14. package/ContributionAgreement +72 -0
  15. package/dist/cjs/abi/iZapper.cjs +85 -0
  16. package/dist/cjs/abi/iZapper.d.ts +123 -0
  17. package/dist/cjs/sdk/index.cjs +19830 -19764
  18. package/dist/cjs/sdk/index.d.ts +3746 -3061
  19. package/dist/esm/abi/iZapper.d.mts +123 -0
  20. package/dist/esm/abi/iZapper.mjs +83 -0
  21. package/dist/esm/sdk/index.d.mts +3746 -3061
  22. package/dist/esm/sdk/index.mjs +19807 -19765
  23. package/jest.config.js +7 -0
  24. package/package.json +32 -2
  25. package/scripts/example.ts +30 -0
  26. package/src/abi/compressors.ts +3962 -0
  27. package/src/abi/errors.ts +196 -0
  28. package/src/abi/iERC20.ts +122 -0
  29. package/src/abi/iPausable.ts +35 -0
  30. package/src/abi/iPriceFeedStore.ts +227 -0
  31. package/src/abi/iUpdatablePriceFeed.ts +16 -0
  32. package/src/abi/iVersion.ts +28 -0
  33. package/src/abi/iZapper.ts +84 -0
  34. package/src/abi/routerV300.ts +378 -0
  35. package/src/abi/v300.ts +4151 -0
  36. package/src/abi/v310.ts +5179 -0
  37. package/src/adapters/AbstractAdapter.ts +28 -0
  38. package/src/adapters/BalancerV2VaultAdapterContract.ts +19 -0
  39. package/src/adapters/BalancerV3RouterAdapterContract.ts +19 -0
  40. package/src/adapters/CamelotV3AdapterContract.ts +20 -0
  41. package/src/adapters/ConvexV1BaseRewardPoolAdapterContract.ts +20 -0
  42. package/src/adapters/ConvexV1BoosterAdapterContract.ts +20 -0
  43. package/src/adapters/Curve2AssetsAdapterContract.ts +20 -0
  44. package/src/adapters/Curve3AssetsAdapterContract.ts +20 -0
  45. package/src/adapters/Curve4AssetsAdapterContract.ts +20 -0
  46. package/src/adapters/CurveV1AdapterStETHContract.ts +20 -0
  47. package/src/adapters/CurveV1StableNGAdapterContract.ts +20 -0
  48. package/src/adapters/DaiUsdsAdapterContract.ts +21 -0
  49. package/src/adapters/ERC4626AdapterContract.ts +20 -0
  50. package/src/adapters/MellowERC4626VaultAdapterContract.ts +20 -0
  51. package/src/adapters/MellowVaultAdapterContract.ts +20 -0
  52. package/src/adapters/PendleRouterAdapterContract.ts +21 -0
  53. package/src/adapters/StakingRewardsAdapterContract.ts +21 -0
  54. package/src/adapters/UniswapV2AdapterContract.ts +20 -0
  55. package/src/adapters/UniswapV3AdapterContract.ts +170 -0
  56. package/src/adapters/VelodromeV2AdapterContract.ts +20 -0
  57. package/src/adapters/WstETHV1AdapterContract.ts +20 -0
  58. package/src/adapters/YearnV2AdapterContract.ts +20 -0
  59. package/src/adapters/abi/adapters.ts +4325 -0
  60. package/src/adapters/abi/iBalancerV3RouterAdapter.ts +126 -0
  61. package/src/adapters/abi/index.ts +2 -0
  62. package/src/adapters/index.ts +2 -0
  63. package/src/adapters/plugin.ts +90 -0
  64. package/src/adapters/types.ts +62 -0
  65. package/src/dev/AccountOpener.ts +611 -0
  66. package/src/dev/PriceFeedStore.ts +95 -0
  67. package/src/dev/SDKExample.ts +167 -0
  68. package/src/dev/abi.ts +14 -0
  69. package/src/dev/calcLiquidatableLTs.ts +77 -0
  70. package/src/dev/createAnvilClient.ts +155 -0
  71. package/src/dev/index.ts +7 -0
  72. package/src/dev/setLTZero.ts +127 -0
  73. package/src/dev/setLTs.ts +68 -0
  74. package/src/sdk/GearboxSDK.ts +488 -0
  75. package/src/sdk/abi/index.ts +1 -0
  76. package/src/sdk/abi/oracles.ts +4614 -0
  77. package/src/sdk/accounts/CreditAccountsService.ts +1123 -0
  78. package/src/sdk/accounts/index.ts +1 -0
  79. package/src/sdk/base/AddressLabeller.ts +35 -0
  80. package/src/sdk/base/BaseContract.ts +237 -0
  81. package/src/sdk/base/IAddressLabeller.ts +13 -0
  82. package/src/sdk/base/PlaceholderContract.ts +12 -0
  83. package/src/sdk/base/SDKConstruct.ts +35 -0
  84. package/src/sdk/base/TokensMeta.ts +45 -0
  85. package/src/sdk/base/index.ts +6 -0
  86. package/src/sdk/base/types.ts +102 -0
  87. package/src/sdk/bots/BotsService.ts +92 -0
  88. package/src/sdk/bots/index.ts +2 -0
  89. package/src/sdk/bots/utils.ts +19 -0
  90. package/src/sdk/chain/Provider.ts +99 -0
  91. package/src/sdk/chain/chains.ts +41 -0
  92. package/src/sdk/chain/detectChain.ts +21 -0
  93. package/src/sdk/chain/index.ts +3 -0
  94. package/src/sdk/constants/address-provider.ts +47 -0
  95. package/src/sdk/constants/addresses.ts +82 -0
  96. package/src/sdk/constants/bot-permissions.ts +36 -0
  97. package/src/sdk/constants/index.ts +6 -0
  98. package/src/sdk/constants/math.ts +23 -0
  99. package/src/sdk/constants/networks.ts +38 -0
  100. package/src/sdk/constants/periphery.ts +7 -0
  101. package/src/sdk/core/BotListV3Contract.ts +103 -0
  102. package/src/sdk/core/GearStakingV3Contract.ts +84 -0
  103. package/src/sdk/core/address-provider/AbstractAddressProviderContract.ts +101 -0
  104. package/src/sdk/core/address-provider/AddressProviderV3Contract.ts +105 -0
  105. package/src/sdk/core/address-provider/AddressProviderV3_1Contract.ts +92 -0
  106. package/src/sdk/core/address-provider/getAddressProvider.ts +45 -0
  107. package/src/sdk/core/address-provider/index.ts +4 -0
  108. package/src/sdk/core/address-provider/types.ts +17 -0
  109. package/src/sdk/core/index.ts +3 -0
  110. package/src/sdk/gauges/GaugeStakingService.ts +100 -0
  111. package/src/sdk/gauges/index.ts +2 -0
  112. package/src/sdk/gauges/utils.ts +25 -0
  113. package/src/sdk/index.ts +17 -0
  114. package/src/sdk/market/MarketConfiguratorContract.ts +78 -0
  115. package/src/sdk/market/MarketRegister.ts +330 -0
  116. package/src/sdk/market/MarketSuite.ts +83 -0
  117. package/src/sdk/market/adapters/PlaceholderAdapterContracts.ts +18 -0
  118. package/src/sdk/market/adapters/factory.ts +34 -0
  119. package/src/sdk/market/adapters/index.ts +3 -0
  120. package/src/sdk/market/adapters/types.ts +7 -0
  121. package/src/sdk/market/credit/CreditConfiguratorV300Contract.ts +164 -0
  122. package/src/sdk/market/credit/CreditConfiguratorV310Contract.ts +139 -0
  123. package/src/sdk/market/credit/CreditFacadeV300Contract.ts +206 -0
  124. package/src/sdk/market/credit/CreditFacadeV310Contract.ts +190 -0
  125. package/src/sdk/market/credit/CreditManagerV300Contract.ts +122 -0
  126. package/src/sdk/market/credit/CreditManagerV310Contract.ts +122 -0
  127. package/src/sdk/market/credit/CreditSuite.ts +65 -0
  128. package/src/sdk/market/credit/createCreditConfigurator.ts +18 -0
  129. package/src/sdk/market/credit/createCreditFacade.ts +18 -0
  130. package/src/sdk/market/credit/createCreditManager.ts +18 -0
  131. package/src/sdk/market/credit/index.ts +8 -0
  132. package/src/sdk/market/credit/types.ts +42 -0
  133. package/src/sdk/market/index.ts +7 -0
  134. package/src/sdk/market/oracle/PriceOracleBaseContract.ts +376 -0
  135. package/src/sdk/market/oracle/PriceOracleV300Contract.ts +71 -0
  136. package/src/sdk/market/oracle/PriceOracleV310Contract.ts +43 -0
  137. package/src/sdk/market/oracle/createPriceOracle.ts +22 -0
  138. package/src/sdk/market/oracle/index.ts +4 -0
  139. package/src/sdk/market/oracle/types.ts +48 -0
  140. package/src/sdk/market/pool/GaugeContract.ts +120 -0
  141. package/src/sdk/market/pool/LinearInterestRateModelContract.ts +75 -0
  142. package/src/sdk/market/pool/PoolQuotaKeeperV300Contract.ts +89 -0
  143. package/src/sdk/market/pool/PoolQuotaKeeperV310Contract.ts +89 -0
  144. package/src/sdk/market/pool/PoolSuite.ts +76 -0
  145. package/src/sdk/market/pool/PoolV300Contract.ts +144 -0
  146. package/src/sdk/market/pool/PoolV310Contract.ts +144 -0
  147. package/src/sdk/market/pool/TumblerContract.ts +73 -0
  148. package/src/sdk/market/pool/createInterestRateModel.ts +33 -0
  149. package/src/sdk/market/pool/createPool.ts +19 -0
  150. package/src/sdk/market/pool/createPoolQuotaKeeper.ts +20 -0
  151. package/src/sdk/market/pool/createRateKeeper.ts +25 -0
  152. package/src/sdk/market/pool/index.ts +6 -0
  153. package/src/sdk/market/pool/types.ts +28 -0
  154. package/src/sdk/market/pricefeeds/AbstractLPPriceFeed.ts +71 -0
  155. package/src/sdk/market/pricefeeds/AbstractPriceFeed.ts +137 -0
  156. package/src/sdk/market/pricefeeds/BalancerStablePriceFeed.ts +24 -0
  157. package/src/sdk/market/pricefeeds/BalancerWeightedPriceFeed.ts +70 -0
  158. package/src/sdk/market/pricefeeds/BoundedPriceFeed.ts +34 -0
  159. package/src/sdk/market/pricefeeds/ChainlinkPriceFeed.ts +16 -0
  160. package/src/sdk/market/pricefeeds/CompositePriceFeed.ts +25 -0
  161. package/src/sdk/market/pricefeeds/CurveCryptoPriceFeed.ts +24 -0
  162. package/src/sdk/market/pricefeeds/CurveStablePriceFeed.ts +24 -0
  163. package/src/sdk/market/pricefeeds/CurveUSDPriceFeed.ts +24 -0
  164. package/src/sdk/market/pricefeeds/Erc4626PriceFeed.ts +36 -0
  165. package/src/sdk/market/pricefeeds/MellowLRTPriceFeed.ts +26 -0
  166. package/src/sdk/market/pricefeeds/PendleTWAPPTPriceFeed.ts +44 -0
  167. package/src/sdk/market/pricefeeds/PriceFeedRef.ts +34 -0
  168. package/src/sdk/market/pricefeeds/PriceFeedsRegister.ts +293 -0
  169. package/src/sdk/market/pricefeeds/RedstonePriceFeed.ts +65 -0
  170. package/src/sdk/market/pricefeeds/RedstoneUpdater.ts +304 -0
  171. package/src/sdk/market/pricefeeds/WstETHPriceFeed.ts +24 -0
  172. package/src/sdk/market/pricefeeds/YearnPriceFeed.ts +24 -0
  173. package/src/sdk/market/pricefeeds/ZeroPriceFeed.ts +17 -0
  174. package/src/sdk/market/pricefeeds/index.ts +20 -0
  175. package/src/sdk/market/pricefeeds/types.ts +82 -0
  176. package/src/sdk/market/pricefeeds/utils.ts +24 -0
  177. package/src/sdk/plugins/index.ts +10 -0
  178. package/src/sdk/router/PathOptionFactory.ts +147 -0
  179. package/src/sdk/router/RouterV3Contract.ts +558 -0
  180. package/src/sdk/router/index.ts +2 -0
  181. package/src/sdk/router/types.ts +48 -0
  182. package/src/sdk/sdk-gov-legacy/contracts/adapters.ts +39 -0
  183. package/src/sdk/sdk-gov-legacy/contracts/contracts.ts +647 -0
  184. package/src/sdk/sdk-gov-legacy/contracts/index.ts +2 -0
  185. package/src/sdk/sdk-gov-legacy/core/constants.ts +11 -0
  186. package/src/sdk/sdk-gov-legacy/index.ts +4 -0
  187. package/src/sdk/sdk-gov-legacy/oracles/PriceFeedType.ts +24 -0
  188. package/src/sdk/sdk-gov-legacy/oracles/index.ts +1 -0
  189. package/src/sdk/sdk-gov-legacy/tokens/aave.ts +101 -0
  190. package/src/sdk/sdk-gov-legacy/tokens/aura.ts +284 -0
  191. package/src/sdk/sdk-gov-legacy/tokens/balancer.ts +421 -0
  192. package/src/sdk/sdk-gov-legacy/tokens/compound.ts +79 -0
  193. package/src/sdk/sdk-gov-legacy/tokens/convex.ts +561 -0
  194. package/src/sdk/sdk-gov-legacy/tokens/curveLP.ts +480 -0
  195. package/src/sdk/sdk-gov-legacy/tokens/decimals.ts +301 -0
  196. package/src/sdk/sdk-gov-legacy/tokens/erc4626.ts +75 -0
  197. package/src/sdk/sdk-gov-legacy/tokens/gear.ts +273 -0
  198. package/src/sdk/sdk-gov-legacy/tokens/index.ts +18 -0
  199. package/src/sdk/sdk-gov-legacy/tokens/normal.ts +613 -0
  200. package/src/sdk/sdk-gov-legacy/tokens/quoted.ts +10 -0
  201. package/src/sdk/sdk-gov-legacy/tokens/stakingRewards.ts +41 -0
  202. package/src/sdk/sdk-gov-legacy/tokens/token.ts +2354 -0
  203. package/src/sdk/sdk-gov-legacy/tokens/tokenData.ts +44 -0
  204. package/src/sdk/sdk-gov-legacy/tokens/tokenType.ts +33 -0
  205. package/src/sdk/sdk-gov-legacy/tokens/wrapped.ts +28 -0
  206. package/src/sdk/sdk-gov-legacy/tokens/yearn.ts +122 -0
  207. package/src/sdk/sdk-gov-legacy/tokens/zircuit.ts +44 -0
  208. package/src/sdk/sdk-legacy/apy/index.ts +149 -0
  209. package/src/sdk/sdk-legacy/core/assets.ts +200 -0
  210. package/src/sdk/sdk-legacy/core/creditAccount.spec.ts +1966 -0
  211. package/src/sdk/sdk-legacy/core/creditAccount.ts +816 -0
  212. package/src/sdk/sdk-legacy/core/creditManager.ts +316 -0
  213. package/src/sdk/sdk-legacy/core/creditSession.ts +352 -0
  214. package/src/sdk/sdk-legacy/core/endpoint.ts +131 -0
  215. package/src/sdk/sdk-legacy/core/eventOrTx.ts +101 -0
  216. package/src/sdk/sdk-legacy/core/pool.ts +439 -0
  217. package/src/sdk/sdk-legacy/core/strategy.ts +82 -0
  218. package/src/sdk/sdk-legacy/core/transactions.ts +865 -0
  219. package/src/sdk/sdk-legacy/gearboxRewards/api.ts +704 -0
  220. package/src/sdk/sdk-legacy/gearboxRewards/apy.ts +267 -0
  221. package/src/sdk/sdk-legacy/gearboxRewards/extraAPY.ts +165 -0
  222. package/src/sdk/sdk-legacy/gearboxRewards/index.ts +3 -0
  223. package/src/sdk/sdk-legacy/gearboxRewards/merklAPI.ts +151 -0
  224. package/src/sdk/sdk-legacy/index.ts +21 -0
  225. package/src/sdk/sdk-legacy/pathfinder/core.ts +18 -0
  226. package/src/sdk/sdk-legacy/pathfinder/index.ts +1 -0
  227. package/src/sdk/sdk-legacy/payload/creditAccount.ts +48 -0
  228. package/src/sdk/sdk-legacy/payload/creditManager.ts +133 -0
  229. package/src/sdk/sdk-legacy/payload/creditSession.ts +143 -0
  230. package/src/sdk/sdk-legacy/payload/graphPayload.ts +10 -0
  231. package/src/sdk/sdk-legacy/payload/pool.ts +198 -0
  232. package/src/sdk/sdk-legacy/payload/token.ts +13 -0
  233. package/src/sdk/sdk-legacy/tokens/tokenData.ts +57 -0
  234. package/src/sdk/sdk-legacy/types/IAirdropDistributor.ts +103 -0
  235. package/src/sdk/sdk-legacy/types/IBaseRewardPool.ts +249 -0
  236. package/src/sdk/sdk-legacy/types/IDataCompressorV3.ts +957 -0
  237. package/src/sdk/sdk-legacy/types/IDegenDistributor.ts +70 -0
  238. package/src/sdk/sdk-legacy/types/IERC20Permit.ts +35 -0
  239. package/src/sdk/sdk-legacy/types/IERC20ZapperDeposits.ts +99 -0
  240. package/src/sdk/sdk-legacy/types/IETHZapperDeposits.ts +27 -0
  241. package/src/sdk/sdk-legacy/types/IFarmingPool.ts +229 -0
  242. package/src/sdk/sdk-legacy/types/IInterestRateModel.ts +23 -0
  243. package/src/sdk/sdk-legacy/types/IMulticall3.ts +242 -0
  244. package/src/sdk/sdk-legacy/types/IOffchainOracle.ts +31 -0
  245. package/src/sdk/sdk-legacy/types/index.ts +11 -0
  246. package/src/sdk/sdk-legacy/utils/formatter.ts +46 -0
  247. package/src/sdk/sdk-legacy/utils/index.ts +3 -0
  248. package/src/sdk/sdk-legacy/utils/math.ts +6 -0
  249. package/src/sdk/sdk-legacy/utils/price.ts +27 -0
  250. package/src/sdk/types/index.ts +5 -0
  251. package/src/sdk/types/logger.ts +13 -0
  252. package/src/sdk/types/state-human.ts +224 -0
  253. package/src/sdk/types/state.ts +8 -0
  254. package/src/sdk/types/transactions.ts +22 -0
  255. package/src/sdk/types/tvl.ts +4 -0
  256. package/src/sdk/utils/AddressMap.ts +111 -0
  257. package/src/sdk/utils/bytes32ToString.ts +6 -0
  258. package/src/sdk/utils/childLogger.ts +8 -0
  259. package/src/sdk/utils/createRawTx.ts +86 -0
  260. package/src/sdk/utils/etherscan.ts +42 -0
  261. package/src/sdk/utils/filterDust.ts +20 -0
  262. package/src/sdk/utils/formatter.ts +124 -0
  263. package/src/sdk/utils/index.ts +10 -0
  264. package/src/sdk/utils/internal/Hooks.ts +51 -0
  265. package/src/sdk/utils/internal/index.ts +1 -0
  266. package/src/sdk/utils/json.ts +27 -0
  267. package/src/sdk/utils/mappers.ts +38 -0
  268. package/src/sdk/utils/retry.ts +24 -0
  269. package/src/sdk/utils/viem/detectNetwork.ts +27 -0
  270. package/src/sdk/utils/viem/index.ts +3 -0
  271. package/src/sdk/utils/viem/sendRawTx.ts +36 -0
  272. package/src/sdk/utils/viem/simulateMulticall.ts +262 -0
  273. package/tsconfig.build.json +4 -0
  274. package/tsconfig.json +16 -0
  275. package/tsup.config.ts +77 -0
@@ -0,0 +1,330 @@
1
+ import type { Address } from "viem";
2
+
3
+ import {
4
+ iMarketCompressorAbi,
5
+ iPeripheryCompressorAbi,
6
+ } from "../../abi/compressors";
7
+ import type { MarketData, MarketFilter, ZapperData } from "../base";
8
+ import { SDKConstruct } from "../base";
9
+ import {
10
+ ADDRESS_0X0,
11
+ AP_MARKET_COMPRESSOR,
12
+ AP_PERIPHERY_COMPRESSOR,
13
+ } from "../constants";
14
+ import type { GearboxSDK } from "../GearboxSDK";
15
+ import type {
16
+ ILogger,
17
+ MarketStateHuman,
18
+ RawTx,
19
+ TVL,
20
+ ZapperStateHuman,
21
+ } from "../types";
22
+ import { AddressMap, childLogger } from "../utils";
23
+ import { simulateMulticall } from "../utils/viem";
24
+ import type { CreditSuite } from "./credit";
25
+ import type { MarketConfiguratorContract } from "./MarketConfiguratorContract";
26
+ import { MarketSuite } from "./MarketSuite";
27
+ import type { PoolSuite } from "./pool";
28
+ import { rawTxToMulticallPriceUpdate } from "./pricefeeds";
29
+
30
+ export interface ZapperDataFull extends ZapperData {
31
+ pool: Address;
32
+ }
33
+
34
+ export class MarketRegister extends SDKConstruct {
35
+ #logger?: ILogger;
36
+ /**
37
+ * Mapping pool.address -> MarketSuite
38
+ */
39
+ #markets = new AddressMap<MarketSuite>(undefined, "markets");
40
+ #zappers = new AddressMap<Array<ZapperDataFull>>(undefined, "zappers");
41
+
42
+ #marketFilter?: MarketFilter;
43
+
44
+ constructor(sdk: GearboxSDK, markets?: MarketData[]) {
45
+ super(sdk);
46
+ this.#logger = childLogger("MarketRegister", sdk.logger);
47
+ for (const data of markets ?? []) {
48
+ this.#markets.upsert(
49
+ data.pool.baseParams.addr,
50
+ new MarketSuite(this.sdk, data),
51
+ );
52
+ }
53
+ }
54
+
55
+ public async loadMarkets(
56
+ marketConfigurators: Address[],
57
+ ignoreUpdateablePrices?: boolean,
58
+ ): Promise<void> {
59
+ if (!marketConfigurators.length) {
60
+ this.#logger?.warn(
61
+ "no market configurators provided, skipping loadMarkets",
62
+ );
63
+ return;
64
+ }
65
+ await this.#loadMarkets(marketConfigurators, [], ignoreUpdateablePrices);
66
+ }
67
+
68
+ public async loadZappers(): Promise<void> {
69
+ const pcAddr = this.sdk.addressProvider.getAddress(
70
+ AP_PERIPHERY_COMPRESSOR,
71
+ 3_10,
72
+ );
73
+ this.#logger?.debug(`loading zappers with periphery compressor ${pcAddr}`);
74
+ const resp = await this.provider.publicClient.multicall({
75
+ contracts: this.markets.map(m => ({
76
+ abi: iPeripheryCompressorAbi,
77
+ address: pcAddr,
78
+ functionName: "getZappers",
79
+ args: [m.configurator.address, m.pool.pool.address],
80
+ })),
81
+ allowFailure: true,
82
+ });
83
+
84
+ for (let i = 0; i < resp.length; i++) {
85
+ const { status, result, error } = resp[i];
86
+ const marketConfigurator = this.markets[i].configurator.address;
87
+ const pool = this.markets[i].pool.pool.address;
88
+
89
+ if (status === "success") {
90
+ const list = result as any as ZapperData[];
91
+
92
+ this.#zappers.upsert(
93
+ pool,
94
+ list.map(z => ({ ...z, pool })),
95
+ );
96
+ } else {
97
+ this.#logger?.error(
98
+ `failed to load zapper for market configurator ${this.labelAddress(marketConfigurator)} and pool ${this.labelAddress(pool)}: ${error}`,
99
+ );
100
+ }
101
+ }
102
+
103
+ const zappersTokens = this.#zappers
104
+ .values()
105
+ .flatMap(l => l.flatMap(z => [z.tokenIn, z.tokenOut]));
106
+ for (const t of zappersTokens) {
107
+ this.sdk.tokensMeta.upsert(t.addr, t);
108
+ this.sdk.provider.addressLabels.set(t.addr as Address, t.symbol);
109
+ }
110
+ }
111
+
112
+ get marketFilter() {
113
+ return this.#marketFilter;
114
+ }
115
+
116
+ public async syncState(): Promise<void> {
117
+ const pools = this.markets
118
+ .filter(m => m.dirty)
119
+ .map(m => m.pool.pool.address);
120
+ if (pools.length) {
121
+ this.#logger?.debug(`need to reload ${pools.length} markets`);
122
+ await this.#loadMarkets([], pools);
123
+ }
124
+ }
125
+
126
+ async #loadMarkets(
127
+ configurators: Address[],
128
+ pools: Address[],
129
+ ignoreUpdateablePrices?: boolean,
130
+ ): Promise<void> {
131
+ this.#marketFilter = {
132
+ configurators,
133
+ pools,
134
+ underlying: ADDRESS_0X0,
135
+ };
136
+ const marketCompressorAddress = this.sdk.addressProvider.getAddress(
137
+ AP_MARKET_COMPRESSOR,
138
+ 3_10,
139
+ );
140
+ let txs: RawTx[] = [];
141
+ if (!ignoreUpdateablePrices) {
142
+ // to have correct prices we must first get all updatable price feeds
143
+ await this.sdk.priceFeeds.preloadUpdatablePriceFeeds(
144
+ configurators,
145
+ pools,
146
+ );
147
+ // the generate updates
148
+ const updates = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs();
149
+ txs = updates.txs;
150
+ }
151
+ this.#logger?.debug(
152
+ { configurators, pools },
153
+ `calling getMarkets with ${txs.length} price updates`,
154
+ );
155
+ // ...and push them using multicall before getting answers
156
+ let markets: readonly MarketData[] = [];
157
+ if (txs.length) {
158
+ const resp = await simulateMulticall(this.provider.publicClient, {
159
+ contracts: [
160
+ ...txs.map(rawTxToMulticallPriceUpdate),
161
+ {
162
+ abi: iMarketCompressorAbi,
163
+ address: marketCompressorAddress,
164
+ functionName: "getMarkets",
165
+ args: [this.#marketFilter],
166
+ },
167
+ ],
168
+ allowFailure: false,
169
+ // gas: 550_000_000n,
170
+ batchSize: 0, // we cannot have price updates and compressor request in different batches
171
+ });
172
+ markets = resp.pop() as MarketData[];
173
+ } else {
174
+ markets = await this.provider.publicClient.readContract({
175
+ abi: iMarketCompressorAbi,
176
+ address: marketCompressorAddress,
177
+ functionName: "getMarkets",
178
+ args: [this.#marketFilter],
179
+ // gas: 550_000_000n,
180
+ });
181
+ }
182
+
183
+ for (const data of markets) {
184
+ this.#markets.upsert(
185
+ data.pool.baseParams.addr,
186
+ new MarketSuite(this.sdk, data),
187
+ );
188
+ }
189
+
190
+ this.#logger?.info(`loaded ${markets.length} markets`);
191
+ }
192
+
193
+ /**
194
+ * Loads new prices and price feeds for given oracles from PriceFeedCompressor, defaults to all oracles
195
+ * Supports v300 and v310 oracles
196
+ */
197
+ public async updatePrices(oracles?: Address[]): Promise<void> {
198
+ const multicalls = this.markets
199
+ .map(m => m.priceOracle)
200
+ .filter(o => !oracles || oracles.includes(o.address))
201
+ .map(o => o.syncStateMulticall());
202
+ if (!multicalls.length) {
203
+ return;
204
+ }
205
+ const { txs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs();
206
+ const resp = await simulateMulticall(this.provider.publicClient, {
207
+ contracts: [
208
+ ...txs.map(rawTxToMulticallPriceUpdate),
209
+ ...multicalls.map(mc => mc.call),
210
+ ],
211
+ allowFailure: false,
212
+ // gas: 550_000_000n,
213
+ batchSize: 0, // we cannot have price updates and compressor request in different batches
214
+ });
215
+ const oraclesStates = resp.slice(txs.length);
216
+ for (let i = 0; i < multicalls.length; i++) {
217
+ const handler = multicalls[i].onResult;
218
+ const result = oraclesStates[i] as any;
219
+ handler(result);
220
+ }
221
+ }
222
+
223
+ public get state(): MarketData[] {
224
+ return this.markets.map(market => market.state);
225
+ }
226
+
227
+ public stateHuman(raw = true): {
228
+ markets: MarketStateHuman[];
229
+ zappers: ZapperStateHuman[];
230
+ } {
231
+ return {
232
+ markets: this.markets.map(market => market.stateHuman(raw)),
233
+ zappers: this.zappers.values().flatMap(l =>
234
+ l.flatMap(z => ({
235
+ address: z.baseParams.addr,
236
+ contractType: z.baseParams.contractType,
237
+ version: Number(z.baseParams.version),
238
+ tokenIn: this.labelAddress(z.tokenIn.addr),
239
+ tokenOut: this.labelAddress(z.tokenOut.addr),
240
+ })),
241
+ ),
242
+ };
243
+ }
244
+
245
+ public get pools(): PoolSuite[] {
246
+ return this.markets.map(market => market.pool);
247
+ }
248
+
249
+ public get creditManagers(): CreditSuite[] {
250
+ return this.markets.flatMap(market => market.creditManagers);
251
+ }
252
+
253
+ public get marketConfigurators(): MarketConfiguratorContract[] {
254
+ const result = new Set<MarketConfiguratorContract>();
255
+ for (const m of this.markets) {
256
+ result.add(m.configurator);
257
+ }
258
+ return Array.from(result);
259
+ }
260
+
261
+ public findCreditManager(creditManager: Address): CreditSuite {
262
+ const addr = creditManager.toLowerCase();
263
+ for (const market of this.markets) {
264
+ for (const cm of market.creditManagers) {
265
+ if (cm.creditManager.address.toLowerCase() === addr) {
266
+ return cm;
267
+ }
268
+ }
269
+ }
270
+ throw new Error(`cannot find credit manager ${creditManager}`);
271
+ }
272
+
273
+ public findByCreditManager(creditManager: Address): MarketSuite {
274
+ const addr = creditManager.toLowerCase();
275
+ const market = this.markets.find(m =>
276
+ m.creditManagers.some(
277
+ cm => cm.creditManager.address.toLowerCase() === addr,
278
+ ),
279
+ );
280
+ if (!market) {
281
+ throw new Error(`cannot find market for credit manager ${creditManager}`);
282
+ }
283
+ return market;
284
+ }
285
+
286
+ public findByPriceOracle(address: Address): MarketSuite {
287
+ const addr = address.toLowerCase();
288
+ for (const market of this.markets) {
289
+ if (market.priceOracle.address.toLowerCase() === addr) {
290
+ return market;
291
+ }
292
+ }
293
+ throw new Error(`cannot find market for price oracle ${address}`);
294
+ }
295
+
296
+ public findByPool(address: Address): MarketSuite {
297
+ const addr = address.toLowerCase();
298
+ for (const market of this.markets) {
299
+ if (market.pool.pool.address.toLowerCase() === addr) {
300
+ return market;
301
+ }
302
+ }
303
+ throw new Error(`cannot find market for pool ${address}`);
304
+ }
305
+
306
+ public get marketsMap() {
307
+ return this.#markets;
308
+ }
309
+
310
+ public get zappers() {
311
+ return this.#zappers;
312
+ }
313
+
314
+ public get markets(): MarketSuite[] {
315
+ return this.#markets.values();
316
+ }
317
+
318
+ public async tvl(): Promise<TVL> {
319
+ const creditManagers = this.creditManagers;
320
+ const tvls = await Promise.all(creditManagers.map(cm => cm.tvl()));
321
+ return tvls.reduce(
322
+ (acc, curr) => {
323
+ acc.tvl += curr.tvl;
324
+ acc.tvlUSD += curr.tvlUSD;
325
+ return acc;
326
+ },
327
+ { tvl: 0n, tvlUSD: 0n },
328
+ );
329
+ }
330
+ }
@@ -0,0 +1,83 @@
1
+ import type { Address } from "viem";
2
+
3
+ import type { MarketData } from "../base";
4
+ import { SDKConstruct } from "../base";
5
+ import type { GearboxSDK } from "../GearboxSDK";
6
+ import type { MarketStateHuman } from "../types";
7
+ import { CreditSuite } from "./credit";
8
+ import { MarketConfiguratorContract } from "./MarketConfiguratorContract";
9
+ import type { PriceOracleContract } from "./oracle";
10
+ import { createPriceOracle } from "./oracle";
11
+ import { PoolSuite } from "./pool";
12
+
13
+ export class MarketSuite extends SDKConstruct {
14
+ public readonly acl: Address;
15
+ public readonly configurator: MarketConfiguratorContract;
16
+ public readonly pool: PoolSuite;
17
+ public readonly priceOracle: PriceOracleContract;
18
+ public readonly creditManagers: CreditSuite[] = [];
19
+ /**
20
+ * Original data received from compressor
21
+ */
22
+ public readonly state: MarketData;
23
+
24
+ constructor(sdk: GearboxSDK, marketData: MarketData) {
25
+ super(sdk);
26
+ this.state = marketData;
27
+
28
+ let configurator = sdk.contracts.get(
29
+ marketData.configurator,
30
+ ) as unknown as MarketConfiguratorContract;
31
+ if (!configurator) {
32
+ configurator = new MarketConfiguratorContract(
33
+ sdk,
34
+ marketData.configurator,
35
+ );
36
+ }
37
+ this.configurator = configurator;
38
+
39
+ this.acl = marketData.acl;
40
+
41
+ for (const t of marketData.tokens) {
42
+ sdk.tokensMeta.upsert(t.addr, t);
43
+ sdk.provider.addressLabels.set(t.addr as Address, t.symbol);
44
+ }
45
+
46
+ this.pool = new PoolSuite(sdk, marketData);
47
+
48
+ for (let i = 0; i < marketData.creditManagers.length; i++) {
49
+ this.creditManagers.push(new CreditSuite(sdk, marketData, i));
50
+ }
51
+
52
+ this.priceOracle = createPriceOracle(
53
+ sdk,
54
+ marketData.priceOracleData,
55
+ marketData.pool.underlying,
56
+ );
57
+ }
58
+
59
+ override get dirty(): boolean {
60
+ return (
61
+ this.configurator.dirty ||
62
+ this.pool.dirty ||
63
+ this.priceOracle.dirty ||
64
+ this.creditManagers.some(cm => cm.dirty)
65
+ );
66
+ }
67
+
68
+ public stateHuman(raw = true): MarketStateHuman {
69
+ return {
70
+ configurator: this.labelAddress(this.configurator.address),
71
+ pool: this.pool.stateHuman(raw),
72
+ creditManagers: this.creditManagers.map(cm => cm.stateHuman(raw)),
73
+ priceOracle: this.priceOracle.stateHuman(raw),
74
+ pausableAdmins: this.state.pausableAdmins.map(a => this.labelAddress(a)),
75
+ unpausableAdmins: this.state.unpausableAdmins.map(a =>
76
+ this.labelAddress(a),
77
+ ),
78
+ emergencyLiquidators: this.state.emergencyLiquidators.map(a =>
79
+ this.labelAddress(a),
80
+ ),
81
+ };
82
+ }
83
+ }
@@ -0,0 +1,18 @@
1
+ import type { Address } from "viem";
2
+
3
+ import type { AdapterData } from "../../base";
4
+ import { PlaceholderContract } from "../../base";
5
+ import type { GearboxSDK } from "../../GearboxSDK";
6
+ import type { IAdapterContract } from "./types";
7
+
8
+ export class PlaceholderAdapterContract
9
+ extends PlaceholderContract
10
+ implements IAdapterContract
11
+ {
12
+ public readonly targetContract: Address;
13
+
14
+ constructor(sdk: GearboxSDK, args: AdapterData) {
15
+ super(sdk, args.baseParams);
16
+ this.targetContract = args.targetContract;
17
+ }
18
+ }
@@ -0,0 +1,34 @@
1
+ import type { Hex } from "viem";
2
+
3
+ import type { AdapterData } from "../../base";
4
+ import type { GearboxSDK } from "../../GearboxSDK";
5
+ import { bytes32ToString } from "../../utils";
6
+ import { PlaceholderAdapterContract } from "./PlaceholderAdapterContracts";
7
+ import type { IAdapterContract } from "./types";
8
+
9
+ export function createAdapter(
10
+ sdk: GearboxSDK,
11
+ args: AdapterData,
12
+ ): IAdapterContract {
13
+ const adapterType = bytes32ToString(args.baseParams.contractType as Hex);
14
+ for (const plugin of sdk.plugins) {
15
+ try {
16
+ const adapter = plugin.createContract(sdk, args);
17
+ if (adapter) {
18
+ sdk.logger?.info(
19
+ ` ${adapterType} v${args.baseParams.version} created using plugin ${plugin.name}`,
20
+ );
21
+ return adapter as IAdapterContract;
22
+ }
23
+ } catch (e) {
24
+ sdk.logger?.warn(
25
+ `plugin ${plugin.name} error while trying to create ${adapterType} v${args.baseParams.version}: ${e}`,
26
+ );
27
+ }
28
+ }
29
+
30
+ sdk.logger?.warn(
31
+ `no class found for ${adapterType} v${args.baseParams.version}, falling back to placeholder`,
32
+ );
33
+ return new PlaceholderAdapterContract(sdk, args);
34
+ }
@@ -0,0 +1,3 @@
1
+ export * from "./factory";
2
+ export * from "./PlaceholderAdapterContracts";
3
+ export * from "./types";
@@ -0,0 +1,7 @@
1
+ import type { Address } from "viem";
2
+
3
+ import type { IBaseContract } from "../../base";
4
+
5
+ export interface IAdapterContract extends IBaseContract {
6
+ targetContract: Address;
7
+ }
@@ -0,0 +1,164 @@
1
+ import type {
2
+ Address,
3
+ ContractEventName,
4
+ DecodeFunctionDataReturnType,
5
+ GetEventArgs,
6
+ Log,
7
+ } from "viem";
8
+
9
+ import { iPausableAbi } from "../../../abi/iPausable";
10
+ import { iCreditConfiguratorV300Abi } from "../../../abi/v300";
11
+ import type { CreditManagerData } from "../../base";
12
+ import { BaseContract } from "../../base";
13
+ import { RAMP_DURATION_BY_NETWORK } from "../../constants";
14
+ import type { GearboxSDK } from "../../GearboxSDK";
15
+ import { formatDuration, percentFmt } from "../../utils";
16
+ import type { ICreditConfiguratorContract } from "./types";
17
+
18
+ const abi = [...iCreditConfiguratorV300Abi, ...iPausableAbi] as const;
19
+ type abi = typeof abi;
20
+
21
+ export type RampEvent = GetEventArgs<
22
+ abi,
23
+ "ScheduleTokenLiquidationThresholdRamp",
24
+ {
25
+ EnableUnion: false;
26
+ IndexedOnly: false;
27
+ Required: true;
28
+ }
29
+ >;
30
+
31
+ export class CreditConfiguratorV300Contract
32
+ extends BaseContract<abi>
33
+ implements ICreditConfiguratorContract
34
+ {
35
+ public readonly adapters: Address[] = [];
36
+ public isPaused = false;
37
+
38
+ constructor(
39
+ sdk: GearboxSDK,
40
+ { creditConfigurator, creditManager }: CreditManagerData,
41
+ ) {
42
+ super(sdk, {
43
+ ...creditConfigurator.baseParams,
44
+ name: `CreditConfigurator(${creditManager.name})`,
45
+ abi,
46
+ });
47
+ }
48
+
49
+ public override processLog(
50
+ log: Log<
51
+ bigint,
52
+ number,
53
+ false,
54
+ undefined,
55
+ undefined,
56
+ abi,
57
+ ContractEventName<abi>
58
+ >,
59
+ ): void {
60
+ switch (log.eventName) {
61
+ case "Paused":
62
+ this.isPaused = true;
63
+ break;
64
+ case "Unpaused":
65
+ this.isPaused = false;
66
+ break;
67
+ case "AddCollateralToken":
68
+ case "AddEmergencyLiquidator":
69
+ case "AllowAdapter":
70
+ case "AllowToken":
71
+ case "CreditConfiguratorUpgraded":
72
+ case "ForbidAdapter":
73
+ case "ForbidToken":
74
+ case "QuoteToken":
75
+ case "RemoveEmergencyLiquidator":
76
+ case "ResetCumulativeLoss":
77
+ case "ScheduleTokenLiquidationThresholdRamp":
78
+ case "SetBorrowingLimits":
79
+ case "SetBotList":
80
+ case "SetCreditFacade":
81
+ case "SetExpirationDate":
82
+ case "SetMaxCumulativeLoss":
83
+ case "SetMaxDebtPerBlockMultiplier":
84
+ case "SetMaxEnabledTokens":
85
+ case "SetPriceOracle":
86
+ case "SetTokenLiquidationThreshold":
87
+ case "UpdateFees":
88
+ this.dirty = true;
89
+ break;
90
+ }
91
+ }
92
+
93
+ public async checkRamps(): Promise<RampEvent[]> {
94
+ let fromBlock =
95
+ this.sdk.currentBlock -
96
+ RAMP_DURATION_BY_NETWORK[this.sdk.provider.networkType];
97
+ fromBlock = fromBlock < 0n ? 0n : fromBlock;
98
+
99
+ const logs = await this.provider.publicClient.getContractEvents({
100
+ address: this.address,
101
+ abi: this.abi,
102
+ fromBlock,
103
+ eventName: "ScheduleTokenLiquidationThresholdRamp",
104
+ strict: true,
105
+ });
106
+
107
+ return logs.map(({ args }) => args);
108
+ }
109
+
110
+ public parseFunctionParams(
111
+ params: DecodeFunctionDataReturnType<abi>,
112
+ ): Array<string> | undefined {
113
+ switch (params.functionName) {
114
+ case "addCollateralToken":
115
+ case "setLiquidationThreshold": {
116
+ const [token, lt] = params.args;
117
+ return [this.labelAddress(token), percentFmt(lt)];
118
+ }
119
+ case "setExpirationDate": {
120
+ const [expirationDate] = params.args;
121
+ // TODO: add date format
122
+ return [`${expirationDate}`];
123
+ }
124
+ case "setFees": {
125
+ const [
126
+ feeInterest,
127
+ feeLiquidation,
128
+ liquidationPremium,
129
+ feeLiquidationExpired,
130
+ liquidationPremiumExpired,
131
+ ] = params.args;
132
+ return [
133
+ percentFmt(feeInterest),
134
+ percentFmt(feeLiquidation),
135
+ percentFmt(liquidationPremium),
136
+ percentFmt(feeLiquidationExpired),
137
+ percentFmt(liquidationPremiumExpired),
138
+ ];
139
+ }
140
+ // case "setMinDebtLimit":
141
+ // case "setMaxDebtLimit": {
142
+ // const [debt] = params.args;
143
+ // return [this.factory.convertUnderlying(debt)];
144
+ // }
145
+ case "setCreditFacade": {
146
+ const [newCreditFacade, migrateParams] = params.args;
147
+ return [this.labelAddress(newCreditFacade), `${migrateParams}`];
148
+ }
149
+ case "rampLiquidationThreshold": {
150
+ const [token, liquidationThresholdFinal, rampStart, rampDuration] =
151
+ params.args;
152
+ return [
153
+ this.labelAddress(token),
154
+ percentFmt(liquidationThresholdFinal),
155
+ `${rampStart}`,
156
+ formatDuration(rampDuration),
157
+ ];
158
+ }
159
+
160
+ default:
161
+ return undefined;
162
+ }
163
+ }
164
+ }