@gearbox-protocol/sdk 13.7.0-kyc.3 → 14.0.0-next.10

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 (214) hide show
  1. package/dist/cjs/dev/AccountOpener.js +5 -45
  2. package/dist/cjs/dev/RevolverTransport.js +10 -4
  3. package/dist/cjs/dev/index.js +0 -2
  4. package/dist/cjs/dev/logSplitterTransport.js +10 -1
  5. package/dist/cjs/permissionless/utils/create2.js +2 -2
  6. package/dist/cjs/permissionless/utils/price-update/get-price-feeds.js +11 -5
  7. package/dist/cjs/permissionless/utils/price-update/get-price-update-tx.js +11 -5
  8. package/dist/cjs/permissionless/utils/price-update/get-prices.js +12 -6
  9. package/dist/cjs/sdk/MultichainSDK.js +232 -0
  10. package/dist/cjs/sdk/OnchainSDK.js +478 -0
  11. package/dist/cjs/sdk/accounts/AbstractCreditAccountsService.js +16 -324
  12. package/dist/cjs/sdk/accounts/CreditAccountsServiceV310.js +1 -7
  13. package/dist/cjs/sdk/base/TokensMeta.js +42 -22
  14. package/dist/cjs/sdk/base/token-types.js +0 -9
  15. package/dist/cjs/sdk/chain/chains.js +1 -2
  16. package/dist/cjs/sdk/constants/address-provider.js +0 -3
  17. package/dist/cjs/sdk/core/errors.js +77 -0
  18. package/dist/cjs/sdk/core/index.js +2 -0
  19. package/dist/cjs/sdk/index.js +4 -2
  20. package/dist/cjs/sdk/market/MarketRegister.js +116 -70
  21. package/dist/cjs/sdk/market/MarketSuite.js +0 -3
  22. package/dist/cjs/sdk/market/index.js +0 -2
  23. package/dist/cjs/sdk/market/pool/PoolSuite.js +0 -3
  24. package/dist/cjs/sdk/market/pool/PoolV310Contract.js +2 -11
  25. package/dist/cjs/sdk/market/pool/index.js +0 -2
  26. package/dist/cjs/sdk/market/pricefeeds/PriceFeedsRegister.js +10 -3
  27. package/dist/cjs/sdk/market/pricefeeds/updates/PythAccumulatorUpdateData.js +20 -23
  28. package/dist/cjs/sdk/market/pricefeeds/updates/PythUpdater.js +7 -4
  29. package/dist/cjs/sdk/market/pricefeeds/updates/RedstoneUpdater.js +4 -4
  30. package/dist/cjs/sdk/market/pricefeeds/updates/fetchPythPayloads.js +1 -1
  31. package/dist/cjs/sdk/market/pricefeeds/updates/index.js +3 -0
  32. package/dist/cjs/sdk/options.js +24 -52
  33. package/dist/cjs/sdk/plugins/BasePlugin.js +11 -4
  34. package/dist/cjs/sdk/pools/PoolService.js +12 -104
  35. package/dist/cjs/sdk/utils/formatter.js +99 -20
  36. package/dist/cjs/sdk/utils/viem/index.js +3 -3
  37. package/dist/cjs/sdk/utils/viem/watchBlocksAsync.js +76 -0
  38. package/dist/esm/dev/AccountOpener.js +6 -47
  39. package/dist/esm/dev/RevolverTransport.js +10 -4
  40. package/dist/esm/dev/index.js +0 -1
  41. package/dist/esm/dev/logSplitterTransport.js +10 -1
  42. package/dist/esm/permissionless/utils/create2.js +1 -1
  43. package/dist/esm/permissionless/utils/price-update/get-price-feeds.js +12 -6
  44. package/dist/esm/permissionless/utils/price-update/get-price-update-tx.js +13 -7
  45. package/dist/esm/permissionless/utils/price-update/get-prices.js +13 -7
  46. package/dist/esm/sdk/MultichainSDK.js +217 -0
  47. package/dist/esm/sdk/OnchainSDK.js +472 -0
  48. package/dist/esm/sdk/accounts/AbstractCreditAccountsService.js +17 -328
  49. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +1 -7
  50. package/dist/esm/sdk/base/TokensMeta.js +44 -22
  51. package/dist/esm/sdk/base/token-types.js +0 -6
  52. package/dist/esm/sdk/chain/chains.js +1 -2
  53. package/dist/esm/sdk/constants/address-provider.js +0 -2
  54. package/dist/esm/sdk/core/errors.js +48 -0
  55. package/dist/esm/sdk/core/index.js +1 -0
  56. package/dist/esm/sdk/index.js +2 -1
  57. package/dist/esm/sdk/market/MarketRegister.js +118 -74
  58. package/dist/esm/sdk/market/MarketSuite.js +0 -3
  59. package/dist/esm/sdk/market/index.js +0 -1
  60. package/dist/esm/sdk/market/pool/PoolSuite.js +0 -3
  61. package/dist/esm/sdk/market/pool/PoolV310Contract.js +2 -11
  62. package/dist/esm/sdk/market/pool/index.js +0 -1
  63. package/dist/esm/sdk/market/pricefeeds/PriceFeedsRegister.js +10 -3
  64. package/dist/esm/sdk/market/pricefeeds/updates/PythAccumulatorUpdateData.js +20 -13
  65. package/dist/esm/sdk/market/pricefeeds/updates/PythUpdater.js +7 -4
  66. package/dist/esm/sdk/market/pricefeeds/updates/RedstoneUpdater.js +4 -4
  67. package/dist/esm/sdk/market/pricefeeds/updates/fetchPythPayloads.js +1 -1
  68. package/dist/esm/sdk/market/pricefeeds/updates/index.js +2 -0
  69. package/dist/esm/sdk/options.js +22 -51
  70. package/dist/esm/sdk/plugins/BasePlugin.js +11 -4
  71. package/dist/esm/sdk/pools/PoolService.js +13 -109
  72. package/dist/esm/sdk/utils/formatter.js +99 -10
  73. package/dist/esm/sdk/utils/viem/index.js +1 -1
  74. package/dist/esm/sdk/utils/viem/watchBlocksAsync.js +52 -0
  75. package/dist/types/dev/RevolverTransport.d.ts +2 -1
  76. package/dist/types/dev/calcLiquidatableLTs.d.ts +2 -2
  77. package/dist/types/dev/claimFromFaucet.d.ts +2 -2
  78. package/dist/types/dev/create2.d.ts +3 -4
  79. package/dist/types/dev/index.d.ts +0 -1
  80. package/dist/types/dev/logSplitterTransport.d.ts +3 -1
  81. package/dist/types/dev/migrateFaucet.d.ts +2 -2
  82. package/dist/types/dev/mint/AbstractMinter.d.ts +2 -2
  83. package/dist/types/dev/mint/FallbackMinter.d.ts +2 -2
  84. package/dist/types/dev/mint/factory.d.ts +2 -2
  85. package/dist/types/dev/replaceStorage.d.ts +1 -1
  86. package/dist/types/permissionless/utils/price-update/get-updatable-feeds.d.ts +2 -2
  87. package/dist/types/plugins/accounts/AccountsPlugin.d.ts +2 -2
  88. package/dist/types/plugins/accounts-counter/AccountsCounterPlugin.d.ts +2 -2
  89. package/dist/types/plugins/adapters/AdaptersPlugin.d.ts +2 -2
  90. package/dist/types/plugins/apy/ApyPlugin.d.ts +2 -2
  91. package/dist/types/plugins/bots/BotsPlugin.d.ts +2 -2
  92. package/dist/types/plugins/bots/PartialLiquidationBotV310Contract.d.ts +2 -2
  93. package/dist/types/plugins/degen-distributors/DegenDistributorsPlugin.d.ts +2 -2
  94. package/dist/types/plugins/delayed-withdrawal/DelayedWithdrawalPlugin.d.ts +2 -2
  95. package/dist/types/sdk/MultichainSDK.d.ts +144 -0
  96. package/dist/types/sdk/OnchainSDK.d.ts +257 -0
  97. package/dist/types/sdk/accounts/AbstractCreditAccountsService.d.ts +4 -54
  98. package/dist/types/sdk/accounts/CreditAccountsServiceV310.d.ts +1 -1
  99. package/dist/types/sdk/accounts/createCreditAccountService.d.ts +2 -2
  100. package/dist/types/sdk/accounts/types.d.ts +15 -95
  101. package/dist/types/sdk/base/SDKConstruct.d.ts +4 -4
  102. package/dist/types/sdk/base/TokensMeta.d.ts +3 -14
  103. package/dist/types/sdk/base/token-types.d.ts +4 -44
  104. package/dist/types/sdk/base/types.d.ts +2 -116
  105. package/dist/types/sdk/chain/chains.d.ts +1 -5
  106. package/dist/types/sdk/constants/address-provider.d.ts +0 -1
  107. package/dist/types/sdk/core/createAddressProvider.d.ts +3 -3
  108. package/dist/types/sdk/core/errors.d.ts +51 -0
  109. package/dist/types/sdk/core/index.d.ts +1 -0
  110. package/dist/types/sdk/index.d.ts +2 -1
  111. package/dist/types/sdk/market/MarketRegister.d.ts +11 -8
  112. package/dist/types/sdk/market/MarketSuite.d.ts +2 -4
  113. package/dist/types/sdk/market/adapters/createAdapter.d.ts +2 -2
  114. package/dist/types/sdk/market/credit/CreditConfiguratorV310Contract.d.ts +3 -3
  115. package/dist/types/sdk/market/credit/CreditManagerV310Contract.d.ts +2 -2
  116. package/dist/types/sdk/market/credit/CreditSuite.d.ts +2 -2
  117. package/dist/types/sdk/market/credit/createCreditConfigurator.d.ts +2 -2
  118. package/dist/types/sdk/market/credit/createCreditFacade.d.ts +2 -2
  119. package/dist/types/sdk/market/credit/createCreditManager.d.ts +2 -2
  120. package/dist/types/sdk/market/credit/types.d.ts +1 -1
  121. package/dist/types/sdk/market/index.d.ts +0 -1
  122. package/dist/types/sdk/market/loss-policy/AliasLossPolicyV310Contract.d.ts +3 -3
  123. package/dist/types/sdk/market/loss-policy/createLossPolicy.d.ts +2 -2
  124. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +5 -6
  125. package/dist/types/sdk/market/oracle/PriceOracleV310Contract.d.ts +2 -2
  126. package/dist/types/sdk/market/oracle/createPriceOracle.d.ts +2 -2
  127. package/dist/types/sdk/market/oracle/types.d.ts +10 -3
  128. package/dist/types/sdk/market/pool/PoolSuite.d.ts +2 -4
  129. package/dist/types/sdk/market/pool/PoolV310Contract.d.ts +2 -6
  130. package/dist/types/sdk/market/pool/createInterestRateModel.d.ts +2 -2
  131. package/dist/types/sdk/market/pool/createPool.d.ts +2 -2
  132. package/dist/types/sdk/market/pool/createPoolQuotaKeeper.d.ts +2 -2
  133. package/dist/types/sdk/market/pool/createRateKeeper.d.ts +2 -2
  134. package/dist/types/sdk/market/pool/index.d.ts +0 -1
  135. package/dist/types/sdk/market/pricefeeds/PriceFeedsRegister.d.ts +8 -3
  136. package/dist/types/sdk/market/pricefeeds/updates/PythAccumulatorUpdateData.d.ts +12 -13
  137. package/dist/types/sdk/market/pricefeeds/updates/PythUpdater.d.ts +8 -3
  138. package/dist/types/sdk/market/pricefeeds/updates/RedstoneUpdater.d.ts +8 -3
  139. package/dist/types/sdk/market/pricefeeds/updates/index.d.ts +1 -0
  140. package/dist/types/sdk/market/pricefeeds/updates/types.d.ts +4 -0
  141. package/dist/types/sdk/market/types.d.ts +1 -1
  142. package/dist/types/sdk/options.d.ts +15 -16
  143. package/dist/types/sdk/plugins/BasePlugin.d.ts +12 -6
  144. package/dist/types/sdk/plugins/errors.d.ts +2 -2
  145. package/dist/types/sdk/plugins/types.d.ts +16 -6
  146. package/dist/types/sdk/pools/PoolService.d.ts +8 -8
  147. package/dist/types/sdk/pools/types.d.ts +2 -3
  148. package/dist/types/sdk/router/AbstractRouterContract.d.ts +3 -3
  149. package/dist/types/sdk/router/RouterV310Contract.d.ts +2 -2
  150. package/dist/types/sdk/router/createRouter.d.ts +2 -2
  151. package/dist/types/sdk/router/helpers.d.ts +1 -1
  152. package/dist/types/sdk/types/state-human.d.ts +10 -2
  153. package/dist/types/sdk/types/state.d.ts +14 -8
  154. package/dist/types/sdk/utils/filterDust.d.ts +2 -2
  155. package/dist/types/sdk/utils/formatter.d.ts +1 -1
  156. package/dist/types/sdk/utils/isDust.d.ts +2 -2
  157. package/dist/types/sdk/utils/toAddress.d.ts +1 -1
  158. package/dist/types/sdk/utils/viem/getLogsPaginated.d.ts +1 -2
  159. package/dist/types/sdk/utils/viem/getLogsSafe.d.ts +1 -1
  160. package/dist/types/sdk/utils/viem/index.d.ts +1 -1
  161. package/dist/types/sdk/utils/viem/simulateWithPriceUpdates.d.ts +1 -2
  162. package/dist/types/sdk/utils/viem/watchBlocksAsync.d.ts +74 -0
  163. package/package.json +3 -6
  164. package/dist/cjs/abi/kyc/iDSRegistryService.js +0 -70
  165. package/dist/cjs/abi/kyc/iDSToken.js +0 -71
  166. package/dist/cjs/abi/kyc/iKYCCompressor.js +0 -196
  167. package/dist/cjs/abi/kyc/iKYCFactory.js +0 -122
  168. package/dist/cjs/abi/kyc/iKYCUnderlying.js +0 -401
  169. package/dist/cjs/abi/kyc/iSecuritizeDegenNFT.js +0 -326
  170. package/dist/cjs/abi/kyc/iSecuritizeKYCFactory.js +0 -319
  171. package/dist/cjs/dev/CachedStateSubscriber.js +0 -78
  172. package/dist/cjs/sdk/GearboxSDK.js +0 -696
  173. package/dist/cjs/sdk/market/kyc/KYCRegistry.js +0 -269
  174. package/dist/cjs/sdk/market/kyc/index.js +0 -26
  175. package/dist/cjs/sdk/market/kyc/securitize/SecuritizeKYCFactory.js +0 -244
  176. package/dist/cjs/sdk/market/kyc/securitize/constants.js +0 -28
  177. package/dist/cjs/sdk/market/kyc/securitize/index.js +0 -26
  178. package/dist/cjs/sdk/market/kyc/securitize/types.js +0 -16
  179. package/dist/cjs/sdk/market/kyc/types.js +0 -34
  180. package/dist/cjs/sdk/utils/viem/executeDelegatedMulticalls.js +0 -38
  181. package/dist/esm/abi/kyc/iDSRegistryService.js +0 -46
  182. package/dist/esm/abi/kyc/iDSToken.js +0 -47
  183. package/dist/esm/abi/kyc/iKYCCompressor.js +0 -172
  184. package/dist/esm/abi/kyc/iKYCFactory.js +0 -98
  185. package/dist/esm/abi/kyc/iKYCUnderlying.js +0 -377
  186. package/dist/esm/abi/kyc/iSecuritizeDegenNFT.js +0 -302
  187. package/dist/esm/abi/kyc/iSecuritizeKYCFactory.js +0 -295
  188. package/dist/esm/dev/CachedStateSubscriber.js +0 -54
  189. package/dist/esm/sdk/GearboxSDK.js +0 -689
  190. package/dist/esm/sdk/market/kyc/KYCRegistry.js +0 -253
  191. package/dist/esm/sdk/market/kyc/index.js +0 -3
  192. package/dist/esm/sdk/market/kyc/securitize/SecuritizeKYCFactory.js +0 -220
  193. package/dist/esm/sdk/market/kyc/securitize/constants.js +0 -4
  194. package/dist/esm/sdk/market/kyc/securitize/index.js +0 -3
  195. package/dist/esm/sdk/market/kyc/securitize/types.js +0 -0
  196. package/dist/esm/sdk/market/kyc/types.js +0 -9
  197. package/dist/esm/sdk/utils/viem/executeDelegatedMulticalls.js +0 -14
  198. package/dist/types/abi/kyc/iDSRegistryService.d.ts +0 -71
  199. package/dist/types/abi/kyc/iDSToken.d.ts +0 -67
  200. package/dist/types/abi/kyc/iKYCCompressor.d.ts +0 -228
  201. package/dist/types/abi/kyc/iKYCFactory.d.ts +0 -139
  202. package/dist/types/abi/kyc/iKYCUnderlying.d.ts +0 -548
  203. package/dist/types/abi/kyc/iSecuritizeDegenNFT.d.ts +0 -404
  204. package/dist/types/abi/kyc/iSecuritizeKYCFactory.d.ts +0 -376
  205. package/dist/types/dev/CachedStateSubscriber.d.ts +0 -21
  206. package/dist/types/sdk/GearboxSDK.d.ts +0 -324
  207. package/dist/types/sdk/market/kyc/KYCRegistry.d.ts +0 -52
  208. package/dist/types/sdk/market/kyc/index.d.ts +0 -3
  209. package/dist/types/sdk/market/kyc/securitize/SecuritizeKYCFactory.d.ts +0 -428
  210. package/dist/types/sdk/market/kyc/securitize/constants.d.ts +0 -1
  211. package/dist/types/sdk/market/kyc/securitize/index.d.ts +0 -3
  212. package/dist/types/sdk/market/kyc/securitize/types.d.ts +0 -127
  213. package/dist/types/sdk/market/kyc/types.d.ts +0 -170
  214. package/dist/types/sdk/utils/viem/executeDelegatedMulticalls.d.ts +0 -28
@@ -4,17 +4,12 @@ import {
4
4
  AP_MARKET_COMPRESSOR,
5
5
  VERSION_RANGE_310
6
6
  } from "../constants/index.js";
7
- import { AddressMap, AddressSet } from "../utils/index.js";
8
- import {
9
- executeDelegatedMulticalls
10
- } from "../utils/viem/index.js";
7
+ import { AddressMap } from "../utils/index.js";
8
+ import { simulateWithPriceUpdates } from "../utils/viem/index.js";
11
9
  import { MarketConfiguratorContract } from "./MarketConfiguratorContract.js";
12
10
  import { MarketSuite } from "./MarketSuite.js";
13
11
  import { ZapperRegister } from "./ZapperRegister.js";
14
12
  class MarketRegister extends ZapperRegister {
15
- /**
16
- * Mapping pool.address -> MarketSuite
17
- */
18
13
  #markets = new AddressMap(void 0, "markets");
19
14
  #marketFilter;
20
15
  #marketConfigurators = new AddressMap(
@@ -28,7 +23,9 @@ class MarketRegister extends ZapperRegister {
28
23
  **/
29
24
  constructor(sdk, ignoreMarkets = []) {
30
25
  super(sdk);
31
- this.#ignoreMarkets = new AddressSet(ignoreMarkets);
26
+ this.#ignoreMarkets = new Set(
27
+ ignoreMarkets.map((m) => m.toLowerCase())
28
+ );
32
29
  }
33
30
  /**
34
31
  * Restores market state from a previously serialized snapshot,
@@ -36,41 +33,40 @@ class MarketRegister extends ZapperRegister {
36
33
  * @param state - Array of market data snapshots.
37
34
  **/
38
35
  hydrate(state) {
36
+ this.#markets.clear();
39
37
  const configurators = new Set(state.map((m) => m.configurator));
40
38
  this.#setMarketFilter([...configurators]);
41
- this.#setMarkets(state);
39
+ for (const data of state) {
40
+ const pool = data.pool.baseParams.addr;
41
+ if (this.#ignoreMarkets.has(pool.toLowerCase())) {
42
+ this.logger?.debug(
43
+ `ignoring market of pool ${pool} (${data.pool.name})`
44
+ );
45
+ continue;
46
+ }
47
+ this.#markets.upsert(
48
+ data.pool.baseParams.addr,
49
+ new MarketSuite(this.sdk, data)
50
+ );
51
+ }
42
52
  }
43
53
  /**
44
- * @internal
45
- * Returns delegated multicalls for loading all markets from the on-chain
46
- * market compressor. Used by the SDK to compose batched RPC calls.
54
+ * Fetches all markets from the on-chain for the given market configurators.
47
55
  *
48
- * @param configurators - Addresses of market configurator contracts to query.
56
+ * @param marketConfigurators - Addresses of market configurator contracts to query.
57
+ * @param ignoreUpdateablePrices - When `true`, skips generating off-chain
58
+ * price updates before loading
49
59
  **/
50
- getLoadMulticalls(configurators) {
51
- this.#setMarketFilter(configurators);
52
- const [marketCompressorAddress] = this.sdk.addressProvider.mustGetLatest(
53
- AP_MARKET_COMPRESSOR,
54
- VERSION_RANGE_310
55
- );
56
- return [
57
- {
58
- call: {
59
- abi: marketCompressorAbi,
60
- address: marketCompressorAddress,
61
- functionName: "getMarkets",
62
- args: [this.marketFilter]
63
- },
64
- onResult: (resp) => {
65
- this.#setMarkets(resp);
66
- this.logger?.info(
67
- `loaded ${this.#markets.size} markets in block ${this.sdk.currentBlock}`
68
- );
69
- }
70
- }
71
- ];
60
+ async loadMarkets(marketConfigurators, ignoreUpdateablePrices) {
61
+ if (!marketConfigurators.length) {
62
+ this.logger?.warn(
63
+ "no market configurators provided, skipping loadMarkets"
64
+ );
65
+ return;
66
+ }
67
+ await this.#loadMarkets(marketConfigurators, [], ignoreUpdateablePrices);
72
68
  }
73
- #setMarketFilter(configurators) {
69
+ #setMarketFilter(configurators, pools = []) {
74
70
  for (const c of configurators) {
75
71
  this.#marketConfigurators.upsert(
76
72
  c,
@@ -79,7 +75,7 @@ class MarketRegister extends ZapperRegister {
79
75
  }
80
76
  this.#marketFilter = {
81
77
  configurators,
82
- pools: [],
78
+ pools,
83
79
  underlying: ADDRESS_0X0
84
80
  };
85
81
  }
@@ -106,45 +102,106 @@ class MarketRegister extends ZapperRegister {
106
102
  **/
107
103
  async syncState(ignoreUpdateablePrices) {
108
104
  const dirty = this.markets.some((m) => m.dirty) || this.marketConfigurators.some((c) => c.dirty);
109
- let multicalls;
110
- let txs = [];
111
105
  if (dirty) {
112
106
  this.logger?.debug(
113
107
  "some markets or market configurators are dirty, reloading everything"
114
108
  );
115
- multicalls = this.getLoadMulticalls([...this.marketFilter.configurators]);
116
- if (!ignoreUpdateablePrices) {
117
- const updatables = await this.sdk.priceFeeds.getPartialUpdatablePriceFeeds([
118
- ...this.marketFilter.configurators
119
- ]);
120
- const updates = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(updatables);
121
- txs = updates.txs;
122
- }
109
+ await this.#loadMarkets(
110
+ [...this.marketFilter.configurators],
111
+ [...this.marketFilter.pools],
112
+ ignoreUpdateablePrices
113
+ );
123
114
  } else if (!ignoreUpdateablePrices) {
124
- multicalls = this.#getOracleSyncMulticalls();
125
- if (!multicalls.length) {
126
- return;
127
- }
128
- this.logger?.debug(`syncing prices on ${multicalls.length} oracles`);
129
- const updates = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs();
115
+ await this.updatePrices();
116
+ }
117
+ }
118
+ async #loadMarkets(configurators, pools, ignoreUpdateablePrices) {
119
+ this.#setMarketFilter(configurators, pools);
120
+ const [marketCompressorAddress] = this.sdk.addressProvider.mustGetLatest(
121
+ AP_MARKET_COMPRESSOR,
122
+ VERSION_RANGE_310
123
+ );
124
+ let txs = [];
125
+ if (!ignoreUpdateablePrices) {
126
+ const updatables = await this.sdk.priceFeeds.getPartialUpdatablePriceFeeds(
127
+ configurators,
128
+ pools
129
+ );
130
+ const updates = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs(updatables);
130
131
  txs = updates.txs;
132
+ }
133
+ this.logger?.debug(
134
+ { configurators, pools },
135
+ `calling getMarkets with ${txs.length} price updates in block ${this.sdk.currentBlock}`
136
+ );
137
+ let markets = [];
138
+ if (txs.length) {
139
+ const [resp] = await simulateWithPriceUpdates(this.client, {
140
+ priceUpdates: txs,
141
+ contracts: [
142
+ {
143
+ abi: marketCompressorAbi,
144
+ address: marketCompressorAddress,
145
+ functionName: "getMarkets",
146
+ args: [this.marketFilter]
147
+ }
148
+ ],
149
+ blockNumber: this.sdk.currentBlock,
150
+ gas: this.sdk.gasLimit
151
+ });
152
+ markets = resp;
131
153
  } else {
132
- return;
154
+ markets = await this.client.readContract({
155
+ abi: marketCompressorAbi,
156
+ address: marketCompressorAddress,
157
+ functionName: "getMarkets",
158
+ args: [this.marketFilter],
159
+ blockNumber: this.sdk.currentBlock,
160
+ // @ts-expect-error
161
+ gas: this.sdk.gasLimit
162
+ });
133
163
  }
134
- await executeDelegatedMulticalls(this.client, multicalls, {
135
- priceUpdates: txs,
136
- blockNumber: this.sdk.currentBlock,
137
- gas: this.sdk.gasLimit
138
- });
164
+ for (const data of markets) {
165
+ const pool = data.pool.baseParams.addr;
166
+ if (this.#ignoreMarkets.has(pool.toLowerCase())) {
167
+ this.logger?.debug(
168
+ `ignoring market of pool ${pool} (${data.pool.name})`
169
+ );
170
+ continue;
171
+ }
172
+ this.#markets.upsert(pool, new MarketSuite(this.sdk, data));
173
+ }
174
+ this.logger?.info(
175
+ `loaded ${this.#markets.size} markets in block ${this.sdk.currentBlock}`
176
+ );
139
177
  }
140
- #getOracleSyncMulticalls(oracles) {
178
+ /**
179
+ * Loads new prices and price feeds for given oracles from PriceFeedCompressor, defaults to all oracles
180
+ */
181
+ async updatePrices(oracles) {
141
182
  const uniqOracles = new AddressMap();
142
183
  for (const m of this.markets) {
143
184
  if (!oracles || oracles.includes(m.priceOracle.address)) {
144
185
  uniqOracles.upsert(m.priceOracle.address, m.priceOracle);
145
186
  }
146
187
  }
147
- return uniqOracles.values().map((o) => o.syncStateMulticall());
188
+ const multicalls = uniqOracles.values().map((o) => o.syncStateMulticall());
189
+ if (!multicalls.length) {
190
+ return;
191
+ }
192
+ this.logger?.debug(`syncing prices on ${multicalls.length} oracles`);
193
+ const { txs } = await this.sdk.priceFeeds.generatePriceFeedsUpdateTxs();
194
+ const oraclesStates = await simulateWithPriceUpdates(this.client, {
195
+ priceUpdates: txs,
196
+ contracts: multicalls.map((mc) => mc.call),
197
+ gas: this.sdk.gasLimit,
198
+ blockNumber: this.sdk.currentBlock
199
+ });
200
+ for (let i = 0; i < multicalls.length; i++) {
201
+ const handler = multicalls[i].onResult;
202
+ const result = oraclesStates[i];
203
+ handler(result);
204
+ }
148
205
  }
149
206
  get watchAddresses() {
150
207
  return /* @__PURE__ */ new Set([
@@ -265,19 +322,6 @@ class MarketRegister extends ZapperRegister {
265
322
  get markets() {
266
323
  return this.#markets.values();
267
324
  }
268
- #setMarkets(markets) {
269
- this.#markets.clear();
270
- for (const data of markets) {
271
- const pool = data.pool.baseParams.addr;
272
- if (this.#ignoreMarkets.has(pool)) {
273
- this.logger?.debug(
274
- `ignoring market of pool ${pool} (${data.pool.name})`
275
- );
276
- continue;
277
- }
278
- this.#markets.upsert(pool, new MarketSuite(this.sdk, data));
279
- }
280
- }
281
325
  }
282
326
  export {
283
327
  MarketRegister
@@ -44,9 +44,6 @@ class MarketSuite extends SDKConstruct {
44
44
  get underlying() {
45
45
  return this.pool.underlying;
46
46
  }
47
- get kycFactory() {
48
- return this.pool.kycFactory;
49
- }
50
47
  get dirty() {
51
48
  return this.configurator.dirty || this.pool.dirty || this.priceOracle.dirty || this.creditManagers.some((cm) => cm.dirty);
52
49
  }
@@ -1,6 +1,5 @@
1
1
  export * from "./adapters/index.js";
2
2
  export * from "./credit/index.js";
3
- export * from "./kyc/index.js";
4
3
  export * from "./MarketRegister.js";
5
4
  export * from "./MarketSuite.js";
6
5
  export * from "./oracle/index.js";
@@ -55,9 +55,6 @@ class PoolSuite extends SDKConstruct {
55
55
  get underlying() {
56
56
  return this.pool.underlying;
57
57
  }
58
- get kycFactory() {
59
- return this.pool.kycFactory;
60
- }
61
58
  get dirty() {
62
59
  return this.pool.dirty || this.rateKeeper.dirty || this.pqk.dirty || this.interestRateModel.dirty;
63
60
  }
@@ -10,15 +10,13 @@ import {
10
10
  const abi = [...iPoolV310Abi, ...iPausableAbi];
11
11
  class PoolV310Contract extends BaseContract {
12
12
  creditManagerDebtParams;
13
- #sdk;
14
- constructor(sdk, data) {
13
+ constructor(options, data) {
15
14
  const { baseParams, creditManagerDebtParams, ...rest } = data;
16
- super(sdk, {
15
+ super(options, {
17
16
  ...data.baseParams,
18
17
  name: `PoolV3(${data.name})`,
19
18
  abi
20
19
  });
21
- this.#sdk = sdk;
22
20
  Object.assign(this, rest);
23
21
  this.creditManagerDebtParams = new AddressMap(
24
22
  creditManagerDebtParams.map((p) => [p.creditManager, p])
@@ -30,13 +28,6 @@ class PoolV310Contract extends BaseContract {
30
28
  symbol: data.symbol
31
29
  });
32
30
  }
33
- get kycFactory() {
34
- const meta = this.#sdk.tokensMeta.mustGet(this.underlying);
35
- if (this.#sdk.tokensMeta.isKYCUnderlying(meta)) {
36
- return this.#sdk.mustGetContract(meta.kycFactory);
37
- }
38
- return void 0;
39
- }
40
31
  stateHuman(raw = true) {
41
32
  return {
42
33
  ...super.stateHuman(raw),
@@ -1,5 +1,4 @@
1
1
  export * from "./GaugeContract.js";
2
2
  export * from "./LinearInterestRateModelContract.js";
3
3
  export * from "./PoolSuite.js";
4
- export * from "./PoolV310Contract.js";
5
4
  export * from "./types.js";
@@ -221,13 +221,13 @@ class PriceFeedRegister extends SDKConstruct {
221
221
  * Loads PARTIAL information about all updatable price feeds from MarketCompressor
222
222
  * Discovered price feeds are not saved anywhere in PriceFeedRegister, and can later be used to load price feed updates
223
223
  */
224
- async getPartialUpdatablePriceFeeds(configurators) {
224
+ async getPartialUpdatablePriceFeeds(configurators, pools) {
225
225
  const [priceFeedCompressorAddress] = this.sdk.addressProvider.mustGetLatest(
226
226
  AP_PRICE_FEED_COMPRESSOR,
227
227
  VERSION_RANGE_310
228
228
  );
229
229
  this.logger?.debug(
230
- { configurators },
230
+ { configurators, pools },
231
231
  `calling getUpdatablePriceFeeds in block ${this.sdk.currentBlock}`
232
232
  );
233
233
  const result = await this.client.readContract({
@@ -237,7 +237,7 @@ class PriceFeedRegister extends SDKConstruct {
237
237
  args: [
238
238
  {
239
239
  configurators,
240
- pools: [],
240
+ pools: pools ?? [],
241
241
  underlying: ADDRESS_0X0
242
242
  }
243
243
  ],
@@ -328,6 +328,13 @@ class PriceFeedRegister extends SDKConstruct {
328
328
  get latestUpdate() {
329
329
  return this.#latestUpdate;
330
330
  }
331
+ /**
332
+ * @internal
333
+ * Returns true if any of the updaters are in historical mode
334
+ */
335
+ get historical() {
336
+ return this.#updaters.some((u) => u.historical);
337
+ }
331
338
  }
332
339
  export {
333
340
  PriceFeedRegister
@@ -1,4 +1,3 @@
1
- import BN from "bn.js";
2
1
  import { Buffer } from "buffer";
3
2
  const ACCUMULATOR_MAGIC = "504e4155";
4
3
  const MAJOR_VERSION = 1;
@@ -6,6 +5,14 @@ const MINOR_VERSION = 0;
6
5
  const KECCAK160_HASH_SIZE = 20;
7
6
  const PRICE_FEED_MESSAGE_VARIANT = 0;
8
7
  const TWAP_MESSAGE_VARIANT = 1;
8
+ function bufToBigInt(buf) {
9
+ if (buf.length === 0) return 0n;
10
+ let result = 0n;
11
+ for (let i = 0; i < buf.length; i++) {
12
+ result = result << 8n | BigInt(buf[i]);
13
+ }
14
+ return result;
15
+ }
9
16
  function isAccumulatorUpdateData(updateBytes) {
10
17
  return updateBytes.toString("hex").slice(0, 8) === ACCUMULATOR_MAGIC && updateBytes[4] === MAJOR_VERSION && updateBytes[5] === MINOR_VERSION;
11
18
  }
@@ -18,19 +25,19 @@ function parsePriceFeedMessage(message) {
18
25
  cursor += 1;
19
26
  const feedId = message.subarray(cursor, cursor + 32);
20
27
  cursor += 32;
21
- const price = new BN(message.subarray(cursor, cursor + 8), "be");
28
+ const price = bufToBigInt(message.subarray(cursor, cursor + 8));
22
29
  cursor += 8;
23
- const confidence = new BN(message.subarray(cursor, cursor + 8), "be");
30
+ const confidence = bufToBigInt(message.subarray(cursor, cursor + 8));
24
31
  cursor += 8;
25
32
  const exponent = message.readInt32BE(cursor);
26
33
  cursor += 4;
27
- const publishTime = new BN(message.subarray(cursor, cursor + 8), "be");
34
+ const publishTime = bufToBigInt(message.subarray(cursor, cursor + 8));
28
35
  cursor += 8;
29
- const prevPublishTime = new BN(message.subarray(cursor, cursor + 8), "be");
36
+ const prevPublishTime = bufToBigInt(message.subarray(cursor, cursor + 8));
30
37
  cursor += 8;
31
- const emaPrice = new BN(message.subarray(cursor, cursor + 8), "be");
38
+ const emaPrice = bufToBigInt(message.subarray(cursor, cursor + 8));
32
39
  cursor += 8;
33
- const emaConf = new BN(message.subarray(cursor, cursor + 8), "be");
40
+ const emaConf = bufToBigInt(message.subarray(cursor, cursor + 8));
34
41
  cursor += 8;
35
42
  return {
36
43
  feedId,
@@ -52,19 +59,19 @@ function parseTwapMessage(message) {
52
59
  cursor += 1;
53
60
  const feedId = message.subarray(cursor, cursor + 32);
54
61
  cursor += 32;
55
- const cumulativePrice = new BN(message.subarray(cursor, cursor + 16), "be");
62
+ const cumulativePrice = bufToBigInt(message.subarray(cursor, cursor + 16));
56
63
  cursor += 16;
57
- const cumulativeConf = new BN(message.subarray(cursor, cursor + 16), "be");
64
+ const cumulativeConf = bufToBigInt(message.subarray(cursor, cursor + 16));
58
65
  cursor += 16;
59
- const numDownSlots = new BN(message.subarray(cursor, cursor + 8), "be");
66
+ const numDownSlots = bufToBigInt(message.subarray(cursor, cursor + 8));
60
67
  cursor += 8;
61
68
  const exponent = message.readInt32BE(cursor);
62
69
  cursor += 4;
63
- const publishTime = new BN(message.subarray(cursor, cursor + 8), "be");
70
+ const publishTime = bufToBigInt(message.subarray(cursor, cursor + 8));
64
71
  cursor += 8;
65
- const prevPublishTime = new BN(message.subarray(cursor, cursor + 8), "be");
72
+ const prevPublishTime = bufToBigInt(message.subarray(cursor, cursor + 8));
66
73
  cursor += 8;
67
- const publishSlot = new BN(message.subarray(cursor, cursor + 8), "be");
74
+ const publishSlot = bufToBigInt(message.subarray(cursor, cursor + 8));
68
75
  cursor += 8;
69
76
  return {
70
77
  feedId,
@@ -30,6 +30,9 @@ const PythOptions = z.object({
30
30
  });
31
31
  class PythUpdater extends SDKConstruct {
32
32
  #cache;
33
+ /**
34
+ * Fixed pyth historic timestamp in seconds
35
+ */
33
36
  #historicalTimestamp;
34
37
  #apiProxy;
35
38
  #failOnMissingFeeds;
@@ -44,10 +47,7 @@ class PythUpdater extends SDKConstruct {
44
47
  `using historical timestamp ${this.#historicalTimestamp}`
45
48
  );
46
49
  }
47
- this.#cache = new PriceUpdatesCache({
48
- // currently staleness period is 240 seconds on all networks, add some buffer
49
- // this period of 4 minutes is selected based on time that is required for user to sign transaction with wallet
50
- // so it's unlikely to decrease
50
+ this.#cache = opts.cache ?? new PriceUpdatesCache({
51
51
  ttl: cacheTTL ?? 225 * 1e3,
52
52
  historical: !!historicTimestamp
53
53
  });
@@ -96,6 +96,9 @@ class PythUpdater extends SDKConstruct {
96
96
  );
97
97
  return results;
98
98
  }
99
+ get historical() {
100
+ return !!this.#historicalTimestamp;
101
+ }
99
102
  /**
100
103
  * Gets pyth payloads
101
104
  * @param dataFeedsIds
@@ -52,10 +52,7 @@ class RedstoneUpdater extends SDKConstruct {
52
52
  `using historical timestamp ${this.#historicalTimestampMs}`
53
53
  );
54
54
  }
55
- this.#cache = new PriceUpdatesCache({
56
- // currently staleness period is 240 seconds on all networks, add some buffer
57
- // this period of 4 minutes is selected based on time that is required for user to sign transaction with wallet
58
- // so it's unlikely to decrease
55
+ this.#cache = opts.cache ?? new PriceUpdatesCache({
59
56
  ttl: opts.cacheTTL ?? 225 * 1e3,
60
57
  historical: !!ts
61
58
  });
@@ -126,6 +123,9 @@ class RedstoneUpdater extends SDKConstruct {
126
123
  );
127
124
  return results;
128
125
  }
126
+ get historical() {
127
+ return !!this.#historicalTimestampMs;
128
+ }
129
129
  /**
130
130
  * Gets payloads, retries once if it has expired while inflight
131
131
  * @param dataServiceId
@@ -104,7 +104,7 @@ function splitAccumulatorUpdates(binary) {
104
104
  const msg = parsePriceFeedMessage(upd);
105
105
  results.push({
106
106
  dataFeedId: toHex(msg.feedId),
107
- timestamp: msg.publishTime.toNumber(),
107
+ timestamp: Number(msg.publishTime),
108
108
  data: toHex(sliceAccumulatorUpdateData(data, i, i + 1))
109
109
  });
110
110
  }
@@ -1,8 +1,10 @@
1
1
  export * from "./fetchPythPayloads.js";
2
2
  export * from "./fetchRedstonePayloads.js";
3
+ import { PriceUpdatesCache } from "./PriceUpdatesCache.js";
3
4
  import { PythOptions, PythUpdater } from "./PythUpdater.js";
4
5
  import { RedstoneOptions, RedstoneUpdater } from "./RedstoneUpdater.js";
5
6
  export {
7
+ PriceUpdatesCache,
6
8
  PythOptions,
7
9
  PythUpdater,
8
10
  RedstoneOptions,
@@ -4,59 +4,13 @@ import {
4
4
  RedstoneOptions
5
5
  } from "./market/pricefeeds/updates/index.js";
6
6
  import { ZodAddress } from "./utils/index.js";
7
- const SDKOptions = z.object({
8
- /**
9
- * Override address of the Gearbox AddressProvider contract.
10
- * If not set, uses default universal address provider address {@link ADDRESS_PROVIDER_V310}
11
- **/
12
- addressProvider: ZodAddress().optional(),
13
- /**
14
- * Addresses of market configurator contracts to load.
15
- * If not set, all default market configurators for the chain are loaded
16
- * (from {@link GearboxChain.defaultMarketConfigurators})
17
- **/
18
- marketConfigurators: z.array(ZodAddress()).optional(),
19
- /**
20
- * Addresses of KYC factory contracts to load.
21
- * If not set, all default KYC factories for the chain are loaded
22
- * (from {@link GearboxChain.kycFactories})
23
- **/
24
- kycFactories: z.array(ZodAddress()).optional(),
25
- /**
26
- * Pin SDK to a specific block number during attach.
27
- * When set, all on-chain reads use this block instead of `latest`.
28
- **/
29
- blockNumber: z.union([z.bigint().nonnegative(), z.number().int().nonnegative()]).optional(),
30
- /**
31
- * Skip fetching updatable price feeds on attach and sync.
32
- * Speeds up initialisation when prices are not needed.
33
- **/
34
- ignoreUpdateablePrices: z.boolean().optional(),
35
- /**
36
- * Pool addresses whose markets should be skipped during attach/hydrate/sync.
37
- **/
38
- ignoreMarkets: z.array(ZodAddress()).optional(),
39
- /**
40
- * When `true`, throw on unrecognised contract types instead of falling
41
- * back to a generic contract wrapper.
42
- **/
7
+ const OnchainSDKOptionsSchema = z.object({
8
+ /** When `true`, throw on unrecognised contract types. */
43
9
  strictContractTypes: z.boolean().optional(),
44
- /**
45
- * Plugins that extend SDK functionality.
46
- **/
10
+ /** Plugins that extend SDK functionality. */
47
11
  plugins: z.record(z.string(), z.any()).optional(),
48
- /**
49
- * Custom logger implementation.
50
- **/
12
+ /** Custom logger implementation. */
51
13
  logger: z.any(),
52
- /**
53
- * Options for Redstone price-feed updates.
54
- **/
55
- redstone: RedstoneOptions.optional(),
56
- /**
57
- * Options for Pyth price-feed updates.
58
- **/
59
- pyth: PythOptions.optional(),
60
14
  /**
61
15
  * Explicit gas limit for read-only `eth_call` requests.
62
16
  * `null` disables the gas limit entirely; `undefined` uses the SDK default.
@@ -64,6 +18,23 @@ const SDKOptions = z.object({
64
18
  **/
65
19
  gasLimit: z.bigint().nonnegative().nullable().optional()
66
20
  });
21
+ const AttachOptionsSchema = z.object({
22
+ /** Override address of the Gearbox AddressProvider contract. */
23
+ addressProvider: ZodAddress().optional(),
24
+ /** Addresses of market configurator contracts to load. */
25
+ marketConfigurators: z.array(ZodAddress()).optional(),
26
+ /** Pin SDK to a specific block number during attach. */
27
+ blockNumber: z.union([z.bigint().nonnegative(), z.number().int().nonnegative()]).optional(),
28
+ /** Skip fetching updatable price feeds on attach and sync. */
29
+ ignoreUpdateablePrices: z.boolean().optional(),
30
+ /** Pool addresses whose markets should be skipped. */
31
+ ignoreMarkets: z.array(ZodAddress()).optional(),
32
+ /** Options for Redstone price-feed updates. */
33
+ redstone: RedstoneOptions.optional(),
34
+ /** Options for Pyth price-feed updates. */
35
+ pyth: PythOptions.optional()
36
+ });
67
37
  export {
68
- SDKOptions
38
+ AttachOptionsSchema,
39
+ OnchainSDKOptionsSchema
69
40
  };
@@ -1,3 +1,4 @@
1
+ import { SdkAlreadyAttachedError, SdkNotAttachedError } from "../core/index.js";
1
2
  class BasePlugin {
2
3
  #sdk;
3
4
  logger;
@@ -20,19 +21,25 @@ class BasePlugin {
20
21
  **/
21
22
  get sdk() {
22
23
  if (!this.#sdk) {
23
- throw new Error("SDK is not attached");
24
+ throw new SdkNotAttachedError();
24
25
  }
25
26
  return this.#sdk;
26
27
  }
28
+ /**
29
+ * @internal
30
+ * Set the SDK instance. Called by the SDK constructor.
31
+ * @param sdk - The SDK instance.
32
+ * @throws Error if the SDK is already attached.
33
+ */
27
34
  set sdk(sdk) {
28
35
  if (this.#sdk) {
29
- throw new Error("SDK is already attached");
36
+ throw new SdkAlreadyAttachedError();
30
37
  }
31
38
  this.#sdk = sdk;
32
39
  this.logger = sdk.logger?.child?.({ name: this.constructor.name }) ?? sdk.logger;
33
40
  }
34
41
  /**
35
- * {@inheritDoc IGearboxSDKPlugin.attach}
42
+ * {@inheritDoc IOnchainSDKPlugin.attach}
36
43
  **/
37
44
  async attach() {
38
45
  if (this.loadOnAttach) {
@@ -40,7 +47,7 @@ class BasePlugin {
40
47
  }
41
48
  }
42
49
  /**
43
- * {@inheritDoc IGearboxSDKPlugin.syncState}
50
+ * {@inheritDoc IOnchainSDKPlugin.syncState}
44
51
  **/
45
52
  async syncState() {
46
53
  await this.load(false);