@gearbox-protocol/sdk 14.12.0-next.65 → 14.12.0-next.67

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 (249) hide show
  1. package/dist/cjs/common-utils/index.js +2 -2
  2. package/dist/cjs/common-utils/utils/apy/calculate-safe-borrow-rate.js +3 -3
  3. package/dist/cjs/common-utils/utils/assets-math.js +7 -7
  4. package/dist/cjs/common-utils/utils/creditAccount/calc-health-factor.js +2 -2
  5. package/dist/cjs/common-utils/utils/creditAccount/debt.js +2 -2
  6. package/dist/cjs/common-utils/utils/creditAccount/quota-utils.js +5 -5
  7. package/dist/cjs/common-utils/utils/index.js +2 -2
  8. package/dist/cjs/common-utils/utils/strategies/leverage/calculate-max-leverage-factor.js +2 -2
  9. package/dist/cjs/common-utils/utils/strategies/leverage/calculate-max-strategy-debt.js +5 -5
  10. package/dist/cjs/common-utils/utils/strategies/strategy-info/calculate-total-points.js +2 -2
  11. package/dist/cjs/common-utils/utils/strategies/strategy-info/get-cm-you-can-earn.js +2 -2
  12. package/dist/cjs/common-utils/utils/validation/validate-open-account-pool-status.js +4 -4
  13. package/dist/cjs/dev/index.js +2 -1
  14. package/dist/cjs/dev/kycUtils.js +1 -1
  15. package/dist/cjs/dev/midasUtils.js +104 -0
  16. package/dist/cjs/model/history.js +28 -0
  17. package/dist/cjs/model/history.schema.js +84 -0
  18. package/dist/cjs/model/index.js +64 -0
  19. package/dist/cjs/model/liquidations.js +23 -0
  20. package/dist/cjs/model/liquidations.schema.js +91 -0
  21. package/dist/cjs/model/opportunities.js +55 -0
  22. package/dist/cjs/model/opportunities.schema.js +220 -0
  23. package/dist/cjs/model/package.json +1 -0
  24. package/dist/cjs/model/positions.js +1 -0
  25. package/dist/cjs/model/primitives.js +1 -0
  26. package/dist/cjs/model/primitives.schema.js +85 -0
  27. package/dist/cjs/new-sdk/AbstractNamespace.js +158 -0
  28. package/dist/cjs/new-sdk/GearboxSDK.js +122 -0
  29. package/dist/cjs/new-sdk/index.js +11 -0
  30. package/dist/cjs/new-sdk/opportunities/OpportunitiesNamespace.js +122 -0
  31. package/dist/cjs/new-sdk/opportunities/index.js +4 -0
  32. package/dist/cjs/new-sdk/opportunities/types.js +1 -0
  33. package/dist/cjs/new-sdk/package.json +1 -0
  34. package/dist/cjs/new-sdk/types.js +22 -0
  35. package/dist/cjs/new-sdk/utils/history.js +1 -0
  36. package/dist/cjs/new-sdk/utils/index.js +2 -0
  37. package/dist/cjs/offchain/GearboxAPI.js +33 -0
  38. package/dist/cjs/offchain/index.js +8 -0
  39. package/dist/cjs/offchain/opportunities/OffchainOpportunities.js +97 -0
  40. package/dist/cjs/offchain/opportunities/index.js +4 -0
  41. package/dist/cjs/offchain/package.json +1 -0
  42. package/dist/cjs/offchain/types.js +1 -0
  43. package/dist/cjs/preview/preview/buildDelayedPreview.js +5 -5
  44. package/dist/cjs/rewards/rewards/api.js +2 -2
  45. package/dist/cjs/rewards/rewards/extra-apy.js +2 -2
  46. package/dist/cjs/sdk/MultichainSDK.js +18 -2
  47. package/dist/cjs/sdk/OnchainSDK.js +8 -1
  48. package/dist/cjs/sdk/accounts/index.js +2 -0
  49. package/dist/cjs/sdk/accounts/liquidations/LiquidationsService.js +150 -106
  50. package/dist/cjs/sdk/accounts/liquidations/MultichainLiquidationsService.js +32 -38
  51. package/dist/cjs/sdk/accounts/liquidations/constants.js +13 -0
  52. package/dist/cjs/sdk/accounts/liquidations/index.js +2 -0
  53. package/dist/cjs/sdk/base/MultichainConstruct.js +80 -0
  54. package/dist/cjs/sdk/base/TokensMeta.js +51 -0
  55. package/dist/cjs/sdk/base/index.js +2 -0
  56. package/dist/cjs/sdk/chain/chains.js +76 -0
  57. package/dist/cjs/sdk/chain/index.js +4 -0
  58. package/dist/cjs/sdk/core/errors.js +13 -0
  59. package/dist/cjs/sdk/core/index.js +2 -1
  60. package/dist/cjs/sdk/index.js +25 -1
  61. package/dist/cjs/sdk/market/MarketConfiguratorContract.js +14 -0
  62. package/dist/cjs/sdk/market/MarketSuite.js +163 -0
  63. package/dist/cjs/sdk/market/credit/CreditManagerV310Contract.js +26 -0
  64. package/dist/cjs/sdk/market/credit/CreditSuite.js +102 -0
  65. package/dist/cjs/sdk/market/math.js +104 -0
  66. package/dist/cjs/sdk/market/oracle/PriceOracleBaseContract.js +52 -0
  67. package/dist/cjs/sdk/market/pool/LinearInterestRateModelContract.js +30 -0
  68. package/dist/cjs/sdk/market/pool/PoolQuotaKeeperV310Contract.js +26 -0
  69. package/dist/cjs/sdk/market/pool/PoolSuite.js +28 -0
  70. package/dist/cjs/sdk/market/pool/PoolV310Contract.js +27 -0
  71. package/dist/cjs/sdk/market/pool/math.js +44 -0
  72. package/dist/cjs/sdk/market/pricefeeds/AbstractPriceFeed.js +17 -0
  73. package/dist/cjs/sdk/opportunities/MultichainOpportunitiesService.js +60 -0
  74. package/dist/cjs/sdk/opportunities/OpportunitiesService.js +103 -0
  75. package/dist/cjs/sdk/opportunities/index.js +12 -0
  76. package/dist/cjs/sdk/types/multichain.js +1 -0
  77. package/dist/cjs/{common-utils → sdk}/utils/bigint-math.js +11 -11
  78. package/dist/cjs/sdk/utils/index.js +3 -0
  79. package/dist/cjs/sdk/utils/zod.js +12 -0
  80. package/dist/esm/common-utils/index.js +1 -1
  81. package/dist/esm/common-utils/utils/apy/calculate-safe-borrow-rate.js +1 -1
  82. package/dist/esm/common-utils/utils/assets-math.js +1 -1
  83. package/dist/esm/common-utils/utils/creditAccount/calc-health-factor.js +1 -1
  84. package/dist/esm/common-utils/utils/creditAccount/debt.js +1 -1
  85. package/dist/esm/common-utils/utils/creditAccount/quota-utils.js +1 -1
  86. package/dist/esm/common-utils/utils/index.js +1 -1
  87. package/dist/esm/common-utils/utils/strategies/leverage/calculate-max-leverage-factor.js +1 -1
  88. package/dist/esm/common-utils/utils/strategies/leverage/calculate-max-strategy-debt.js +1 -1
  89. package/dist/esm/common-utils/utils/strategies/strategy-info/calculate-total-points.js +1 -1
  90. package/dist/esm/common-utils/utils/strategies/strategy-info/get-cm-you-can-earn.js +1 -1
  91. package/dist/esm/common-utils/utils/validation/validate-open-account-pool-status.js +1 -1
  92. package/dist/esm/dev/AccountOpener.js +1 -1
  93. package/dist/esm/dev/index.js +3 -3
  94. package/dist/esm/dev/kycUtils.js +1 -1
  95. package/dist/esm/dev/midasUtils.js +105 -2
  96. package/dist/esm/dev/withdrawalUtils.js +1 -1
  97. package/dist/esm/model/history.js +26 -0
  98. package/dist/esm/model/history.schema.js +76 -0
  99. package/dist/esm/model/index.js +9 -0
  100. package/dist/esm/model/liquidations.js +22 -0
  101. package/dist/esm/model/liquidations.schema.js +83 -0
  102. package/dist/esm/model/opportunities.js +51 -0
  103. package/dist/esm/model/opportunities.schema.js +198 -0
  104. package/dist/esm/model/package.json +1 -0
  105. package/dist/esm/model/positions.js +1 -0
  106. package/dist/esm/model/primitives.js +1 -0
  107. package/dist/esm/model/primitives.schema.js +75 -0
  108. package/dist/esm/new-sdk/AbstractNamespace.js +157 -0
  109. package/dist/esm/new-sdk/GearboxSDK.js +121 -0
  110. package/dist/esm/new-sdk/index.js +7 -0
  111. package/dist/esm/new-sdk/opportunities/OpportunitiesNamespace.js +121 -0
  112. package/dist/esm/new-sdk/opportunities/index.js +3 -0
  113. package/dist/esm/new-sdk/opportunities/types.js +1 -0
  114. package/dist/esm/new-sdk/package.json +1 -0
  115. package/dist/esm/new-sdk/types.js +21 -0
  116. package/dist/esm/new-sdk/utils/history.js +1 -0
  117. package/dist/esm/new-sdk/utils/index.js +2 -0
  118. package/dist/esm/offchain/GearboxAPI.js +32 -0
  119. package/dist/esm/offchain/index.js +5 -0
  120. package/dist/esm/offchain/opportunities/OffchainOpportunities.js +95 -0
  121. package/dist/esm/offchain/opportunities/index.js +2 -0
  122. package/dist/esm/offchain/package.json +1 -0
  123. package/dist/esm/offchain/types.js +1 -0
  124. package/dist/esm/preview/preview/buildDelayedPreview.js +1 -1
  125. package/dist/esm/preview/simulate/simulatePoolOperation.js +1 -1
  126. package/dist/esm/preview/trace/extractTransfers.js +1 -1
  127. package/dist/esm/rewards/rewards/api.js +1 -1
  128. package/dist/esm/rewards/rewards/extra-apy.js +1 -1
  129. package/dist/esm/sdk/MultichainSDK.js +18 -2
  130. package/dist/esm/sdk/OnchainSDK.js +8 -1
  131. package/dist/esm/sdk/accounts/CreditAccountsServiceV310.js +2 -2
  132. package/dist/esm/sdk/accounts/index.js +2 -2
  133. package/dist/esm/sdk/accounts/liquidations/LiquidationsService.js +153 -109
  134. package/dist/esm/sdk/accounts/liquidations/MultichainLiquidationsService.js +32 -38
  135. package/dist/esm/sdk/accounts/liquidations/constants.js +12 -1
  136. package/dist/esm/sdk/accounts/liquidations/index.js +2 -2
  137. package/dist/esm/sdk/accounts/withdrawal-compressor/RedemptionLoggerV310Contract.js +1 -1
  138. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV310Contract.js +1 -1
  139. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV311Contract.js +1 -1
  140. package/dist/esm/sdk/accounts/withdrawal-compressor/WithdrawalCompressorV313Contract.js +1 -1
  141. package/dist/esm/sdk/base/MultichainConstruct.js +79 -0
  142. package/dist/esm/sdk/base/TokensMeta.js +53 -2
  143. package/dist/esm/sdk/base/index.js +2 -1
  144. package/dist/esm/sdk/chain/chains.js +74 -2
  145. package/dist/esm/sdk/chain/detectNetwork.js +1 -1
  146. package/dist/esm/sdk/chain/index.js +2 -2
  147. package/dist/esm/sdk/core/createAddressProvider.js +1 -1
  148. package/dist/esm/sdk/core/errors.js +13 -1
  149. package/dist/esm/sdk/core/index.js +2 -2
  150. package/dist/esm/sdk/index.js +11 -5
  151. package/dist/esm/sdk/market/MarketConfiguratorContract.js +14 -0
  152. package/dist/esm/sdk/market/MarketSuite.js +163 -0
  153. package/dist/esm/sdk/market/credit/CreditFacadeV310BaseContract.js +1 -1
  154. package/dist/esm/sdk/market/credit/CreditManagerV310Contract.js +26 -0
  155. package/dist/esm/sdk/market/credit/CreditSuite.js +102 -0
  156. package/dist/esm/sdk/market/math.js +98 -0
  157. package/dist/esm/sdk/market/oracle/PriceOracleBaseContract.js +52 -0
  158. package/dist/esm/sdk/market/pool/LinearInterestRateModelContract.js +30 -0
  159. package/dist/esm/sdk/market/pool/PoolQuotaKeeperV310Contract.js +26 -0
  160. package/dist/esm/sdk/market/pool/PoolSuite.js +28 -0
  161. package/dist/esm/sdk/market/pool/PoolV310Contract.js +28 -1
  162. package/dist/esm/sdk/market/pool/math.js +41 -0
  163. package/dist/esm/sdk/market/pricefeeds/AbstractPriceFeed.js +17 -0
  164. package/dist/esm/sdk/market/zapper/IETHZapperContract.js +1 -1
  165. package/dist/esm/sdk/market/zapper/ZapperContract.js +1 -1
  166. package/dist/esm/sdk/opportunities/MultichainOpportunitiesService.js +59 -0
  167. package/dist/esm/sdk/opportunities/OpportunitiesService.js +102 -0
  168. package/dist/esm/sdk/opportunities/index.js +4 -0
  169. package/dist/esm/sdk/pools/PoolService.js +1 -1
  170. package/dist/esm/sdk/types/multichain.js +1 -0
  171. package/dist/esm/{common-utils → sdk}/utils/bigint-math.js +11 -11
  172. package/dist/esm/sdk/utils/index.js +3 -2
  173. package/dist/esm/sdk/utils/viem/simulateWithPriceUpdates.js +1 -1
  174. package/dist/esm/sdk/utils/zod.js +13 -2
  175. package/dist/types/common-utils/index.d.ts +1 -1
  176. package/dist/types/common-utils/utils/index.d.ts +1 -1
  177. package/dist/types/dev/index.d.ts +2 -2
  178. package/dist/types/dev/midasUtils.d.ts +31 -2
  179. package/dist/types/model/history.d.ts +105 -0
  180. package/dist/types/model/history.schema.d.ts +66 -0
  181. package/dist/types/model/index.d.ts +9 -0
  182. package/dist/types/model/liquidations.d.ts +230 -0
  183. package/dist/types/model/liquidations.schema.d.ts +292 -0
  184. package/dist/types/model/opportunities.d.ts +543 -0
  185. package/dist/types/model/opportunities.schema.d.ts +1066 -0
  186. package/dist/types/model/positions.d.ts +11 -0
  187. package/dist/types/model/primitives.d.ts +193 -0
  188. package/dist/types/model/primitives.schema.d.ts +81 -0
  189. package/dist/types/new-sdk/AbstractNamespace.d.ts +119 -0
  190. package/dist/types/new-sdk/GearboxSDK.d.ts +78 -0
  191. package/dist/types/new-sdk/index.d.ts +9 -0
  192. package/dist/types/new-sdk/opportunities/OpportunitiesNamespace.d.ts +69 -0
  193. package/dist/types/new-sdk/opportunities/index.d.ts +3 -0
  194. package/dist/types/new-sdk/opportunities/types.d.ts +66 -0
  195. package/dist/types/new-sdk/types.d.ts +149 -0
  196. package/dist/types/new-sdk/utils/history.d.ts +44 -0
  197. package/dist/types/new-sdk/utils/index.d.ts +2 -0
  198. package/dist/types/offchain/GearboxAPI.d.ts +31 -0
  199. package/dist/types/offchain/index.d.ts +5 -0
  200. package/dist/types/offchain/opportunities/OffchainOpportunities.d.ts +69 -0
  201. package/dist/types/offchain/opportunities/index.d.ts +2 -0
  202. package/dist/types/offchain/types.d.ts +50 -0
  203. package/dist/types/sdk/MultichainSDK.d.ts +15 -2
  204. package/dist/types/sdk/OnchainSDK.d.ts +9 -3
  205. package/dist/types/sdk/accounts/index.d.ts +3 -3
  206. package/dist/types/sdk/accounts/liquidations/LiquidationsService.d.ts +24 -16
  207. package/dist/types/sdk/accounts/liquidations/MultichainLiquidationsService.d.ts +26 -20
  208. package/dist/types/sdk/accounts/liquidations/constants.d.ts +12 -1
  209. package/dist/types/sdk/accounts/liquidations/index.d.ts +3 -3
  210. package/dist/types/sdk/accounts/liquidations/types.d.ts +34 -309
  211. package/dist/types/sdk/base/MultichainConstruct.d.ts +57 -0
  212. package/dist/types/sdk/base/TokensMeta.d.ts +26 -0
  213. package/dist/types/sdk/base/index.d.ts +2 -1
  214. package/dist/types/sdk/chain/chains.d.ts +68 -1
  215. package/dist/types/sdk/chain/index.d.ts +2 -2
  216. package/dist/types/sdk/core/errors.d.ts +10 -1
  217. package/dist/types/sdk/core/index.d.ts +2 -2
  218. package/dist/types/sdk/index.d.ts +15 -8
  219. package/dist/types/sdk/market/MarketConfiguratorContract.d.ts +9 -0
  220. package/dist/types/sdk/market/MarketSuite.d.ts +109 -1
  221. package/dist/types/sdk/market/credit/CreditManagerV310Contract.d.ts +14 -0
  222. package/dist/types/sdk/market/credit/CreditSuite.d.ts +47 -0
  223. package/dist/types/sdk/market/credit/types.d.ts +22 -0
  224. package/dist/types/sdk/market/index.d.ts +2 -2
  225. package/dist/types/sdk/market/math.d.ts +74 -0
  226. package/dist/types/sdk/market/oracle/PriceOracleBaseContract.d.ts +23 -0
  227. package/dist/types/sdk/market/oracle/types.d.ts +46 -0
  228. package/dist/types/sdk/market/pool/LinearInterestRateModelContract.d.ts +12 -0
  229. package/dist/types/sdk/market/pool/PoolQuotaKeeperV310Contract.d.ts +22 -1
  230. package/dist/types/sdk/market/pool/PoolSuite.d.ts +23 -0
  231. package/dist/types/sdk/market/pool/PoolV310Contract.d.ts +18 -0
  232. package/dist/types/sdk/market/pool/math.d.ts +57 -0
  233. package/dist/types/sdk/market/pool/types.d.ts +23 -0
  234. package/dist/types/sdk/market/pricefeeds/AbstractPriceFeed.d.ts +6 -0
  235. package/dist/types/sdk/market/pricefeeds/types.d.ts +10 -0
  236. package/dist/types/sdk/opportunities/MultichainOpportunitiesService.d.ts +40 -0
  237. package/dist/types/sdk/opportunities/OpportunitiesService.d.ts +47 -0
  238. package/dist/types/sdk/opportunities/index.d.ts +4 -0
  239. package/dist/types/sdk/types/index.d.ts +2 -1
  240. package/dist/types/sdk/types/multichain.d.ts +65 -0
  241. package/dist/types/sdk/types/state.d.ts +1 -1
  242. package/dist/types/sdk/types/transactions.d.ts +3 -0
  243. package/dist/types/{common-utils → sdk}/utils/bigint-math.d.ts +7 -11
  244. package/dist/types/sdk/utils/index.d.ts +3 -2
  245. package/dist/types/sdk/utils/zod.d.ts +6 -2
  246. package/package.json +16 -1
  247. package/dist/cjs/sdk/accounts/liquidations/helpers.js +0 -201
  248. package/dist/esm/sdk/accounts/liquidations/helpers.js +0 -192
  249. package/dist/types/sdk/accounts/liquidations/helpers.d.ts +0 -140
@@ -0,0 +1,44 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_constants_math = require("../../constants/math.js");
3
+ //#region src/sdk/market/pool/math.ts
4
+ const FULL = Number(require_sdk_constants_math.PERCENTAGE_FACTOR);
5
+ /**
6
+ * Base rate borrowers pay at a given utilization, in basis points, following
7
+ * the linear interest rate model's three segments.
8
+ *
9
+ * The result excludes the per-credit-manager interest fee: the model belongs to
10
+ * the pool, and every credit manager of a market can charge a different one.
11
+ **/
12
+ function borrowRateAtUtilization(utilization, params) {
13
+ const { U1, U2, Rbase, Rslope1, Rslope2, Rslope3 } = params;
14
+ const u = Math.min(Math.max(utilization, 0), FULL);
15
+ if (u <= 0) return Rbase;
16
+ if (u <= U1) return Math.round(Rbase + Rslope1 * u / U1);
17
+ if (u <= U2) return Math.round(Rbase + Rslope1 + Rslope2 * (u - U1) / Math.max(U2 - U1, 1));
18
+ return Math.round(Rbase + Rslope1 + Rslope2 + Rslope3 * (u - U2) / Math.max(FULL - U2, 1));
19
+ }
20
+ /**
21
+ * Rate depositors earn at a given utilization, in basis points: the interest
22
+ * borrowers pay, spread over the pool's whole liquidity.
23
+ **/
24
+ function supplyRateAtUtilization(utilization, params) {
25
+ const u = Math.min(Math.max(utilization, 0), FULL);
26
+ return Math.round(borrowRateAtUtilization(u, params) * u / FULL);
27
+ }
28
+ /**
29
+ * Utilizations the rate curve is sampled at: a fixed grid plus both kinks of
30
+ * the model, so the borrow leg is exact and the supply leg — which is
31
+ * quadratic between kinks — is smooth.
32
+ **/
33
+ function rateCurveUtilizations(params) {
34
+ const step = FULL / 20;
35
+ const grid = /* @__PURE__ */ new Set();
36
+ for (let u = 0; u <= FULL; u += step) grid.add(u);
37
+ grid.add(params.U1);
38
+ grid.add(params.U2);
39
+ return [...grid].filter((u) => u >= 0 && u <= FULL).sort((a, b) => a - b);
40
+ }
41
+ //#endregion
42
+ exports.borrowRateAtUtilization = borrowRateAtUtilization;
43
+ exports.rateCurveUtilizations = rateCurveUtilizations;
44
+ exports.supplyRateAtUtilization = supplyRateAtUtilization;
@@ -89,6 +89,23 @@ var AbstractPriceFeedContract = class extends require_sdk_base_BaseContract.Base
89
89
  const underlying = this.underlyingPriceFeeds.flatMap((f) => f.priceFeed.updatableDependencies());
90
90
  return require_sdk_market_pricefeeds_isUpdatablePriceFeed.isUpdatablePriceFeed(this) ? [this, ...underlying] : underlying;
91
91
  }
92
+ /**
93
+ * {@inheritDoc IPriceFeedContract.describe}
94
+ */
95
+ describe() {
96
+ let dependencies = [];
97
+ try {
98
+ dependencies = this.underlyingPriceFeeds.map((ref) => ref.priceFeed.describe());
99
+ } catch {
100
+ dependencies = [];
101
+ }
102
+ return {
103
+ name: this.name,
104
+ type: this.contractType,
105
+ feedAddress: this.address,
106
+ dependencies
107
+ };
108
+ }
92
109
  };
93
110
  //#endregion
94
111
  exports.AbstractPriceFeedContract = AbstractPriceFeedContract;
@@ -0,0 +1,60 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_chain_chains = require("../chain/chains.js");
3
+ const require_sdk_base_MultichainConstruct = require("../base/MultichainConstruct.js");
4
+ require("../base/index.js");
5
+ //#region src/sdk/opportunities/MultichainOpportunitiesService.ts
6
+ /**
7
+ * Cross-chain counterpart of {@link OpportunitiesService}.
8
+ *
9
+ * Fans out over every chain configured in {@link MultichainSDK}. A chain that
10
+ * fails is logged and skipped so one dead RPC does not empty the list; its
11
+ * failure is reported in {@link MultichainResult.meta}.
12
+ *
13
+ * Detail reads need no fan-out: an opportunity key names its chain.
14
+ *
15
+ * @typeParam Plugins - Map of attached plugin types.
16
+ **/
17
+ var MultichainOpportunitiesService = class extends require_sdk_base_MultichainConstruct.MultichainConstruct {
18
+ /**
19
+ * Opportunities of all queried chains, see {@link OpportunitiesService.list}.
20
+ *
21
+ * A filter that names chains narrows the fan-out itself, so chains whose rows
22
+ * would be discarded are never queried and never appear in the meta.
23
+ **/
24
+ async list(filter) {
25
+ return this.queryChains({
26
+ networks: this.#networksOf(filter),
27
+ label: "list opportunities",
28
+ run: (sdk) => sdk.opportunities.list(filter)
29
+ });
30
+ }
31
+ /**
32
+ * {@inheritDoc OpportunitiesService.getPool}
33
+ **/
34
+ async getPool(key) {
35
+ return this.sdk.chain(key.chainId).opportunities.getPool(key);
36
+ }
37
+ /**
38
+ * {@inheritDoc OpportunitiesService.getStrategy}
39
+ **/
40
+ async getStrategy(key) {
41
+ return this.sdk.chain(key.chainId).opportunities.getStrategy(key);
42
+ }
43
+ /**
44
+ * Chains named by the filter, or `undefined` to query all of them. Chain ids
45
+ * the SDK does not support are dropped here rather than reported as failures:
46
+ * a filter naming them is a narrowing, not a request.
47
+ **/
48
+ #networksOf(filter) {
49
+ if (!filter?.chainIds) return;
50
+ const networks = [];
51
+ for (const chainId of filter.chainIds) try {
52
+ networks.push(require_sdk_chain_chains.getNetworkType(chainId));
53
+ } catch {
54
+ this.sdk.logger?.debug(`ignoring unsupported chain ${chainId} in opportunities filter`);
55
+ }
56
+ return networks;
57
+ }
58
+ };
59
+ //#endregion
60
+ exports.MultichainOpportunitiesService = MultichainOpportunitiesService;
@@ -0,0 +1,103 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_base_SDKConstruct = require("../base/SDKConstruct.js");
3
+ require("../base/index.js");
4
+ const require_sdk_market_math = require("../market/math.js");
5
+ //#region src/sdk/opportunities/OpportunitiesService.ts
6
+ /**
7
+ * A lookup that knows of no strategy, used when a filter rules strategies out
8
+ * and the credit-account query is skipped altogether.
9
+ **/
10
+ const NO_TOTALS = () => void 0;
11
+ /**
12
+ * Builds the `opportunities` read model from the chain.
13
+ *
14
+ * Everything except the credit-account totals comes from the market state the
15
+ * SDK already holds, so a list costs one RPC round-trip at most. Yield figures
16
+ * that fold in incentives, points or history are deliberately absent: they are
17
+ * the backend's job, and this service never guesses them.
18
+ *
19
+ * The rows themselves are assembled by the market wrappers — see
20
+ * {@link MarketSuite.opportunities} — because every value in them is market
21
+ * state. What is left here is the one thing no single market can answer: how
22
+ * much the credit accounts of a strategy are worth.
23
+ **/
24
+ var OpportunitiesService = class extends require_sdk_base_SDKConstruct.SDKConstruct {
25
+ /**
26
+ * Every pool and strategy of every loaded market on this chain.
27
+ *
28
+ * Strategies are measured by the value locked in their credit accounts, so
29
+ * the list issues one credit-account query unless the filter rules strategies
30
+ * out entirely.
31
+ *
32
+ * @param filter - Optional narrowing, applied to the built rows.
33
+ **/
34
+ async list(filter) {
35
+ if (filter?.chainIds && !filter.chainIds.includes(this.chainId)) return [];
36
+ const { markets } = this.sdk.marketRegister;
37
+ const totals = filter?.kind === "pool" ? NO_TOTALS : await this.#strategyTotals(markets);
38
+ return markets.flatMap((market) => market.opportunities(totals, filter));
39
+ }
40
+ /**
41
+ * A single pool opportunity plus its interest rate curve and quotas.
42
+ *
43
+ * @throws If no loaded market has this pool.
44
+ **/
45
+ async getPool(key) {
46
+ return this.sdk.marketRegister.findByPool(key.pool).poolOpportunityDetail();
47
+ }
48
+ /**
49
+ * A single strategy opportunity plus the rate curve of the pool it borrows
50
+ * from and the price feeds its liquidation price depends on.
51
+ *
52
+ * @throws If the credit manager is unknown, or does not accept the requested
53
+ * collateral as a strategy.
54
+ **/
55
+ async getStrategy(key) {
56
+ const market = this.sdk.marketRegister.findByCreditManager(key.creditManager);
57
+ const { suite } = market.mustFindStrategy(key.creditManager, key.targetCollateral);
58
+ const totals = await this.#strategyTotals([market]);
59
+ return suite.strategyOpportunityDetail(key.targetCollateral, totals(key.creditManager, key.targetCollateral));
60
+ }
61
+ /**
62
+ * Total value held by the credit accounts backing every strategy of the given
63
+ * markets.
64
+ *
65
+ * An account that holds several strategy collaterals counts in full towards
66
+ * each of them: the read model reports what a strategy's accounts are worth,
67
+ * not how that worth splits across the collaterals inside them.
68
+ **/
69
+ async #strategyTotals(markets) {
70
+ const wanted = /* @__PURE__ */ new Map();
71
+ for (const market of markets) for (const { suite, collateral } of market.strategies) {
72
+ const cm = suite.creditManager.address.toLowerCase();
73
+ const tokens = wanted.get(cm) ?? /* @__PURE__ */ new Set();
74
+ tokens.add(collateral.toLowerCase());
75
+ wanted.set(cm, tokens);
76
+ }
77
+ if (wanted.size === 0) return NO_TOTALS;
78
+ const accounts = await this.sdk.accounts.getCreditAccounts({ includeZeroDebt: true });
79
+ const totals = /* @__PURE__ */ new Map();
80
+ for (const account of accounts) {
81
+ const tokens = wanted.get(account.creditManager.toLowerCase());
82
+ if (!tokens) continue;
83
+ for (const token of account.tokens) {
84
+ if (token.balance <= 0n || !tokens.has(token.token.toLowerCase())) continue;
85
+ const key = strategyKey(account.creditManager, token.token);
86
+ const current = totals.get(key);
87
+ totals.set(key, {
88
+ value: (current?.value ?? 0n) + account.totalValue,
89
+ valueUsd: (current?.valueUsd ?? 0) + require_sdk_market_math.usdToNumber(account.totalValueUSD)
90
+ });
91
+ }
92
+ }
93
+ return (creditManager, collateral) => totals.get(strategyKey(creditManager, collateral));
94
+ }
95
+ };
96
+ /**
97
+ * Both halves of a strategy key folded into one map key.
98
+ **/
99
+ function strategyKey(creditManager, collateral) {
100
+ return `${creditManager.toLowerCase()}:${collateral.toLowerCase()}`;
101
+ }
102
+ //#endregion
103
+ exports.OpportunitiesService = OpportunitiesService;
@@ -0,0 +1,12 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_sdk_market_math = require("../market/math.js");
3
+ const require_sdk_opportunities_MultichainOpportunitiesService = require("./MultichainOpportunitiesService.js");
4
+ const require_sdk_opportunities_OpportunitiesService = require("./OpportunitiesService.js");
5
+ exports.MultichainOpportunitiesService = require_sdk_opportunities_MultichainOpportunitiesService.MultichainOpportunitiesService;
6
+ exports.OpportunitiesService = require_sdk_opportunities_OpportunitiesService.OpportunitiesService;
7
+ exports.additionalBorrowApyBps = require_sdk_market_math.additionalBorrowApyBps;
8
+ exports.borrowApyBps = require_sdk_market_math.borrowApyBps;
9
+ exports.maxLeverage = require_sdk_market_math.maxLeverage;
10
+ exports.rayToBps = require_sdk_market_math.rayToBps;
11
+ exports.usdToNumber = require_sdk_market_math.usdToNumber;
12
+ exports.utilizationBps = require_sdk_market_math.utilizationBps;
@@ -0,0 +1 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region src/common-utils/utils/bigint-math.ts
2
+ //#region src/sdk/utils/bigint-math.ts
3
3
  /**
4
4
  * Utility namespace for common `bigint` operations.
5
5
  *
@@ -17,20 +17,20 @@ var BigIntMath = class {
17
17
  static abs = (x) => x < 0n ? -x : x;
18
18
  /**
19
19
  * Returns the greater of two bigint values.
20
- *
21
- * @param a First candidate value.
22
- * @param b Second candidate value.
23
- * @returns The larger value between `a` and `b`.
20
+ * @param values - The values to find the maximum of.
21
+ * @returns The maximum value.
24
22
  */
25
- static max = (a, b) => a > b ? a : b;
23
+ static max = (...values) => {
24
+ return values.reduce((max, v) => v > max ? v : max);
25
+ };
26
26
  /**
27
27
  * Returns the smaller of two bigint values.
28
- *
29
- * @param a First candidate value.
30
- * @param b Second candidate value.
31
- * @returns The smaller value between `a` and `b`.
28
+ * @param values - The values to find the minimum of.
29
+ * @returns The minimum value.
32
30
  */
33
- static min = (a, b) => a < b ? a : b;
31
+ static min = (...values) => {
32
+ return values.reduce((min, v) => v < min ? v : min);
33
+ };
34
34
  /**
35
35
  * Returns the negative form of a bigint if it is currently positive.
36
36
  *
@@ -4,6 +4,7 @@ const require_sdk_utils_AddressSet = require("./AddressSet.js");
4
4
  const require_sdk_utils_AssetsMap = require("./AssetsMap.js");
5
5
  const require_sdk_utils_json = require("./json.js");
6
6
  const require_sdk_utils_abi_decode = require("./abi-decode.js");
7
+ const require_sdk_utils_bigint_math = require("./bigint-math.js");
7
8
  const require_sdk_utils_bytes32ToString = require("./bytes32ToString.js");
8
9
  const require_sdk_utils_childLogger = require("./childLogger.js");
9
10
  const require_sdk_utils_createRawTx = require("./createRawTx.js");
@@ -20,8 +21,10 @@ const require_sdk_utils_zod = require("./zod.js");
20
21
  exports.AddressMap = require_sdk_utils_AddressMap.AddressMap;
21
22
  exports.AddressSet = require_sdk_utils_AddressSet.AddressSet;
22
23
  exports.AssetsMap = require_sdk_utils_AssetsMap.AssetsMap;
24
+ exports.BigIntMath = require_sdk_utils_bigint_math.BigIntMath;
23
25
  exports.TypedObjectUtils = require_sdk_utils_mappers.TypedObjectUtils;
24
26
  exports.ZodAddress = require_sdk_utils_zod.ZodAddress;
27
+ exports.ZodHex = require_sdk_utils_zod.ZodHex;
25
28
  exports.bytes32ToString = require_sdk_utils_bytes32ToString.bytes32ToString;
26
29
  exports.childLogger = require_sdk_utils_childLogger.childLogger;
27
30
  exports.createRawTx = require_sdk_utils_createRawTx.createRawTx;
@@ -13,5 +13,17 @@ const ZodAddress = () => zod_v4.z.string().transform((val, ctx) => {
13
13
  });
14
14
  return (0, viem.getAddress)(val);
15
15
  });
16
+ /**
17
+ * A `0x`-prefixed hex string, as viem's Hex.
18
+ */
19
+ const ZodHex = () => zod_v4.z.string().transform((val, ctx) => {
20
+ if (!(0, viem.isHex)(val)) ctx.issues.push({
21
+ code: "custom",
22
+ message: `invalid hex string ${val}`,
23
+ input: ctx.value
24
+ });
25
+ return val;
26
+ });
16
27
  //#endregion
17
28
  exports.ZodAddress = ZodAddress;
29
+ exports.ZodHex = ZodHex;
@@ -1,5 +1,6 @@
1
1
  import { AxiosCache } from "./axios-cache/AxiosCache.js";
2
2
  import "./axios-cache/index.js";
3
+ import { BigIntMath } from "../sdk/utils/bigint-math.js";
3
4
  import { ChartsCreditManagerData } from "./charts/credit-manager.js";
4
5
  import { CREDIT_SESSION_ID_BY_STATUS, CREDIT_SESSION_STATUS_BY_ID, CreditSession, CreditSessionFiltered, UserCreditSessionsBuilder } from "./charts/credit-session.js";
5
6
  import { ChartsPoolData, UserPoolData } from "./charts/pool.js";
@@ -11,7 +12,6 @@ import { calculateBorrowRateFromUtilization } from "./utils/apy/calculate-borrow
11
12
  import { PriceUtils } from "./utils/price-math.js";
12
13
  import { calculateEarnings } from "./utils/apy/calculate-earnings.js";
13
14
  import { calculateEffectiveBorrowRate } from "./utils/apy/calculate-effective-borrow-rate.js";
14
- import { BigIntMath } from "./utils/bigint-math.js";
15
15
  import { calculateSafeBorrowRate } from "./utils/apy/calculate-safe-borrow-rate.js";
16
16
  import { getComplexAPYList } from "./utils/apy/get-complex-apy-list.js";
17
17
  import { getRateWithFee } from "./utils/apy/get-rate-with-fee.js";
@@ -1,6 +1,6 @@
1
+ import { BigIntMath } from "../../../sdk/utils/bigint-math.js";
1
2
  import { PERCENTAGE_DECIMALS, PERCENTAGE_FACTOR } from "../../../sdk/constants/math.js";
2
3
  import { calculateBorrowRateFromUtilization } from "./calculate-borrow-rate-from-utilization.js";
3
- import { BigIntMath } from "../bigint-math.js";
4
4
  //#region src/common-utils/utils/apy/calculate-safe-borrow-rate.ts
5
5
  /**
6
6
  * Returns borrow rate multiplied by feeInterest
@@ -1,5 +1,5 @@
1
+ import { BigIntMath } from "../../sdk/utils/bigint-math.js";
1
2
  import { PriceUtils } from "./price-math.js";
2
- import { BigIntMath } from "./bigint-math.js";
3
3
  import { sortBalances } from "./creditAccount/sort.js";
4
4
  //#region src/common-utils/utils/assets-math.ts
5
5
  /**
@@ -1,7 +1,7 @@
1
+ import { BigIntMath } from "../../../sdk/utils/bigint-math.js";
1
2
  import { PERCENTAGE_FACTOR, PRICE_DECIMALS } from "../../../sdk/constants/math.js";
2
3
  import "../../../sdk/index.js";
3
4
  import { PriceUtils } from "../price-math.js";
4
- import { BigIntMath } from "../bigint-math.js";
5
5
  //#region src/common-utils/utils/creditAccount/calc-health-factor.ts
6
6
  const MAX_UINT16 = 65535;
7
7
  /**
@@ -1,7 +1,7 @@
1
+ import { BigIntMath } from "../../../sdk/utils/bigint-math.js";
1
2
  import { PERCENTAGE_FACTOR } from "../../../sdk/constants/math.js";
2
3
  import "../../../sdk/index.js";
3
4
  import { PriceUtils } from "../price-math.js";
4
- import { BigIntMath } from "../bigint-math.js";
5
5
  //#region src/common-utils/utils/creditAccount/debt.ts
6
6
  /**
7
7
  * Calculates additional debt that can be borrowed while targeting
@@ -1,6 +1,6 @@
1
+ import { BigIntMath } from "../../../sdk/utils/bigint-math.js";
1
2
  import { MIN_INT96, PERCENTAGE_FACTOR } from "../../../sdk/constants/math.js";
2
3
  import "../../../sdk/index.js";
3
- import { BigIntMath } from "../bigint-math.js";
4
4
  //#region src/common-utils/utils/creditAccount/quota-utils.ts
5
5
  /**
6
6
  * Rounds quota deltas to protocol precision step (`PERCENTAGE_FACTOR`).
@@ -1,9 +1,9 @@
1
+ import { BigIntMath } from "../../sdk/utils/bigint-math.js";
1
2
  import { BONUS_APY_FROM_POINTS } from "./apy/bonus-apy-from-points.js";
2
3
  import { calculateBorrowRateFromUtilization } from "./apy/calculate-borrow-rate-from-utilization.js";
3
4
  import { PriceUtils } from "./price-math.js";
4
5
  import { calculateEarnings } from "./apy/calculate-earnings.js";
5
6
  import { calculateEffectiveBorrowRate } from "./apy/calculate-effective-borrow-rate.js";
6
- import { BigIntMath } from "./bigint-math.js";
7
7
  import { calculateSafeBorrowRate } from "./apy/calculate-safe-borrow-rate.js";
8
8
  import { getComplexAPYList } from "./apy/get-complex-apy-list.js";
9
9
  import { getRateWithFee } from "./apy/get-rate-with-fee.js";
@@ -1,6 +1,6 @@
1
+ import { BigIntMath } from "../../../../sdk/utils/bigint-math.js";
1
2
  import { PERCENTAGE_FACTOR } from "../../../../sdk/constants/math.js";
2
3
  import "../../../../sdk/index.js";
3
- import { BigIntMath } from "../../bigint-math.js";
4
4
  import { calculateLossCoefficient } from "./calculate-loss-coefficient.js";
5
5
  import { maxLeverage } from "./max-leverage.js";
6
6
  //#region src/common-utils/utils/strategies/leverage/calculate-max-leverage-factor.ts
@@ -1,5 +1,5 @@
1
+ import { BigIntMath } from "../../../../sdk/utils/bigint-math.js";
1
2
  import { LEVERAGE_DECIMALS, PERCENTAGE_FACTOR } from "../../../../sdk/constants/math.js";
2
- import { BigIntMath } from "../../bigint-math.js";
3
3
  import { calculateLossCoefficient } from "./calculate-loss-coefficient.js";
4
4
  import { maxLeverage } from "./max-leverage.js";
5
5
  //#region src/common-utils/utils/strategies/leverage/calculate-max-strategy-debt.ts
@@ -1,6 +1,6 @@
1
+ import { BigIntMath } from "../../../../sdk/utils/bigint-math.js";
1
2
  import { LEVERAGE_DECIMALS, PERCENTAGE_FACTOR, PRICE_DECIMALS } from "../../../../sdk/constants/math.js";
2
3
  import { PriceUtils } from "../../price-math.js";
3
- import { BigIntMath } from "../../bigint-math.js";
4
4
  import { getPointsRates } from "../points/get-points-rates.js";
5
5
  //#region src/common-utils/utils/strategies/strategy-info/calculate-total-points.ts
6
6
  const THRESHOLD_POINTS = 1e3;
@@ -1,9 +1,9 @@
1
+ import { BigIntMath } from "../../../../sdk/utils/bigint-math.js";
1
2
  import { LEVERAGE_DECIMALS } from "../../../../sdk/constants/math.js";
2
3
  import { formatBN, toBN, toBigInt } from "../../../../sdk/utils/formatter.js";
3
4
  import { PriceUtils } from "../../price-math.js";
4
5
  import { calculateEarnings } from "../../apy/calculate-earnings.js";
5
6
  import { calculateEffectiveBorrowRate } from "../../apy/calculate-effective-borrow-rate.js";
6
- import { BigIntMath } from "../../bigint-math.js";
7
7
  import { getComplexAPYList } from "../../apy/get-complex-apy-list.js";
8
8
  import { getSafeBaseBorrowRate } from "../../apy/get-safe-base-borrow-rate.js";
9
9
  import { getCollateralByDebt } from "../leverage/get-collateral-by-debt.js";
@@ -1,4 +1,4 @@
1
- import { BigIntMath } from "../bigint-math.js";
1
+ import { BigIntMath } from "../../../sdk/utils/bigint-math.js";
2
2
  import { validateOpenAccountPoolQuotaStatus } from "./validate-open-account-pool-quota-status.js";
3
3
  //#region src/common-utils/utils/validation/validate-open-account-pool-status.ts
4
4
  function validateOpenAccountPoolStatus(props) {
@@ -1,9 +1,9 @@
1
+ import { ierc20Abi } from "../abi/iERC20.js";
1
2
  import { iCreditFacadeV310Abi } from "../abi/310/generated.js";
2
3
  import { AddressMap } from "../sdk/utils/AddressMap.js";
3
4
  import { AddressSet } from "../sdk/utils/AddressSet.js";
4
5
  import { AssetsMap } from "../sdk/utils/AssetsMap.js";
5
6
  import { childLogger } from "../sdk/utils/childLogger.js";
6
- import { ierc20Abi } from "../abi/iERC20.js";
7
7
  import "../sdk/constants/addresses.js";
8
8
  import { MAX_UINT256, PERCENTAGE_FACTOR } from "../sdk/constants/math.js";
9
9
  import { SDKConstruct } from "../sdk/base/SDKConstruct.js";
@@ -1,7 +1,8 @@
1
1
  import { faucetAbi, iDegenNftv2Abi, iOnchainExecutionIdAbi, iOwnableAbi, iaclTraitAbi } from "./abi.js";
2
2
  import { claimFromFaucet } from "./claimFromFaucet.js";
3
3
  import { anvilNodeInfo, createAnvilClient, evmMineDetailed, extendAnvilClient, isAnvil } from "./createAnvilClient.js";
4
- import { prependMidasReceiveGreenlist } from "./midasUtils.js";
4
+ import { greenlistMidasGateway, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, writeAndWait } from "./kycUtils.js";
5
+ import { prependMidasReceiveGreenlist, unpauseMidasIssuanceVault } from "./midasUtils.js";
5
6
  import { createMinter } from "./mint/factory.js";
6
7
  import "./mint/index.js";
7
8
  import { AccountOpener, OpenTxRevertedError } from "./AccountOpener.js";
@@ -14,7 +15,6 @@ import { detectChain } from "./detectChain.js";
14
15
  import { isOutOfSyncError } from "./isOutOfSyncError.js";
15
16
  import { isRateLimitError } from "./isRateLimitError.js";
16
17
  import { isTransientError } from "./isTransientError.js";
17
- import { greenlistMidasGateway, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, writeAndWait } from "./kycUtils.js";
18
18
  import { isRangeError, logSplitterTransport } from "./logSplitterTransport.js";
19
19
  import { setLTZero, setLTs } from "./ltUtils.js";
20
20
  import { migrateFaucet } from "./migrateFaucet.js";
@@ -25,4 +25,4 @@ import { claimDSToken, claimDSTokens, enableDSTokenBackDating } from "./securiti
25
25
  import "./types.js";
26
26
  import { ONCHAIN_EXECUTION_ID_ADDRESS, verifyTestnet } from "./verifyTestnet.js";
27
27
  import { makePendingWithdrawalsClaimable } from "./withdrawalUtils.js";
28
- export { AccountOpener, Create2Deployer, DEFAULT_CREATE2_SALT, EthCallSpy, NoAvailableTransportsError, ONCHAIN_EXECUTION_ID_ADDRESS, OpenTxRevertedError, PUBLIC_CREATE2_FACTORY, RevolverTransport, SUPPORTED_RPC_PROVIDERS, SelectionStrategy, anvilNodeInfo, calcLiquidatableLTs, claimDSToken, claimDSTokens, claimFromFaucet, createAnvilClient, createMinter, deployUsingPublicCreate2, detectChain, enableDSTokenBackDating, evmMineDetailed, extendAnvilClient, faucetAbi, getAlchemyUrl, getAnkrUrl, getDrpcUrl, getErpcKey, getPublicCreate2Address, getRpcProviderUrl, getThirdWebUrl, greenlistMidasGateway, httpTransportOptionsSchema, iDegenNftv2Abi, iOnchainExecutionIdAbi, iOwnableAbi, iaclTraitAbi, isAnvil, isDeployedUsingPublicCreate2, isOutOfSyncError, isRangeError, isRateLimitError, isTransientError, logSplitterTransport, makePendingWithdrawalsClaimable, migrateFaucet, prependMidasReceiveGreenlist, providerConfigSchema, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, replaceStorage, resilientTransport, resilientTransportOptionsSchema, revolverTransportConfigBaseSchema, revolverTransportConfigSchema, rpcProvidersSchema, setLTZero, setLTs, verifyTestnet, writeAndWait };
28
+ export { AccountOpener, Create2Deployer, DEFAULT_CREATE2_SALT, EthCallSpy, NoAvailableTransportsError, ONCHAIN_EXECUTION_ID_ADDRESS, OpenTxRevertedError, PUBLIC_CREATE2_FACTORY, RevolverTransport, SUPPORTED_RPC_PROVIDERS, SelectionStrategy, anvilNodeInfo, calcLiquidatableLTs, claimDSToken, claimDSTokens, claimFromFaucet, createAnvilClient, createMinter, deployUsingPublicCreate2, detectChain, enableDSTokenBackDating, evmMineDetailed, extendAnvilClient, faucetAbi, getAlchemyUrl, getAnkrUrl, getDrpcUrl, getErpcKey, getPublicCreate2Address, getRpcProviderUrl, getThirdWebUrl, greenlistMidasGateway, httpTransportOptionsSchema, iDegenNftv2Abi, iOnchainExecutionIdAbi, iOwnableAbi, iaclTraitAbi, isAnvil, isDeployedUsingPublicCreate2, isOutOfSyncError, isRangeError, isRateLimitError, isTransientError, logSplitterTransport, makePendingWithdrawalsClaimable, migrateFaucet, prependMidasReceiveGreenlist, providerConfigSchema, registerMidasInvestor, registerRWAInvestor, registerSecuritizeInvestor, replaceStorage, resilientTransport, resilientTransportOptionsSchema, revolverTransportConfigBaseSchema, revolverTransportConfigSchema, rpcProvidersSchema, setLTZero, setLTs, unpauseMidasIssuanceVault, verifyTestnet, writeAndWait };
@@ -2,9 +2,9 @@ import { AddressSet } from "../sdk/utils/AddressSet.js";
2
2
  import { MAX_UINT256 } from "../sdk/constants/math.js";
3
3
  import { OnchainSDK } from "../sdk/OnchainSDK.js";
4
4
  import "../sdk/index.js";
5
- import { midasGatewayAbi } from "./withdrawalAbi.js";
6
5
  import { iDSRegistryServiceAbi } from "../abi/rwa/iDSRegistryService.js";
7
6
  import { iDSTokenAbi } from "../abi/rwa/iDSToken.js";
7
+ import { midasGatewayAbi } from "./withdrawalAbi.js";
8
8
  import { isAddressEqual, parseAbi, parseEther, zeroAddress } from "viem";
9
9
  import { privateKeyToAccount } from "viem/accounts";
10
10
  //#region src/dev/kycUtils.ts
@@ -1,5 +1,6 @@
1
1
  import { midasGatewayAbi } from "./withdrawalAbi.js";
2
- import { encodeFunctionData, isAddressEqual, parseAbi } from "viem";
2
+ import { writeAndWait } from "./kycUtils.js";
3
+ import { encodeFunctionData, isAddressEqual, parseAbi, parseEther } from "viem";
3
4
  //#region src/dev/midasUtils.ts
4
5
  const ADAPTER_MIDAS_GATEWAY = "ADAPTER::MIDAS_GATEWAY";
5
6
  const ADAPTER_MIDAS_ISSUANCE_VAULT = "ADAPTER::MIDAS_ISSUANCE_VAULT";
@@ -15,6 +16,18 @@ const MIDAS_MODE_PERMISSIONLESS = 0;
15
16
  */
16
17
  const iMidasMTokenAbi = parseAbi(["function mToken() external view returns (address)"]);
17
18
  const iMidasGatewayAdapterExtAbi = parseAbi(["function receiveGreenlist() external returns (bool)"]);
19
+ /**
20
+ * Midas vaults inherit their own `Pausable`, whose global pause is guarded by
21
+ * `pauseAdminRole()` in the vault's access control instead of `Ownable`
22
+ */
23
+ const iMidasPausableVaultAbi = parseAbi([
24
+ "function paused() external view returns (bool)",
25
+ "function pause() external",
26
+ "function unpause() external",
27
+ "function pauseAdminRole() external view returns (bytes32)",
28
+ "function accessControl() external view returns (address)"
29
+ ]);
30
+ const iMidasAccessControlAbi = parseAbi(["function hasRole(bytes32 role, address account) external view returns (bool)", "function grantRole(bytes32 role, address account) external"]);
18
31
  const receiveGreenlistCallData = encodeFunctionData({
19
32
  abi: iMidasGatewayAdapterExtAbi,
20
33
  functionName: "receiveGreenlist"
@@ -85,6 +98,96 @@ async function prependMidasReceiveGreenlist(props) {
85
98
  }
86
99
  return prepended.length > 0 ? [...prepended, ...calls] : calls;
87
100
  }
101
+ /**
102
+ * Unpauses a globally paused Midas issuance vault on an anvil fork, so that
103
+ * `depositInstant` stops reverting with `Pausable: paused`, and returns a
104
+ * callback that restores the original pause state.
105
+ *
106
+ * Impersonates `admin` and grants it `pauseAdminRole()` when missing, same as
107
+ * `greenlistMidasGateway` does with the greenlist roles. The grant is not
108
+ * reverted by the callback, only the pause state is.
109
+ */
110
+ async function unpauseMidasIssuanceVault(props) {
111
+ const { anvil, vault, admin, logger } = props;
112
+ if (!await anvil.readContract({
113
+ address: vault,
114
+ abi: iMidasPausableVaultAbi,
115
+ functionName: "paused"
116
+ })) {
117
+ logger?.debug(`midas: issuance vault ${vault} is not paused`);
118
+ return async () => {};
119
+ }
120
+ const [accessControl, pauseAdminRole] = await anvil.multicall({
121
+ allowFailure: false,
122
+ contracts: [{
123
+ address: vault,
124
+ abi: iMidasPausableVaultAbi,
125
+ functionName: "accessControl"
126
+ }, {
127
+ address: vault,
128
+ abi: iMidasPausableVaultAbi,
129
+ functionName: "pauseAdminRole"
130
+ }]
131
+ });
132
+ const isPauseAdmin = await anvil.readContract({
133
+ address: accessControl,
134
+ abi: iMidasAccessControlAbi,
135
+ functionName: "hasRole",
136
+ args: [pauseAdminRole, admin]
137
+ });
138
+ logger?.debug(`midas: unpausing issuance vault ${vault} as ${admin}, access control ${accessControl}, pause admin role ${pauseAdminRole}`);
139
+ await anvil.impersonateAccount({ address: admin });
140
+ try {
141
+ await anvil.setBalance({
142
+ address: admin,
143
+ value: parseEther("100")
144
+ });
145
+ if (!isPauseAdmin) {
146
+ await writeAndWait(anvil, {
147
+ account: admin,
148
+ chain: anvil.chain,
149
+ address: accessControl,
150
+ abi: iMidasAccessControlAbi,
151
+ functionName: "grantRole",
152
+ args: [pauseAdminRole, admin]
153
+ });
154
+ logger?.debug(`midas: granted pause admin role to ${admin}`);
155
+ }
156
+ await writeAndWait(anvil, {
157
+ account: admin,
158
+ chain: anvil.chain,
159
+ address: vault,
160
+ abi: iMidasPausableVaultAbi,
161
+ functionName: "unpause"
162
+ });
163
+ } finally {
164
+ await anvil.stopImpersonatingAccount({ address: admin });
165
+ }
166
+ let toRestore = true;
167
+ return async () => {
168
+ if (!toRestore) return;
169
+ toRestore = false;
170
+ logger?.debug(`midas: pausing issuance vault ${vault} back`);
171
+ await anvil.impersonateAccount({ address: admin });
172
+ try {
173
+ await anvil.setBalance({
174
+ address: admin,
175
+ value: parseEther("100")
176
+ });
177
+ await writeAndWait(anvil, {
178
+ account: admin,
179
+ chain: anvil.chain,
180
+ address: vault,
181
+ abi: iMidasPausableVaultAbi,
182
+ functionName: "pause"
183
+ });
184
+ } catch (e) {
185
+ logger?.warn(`midas: failed to pause issuance vault ${vault} back: ${e}`);
186
+ } finally {
187
+ await anvil.stopImpersonatingAccount({ address: admin });
188
+ }
189
+ };
190
+ }
88
191
  async function readMTokens(client, adapters) {
89
192
  return await client.multicall({
90
193
  allowFailure: false,
@@ -96,4 +199,4 @@ async function readMTokens(client, adapters) {
96
199
  });
97
200
  }
98
201
  //#endregion
99
- export { prependMidasReceiveGreenlist };
202
+ export { prependMidasReceiveGreenlist, unpauseMidasIssuanceVault };
@@ -1,6 +1,6 @@
1
+ import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
1
2
  import { getNetworkType } from "../sdk/chain/chains.js";
2
3
  import { getWithdrawalCompressorAddress } from "../sdk/accounts/withdrawal-compressor/addresses.js";
3
- import { iWithdrawalCompressorV313Abi } from "../abi/IWithdrawalCompressorV313.js";
4
4
  import "../sdk/index.js";
5
5
  import { iMidasDataFeedAbi, iMidasRedemptionVaultAbi, midasGatewayAbi, midasRedeemerAbi, midasRedemptionVaultPhantomTokenAbi, securitizeRedeemerAbi, securitizeRedemptionGatewayAbi, securitizeRedemptionPhantomTokenAbi } from "./withdrawalAbi.js";
6
6
  import { erc20Abi, hexToString, parseAbi, parseEther } from "viem";