@gearbox-protocol/sdk 17.0.0-next.4 → 17.0.0

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 (364) hide show
  1. package/dist/cjs/dev/abi.js +14 -15
  2. package/dist/cjs/dev/claimFromFaucet.js +4 -8
  3. package/dist/cjs/dev/createAnvilClient.js +35 -17
  4. package/dist/cjs/dev/index.js +7 -2
  5. package/dist/cjs/dev/kycUtils.js +66 -58
  6. package/dist/cjs/dev/midasUtils.js +113 -16
  7. package/dist/cjs/dev/securitizeUtils.js +82 -42
  8. package/dist/cjs/dev/withdrawalUtils.js +3 -6
  9. package/dist/cjs/model/errors/index.js +2 -0
  10. package/dist/cjs/model/errors/operation-errors.js +19 -1
  11. package/dist/cjs/model/index.js +4 -2
  12. package/dist/cjs/model/rwa.js +4 -4
  13. package/dist/cjs/model/rwa.schema.js +4 -4
  14. package/dist/cjs/offchain/opportunities/OffchainOpportunities.js +1 -1
  15. package/dist/cjs/onchain/OnchainSDK.js +3 -3
  16. package/dist/cjs/onchain/accounts/CreditAccountsServiceV310.js +2 -17
  17. package/dist/cjs/onchain/accounts/intents/borrow.js +140 -0
  18. package/dist/cjs/onchain/accounts/intents/collateral-valuation.js +41 -0
  19. package/dist/cjs/onchain/accounts/intents/guards.js +15 -3
  20. package/dist/cjs/onchain/accounts/intents/index.js +107 -20
  21. package/dist/cjs/onchain/accounts/intents/leverage-band.js +2 -12
  22. package/dist/cjs/onchain/accounts/intents/maxBorrow.js +89 -0
  23. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  24. package/dist/cjs/onchain/accounts/intents/open-strategy.js +8 -46
  25. package/dist/cjs/onchain/accounts/intents/operations.js +0 -1
  26. package/dist/cjs/onchain/accounts/intents/realize.js +61 -4
  27. package/dist/cjs/onchain/accounts/intents/tail.js +1 -1
  28. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  29. package/dist/cjs/onchain/accounts/intents/utils/common.js +19 -0
  30. package/dist/cjs/onchain/accounts/intents/utils/credit-account-slice.js +21 -0
  31. package/dist/cjs/onchain/accounts/intents/utils/index.js +2 -0
  32. package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +12 -9
  33. package/dist/cjs/onchain/accounts/intents/utils/router-path.js +4 -5
  34. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +97 -0
  35. package/dist/cjs/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  36. package/dist/cjs/onchain/constants/address-provider.js +0 -2
  37. package/dist/cjs/onchain/constants/index.js +0 -1
  38. package/dist/cjs/onchain/core/createAddressProvider.js +2 -5
  39. package/dist/cjs/onchain/index.js +60 -43
  40. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +2 -2
  41. package/dist/cjs/onchain/market/adapters/contracts/AbstractAdapter.js +6 -0
  42. package/dist/cjs/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +49 -5
  43. package/dist/cjs/onchain/market/credit/CreditSuite.js +26 -9
  44. package/dist/cjs/onchain/market/index.js +50 -38
  45. package/dist/cjs/onchain/market/oracle/PriceOracleBaseContract.js +3 -3
  46. package/dist/cjs/onchain/market/pricefeeds/AbstractPriceFeed.js +0 -5
  47. package/dist/cjs/onchain/market/pricefeeds/PriceFeedRegistry.js +127 -0
  48. package/dist/cjs/onchain/market/pricefeeds/{BalancerStablePriceFeed.js → feeds/BalancerStablePriceFeed.js} +4 -4
  49. package/dist/cjs/onchain/market/pricefeeds/{BalancerWeightedPriceFeed.js → feeds/BalancerWeightedPriceFeed.js} +4 -4
  50. package/dist/cjs/onchain/market/pricefeeds/{BoundedPriceFeed.js → feeds/BoundedPriceFeed.js} +4 -4
  51. package/dist/cjs/onchain/market/pricefeeds/{CompositePriceFeed.js → feeds/CompositePriceFeed.js} +4 -4
  52. package/dist/cjs/onchain/market/pricefeeds/{ConstantPriceFeed.js → feeds/ConstantPriceFeed.js} +3 -3
  53. package/dist/cjs/onchain/market/pricefeeds/{CurveCryptoPriceFeed.js → feeds/CurveCryptoPriceFeed.js} +4 -4
  54. package/dist/cjs/onchain/market/pricefeeds/{CurveStablePriceFeed.js → feeds/CurveStablePriceFeed.js} +4 -4
  55. package/dist/cjs/onchain/market/pricefeeds/{CurveUSDPriceFeed.js → feeds/CurveUSDPriceFeed.js} +4 -4
  56. package/dist/cjs/onchain/market/pricefeeds/{Erc4626PriceFeed.js → feeds/Erc4626PriceFeed.js} +4 -4
  57. package/dist/cjs/onchain/market/pricefeeds/{ExternalPriceFeed.js → feeds/ExternalPriceFeed.js} +4 -4
  58. package/dist/cjs/onchain/market/pricefeeds/{MellowLRTPriceFeed.js → feeds/MellowLRTPriceFeed.js} +4 -4
  59. package/dist/cjs/onchain/market/pricefeeds/{PendleTWAPPTPriceFeed.js → feeds/PendleTWAPPTPriceFeed.js} +4 -4
  60. package/dist/cjs/onchain/market/pricefeeds/{PythPriceFeed.js → feeds/PythPriceFeed.js} +3 -3
  61. package/dist/cjs/onchain/market/pricefeeds/{RedstonePriceFeed.js → feeds/RedstonePriceFeed.js} +6 -6
  62. package/dist/cjs/onchain/market/pricefeeds/{WstETHPriceFeed.js → feeds/WstETHPriceFeed.js} +4 -4
  63. package/dist/cjs/onchain/market/pricefeeds/{YearnPriceFeed.js → feeds/YearnPriceFeed.js} +4 -4
  64. package/dist/cjs/onchain/market/pricefeeds/{ZeroPriceFeed.js → feeds/ZeroPriceFeed.js} +4 -4
  65. package/dist/cjs/onchain/market/pricefeeds/feeds/index.js +35 -0
  66. package/dist/cjs/onchain/market/pricefeeds/index.js +51 -39
  67. package/dist/cjs/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.js +189 -0
  68. package/dist/cjs/onchain/market/pricefeeds/{getRawPriceUpdates.js → updates/getRawPriceUpdates.js} +2 -2
  69. package/dist/cjs/onchain/market/pricefeeds/updates/index.js +8 -0
  70. package/dist/cjs/onchain/market/pricefeeds/{isUpdatablePriceFeed.js → updates/isUpdatablePriceFeed.js} +1 -1
  71. package/dist/cjs/onchain/market/pricefeeds/updates/updatableDependencies.js +14 -0
  72. package/dist/cjs/onchain/market/rwa/RWARegistry.js +4 -7
  73. package/dist/cjs/onchain/market/rwa/index.js +1 -0
  74. package/dist/cjs/onchain/market/rwa/midas/MidasDegenNFT.js +45 -5
  75. package/dist/cjs/onchain/market/rwa/securitize/SecuritizeDegenNFT.js +56 -12
  76. package/dist/cjs/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +0 -37
  77. package/dist/cjs/onchain/opportunities/MultichainOpportunitiesService.js +8 -2
  78. package/dist/cjs/onchain/opportunities/OpportunitiesService.js +16 -4
  79. package/dist/cjs/onchain/positions/calcHealthFactor.js +3 -3
  80. package/dist/cjs/onchain/preview/index.js +2 -0
  81. package/dist/cjs/onchain/preview/parse/parseRWAFactoryOperationCalldata.js +2 -2
  82. package/dist/cjs/onchain/preview/preview/index.js +2 -0
  83. package/dist/cjs/onchain/preview/preview/midasGreenlistsAccount.js +17 -0
  84. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +13 -16
  85. package/dist/cjs/onchain/preview/preview/previewOperation.js +19 -11
  86. package/dist/cjs/onchain/preview/preview/replayMulticall.js +4 -3
  87. package/dist/cjs/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  88. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +11 -9
  89. package/dist/cjs/onchain/validation/bundles/{checkDraw.js → checkIncreaseDebt.js} +10 -10
  90. package/dist/cjs/onchain/validation/bundles/{checkQuotasAsked.js → checkIncreaseQuota.js} +3 -3
  91. package/dist/cjs/onchain/validation/bundles/checkMidasAccountGreenlist.js +44 -0
  92. package/dist/cjs/onchain/validation/bundles/checkRWAOpenRequirements.js +9 -9
  93. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +18 -8
  94. package/dist/cjs/onchain/validation/bundles/index.js +6 -4
  95. package/dist/cjs/onchain/validation/checkOperation.js +0 -1
  96. package/dist/cjs/onchain/validation/checks/checkBorrowLimit.js +1 -1
  97. package/dist/cjs/onchain/validation/checks/checkPoolLiquidity.js +1 -1
  98. package/dist/cjs/onchain/validation/checks/checkReservePriceLimited.js +30 -0
  99. package/dist/cjs/onchain/validation/checks/index.js +2 -0
  100. package/dist/cjs/onchain/validation/index.js +8 -4
  101. package/dist/cjs/permissionless/utils/price-update/get-price-update-tx.js +2 -2
  102. package/dist/cjs/permissionless/utils/price-update/get-updatable-feeds.js +2 -2
  103. package/dist/cjs/sdk/execute/ExecuteApi.js +67 -7
  104. package/dist/cjs/sdk/opportunities/OpportunitiesNamespace.js +9 -3
  105. package/dist/cjs/sdk/prepare/PrepareApi.js +89 -14
  106. package/dist/esm/dev/abi.js +14 -15
  107. package/dist/esm/dev/claimFromFaucet.js +4 -8
  108. package/dist/esm/dev/createAnvilClient.js +36 -19
  109. package/dist/esm/dev/index.js +4 -4
  110. package/dist/esm/dev/kycUtils.js +66 -59
  111. package/dist/esm/dev/midasUtils.js +112 -18
  112. package/dist/esm/dev/securitizeUtils.js +84 -44
  113. package/dist/esm/dev/withdrawalUtils.js +3 -6
  114. package/dist/esm/model/errors/index.js +2 -2
  115. package/dist/esm/model/errors/operation-errors.js +18 -2
  116. package/dist/esm/model/index.js +4 -4
  117. package/dist/esm/model/rwa.js +4 -4
  118. package/dist/esm/model/rwa.schema.js +5 -5
  119. package/dist/esm/offchain/opportunities/OffchainOpportunities.js +1 -1
  120. package/dist/esm/onchain/OnchainSDK.js +3 -3
  121. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -17
  122. package/dist/esm/onchain/accounts/intents/borrow.js +138 -0
  123. package/dist/esm/onchain/accounts/intents/collateral-valuation.js +40 -0
  124. package/dist/esm/onchain/accounts/intents/guards.js +15 -3
  125. package/dist/esm/onchain/accounts/intents/index.js +107 -20
  126. package/dist/esm/onchain/accounts/intents/leverage-band.js +2 -12
  127. package/dist/esm/onchain/accounts/intents/maxBorrow.js +87 -0
  128. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  129. package/dist/esm/onchain/accounts/intents/open-strategy.js +8 -46
  130. package/dist/esm/onchain/accounts/intents/operations.js +0 -1
  131. package/dist/esm/onchain/accounts/intents/realize.js +61 -4
  132. package/dist/esm/onchain/accounts/intents/tail.js +1 -1
  133. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  134. package/dist/esm/onchain/accounts/intents/utils/common.js +19 -1
  135. package/dist/esm/onchain/accounts/intents/utils/credit-account-slice.js +21 -1
  136. package/dist/esm/onchain/accounts/intents/utils/index.js +3 -3
  137. package/dist/esm/onchain/accounts/intents/utils/price-impact.js +12 -9
  138. package/dist/esm/onchain/accounts/intents/utils/router-path.js +4 -5
  139. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +95 -0
  140. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  141. package/dist/esm/onchain/constants/address-provider.js +1 -2
  142. package/dist/esm/onchain/constants/index.js +2 -2
  143. package/dist/esm/onchain/core/createAddressProvider.js +2 -5
  144. package/dist/esm/onchain/index.js +32 -24
  145. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +2 -2
  146. package/dist/esm/onchain/market/adapters/contracts/AbstractAdapter.js +6 -0
  147. package/dist/esm/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +50 -6
  148. package/dist/esm/onchain/market/credit/CreditSuite.js +26 -9
  149. package/dist/esm/onchain/market/index.js +26 -21
  150. package/dist/esm/onchain/market/oracle/PriceOracleBaseContract.js +1 -1
  151. package/dist/esm/onchain/market/pricefeeds/AbstractPriceFeed.js +0 -5
  152. package/dist/esm/onchain/market/pricefeeds/PriceFeedRegistry.js +126 -0
  153. package/dist/esm/onchain/market/pricefeeds/{BalancerStablePriceFeed.js → feeds/BalancerStablePriceFeed.js} +4 -4
  154. package/dist/esm/onchain/market/pricefeeds/{BalancerWeightedPriceFeed.js → feeds/BalancerWeightedPriceFeed.js} +4 -4
  155. package/dist/esm/onchain/market/pricefeeds/{BoundedPriceFeed.js → feeds/BoundedPriceFeed.js} +4 -4
  156. package/dist/esm/onchain/market/pricefeeds/{CompositePriceFeed.js → feeds/CompositePriceFeed.js} +4 -4
  157. package/dist/esm/onchain/market/pricefeeds/{ConstantPriceFeed.js → feeds/ConstantPriceFeed.js} +3 -3
  158. package/dist/esm/onchain/market/pricefeeds/{CurveCryptoPriceFeed.js → feeds/CurveCryptoPriceFeed.js} +4 -4
  159. package/dist/esm/onchain/market/pricefeeds/{CurveStablePriceFeed.js → feeds/CurveStablePriceFeed.js} +4 -4
  160. package/dist/esm/onchain/market/pricefeeds/{CurveUSDPriceFeed.js → feeds/CurveUSDPriceFeed.js} +4 -4
  161. package/dist/esm/onchain/market/pricefeeds/{Erc4626PriceFeed.js → feeds/Erc4626PriceFeed.js} +4 -4
  162. package/dist/esm/onchain/market/pricefeeds/{ExternalPriceFeed.js → feeds/ExternalPriceFeed.js} +4 -4
  163. package/dist/esm/onchain/market/pricefeeds/{MellowLRTPriceFeed.js → feeds/MellowLRTPriceFeed.js} +4 -4
  164. package/dist/esm/onchain/market/pricefeeds/{PendleTWAPPTPriceFeed.js → feeds/PendleTWAPPTPriceFeed.js} +4 -4
  165. package/dist/esm/onchain/market/pricefeeds/{PythPriceFeed.js → feeds/PythPriceFeed.js} +3 -3
  166. package/dist/esm/onchain/market/pricefeeds/{RedstonePriceFeed.js → feeds/RedstonePriceFeed.js} +6 -6
  167. package/dist/esm/onchain/market/pricefeeds/{WstETHPriceFeed.js → feeds/WstETHPriceFeed.js} +4 -4
  168. package/dist/esm/onchain/market/pricefeeds/{YearnPriceFeed.js → feeds/YearnPriceFeed.js} +4 -4
  169. package/dist/esm/onchain/market/pricefeeds/{ZeroPriceFeed.js → feeds/ZeroPriceFeed.js} +4 -4
  170. package/dist/esm/onchain/market/pricefeeds/feeds/index.js +18 -0
  171. package/dist/esm/onchain/market/pricefeeds/index.js +27 -21
  172. package/dist/esm/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.js +188 -0
  173. package/dist/esm/onchain/market/pricefeeds/{getRawPriceUpdates.js → updates/getRawPriceUpdates.js} +2 -2
  174. package/dist/esm/onchain/market/pricefeeds/updates/index.js +5 -1
  175. package/dist/esm/onchain/market/pricefeeds/{isUpdatablePriceFeed.js → updates/isUpdatablePriceFeed.js} +1 -1
  176. package/dist/esm/onchain/market/pricefeeds/updates/updatableDependencies.js +13 -0
  177. package/dist/esm/onchain/market/rwa/RWARegistry.js +4 -8
  178. package/dist/esm/onchain/market/rwa/index.js +2 -2
  179. package/dist/esm/onchain/market/rwa/midas/MidasDegenNFT.js +45 -5
  180. package/dist/esm/onchain/market/rwa/securitize/SecuritizeDegenNFT.js +55 -10
  181. package/dist/esm/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +0 -37
  182. package/dist/esm/onchain/opportunities/MultichainOpportunitiesService.js +8 -2
  183. package/dist/esm/onchain/opportunities/OpportunitiesService.js +16 -4
  184. package/dist/esm/onchain/positions/calcHealthFactor.js +3 -3
  185. package/dist/esm/onchain/preview/index.js +2 -1
  186. package/dist/esm/onchain/preview/parse/parseRWAFactoryOperationCalldata.js +2 -2
  187. package/dist/esm/onchain/preview/preview/index.js +2 -1
  188. package/dist/esm/onchain/preview/preview/midasGreenlistsAccount.js +16 -0
  189. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +14 -17
  190. package/dist/esm/onchain/preview/preview/previewOperation.js +19 -11
  191. package/dist/esm/onchain/preview/preview/replayMulticall.js +4 -3
  192. package/dist/esm/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  193. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +11 -9
  194. package/dist/esm/onchain/validation/bundles/checkIncreaseDebt.js +27 -0
  195. package/dist/esm/onchain/validation/bundles/{checkQuotasAsked.js → checkIncreaseQuota.js} +3 -3
  196. package/dist/esm/onchain/validation/bundles/checkMidasAccountGreenlist.js +43 -0
  197. package/dist/esm/onchain/validation/bundles/checkRWAOpenRequirements.js +9 -9
  198. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +18 -8
  199. package/dist/esm/onchain/validation/bundles/index.js +4 -3
  200. package/dist/esm/onchain/validation/checkOperation.js +0 -1
  201. package/dist/esm/onchain/validation/checks/checkBorrowLimit.js +1 -1
  202. package/dist/esm/onchain/validation/checks/checkPoolLiquidity.js +1 -1
  203. package/dist/esm/onchain/validation/checks/checkReservePriceLimited.js +29 -0
  204. package/dist/esm/onchain/validation/checks/index.js +2 -1
  205. package/dist/esm/onchain/validation/index.js +5 -3
  206. package/dist/esm/permissionless/utils/price-update/get-price-update-tx.js +1 -1
  207. package/dist/esm/permissionless/utils/price-update/get-updatable-feeds.js +1 -1
  208. package/dist/esm/sdk/execute/ExecuteApi.js +67 -7
  209. package/dist/esm/sdk/opportunities/OpportunitiesNamespace.js +9 -3
  210. package/dist/esm/sdk/prepare/PrepareApi.js +94 -19
  211. package/dist/types/dev/abi.d.ts +13 -15
  212. package/dist/types/dev/claimFromFaucet.d.ts +0 -1
  213. package/dist/types/dev/createAnvilClient.d.ts +10 -3
  214. package/dist/types/dev/index.d.ts +4 -4
  215. package/dist/types/dev/kycUtils.d.ts +15 -24
  216. package/dist/types/dev/midasUtils.d.ts +35 -4
  217. package/dist/types/dev/securitizeUtils.d.ts +3 -9
  218. package/dist/types/model/errors/index.d.ts +2 -2
  219. package/dist/types/model/errors/operation-errors.d.ts +62 -7
  220. package/dist/types/model/index.d.ts +5 -5
  221. package/dist/types/model/opportunities.d.ts +6 -7
  222. package/dist/types/model/previews.d.ts +25 -19
  223. package/dist/types/model/rwa.d.ts +47 -27
  224. package/dist/types/model/rwa.schema.d.ts +3 -3
  225. package/dist/types/offchain/opportunities/OffchainOpportunities.d.ts +1 -2
  226. package/dist/types/offchain/opportunities/types.d.ts +1 -4
  227. package/dist/types/onchain/OnchainSDK.d.ts +2 -2
  228. package/dist/types/onchain/accounts/index.d.ts +5 -4
  229. package/dist/types/onchain/accounts/intents/borrow.d.ts +141 -0
  230. package/dist/types/onchain/accounts/intents/collateral-valuation.d.ts +42 -0
  231. package/dist/types/onchain/accounts/intents/guards.d.ts +18 -2
  232. package/dist/types/onchain/accounts/intents/index.d.ts +103 -15
  233. package/dist/types/onchain/accounts/intents/maxBorrow.d.ts +54 -0
  234. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -8
  235. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -17
  236. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +2 -0
  237. package/dist/types/onchain/accounts/intents/tests/open-strategy.fixtures.d.ts +2 -2
  238. package/dist/types/onchain/accounts/intents/types.d.ts +51 -6
  239. package/dist/types/onchain/accounts/intents/utils/common.d.ts +15 -1
  240. package/dist/types/onchain/accounts/intents/utils/credit-account-slice.d.ts +14 -1
  241. package/dist/types/onchain/accounts/intents/utils/index.d.ts +3 -3
  242. package/dist/types/onchain/accounts/intents/utils/price-impact.d.ts +4 -1
  243. package/dist/types/onchain/accounts/intents/utils/router-path.d.ts +2 -5
  244. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +80 -0
  245. package/dist/types/onchain/accounts/types.d.ts +4 -2
  246. package/dist/types/onchain/constants/address-provider.d.ts +1 -2
  247. package/dist/types/onchain/constants/index.d.ts +2 -2
  248. package/dist/types/onchain/index.d.ts +40 -31
  249. package/dist/types/onchain/market/adapters/contracts/AbstractAdapter.d.ts +6 -0
  250. package/dist/types/onchain/market/adapters/contracts/MidasGatewayAdapterContract.d.ts +20 -4
  251. package/dist/types/onchain/market/adapters/types.d.ts +8 -0
  252. package/dist/types/onchain/market/credit/CreditSuite.d.ts +13 -3
  253. package/dist/types/onchain/market/index.d.ts +29 -24
  254. package/dist/types/onchain/market/oracle/PriceOracleBaseContract.d.ts +2 -1
  255. package/dist/types/onchain/market/oracle/types.d.ts +2 -1
  256. package/dist/types/onchain/market/pool/types.d.ts +1 -1
  257. package/dist/types/onchain/market/pricefeeds/AbstractPriceFeed.d.ts +1 -2
  258. package/dist/types/onchain/market/pricefeeds/PriceFeedRegistry.d.ts +60 -0
  259. package/dist/types/onchain/market/pricefeeds/feeds/BalancerStablePriceFeed.d.ts +12 -0
  260. package/dist/types/onchain/market/pricefeeds/{BalancerWeightedPriceFeed.d.ts → feeds/BalancerWeightedPriceFeed.d.ts} +7 -7
  261. package/dist/types/onchain/market/pricefeeds/feeds/BoundedPriceFeed.d.ts +15 -0
  262. package/dist/types/onchain/market/pricefeeds/{CompositePriceFeed.d.ts → feeds/CompositePriceFeed.d.ts} +6 -6
  263. package/dist/types/onchain/market/pricefeeds/{ConstantPriceFeed.d.ts → feeds/ConstantPriceFeed.d.ts} +6 -6
  264. package/dist/types/onchain/market/pricefeeds/feeds/CurveCryptoPriceFeed.d.ts +12 -0
  265. package/dist/types/onchain/market/pricefeeds/feeds/CurveStablePriceFeed.d.ts +12 -0
  266. package/dist/types/onchain/market/pricefeeds/feeds/CurveUSDPriceFeed.d.ts +12 -0
  267. package/dist/types/onchain/market/pricefeeds/feeds/Erc4626PriceFeed.d.ts +12 -0
  268. package/dist/types/onchain/market/pricefeeds/feeds/ExternalPriceFeed.d.ts +11 -0
  269. package/dist/types/onchain/market/pricefeeds/feeds/MellowLRTPriceFeed.d.ts +12 -0
  270. package/dist/types/onchain/market/pricefeeds/{PendleTWAPPTPriceFeed.d.ts → feeds/PendleTWAPPTPriceFeed.d.ts} +3 -3
  271. package/dist/types/onchain/market/pricefeeds/{PythPriceFeed.d.ts → feeds/PythPriceFeed.d.ts} +3 -3
  272. package/dist/types/onchain/market/pricefeeds/{RedstonePriceFeed.d.ts → feeds/RedstonePriceFeed.d.ts} +9 -9
  273. package/dist/types/onchain/market/pricefeeds/feeds/WstETHPriceFeed.d.ts +12 -0
  274. package/dist/types/onchain/market/pricefeeds/feeds/YearnPriceFeed.d.ts +12 -0
  275. package/dist/types/onchain/market/pricefeeds/feeds/ZeroPriceFeed.d.ts +11 -0
  276. package/dist/types/onchain/market/pricefeeds/feeds/index.d.ts +18 -0
  277. package/dist/types/onchain/market/pricefeeds/index.d.ts +28 -22
  278. package/dist/types/onchain/market/pricefeeds/types.d.ts +1 -31
  279. package/dist/types/onchain/market/pricefeeds/updates/RedstoneUpdater.d.ts +1 -1
  280. package/dist/types/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.d.ts +106 -0
  281. package/dist/types/onchain/market/pricefeeds/updates/getRawPriceUpdates.d.ts +6 -0
  282. package/dist/types/onchain/market/pricefeeds/updates/index.d.ts +7 -3
  283. package/dist/types/onchain/market/pricefeeds/updates/isUpdatablePriceFeed.d.ts +6 -0
  284. package/dist/types/onchain/market/pricefeeds/updates/types.d.ts +56 -2
  285. package/dist/types/onchain/market/pricefeeds/updates/updatableDependencies.d.ts +10 -0
  286. package/dist/types/onchain/market/rwa/RWARegistry.d.ts +2 -1
  287. package/dist/types/onchain/market/rwa/index.d.ts +3 -3
  288. package/dist/types/onchain/market/rwa/midas/MidasDegenNFT.d.ts +19 -4
  289. package/dist/types/onchain/market/rwa/securitize/SecuritizeDegenNFT.d.ts +24 -4
  290. package/dist/types/onchain/market/rwa/securitize/SecuritizeRWAFactory.d.ts +2 -14
  291. package/dist/types/onchain/market/rwa/types.d.ts +39 -37
  292. package/dist/types/onchain/opportunities/MultichainOpportunitiesService.d.ts +5 -1
  293. package/dist/types/onchain/opportunities/OpportunitiesService.d.ts +10 -3
  294. package/dist/types/onchain/opportunities/types.d.ts +6 -1
  295. package/dist/types/onchain/preview/index.d.ts +2 -1
  296. package/dist/types/onchain/preview/preview/index.d.ts +2 -1
  297. package/dist/types/onchain/preview/preview/midasGreenlistsAccount.d.ts +13 -0
  298. package/dist/types/onchain/preview/preview/previewOpenStrategyPosition.d.ts +5 -3
  299. package/dist/types/onchain/preview/preview/replayMulticall.d.ts +8 -7
  300. package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +5 -4
  301. package/dist/types/onchain/validation/bundles/{checkDraw.d.ts → checkIncreaseDebt.d.ts} +7 -7
  302. package/dist/types/onchain/validation/bundles/{checkQuotasAsked.d.ts → checkIncreaseQuota.d.ts} +3 -3
  303. package/dist/types/onchain/validation/bundles/checkMidasAccountGreenlist.d.ts +22 -0
  304. package/dist/types/onchain/validation/bundles/checkRWAOpenRequirements.d.ts +2 -2
  305. package/dist/types/onchain/validation/bundles/checkRWAOpening.d.ts +9 -7
  306. package/dist/types/onchain/validation/bundles/index.d.ts +5 -4
  307. package/dist/types/onchain/validation/checks/checkBorrowLimit.d.ts +1 -1
  308. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +2 -2
  309. package/dist/types/onchain/validation/checks/checkPoolLiquidity.d.ts +1 -1
  310. package/dist/types/onchain/validation/checks/checkReservePriceLimited.d.ts +31 -0
  311. package/dist/types/onchain/validation/checks/index.d.ts +2 -1
  312. package/dist/types/onchain/validation/index.d.ts +6 -4
  313. package/dist/types/onchain/validation/raise.d.ts +2 -2
  314. package/dist/types/sdk/execute/index.d.ts +2 -2
  315. package/dist/types/sdk/execute/types.d.ts +48 -6
  316. package/dist/types/sdk/index.d.ts +5 -4
  317. package/dist/types/sdk/opportunities/OpportunitiesNamespace.d.ts +5 -1
  318. package/dist/types/sdk/opportunities/types.d.ts +9 -3
  319. package/dist/types/sdk/prepare/PrepareApi.d.ts +16 -4
  320. package/dist/types/sdk/prepare/index.d.ts +4 -3
  321. package/dist/types/sdk/prepare/types.d.ts +200 -66
  322. package/package.json +1 -1
  323. package/dist/cjs/onchain/accounts/utils/midasUtils.js +0 -70
  324. package/dist/cjs/onchain/market/pricefeeds/PriceFeedsRegister.js +0 -301
  325. package/dist/cjs/plugins/degen-distributors/DegenDistributorsPlugin.js +0 -61
  326. package/dist/cjs/plugins/degen-distributors/index.js +0 -4
  327. package/dist/cjs/plugins/degen-distributors/package.json +0 -1
  328. package/dist/cjs/plugins/degen-distributors/types.js +0 -1
  329. package/dist/cjs/plugins/delayed-withdrawal/DelayedWithdrawalPlugin.js +0 -114
  330. package/dist/cjs/plugins/delayed-withdrawal/index.js +0 -4
  331. package/dist/cjs/plugins/delayed-withdrawal/package.json +0 -1
  332. package/dist/cjs/plugins/delayed-withdrawal/types.js +0 -1
  333. package/dist/esm/onchain/accounts/utils/midasUtils.js +0 -69
  334. package/dist/esm/onchain/market/pricefeeds/PriceFeedsRegister.js +0 -300
  335. package/dist/esm/onchain/validation/bundles/checkDraw.js +0 -27
  336. package/dist/esm/plugins/degen-distributors/DegenDistributorsPlugin.js +0 -60
  337. package/dist/esm/plugins/degen-distributors/index.js +0 -3
  338. package/dist/esm/plugins/degen-distributors/package.json +0 -1
  339. package/dist/esm/plugins/degen-distributors/types.js +0 -1
  340. package/dist/esm/plugins/delayed-withdrawal/DelayedWithdrawalPlugin.js +0 -113
  341. package/dist/esm/plugins/delayed-withdrawal/index.js +0 -3
  342. package/dist/esm/plugins/delayed-withdrawal/package.json +0 -1
  343. package/dist/esm/plugins/delayed-withdrawal/types.js +0 -1
  344. package/dist/types/onchain/accounts/utils/midasUtils.d.ts +0 -38
  345. package/dist/types/onchain/market/pricefeeds/BalancerStablePriceFeed.d.ts +0 -12
  346. package/dist/types/onchain/market/pricefeeds/BoundedPriceFeed.d.ts +0 -15
  347. package/dist/types/onchain/market/pricefeeds/CurveCryptoPriceFeed.d.ts +0 -12
  348. package/dist/types/onchain/market/pricefeeds/CurveStablePriceFeed.d.ts +0 -12
  349. package/dist/types/onchain/market/pricefeeds/CurveUSDPriceFeed.d.ts +0 -12
  350. package/dist/types/onchain/market/pricefeeds/Erc4626PriceFeed.d.ts +0 -12
  351. package/dist/types/onchain/market/pricefeeds/ExternalPriceFeed.d.ts +0 -11
  352. package/dist/types/onchain/market/pricefeeds/MellowLRTPriceFeed.d.ts +0 -12
  353. package/dist/types/onchain/market/pricefeeds/PriceFeedsRegister.d.ts +0 -180
  354. package/dist/types/onchain/market/pricefeeds/WstETHPriceFeed.d.ts +0 -12
  355. package/dist/types/onchain/market/pricefeeds/YearnPriceFeed.d.ts +0 -12
  356. package/dist/types/onchain/market/pricefeeds/ZeroPriceFeed.d.ts +0 -11
  357. package/dist/types/onchain/market/pricefeeds/getRawPriceUpdates.d.ts +0 -5
  358. package/dist/types/onchain/market/pricefeeds/isUpdatablePriceFeed.d.ts +0 -5
  359. package/dist/types/plugins/degen-distributors/DegenDistributorsPlugin.d.ts +0 -25
  360. package/dist/types/plugins/degen-distributors/index.d.ts +0 -3
  361. package/dist/types/plugins/degen-distributors/types.d.ts +0 -8
  362. package/dist/types/plugins/delayed-withdrawal/DelayedWithdrawalPlugin.d.ts +0 -25
  363. package/dist/types/plugins/delayed-withdrawal/index.d.ts +0 -3
  364. package/dist/types/plugins/delayed-withdrawal/types.d.ts +0 -10
@@ -2,9 +2,8 @@ import { AddressSet } from "../onchain/utils/AddressSet.js";
2
2
  import { OnchainSDK } from "../onchain/OnchainSDK.js";
3
3
  import "../onchain/index.js";
4
4
  import { iDSTokenAbi } from "../abi/rwa/iDSToken.js";
5
- import { registerSecuritizeInvestor, writeAndWait } from "./kycUtils.js";
6
- import { erc20Abi, isAddressEqual, parseAbi, zeroAddress } from "viem";
7
- import { privateKeyToAccount } from "viem/accounts";
5
+ import { getSecuritizeAdmin, registerSecuritizeInvestor } from "./kycUtils.js";
6
+ import { erc20Abi, getAddress, isAddressEqual, parseAbi, parseEther, zeroAddress } from "viem";
8
7
  //#region src/dev/securitizeUtils.ts
9
8
  /**
10
9
  * `COMPLIANCE_CONFIGURATION_SERVICE` id in the DS protocol service registry
@@ -64,7 +63,7 @@ async function issueDSTokens(props) {
64
63
  const { timestamp } = await anvil.getBlock();
65
64
  const issuanceTime = timestamp - lockPeriod - 1n;
66
65
  try {
67
- const hash = await writeAndWait(anvil, {
66
+ const receipt = await anvil.writeContractSync({
68
67
  account,
69
68
  chain: anvil.chain,
70
69
  address: token,
@@ -77,14 +76,15 @@ async function issueDSTokens(props) {
77
76
  0n,
78
77
  "",
79
78
  0n
80
- ]
79
+ ],
80
+ throwOnReceiptRevert: true
81
81
  });
82
82
  logger?.debug({
83
83
  issuanceTime,
84
84
  investor,
85
85
  amount
86
86
  }, "issueTokensCustom successful");
87
- return hash;
87
+ return receipt.transactionHash;
88
88
  } catch (e) {
89
89
  logger?.debug(`issueTokensCustom failed: ${e}`);
90
90
  }
@@ -93,14 +93,15 @@ async function issueDSTokens(props) {
93
93
  investor,
94
94
  amount
95
95
  }, "Falling back to issueTokens");
96
- return writeAndWait(anvil, {
96
+ return (await anvil.writeContractSync({
97
97
  account,
98
98
  chain: anvil.chain,
99
99
  address: token,
100
100
  abi: iDSTokenAbi,
101
101
  functionName: "issueTokens",
102
- args: [investor, amount]
103
- });
102
+ args: [investor, amount],
103
+ throwOnReceiptRevert: true
104
+ })).transactionHash;
104
105
  }
105
106
  /**
106
107
  * Resolves unique compliance configuration services of `tokens`: several
@@ -108,7 +109,7 @@ async function issueDSTokens(props) {
108
109
  * Tokens without one (e.g. MockDSToken) are skipped
109
110
  */
110
111
  async function getComplianceConfigurationServices({ anvil, tokens, logger }) {
111
- const services = new AddressSet();
112
+ const services = /* @__PURE__ */ new Map();
112
113
  for (const token of new AddressSet(tokens)) try {
113
114
  const service = await anvil.readContract({
114
115
  address: token,
@@ -120,11 +121,16 @@ async function getComplianceConfigurationServices({ anvil, tokens, logger }) {
120
121
  logger?.debug(`${token} has no compliance configuration service`);
121
122
  continue;
122
123
  }
123
- services.add(service);
124
+ const checksummed = getAddress(service);
125
+ if (services.has(checksummed)) continue;
126
+ services.set(checksummed, await getSecuritizeAdmin(anvil, token, logger));
124
127
  } catch (e) {
125
128
  logger?.debug(`Failed to get compliance configuration service of ${token}: ${e}`);
126
129
  }
127
- return [...services];
130
+ return [...services].map(([service, admin]) => ({
131
+ service,
132
+ admin
133
+ }));
128
134
  }
129
135
  /**
130
136
  * Sets `disallowBackDating` to false on compliance configuration services of
@@ -132,18 +138,17 @@ async function getComplianceConfigurationServices({ anvil, tokens, logger }) {
132
138
  * honoured: DS protocol silently replaces it with `block.timestamp` otherwise,
133
139
  * and freshly minted tokens stay under lock-up.
134
140
  *
135
- * Must be signed by a DS admin with sufficient trust (same key as
136
- * `issueTokens` / registerInvestor); Ownable `owner()` alone is not enough.
141
+ * Impersonates the DS trust-service admin of each token. Ownable `owner()` of
142
+ * the compliance configuration service alone is not enough.
137
143
  *
138
144
  * The flag is only read while tokens are issued, so restoring it does not
139
145
  * re-lock tokens minted in the meantime.
140
146
  */
141
147
  async function enableDSTokenBackDating(props) {
142
- const { anvil, adminPrivateKey, logger } = props;
143
- const account = privateKeyToAccount(adminPrivateKey);
148
+ const { anvil, logger } = props;
144
149
  const services = await getComplianceConfigurationServices(props);
145
150
  let toRestore = [];
146
- for (const service of services) {
151
+ for (const { service, admin } of services) {
147
152
  let disallowBackDating;
148
153
  try {
149
154
  disallowBackDating = await anvil.readContract({
@@ -160,30 +165,53 @@ async function enableDSTokenBackDating(props) {
160
165
  continue;
161
166
  }
162
167
  logger?.info(`Allowing back-dating on ${service}`);
163
- await writeAndWait(anvil, {
164
- account,
165
- chain: anvil.chain,
166
- address: service,
167
- abi: iDSComplianceConfigurationServiceAbi,
168
- functionName: "setDisallowBackDating",
169
- args: [false]
168
+ await anvil.impersonateAccount({ address: admin });
169
+ try {
170
+ await anvil.setBalance({
171
+ address: admin,
172
+ value: parseEther("100")
173
+ });
174
+ await anvil.writeContractSync({
175
+ account: admin,
176
+ chain: anvil.chain,
177
+ address: service,
178
+ abi: iDSComplianceConfigurationServiceAbi,
179
+ functionName: "setDisallowBackDating",
180
+ args: [false],
181
+ throwOnReceiptRevert: true
182
+ });
183
+ } finally {
184
+ await anvil.stopImpersonatingAccount({ address: admin });
185
+ }
186
+ toRestore.push({
187
+ service,
188
+ admin
170
189
  });
171
- toRestore.push(service);
172
190
  }
173
191
  return async () => {
174
192
  const services = toRestore;
175
193
  toRestore = [];
176
- for (const service of services) {
194
+ for (const { service, admin } of services) {
177
195
  logger?.info(`Disallowing back-dating on ${service}`);
178
196
  try {
179
- await writeAndWait(anvil, {
180
- account,
181
- chain: anvil.chain,
182
- address: service,
183
- abi: iDSComplianceConfigurationServiceAbi,
184
- functionName: "setDisallowBackDating",
185
- args: [true]
186
- });
197
+ await anvil.impersonateAccount({ address: admin });
198
+ try {
199
+ await anvil.setBalance({
200
+ address: admin,
201
+ value: parseEther("100")
202
+ });
203
+ await anvil.writeContractSync({
204
+ account: admin,
205
+ chain: anvil.chain,
206
+ address: service,
207
+ abi: iDSComplianceConfigurationServiceAbi,
208
+ functionName: "setDisallowBackDating",
209
+ args: [true],
210
+ throwOnReceiptRevert: true
211
+ });
212
+ } finally {
213
+ await anvil.stopImpersonatingAccount({ address: admin });
214
+ }
187
215
  } catch (e) {
188
216
  logger?.warn(`Failed to restore disallowBackDating on ${service}: ${e}`);
189
217
  }
@@ -191,8 +219,7 @@ async function enableDSTokenBackDating(props) {
191
219
  };
192
220
  }
193
221
  async function claimDSToken(props) {
194
- const { anvil, investor, adminPrivateKey, token, marketConfigurators, rwaFactories, usdAmount: usdAmountProp = "100000" } = props;
195
- const account = privateKeyToAccount(adminPrivateKey);
222
+ const { anvil, investor, token, marketConfigurators, rwaFactories, usdAmount: usdAmountProp = "100000" } = props;
196
223
  const symbol = await anvil.readContract({
197
224
  address: token,
198
225
  abi: erc20Abi,
@@ -216,18 +243,31 @@ async function claimDSToken(props) {
216
243
  if (amount === 0n) throw new Error(`No market found for token ${token}`);
217
244
  logger?.debug(`${usdAmountProp} USD === ${amount} ${symbol}`);
218
245
  await registerSecuritizeInvestor({
219
- ...props,
220
- logger
221
- });
222
- logger?.debug(`Issuing ${amount} tokens to ${investor}...`);
223
- const mintHash = await issueDSTokens({
224
246
  anvil,
225
- account,
226
- token,
227
247
  investor,
228
- amount,
248
+ token,
229
249
  logger
230
250
  });
251
+ const admin = await getSecuritizeAdmin(anvil, token, logger);
252
+ logger?.debug(`Issuing ${amount} tokens to ${investor}...`);
253
+ await anvil.impersonateAccount({ address: admin });
254
+ let mintHash;
255
+ try {
256
+ await anvil.setBalance({
257
+ address: admin,
258
+ value: parseEther("100")
259
+ });
260
+ mintHash = await issueDSTokens({
261
+ anvil,
262
+ account: admin,
263
+ token,
264
+ investor,
265
+ amount,
266
+ logger
267
+ });
268
+ } finally {
269
+ await anvil.stopImpersonatingAccount({ address: admin });
270
+ }
231
271
  logger?.debug(`Done! tx: ${mintHash}`);
232
272
  const balance = await anvil.readContract({
233
273
  address: token,
@@ -204,18 +204,15 @@ async function fulfillMidasRedeemer(anvil, redeemer, logger) {
204
204
  address: MIDAS_VAULT_ADMIN,
205
205
  value: parseEther("100")
206
206
  });
207
- const hash = await anvil.writeContract({
207
+ await anvil.writeContractSync({
208
208
  chain: anvil.chain,
209
209
  address: midasRedemptionVault,
210
210
  account: MIDAS_VAULT_ADMIN,
211
211
  abi: iMidasRedemptionVaultExtAbi,
212
212
  functionName: "safeApproveRequest",
213
- args: [requestId, mTokenRate]
213
+ args: [requestId, mTokenRate],
214
+ throwOnReceiptRevert: true
214
215
  });
215
- if ((await anvil.waitForTransactionReceipt({
216
- hash,
217
- pollingInterval: 100
218
- })).status !== "success") throw new Error(`midas: safeApproveRequest tx ${hash} reverted`);
219
216
  await anvil.stopImpersonatingAccount({ address: MIDAS_VAULT_ADMIN });
220
217
  }
221
218
  /**
@@ -1,7 +1,7 @@
1
1
  import "./base.js";
2
2
  import { creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator } from "./liquidation-errors.js";
3
- import { creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet } from "./operation-errors.js";
3
+ import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet } from "./operation-errors.js";
4
4
  import { unpriceableTokenError } from "./oracle-errors.js";
5
5
  import { creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./prepare-errors.js";
6
6
  import { malformedTransaction } from "./preview-errors.js";
7
- export { creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
7
+ export { accountNotMidasGreenlisted, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, liquidatorNotEligible, malformedTransaction, marketExpired, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress };
@@ -66,6 +66,14 @@ function insufficientCollateral(args) {
66
66
  ...args
67
67
  };
68
68
  }
69
+ /** {@inheritDoc ReservePriceLimitedError} */
70
+ function reservePriceLimited(args) {
71
+ return {
72
+ code: "reservePriceLimited",
73
+ message: `The reserve price feed values this collateral below what the operation pays out: the account covers its debt at ${args.atMainPrices} on the main feed and only ${args.healthFactor} at the reserve one, below ${args.healthFactorThreshold}.`,
74
+ ...args
75
+ };
76
+ }
69
77
  /** {@inheritDoc ForbiddenTokenError} */
70
78
  function forbiddenToken(token) {
71
79
  return {
@@ -113,9 +121,17 @@ function insufficientAllowance(args) {
113
121
  function rwaOpenRequirementsNotMet(args) {
114
122
  return {
115
123
  code: "rwaOpenRequirementsNotMet",
116
- message: `The RWA factory still wants something from the borrower before ${args.token.symbol} can be opened on.`,
124
+ message: `${args.protocol} still wants something from the borrower before ${args.token.symbol} can be opened on.`,
125
+ ...args
126
+ };
127
+ }
128
+ /** {@inheritDoc AccountNotMidasGreenlistedError} */
129
+ function accountNotMidasGreenlisted(args) {
130
+ return {
131
+ code: "accountNotMidasGreenlisted",
132
+ message: `The credit account is not Midas-greenlisted for ${args.token.symbol}.`,
117
133
  ...args
118
134
  };
119
135
  }
120
136
  //#endregion
121
- export { creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet };
137
+ export { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet };
@@ -7,15 +7,15 @@ import { FILTER_ALL, isFilterSet } from "./filters.js";
7
7
  import { booleanParamSchema, encodeFlag, filterAllSchema, filterable } from "./filters.schema.js";
8
8
  import { curatorNameSchema, curatorSchema } from "./curators.schema.js";
9
9
  import { delayedReceivedAssetSchema, instantReceivedAssetSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionSchema, receivedAssetSchema } from "./liquidations.schema.js";
10
- import { KYC_PROTOCOLS, KYC_REGISTRATION_LINKS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, SECURITIZE_REGISTER_VAULT_TYPES } from "./rwa.js";
11
- import { kycProtocolSchema, kycRequirementSchema } from "./rwa.schema.js";
10
+ import { KYC_REGISTRATION_LINKS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, SECURITIZE_REGISTER_VAULT_TYPES } from "./rwa.js";
11
+ import { kycRequirementSchema, rwaProtocolSchema } from "./rwa.schema.js";
12
12
  import { apyBreakdownSchema, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pointRewardsSchema, pointsProgramSchema, poolOpportunityDetailSchema, poolOpportunityKeySchema, poolOpportunitySchema, priceFeedDataSchema, priceFeedSummarySchema, quotaAssetSchema, rateCurvePointSchema, rateCurveSchema, rewardsSchema, strategyOpportunityDetailSchema, strategyOpportunityKeySchema, strategyOpportunitySchema, tokenRewardsSchema } from "./opportunities.schema.js";
13
13
  import { borrowRateBreakdownSchema, pnlBreakdownSchema, pointsProgramPnLSchema, pointsRewardsPnLSchema, poolPositionKeySchema, poolPositionSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionKeySchema, positionKindSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionsTotalsSchema, rewardsPnLSchema, strategyPositionKeySchema, strategyPositionSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema } from "./positions.schema.js";
14
14
  import { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema } from "./analytics.schema.js";
15
15
  import "./curators.js";
16
16
  import "./delayed-intents.js";
17
17
  import { creditAccountFrozen, liquidatorNotEligible, notEmergencyLiquidator } from "./errors/liquidation-errors.js";
18
- import { creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
18
+ import { accountNotMidasGreenlisted, creditManagerPaused, debtOutOfRange, forbiddenToken, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, leverageOutOfRange, marketExpired, poolPaused, poolSunset, quotaCountExceeded, quotaLimitReached, reservePriceLimited, rwaOpenRequirementsNotMet } from "./errors/operation-errors.js";
19
19
  import { unpriceableTokenError } from "./errors/oracle-errors.js";
20
20
  import { creditAccountNotEmpty, creditAccountNotFound, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, unexpectedFailure, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress } from "./errors/prepare-errors.js";
21
21
  import { malformedTransaction } from "./errors/preview-errors.js";
@@ -32,4 +32,4 @@ import { chainFailedSchema, chainMetadataSchema, chainSucceededSchema, dataSourc
32
32
  import { safeValue, sdkErr, sdkOk } from "./result.js";
33
33
  import "./withdrawals.js";
34
34
  import { positionClaimableWithdrawalSchema, positionPendingWithdrawalSchema, positionWithdrawalsSchema, withdrawalOutputAmountSchema } from "./withdrawals.schema.js";
35
- export { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, FILTER_ALL, KYC_PROTOCOLS, KYC_REGISTRATION_LINKS, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PROTOCOL_CHART_METRICS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, SECURITIZE_REGISTER_VAULT_TYPES, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, amountSchema, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, curatorNameSchema, curatorSchema, dataSourceSchema, debtOutOfRange, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, forbiddenToken, instantReceivedAssetSchema, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, isFilterSet, kycProtocolSchema, kycRequirementSchema, leverageOutOfRange, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, liquidatorNotEligible, malformedTransaction, marketExpired, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPaused, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, poolSunset, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, protocolChartMetricSchema, quotaAssetSchema, quotaCountExceeded, quotaLimitReached, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, rwaOpenRequirementsNotMet, safeValue, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress, withdrawalOutputAmountSchema };
35
+ export { ANALYTICS_POSITIONS_DEFAULT_LIMIT, ANALYTICS_POSITIONS_MAX_LIMIT, CHART_METRIC_UNITS, CHART_RANGES, CHART_UNAVAILABLE_CODES, FILTER_ALL, KYC_REGISTRATION_LINKS, POOL_OPPORTUNITY_CHART_METRICS, POOL_POSITION_CHART_METRICS, PROTOCOL_CHART_METRICS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, SECURITIZE_REGISTER_VAULT_TYPES, STRATEGY_OPPORTUNITY_CHART_METRICS, STRATEGY_POSITION_CHART_METRICS, STRATEGY_POSITION_COLLATERAL_ERROR, accountNotMidasGreenlisted, amountSchema, analyticsChartQueryOptionsSchema, analyticsChartQueryParamsSchema, analyticsChartQuerySchema, analyticsPositionListOptionsSchema, analyticsPositionListQueryParamsSchema, analyticsPositionListQuerySchema, analyticsPositionPageSchema, analyticsPositionSchema, analyticsPositionSortFieldSchema, analyticsSortDirectionSchema, apyBreakdownSchema, asEstimated, assetTypeSchema, backendPreferred, booleanParamSchema, borrowRateBreakdownSchema, bpsSchema, chainFailedSchema, chainIdSchema, chainMetadataSchema, chainSucceededSchema, chartBundleSchemaFor, chartDenominationSchema, chartMetricSchema, chartQueryCodec, chartQueryParamsSchema, chartQuerySchema, chartRangeSchema, chartSeriesSchema, chartValueSchema, chartWindowSchema, compareTagOf, creditAccountFrozen, creditAccountNotEmpty, creditAccountNotFound, creditManagerPaused, curatorNameSchema, curatorSchema, dataSourceSchema, debtOutOfRange, delayedReceivedAssetSchema, encodeFlag, filterAllSchema, filterable, forbiddenToken, instantReceivedAssetSchema, insufficientAllowance, insufficientBalance, insufficientCollateral, insufficientPoolLiquidity, isFilterSet, kycRequirementSchema, leverageOutOfRange, leverageSchema, liquidatableAccountFilterSchema, liquidatableAccountSchema, liquidationApprovalSchema, liquidationDetailsSchema, liquidationPositionId, liquidationPositionSchema, liquidatorNotEligible, malformedTransaction, marketExpired, matchesLiquidatableAccountFilter, matchesOpportunityFilter, matchesPositionFilter, multipleDelayedWithdrawals, noDelayedRoute, noRecordedIntent, noStrategyTargetCollateral, notEmergencyLiquidator, noticeKindSchema, noticeSchema, offchainOnly, onchainOnly, opportunityBaseSchema, opportunityDetailSchema, opportunityFilterQueryParamsSchema, opportunityFilterQuerySchema, opportunityFilterSchema, opportunityId, opportunityKeySchema, opportunityKindSchema, opportunitySchema, opportunityTotalsSchema, pnlBreakdownSchema, pointRewardsSchema, pointsProgramPnLSchema, pointsProgramSchema, pointsRewardsPnLSchema, poolOpportunityChartMetricSchema, poolOpportunityDetailSchema, poolOpportunityId, poolOpportunityKeySchema, poolOpportunitySchema, poolPaused, poolPositionChartMetricSchema, poolPositionId, poolPositionKeySchema, poolPositionSchema, poolSunset, positionClaimableWithdrawalSchema, positionCollateralSchema, positionFilterQueryParamsSchema, positionFilterQuerySchema, positionFilterSchema, positionId, positionKeySchema, positionKindSchema, positionPendingWithdrawalSchema, positionSchema, positionTransactionKindSchema, positionTransactionSchema, positionWithdrawalsSchema, positionsTotalsSchema, priceFeedDataSchema, priceFeedSummarySchema, protocolChartMetricSchema, quotaAssetSchema, quotaCountExceeded, quotaLimitReached, rateCurvePointSchema, rateCurveSchema, receivedAssetSchema, reservePriceLimited, responseMetadataSchema, responseSchema, rewardsPnLSchema, rewardsSchema, rwaOpenRequirementsNotMet, rwaProtocolSchema, safeValue, sdkErr, sdkOk, strategyOpportunityChartMetricSchema, strategyOpportunityDetailSchema, strategyOpportunityId, strategyOpportunityKeySchema, strategyOpportunitySchema, strategyPositionChartMetricSchema, strategyPositionId, strategyPositionKeySchema, strategyPositionSchema, timestampSchema, tokenAmountSchema, tokenQuotaRateSchema, tokenRewardsPnLSchema, tokenRewardsSchema, tokenSchema, tolerance, txCallSchema, underlyingTokenSchema, unexpectedFailure, unpriceableTokenError, unsupportedCollateralToken, unsupportedTokenPair, withdrawalInProgress, withdrawalOutputAmountSchema };
@@ -34,15 +34,15 @@ const SECURITIZE_REGISTER_VAULT_TYPES = { RegisterVault: [
34
34
  }
35
35
  ] };
36
36
  /**
37
- * KYC providers a strategy may be gated by
37
+ * RWA protocols that require dedicated flows
38
38
  **/
39
- const KYC_PROTOCOLS = ["securitize", "midas"];
39
+ const RWA_PROTOCOLS = ["securitize", "midas"];
40
40
  /**
41
- * Hardcoded registration URLs for each {@link KycProtocol}.
41
+ * Hardcoded registration URLs for each {@link RWAProtocol}.
42
42
  **/
43
43
  const KYC_REGISTRATION_LINKS = {
44
44
  securitize: "https://securitize.io/",
45
45
  midas: "https://form.typeform.com/to/DqZaw6kr"
46
46
  };
47
47
  //#endregion
48
- export { KYC_PROTOCOLS, KYC_REGISTRATION_LINKS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, SECURITIZE_REGISTER_VAULT_TYPES };
48
+ export { KYC_REGISTRATION_LINKS, RWA_FACTORY_SECURITIZE, RWA_FACTORY_TYPES, RWA_PROTOCOLS, SECURITIZE_REGISTER_VAULT_TYPES };
@@ -1,18 +1,18 @@
1
1
  import { tokenSchema } from "./primitives.schema.js";
2
- import { KYC_PROTOCOLS } from "./rwa.js";
2
+ import { RWA_PROTOCOLS } from "./rwa.js";
3
3
  import { z } from "zod/v4";
4
4
  //#region src/model/rwa.schema.ts
5
5
  /**
6
- * {@link ./rwa.js#KycProtocol}
6
+ * {@link ./rwa.js#RWAProtocol}
7
7
  **/
8
- const kycProtocolSchema = z.enum(KYC_PROTOCOLS);
8
+ const rwaProtocolSchema = z.enum(RWA_PROTOCOLS);
9
9
  /**
10
10
  * {@link ./rwa.js#KycRequirement}
11
11
  **/
12
12
  const kycRequirementSchema = z.object({
13
- protocol: kycProtocolSchema,
13
+ protocol: rwaProtocolSchema,
14
14
  token: tokenSchema.optional(),
15
15
  registrationLink: z.string()
16
16
  });
17
17
  //#endregion
18
- export { kycProtocolSchema, kycRequirementSchema };
18
+ export { kycRequirementSchema, rwaProtocolSchema };
@@ -35,7 +35,7 @@ var OffchainOpportunities = class extends AbstractOffchainNamespace {
35
35
  /**
36
36
  * {@inheritDoc IOffchainOpportunities.getStrategy}
37
37
  **/
38
- async getStrategy(key, _wallet) {
38
+ async getStrategy(key) {
39
39
  return this.get({
40
40
  path: this.#strategyPath(key),
41
41
  schema: strategyOpportunityDetailSchema
@@ -13,7 +13,7 @@ import { ChainContractsRegister } from "./base/ChainContractsRegister.js";
13
13
  import "./base/index.js";
14
14
  import { executeDelegatedMulticalls } from "./utils/viem/executeDelegatedMulticalls.js";
15
15
  import "./utils/viem/index.js";
16
- import { PriceFeedRegister } from "./market/pricefeeds/PriceFeedsRegister.js";
16
+ import { UpdatablePriceFeedRegistry } from "./market/pricefeeds/updates/UpdatablePriceFeedRegistry.js";
17
17
  import "./market/pricefeeds/index.js";
18
18
  import { MarketRegister } from "./market/MarketRegister.js";
19
19
  import { RWARegistry } from "./market/rwa/RWARegistry.js";
@@ -167,7 +167,7 @@ var OnchainSDK = class extends ChainContractsRegister {
167
167
  this.#currentBlock = block.number;
168
168
  this.#timestamp = block.timestamp;
169
169
  if (blockNumber && !redstone?.historicTimestamp && time - Number(block.timestamp) * 1e3 > 6e4) this.logger?.warn("attaching to fixed block number, but redstone historicTimestamp is not set. price updates might fail");
170
- this.#priceFeeds = new PriceFeedRegister(this, { redstone });
170
+ this.#priceFeeds = new UpdatablePriceFeedRegistry(this, { redstone });
171
171
  this.logger?.debug(`attach block number ${this.currentBlock} timestamp ${this.timestamp}`);
172
172
  this.#addressProvider = await createAddressProvider(this, addressProvider);
173
173
  this.logger?.debug(`address provider version: ${this.#addressProvider.version}`);
@@ -262,7 +262,7 @@ var OnchainSDK = class extends ChainContractsRegister {
262
262
  this.logger?.info({ networkType: this.networkType }, "hydrating sdk state");
263
263
  this.#currentBlock = state.currentBlock;
264
264
  this.#timestamp = state.timestamp;
265
- this.#priceFeeds = new PriceFeedRegister(this, { redstone });
265
+ this.#priceFeeds = new UpdatablePriceFeedRegistry(this, { redstone });
266
266
  this.#addressProvider = hydrateAddressProvider(this, state.addressProvider);
267
267
  this.logger?.debug(`address provider version: ${this.#addressProvider.version}`);
268
268
  this.#marketRegister = new MarketRegister(this, ignoreMarkets);
@@ -15,7 +15,6 @@ import "../market/index.js";
15
15
  import { CreditAccountCompressor } from "./credit-account-compressor/CreditAccountCompressor.js";
16
16
  import "./credit-account-compressor/index.js";
17
17
  import { extractPriceUpdates, extractQuotaTokens, mergePriceUpdates } from "./multicall-utils.js";
18
- import { prependMidasReceiveGreenlist } from "./utils/midasUtils.js";
19
18
  import { encodeFunctionData } from "viem";
20
19
  //#region src/onchain/accounts/CreditAccountsServiceV310.ts
21
20
  /**
@@ -188,9 +187,7 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
188
187
  * {@inheritDoc ICreditAccountsService.getOpenAccountRequirements}
189
188
  */
190
189
  async getOpenAccountRequirements(borrower, creditManager, props) {
191
- const { rwaFactory } = this.sdk.marketRegister.findCreditManager(creditManager);
192
- if (!rwaFactory) return;
193
- return rwaFactory.getOpenAccountRequirements(borrower, props);
190
+ return (await this.sdk.marketRegister.findCreditManager(creditManager).degenNFT())?.getOpenAccountRequirements(borrower, props);
194
191
  }
195
192
  /**
196
193
  * {@inheritDoc ICreditAccountsService.openCA}
@@ -214,7 +211,7 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
214
211
  }),
215
212
  ...callsAfter ?? []
216
213
  ];
217
- calls = await this.#prependMidasReceiveGreenlist(cm.address, calls);
214
+ calls = [...await cmSuite.openingCalls(), ...calls];
218
215
  calls = await this.prependPriceUpdates(cm.address, calls);
219
216
  const tx = reopenCreditAccount ? cmSuite.multicallTx(reopenCreditAccount, calls, rwaOptions) : cmSuite.openCreditAccountTx(to, calls, referralCode, rwaOptions);
220
217
  tx.value = ethAmount.toString(10);
@@ -441,18 +438,6 @@ var CreditAccountsServiceV310 = class extends SDKConstruct {
441
438
  return this.sdk.addressProvider.mustGetLatest(AP_REWARDS_COMPRESSOR, VERSION_RANGE_310)[0];
442
439
  }
443
440
  /**
444
- * {@inheritDoc ICreditAccountsService.prependMidasReceiveGreenlist}
445
- */
446
- async #prependMidasReceiveGreenlist(creditManager, calls) {
447
- const cm = this.sdk.marketRegister.findCreditManager(creditManager);
448
- return prependMidasReceiveGreenlist({
449
- cm,
450
- client: this.client,
451
- calls,
452
- logger: this.logger
453
- });
454
- }
455
- /**
456
441
  * Withdrawal compressor of the current chain.
457
442
  * @throws If no withdrawal compressor is supported on the current chain.
458
443
  **/
@@ -0,0 +1,138 @@
1
+ import { insufficientBalance } from "../../../model/errors/operation-errors.js";
2
+ import { unsupportedCollateralToken } from "../../../model/errors/prepare-errors.js";
3
+ import "../../../model/index.js";
4
+ import { toToken } from "../../validation/helpers/token.js";
5
+ import { IntentPreviewError } from "../../validation/raise.js";
6
+ import "../../validation/index.js";
7
+ import { eq, toTargetDecimals } from "./utils/common.js";
8
+ import { assertCanBorrow, assertCollateralised, assertGrowthAllowed, assertMarketOperable, assertQuotaAvailable } from "./guards.js";
9
+ import { assertDebtLimits } from "./math.js";
10
+ import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
11
+ import { collectPriceImpact } from "./utils/price-impact.js";
12
+ import { getQuotasForUpdate } from "./utils/quotas-for-update.js";
13
+ import { createRouterPaths } from "./utils/router-path.js";
14
+ import "./utils/index.js";
15
+ //#region src/onchain/accounts/intents/borrow.ts
16
+ /**
17
+ * Builds the state a borrow would leave behind.
18
+ *
19
+ * The debt is named rather than derived: a borrow asks for an amount, where an
20
+ * opening asks for a leverage and lets the collateral decide. Everything the
21
+ * loan pays out leaves the account, so the collateral alone backs it — which
22
+ * is what makes the health factor here a straight function of the two amounts.
23
+ *
24
+ * Produces no operation list, as opening never does: the caller hands the
25
+ * numbers and the calls to `sdk.accounts.openCA`, with `withdrawToken` set to
26
+ * the payout.
27
+ */
28
+ async function buildBorrowState(props) {
29
+ const { sdk, creditManager, collateralAmount, borrowAmount, slippage = 0, quotaReserve, creditAccount: existing } = props;
30
+ const suite = sdk.marketRegister.findCreditManager(creditManager);
31
+ const market = sdk.marketRegister.findByCreditManager(creditManager);
32
+ assertMarketOperable(suite);
33
+ const underlying = market.pool.underlying.toLowerCase();
34
+ const collateralToken = props.collateralToken.toLowerCase();
35
+ const borrowToken = props.borrowToken.toLowerCase();
36
+ const convert = (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value;
37
+ if (eq(collateralToken, borrowToken)) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, collateralToken)), "borrow: the payout token cannot also be the collateral");
38
+ const rwaAsset = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset?.toLowerCase();
39
+ const unwrapsPayout = !!rwaAsset && eq(borrowToken, rwaAsset);
40
+ if (rwaAsset && eq(borrowToken, underlying)) throw new IntentPreviewError(unsupportedCollateralToken(toToken(sdk, borrowToken)), `borrow: ${underlying} cannot leave the account, ask for the payout in ${rwaAsset}`);
41
+ if (collateralAmount <= 0n) throw new IntentPreviewError(insufficientBalance(), "borrow: no collateral supplied");
42
+ if (borrowAmount <= 0n) throw new IntentPreviewError(insufficientBalance(), "borrow: nothing to borrow");
43
+ const margin = convert(collateralToken, underlying, collateralAmount);
44
+ if (margin <= 0n) throw new IntentPreviewError(insufficientBalance(), "borrow: collateral is worth nothing in underlying");
45
+ const debt = eq(borrowToken, underlying) ? borrowAmount : unwrapsPayout ? toTargetDecimals(borrowAmount, borrowToken, underlying, sdk) : convert(borrowToken, underlying, borrowAmount);
46
+ assertDebtLimits(sdk, debt, suite.creditFacade, underlying);
47
+ assertCanBorrow(sdk, suite, debt);
48
+ const account = existing ?? unopenedAccountSlice({
49
+ creditManager,
50
+ creditFacade: suite.creditFacade.address,
51
+ underlying
52
+ });
53
+ const leg = eq(borrowToken, underlying) || unwrapsPayout ? void 0 : await createRouterPaths({
54
+ sdk,
55
+ creditAccount: account,
56
+ slippage
57
+ }).swap({
58
+ tokenIn: underlying,
59
+ tokenOut: borrowToken,
60
+ amount: debt,
61
+ keep: eq(collateralToken, underlying) ? collateralAmount : 0n
62
+ });
63
+ const unwrap = unwrapsPayout ? await sdk.accounts.assembleRWAUnwrapCalls(debt, creditManager) : void 0;
64
+ if (unwrapsPayout && !unwrap) throw new Error(`borrow: no unwrap calls found for ${borrowToken}`);
65
+ const assets = [{
66
+ token: collateralToken,
67
+ balance: collateralAmount
68
+ }];
69
+ const quotaIncrease = borrowCollateralQuota({
70
+ sdk,
71
+ creditManager,
72
+ assets,
73
+ quotaReserve
74
+ });
75
+ assertGrowthAllowed({
76
+ sdk,
77
+ suite,
78
+ market,
79
+ before: [],
80
+ after: assets
81
+ });
82
+ assertQuotaAvailable(sdk, market, quotaIncrease);
83
+ const snapshot = {
84
+ creditManager,
85
+ assets,
86
+ quotas: quotaIncrease,
87
+ totalDebt: debt,
88
+ totalValue: margin
89
+ };
90
+ const projection = sdk.positions.projection(snapshot, { availableLiquidityChange: -debt });
91
+ assertCollateralised(projection.safeHealthFactor, true);
92
+ const priced = (token, balance) => market.priceOracle.toTokenAmount(token, balance);
93
+ const payout = unwrapsPayout ? toTargetDecimals(debt, underlying, borrowToken, sdk) : leg ? leg.amount : debt;
94
+ return {
95
+ ...projection,
96
+ currentPrice: sdk.positions.currentPrice(snapshot),
97
+ executionCost: void 0,
98
+ priceImpact: await collectPriceImpact(leg?.probe ? [leg.probe] : [], {
99
+ totalValue: margin,
100
+ netValue: margin - debt,
101
+ toUnderlying: (from, amount) => convert(from, underlying, amount),
102
+ toUnderlyingAmount: market.toUnderlyingAmount
103
+ }),
104
+ collateral: priced(collateralToken, collateralAmount),
105
+ borrowed: priced(borrowToken, payout),
106
+ minBorrowed: priced(borrowToken, leg ? leg.minAmount : payout),
107
+ slippage,
108
+ quotaIncrease,
109
+ calls: leg ? [...leg.calls] : unwrap ?? [],
110
+ creditAccount: existing?.creditAccount
111
+ };
112
+ }
113
+ /**
114
+ * Quota a borrow buys for its collateral on an account that holds none yet.
115
+ *
116
+ * Shared with `maxBorrow`, because a quota short of the collateral's weighted
117
+ * value is what caps the loan: the two have to read the same number or the
118
+ * ceiling one offers is one the other refuses.
119
+ *
120
+ * @param props - {@link BorrowCollateralQuotaProps}
121
+ **/
122
+ function borrowCollateralQuota({ sdk, creditManager, assets, quotaReserve }) {
123
+ const suite = sdk.marketRegister.findCreditManager(creditManager);
124
+ const market = sdk.marketRegister.findByCreditManager(creditManager);
125
+ return getQuotasForUpdate({
126
+ assetsBefore: [],
127
+ assetsAfter: assets,
128
+ initialQuotas: [],
129
+ quotaReserve,
130
+ underlyingToken: market.pool.underlying,
131
+ liquidationThresholds: suite.creditManager.liquidationThresholds,
132
+ quotas: market.pool.pqk.quotas,
133
+ maxDebt: suite.creditFacade.maxDebt,
134
+ convert: (from, to, amount) => market.priceOracle.safeConvert(from, to, amount).value
135
+ }).quotaIncrease;
136
+ }
137
+ //#endregion
138
+ export { borrowCollateralQuota, buildBorrowState };
@@ -0,0 +1,40 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import { PERCENTAGE_FACTOR } from "../../constants/math.js";
3
+ import "../../utils/index.js";
4
+ import { eq } from "./utils/common.js";
5
+ //#region src/onchain/accounts/intents/collateral-valuation.ts
6
+ /** {@inheritDoc CollateralValuation} */
7
+ function collateralValuation(creditAccount, sdk) {
8
+ const { market, creditManager } = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
9
+ const { priceOracle } = market;
10
+ const { pqk } = market.pool;
11
+ const underlying = market.pool.underlying;
12
+ const masked = creditAccount.enabledTokensMask !== 0n;
13
+ const mainUsd = (token, amount) => {
14
+ try {
15
+ return priceOracle.convertToUSD(token, amount);
16
+ } catch {
17
+ return;
18
+ }
19
+ };
20
+ const lt = (token) => BigInt(creditManager.liquidationThresholds.get(token) ?? 0);
21
+ const checkedUsd = (holding) => eq(holding.token, underlying) ? mainUsd(holding.token, holding.balance) ?? 0n : priceOracle.safeConvertMinUSD(holding.token, holding.balance).value;
22
+ /** A quota is underlying-denominated, and a closed market backs nothing. */
23
+ const quotaValue = (holding) => pqk.hasActiveQuota(holding.token) ? (mainUsd(underlying, holding.quota) ?? 0n) * PERCENTAGE_FACTOR : 0n;
24
+ const weigh = (holding) => {
25
+ const weighted = checkedUsd(holding) * lt(holding.token);
26
+ if (holding.quota === 0n) return weighted;
27
+ return BigIntMath.min(quotaValue(holding), weighted);
28
+ };
29
+ return {
30
+ underlying,
31
+ counts: (holding) => holding.balance > 10n && (!masked || (holding.mask & creditAccount.enabledTokensMask) !== 0n),
32
+ weigh,
33
+ quotaValue,
34
+ mainUsd,
35
+ checkedUsd,
36
+ lt
37
+ };
38
+ }
39
+ //#endregion
40
+ export { collateralValuation };