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

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 (376) 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/math.js +12 -3
  23. package/dist/cjs/onchain/accounts/intents/maxBorrow.js +89 -0
  24. package/dist/cjs/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  25. package/dist/cjs/onchain/accounts/intents/open-strategy.js +8 -46
  26. package/dist/cjs/onchain/accounts/intents/operations.js +0 -1
  27. package/dist/cjs/onchain/accounts/intents/plan.js +1 -8
  28. package/dist/cjs/onchain/accounts/intents/realize.js +61 -4
  29. package/dist/cjs/onchain/accounts/intents/tail.js +1 -1
  30. package/dist/cjs/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  31. package/dist/cjs/onchain/accounts/intents/utils/common.js +19 -0
  32. package/dist/cjs/onchain/accounts/intents/utils/credit-account-slice.js +21 -0
  33. package/dist/cjs/onchain/accounts/intents/utils/index.js +2 -0
  34. package/dist/cjs/onchain/accounts/intents/utils/price-impact.js +12 -9
  35. package/dist/cjs/onchain/accounts/intents/utils/router-path.js +4 -5
  36. package/dist/cjs/onchain/accounts/intents/withdraw-limits.js +97 -0
  37. package/dist/cjs/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  38. package/dist/cjs/onchain/constants/address-provider.js +0 -2
  39. package/dist/cjs/onchain/constants/index.js +0 -1
  40. package/dist/cjs/onchain/core/createAddressProvider.js +2 -5
  41. package/dist/cjs/onchain/index.js +60 -43
  42. package/dist/cjs/onchain/market/adapters/abi/conctructorAbi.js +2 -2
  43. package/dist/cjs/onchain/market/adapters/contracts/AbstractAdapter.js +6 -0
  44. package/dist/cjs/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +49 -5
  45. package/dist/cjs/onchain/market/credit/CreditSuite.js +26 -9
  46. package/dist/cjs/onchain/market/index.js +50 -38
  47. package/dist/cjs/onchain/market/oracle/PriceOracleBaseContract.js +3 -3
  48. package/dist/cjs/onchain/market/pricefeeds/AbstractPriceFeed.js +0 -5
  49. package/dist/cjs/onchain/market/pricefeeds/PriceFeedRegistry.js +127 -0
  50. package/dist/cjs/onchain/market/pricefeeds/{BalancerStablePriceFeed.js → feeds/BalancerStablePriceFeed.js} +4 -4
  51. package/dist/cjs/onchain/market/pricefeeds/{BalancerWeightedPriceFeed.js → feeds/BalancerWeightedPriceFeed.js} +4 -4
  52. package/dist/cjs/onchain/market/pricefeeds/{BoundedPriceFeed.js → feeds/BoundedPriceFeed.js} +4 -4
  53. package/dist/cjs/onchain/market/pricefeeds/{CompositePriceFeed.js → feeds/CompositePriceFeed.js} +4 -4
  54. package/dist/cjs/onchain/market/pricefeeds/{ConstantPriceFeed.js → feeds/ConstantPriceFeed.js} +3 -3
  55. package/dist/cjs/onchain/market/pricefeeds/{CurveCryptoPriceFeed.js → feeds/CurveCryptoPriceFeed.js} +4 -4
  56. package/dist/cjs/onchain/market/pricefeeds/{CurveStablePriceFeed.js → feeds/CurveStablePriceFeed.js} +4 -4
  57. package/dist/cjs/onchain/market/pricefeeds/{CurveUSDPriceFeed.js → feeds/CurveUSDPriceFeed.js} +4 -4
  58. package/dist/cjs/onchain/market/pricefeeds/{Erc4626PriceFeed.js → feeds/Erc4626PriceFeed.js} +4 -4
  59. package/dist/cjs/onchain/market/pricefeeds/{ExternalPriceFeed.js → feeds/ExternalPriceFeed.js} +4 -4
  60. package/dist/cjs/onchain/market/pricefeeds/{MellowLRTPriceFeed.js → feeds/MellowLRTPriceFeed.js} +4 -4
  61. package/dist/cjs/onchain/market/pricefeeds/{PendleTWAPPTPriceFeed.js → feeds/PendleTWAPPTPriceFeed.js} +4 -4
  62. package/dist/cjs/onchain/market/pricefeeds/{PythPriceFeed.js → feeds/PythPriceFeed.js} +3 -3
  63. package/dist/cjs/onchain/market/pricefeeds/{RedstonePriceFeed.js → feeds/RedstonePriceFeed.js} +6 -6
  64. package/dist/cjs/onchain/market/pricefeeds/{WstETHPriceFeed.js → feeds/WstETHPriceFeed.js} +4 -4
  65. package/dist/cjs/onchain/market/pricefeeds/{YearnPriceFeed.js → feeds/YearnPriceFeed.js} +4 -4
  66. package/dist/cjs/onchain/market/pricefeeds/{ZeroPriceFeed.js → feeds/ZeroPriceFeed.js} +4 -4
  67. package/dist/cjs/onchain/market/pricefeeds/feeds/index.js +35 -0
  68. package/dist/cjs/onchain/market/pricefeeds/index.js +51 -39
  69. package/dist/cjs/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.js +189 -0
  70. package/dist/cjs/onchain/market/pricefeeds/{getRawPriceUpdates.js → updates/getRawPriceUpdates.js} +2 -2
  71. package/dist/cjs/onchain/market/pricefeeds/updates/index.js +8 -0
  72. package/dist/cjs/onchain/market/pricefeeds/{isUpdatablePriceFeed.js → updates/isUpdatablePriceFeed.js} +1 -1
  73. package/dist/cjs/onchain/market/pricefeeds/updates/updatableDependencies.js +14 -0
  74. package/dist/cjs/onchain/market/rwa/RWARegistry.js +4 -7
  75. package/dist/cjs/onchain/market/rwa/index.js +1 -0
  76. package/dist/cjs/onchain/market/rwa/midas/MidasDegenNFT.js +45 -5
  77. package/dist/cjs/onchain/market/rwa/securitize/SecuritizeDegenNFT.js +56 -12
  78. package/dist/cjs/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +0 -37
  79. package/dist/cjs/onchain/opportunities/MultichainOpportunitiesService.js +8 -2
  80. package/dist/cjs/onchain/opportunities/OpportunitiesService.js +16 -4
  81. package/dist/cjs/onchain/pools/PoolService.js +7 -8
  82. package/dist/cjs/onchain/positions/calcHealthFactor.js +3 -3
  83. package/dist/cjs/onchain/preview/index.js +2 -0
  84. package/dist/cjs/onchain/preview/parse/parseRWAFactoryOperationCalldata.js +2 -2
  85. package/dist/cjs/onchain/preview/preview/index.js +2 -0
  86. package/dist/cjs/onchain/preview/preview/midasGreenlistsAccount.js +17 -0
  87. package/dist/cjs/onchain/preview/preview/previewOpenStrategyPosition.js +13 -16
  88. package/dist/cjs/onchain/preview/preview/previewOperation.js +19 -11
  89. package/dist/cjs/onchain/preview/preview/replayMulticall.js +4 -3
  90. package/dist/cjs/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  91. package/dist/cjs/onchain/validation/bundles/checkCreditOperation.js +11 -9
  92. package/dist/cjs/onchain/validation/bundles/{checkDraw.js → checkIncreaseDebt.js} +10 -10
  93. package/dist/cjs/onchain/validation/bundles/{checkQuotasAsked.js → checkIncreaseQuota.js} +3 -3
  94. package/dist/cjs/onchain/validation/bundles/checkMidasAccountGreenlist.js +44 -0
  95. package/dist/cjs/onchain/validation/bundles/checkPoolOperation.js +2 -8
  96. package/dist/cjs/onchain/validation/bundles/checkRWAOpenRequirements.js +9 -9
  97. package/dist/cjs/onchain/validation/bundles/checkRWAOpening.js +18 -8
  98. package/dist/cjs/onchain/validation/bundles/index.js +6 -4
  99. package/dist/cjs/onchain/validation/checkOperation.js +0 -1
  100. package/dist/cjs/onchain/validation/checks/checkBorrowLimit.js +1 -1
  101. package/dist/cjs/onchain/validation/checks/checkPoolLiquidity.js +2 -9
  102. package/dist/cjs/onchain/validation/checks/checkReservePriceLimited.js +30 -0
  103. package/dist/cjs/onchain/validation/checks/index.js +2 -0
  104. package/dist/cjs/onchain/validation/index.js +8 -4
  105. package/dist/cjs/permissionless/utils/price-update/get-price-update-tx.js +2 -2
  106. package/dist/cjs/permissionless/utils/price-update/get-updatable-feeds.js +2 -2
  107. package/dist/cjs/sdk/execute/ExecuteApi.js +67 -7
  108. package/dist/cjs/sdk/opportunities/OpportunitiesNamespace.js +9 -3
  109. package/dist/cjs/sdk/prepare/PrepareApi.js +89 -14
  110. package/dist/esm/dev/abi.js +14 -15
  111. package/dist/esm/dev/claimFromFaucet.js +4 -8
  112. package/dist/esm/dev/createAnvilClient.js +36 -19
  113. package/dist/esm/dev/index.js +4 -4
  114. package/dist/esm/dev/kycUtils.js +66 -59
  115. package/dist/esm/dev/midasUtils.js +112 -18
  116. package/dist/esm/dev/securitizeUtils.js +84 -44
  117. package/dist/esm/dev/withdrawalUtils.js +3 -6
  118. package/dist/esm/model/errors/index.js +2 -2
  119. package/dist/esm/model/errors/operation-errors.js +18 -2
  120. package/dist/esm/model/index.js +4 -4
  121. package/dist/esm/model/rwa.js +4 -4
  122. package/dist/esm/model/rwa.schema.js +5 -5
  123. package/dist/esm/offchain/opportunities/OffchainOpportunities.js +1 -1
  124. package/dist/esm/onchain/OnchainSDK.js +3 -3
  125. package/dist/esm/onchain/accounts/CreditAccountsServiceV310.js +2 -17
  126. package/dist/esm/onchain/accounts/intents/borrow.js +138 -0
  127. package/dist/esm/onchain/accounts/intents/collateral-valuation.js +40 -0
  128. package/dist/esm/onchain/accounts/intents/guards.js +15 -3
  129. package/dist/esm/onchain/accounts/intents/index.js +107 -20
  130. package/dist/esm/onchain/accounts/intents/leverage-band.js +2 -12
  131. package/dist/esm/onchain/accounts/intents/math.js +13 -5
  132. package/dist/esm/onchain/accounts/intents/maxBorrow.js +87 -0
  133. package/dist/esm/onchain/accounts/intents/maxWithdrawCollateral.js +15 -41
  134. package/dist/esm/onchain/accounts/intents/open-strategy.js +8 -46
  135. package/dist/esm/onchain/accounts/intents/operations.js +0 -1
  136. package/dist/esm/onchain/accounts/intents/plan.js +1 -8
  137. package/dist/esm/onchain/accounts/intents/realize.js +61 -4
  138. package/dist/esm/onchain/accounts/intents/tail.js +1 -1
  139. package/dist/esm/onchain/accounts/intents/testing/sdk-mock.js +1 -0
  140. package/dist/esm/onchain/accounts/intents/utils/common.js +19 -1
  141. package/dist/esm/onchain/accounts/intents/utils/credit-account-slice.js +21 -1
  142. package/dist/esm/onchain/accounts/intents/utils/index.js +3 -3
  143. package/dist/esm/onchain/accounts/intents/utils/price-impact.js +12 -9
  144. package/dist/esm/onchain/accounts/intents/utils/router-path.js +4 -5
  145. package/dist/esm/onchain/accounts/intents/withdraw-limits.js +95 -0
  146. package/dist/esm/onchain/accounts/liquidations/LiquidationsService.js +1 -1
  147. package/dist/esm/onchain/constants/address-provider.js +1 -2
  148. package/dist/esm/onchain/constants/index.js +2 -2
  149. package/dist/esm/onchain/core/createAddressProvider.js +2 -5
  150. package/dist/esm/onchain/index.js +32 -24
  151. package/dist/esm/onchain/market/adapters/abi/conctructorAbi.js +2 -2
  152. package/dist/esm/onchain/market/adapters/contracts/AbstractAdapter.js +6 -0
  153. package/dist/esm/onchain/market/adapters/contracts/MidasGatewayAdapterContract.js +50 -6
  154. package/dist/esm/onchain/market/credit/CreditSuite.js +26 -9
  155. package/dist/esm/onchain/market/index.js +26 -21
  156. package/dist/esm/onchain/market/oracle/PriceOracleBaseContract.js +1 -1
  157. package/dist/esm/onchain/market/pricefeeds/AbstractPriceFeed.js +0 -5
  158. package/dist/esm/onchain/market/pricefeeds/PriceFeedRegistry.js +126 -0
  159. package/dist/esm/onchain/market/pricefeeds/{BalancerStablePriceFeed.js → feeds/BalancerStablePriceFeed.js} +4 -4
  160. package/dist/esm/onchain/market/pricefeeds/{BalancerWeightedPriceFeed.js → feeds/BalancerWeightedPriceFeed.js} +4 -4
  161. package/dist/esm/onchain/market/pricefeeds/{BoundedPriceFeed.js → feeds/BoundedPriceFeed.js} +4 -4
  162. package/dist/esm/onchain/market/pricefeeds/{CompositePriceFeed.js → feeds/CompositePriceFeed.js} +4 -4
  163. package/dist/esm/onchain/market/pricefeeds/{ConstantPriceFeed.js → feeds/ConstantPriceFeed.js} +3 -3
  164. package/dist/esm/onchain/market/pricefeeds/{CurveCryptoPriceFeed.js → feeds/CurveCryptoPriceFeed.js} +4 -4
  165. package/dist/esm/onchain/market/pricefeeds/{CurveStablePriceFeed.js → feeds/CurveStablePriceFeed.js} +4 -4
  166. package/dist/esm/onchain/market/pricefeeds/{CurveUSDPriceFeed.js → feeds/CurveUSDPriceFeed.js} +4 -4
  167. package/dist/esm/onchain/market/pricefeeds/{Erc4626PriceFeed.js → feeds/Erc4626PriceFeed.js} +4 -4
  168. package/dist/esm/onchain/market/pricefeeds/{ExternalPriceFeed.js → feeds/ExternalPriceFeed.js} +4 -4
  169. package/dist/esm/onchain/market/pricefeeds/{MellowLRTPriceFeed.js → feeds/MellowLRTPriceFeed.js} +4 -4
  170. package/dist/esm/onchain/market/pricefeeds/{PendleTWAPPTPriceFeed.js → feeds/PendleTWAPPTPriceFeed.js} +4 -4
  171. package/dist/esm/onchain/market/pricefeeds/{PythPriceFeed.js → feeds/PythPriceFeed.js} +3 -3
  172. package/dist/esm/onchain/market/pricefeeds/{RedstonePriceFeed.js → feeds/RedstonePriceFeed.js} +6 -6
  173. package/dist/esm/onchain/market/pricefeeds/{WstETHPriceFeed.js → feeds/WstETHPriceFeed.js} +4 -4
  174. package/dist/esm/onchain/market/pricefeeds/{YearnPriceFeed.js → feeds/YearnPriceFeed.js} +4 -4
  175. package/dist/esm/onchain/market/pricefeeds/{ZeroPriceFeed.js → feeds/ZeroPriceFeed.js} +4 -4
  176. package/dist/esm/onchain/market/pricefeeds/feeds/index.js +18 -0
  177. package/dist/esm/onchain/market/pricefeeds/index.js +27 -21
  178. package/dist/esm/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.js +188 -0
  179. package/dist/esm/onchain/market/pricefeeds/{getRawPriceUpdates.js → updates/getRawPriceUpdates.js} +2 -2
  180. package/dist/esm/onchain/market/pricefeeds/updates/index.js +5 -1
  181. package/dist/esm/onchain/market/pricefeeds/{isUpdatablePriceFeed.js → updates/isUpdatablePriceFeed.js} +1 -1
  182. package/dist/esm/onchain/market/pricefeeds/updates/updatableDependencies.js +13 -0
  183. package/dist/esm/onchain/market/rwa/RWARegistry.js +4 -8
  184. package/dist/esm/onchain/market/rwa/index.js +2 -2
  185. package/dist/esm/onchain/market/rwa/midas/MidasDegenNFT.js +45 -5
  186. package/dist/esm/onchain/market/rwa/securitize/SecuritizeDegenNFT.js +55 -10
  187. package/dist/esm/onchain/market/rwa/securitize/SecuritizeRWAFactory.js +0 -37
  188. package/dist/esm/onchain/opportunities/MultichainOpportunitiesService.js +8 -2
  189. package/dist/esm/onchain/opportunities/OpportunitiesService.js +16 -4
  190. package/dist/esm/onchain/pools/PoolService.js +7 -8
  191. package/dist/esm/onchain/positions/calcHealthFactor.js +3 -3
  192. package/dist/esm/onchain/preview/index.js +2 -1
  193. package/dist/esm/onchain/preview/parse/parseRWAFactoryOperationCalldata.js +2 -2
  194. package/dist/esm/onchain/preview/preview/index.js +2 -1
  195. package/dist/esm/onchain/preview/preview/midasGreenlistsAccount.js +16 -0
  196. package/dist/esm/onchain/preview/preview/previewOpenStrategyPosition.js +14 -17
  197. package/dist/esm/onchain/preview/preview/previewOperation.js +19 -11
  198. package/dist/esm/onchain/preview/preview/replayMulticall.js +4 -3
  199. package/dist/esm/onchain/validation/bundles/checkCollateralFunding.js +3 -3
  200. package/dist/esm/onchain/validation/bundles/checkCreditOperation.js +11 -9
  201. package/dist/esm/onchain/validation/bundles/checkIncreaseDebt.js +27 -0
  202. package/dist/esm/onchain/validation/bundles/{checkQuotasAsked.js → checkIncreaseQuota.js} +3 -3
  203. package/dist/esm/onchain/validation/bundles/checkMidasAccountGreenlist.js +43 -0
  204. package/dist/esm/onchain/validation/bundles/checkPoolOperation.js +2 -8
  205. package/dist/esm/onchain/validation/bundles/checkRWAOpenRequirements.js +9 -9
  206. package/dist/esm/onchain/validation/bundles/checkRWAOpening.js +18 -8
  207. package/dist/esm/onchain/validation/bundles/index.js +4 -3
  208. package/dist/esm/onchain/validation/checkOperation.js +0 -1
  209. package/dist/esm/onchain/validation/checks/checkBorrowLimit.js +1 -1
  210. package/dist/esm/onchain/validation/checks/checkPoolLiquidity.js +2 -9
  211. package/dist/esm/onchain/validation/checks/checkReservePriceLimited.js +29 -0
  212. package/dist/esm/onchain/validation/checks/index.js +2 -1
  213. package/dist/esm/onchain/validation/index.js +5 -3
  214. package/dist/esm/permissionless/utils/price-update/get-price-update-tx.js +1 -1
  215. package/dist/esm/permissionless/utils/price-update/get-updatable-feeds.js +1 -1
  216. package/dist/esm/sdk/execute/ExecuteApi.js +67 -7
  217. package/dist/esm/sdk/opportunities/OpportunitiesNamespace.js +9 -3
  218. package/dist/esm/sdk/prepare/PrepareApi.js +94 -19
  219. package/dist/types/dev/abi.d.ts +13 -15
  220. package/dist/types/dev/claimFromFaucet.d.ts +0 -1
  221. package/dist/types/dev/createAnvilClient.d.ts +10 -3
  222. package/dist/types/dev/index.d.ts +4 -4
  223. package/dist/types/dev/kycUtils.d.ts +15 -24
  224. package/dist/types/dev/midasUtils.d.ts +35 -4
  225. package/dist/types/dev/securitizeUtils.d.ts +3 -9
  226. package/dist/types/model/errors/index.d.ts +2 -2
  227. package/dist/types/model/errors/operation-errors.d.ts +62 -7
  228. package/dist/types/model/index.d.ts +5 -5
  229. package/dist/types/model/opportunities.d.ts +6 -7
  230. package/dist/types/model/previews.d.ts +25 -19
  231. package/dist/types/model/rwa.d.ts +47 -27
  232. package/dist/types/model/rwa.schema.d.ts +3 -3
  233. package/dist/types/offchain/opportunities/OffchainOpportunities.d.ts +1 -2
  234. package/dist/types/offchain/opportunities/types.d.ts +1 -4
  235. package/dist/types/onchain/OnchainSDK.d.ts +2 -2
  236. package/dist/types/onchain/accounts/index.d.ts +5 -4
  237. package/dist/types/onchain/accounts/intents/borrow.d.ts +141 -0
  238. package/dist/types/onchain/accounts/intents/collateral-valuation.d.ts +42 -0
  239. package/dist/types/onchain/accounts/intents/guards.d.ts +18 -2
  240. package/dist/types/onchain/accounts/intents/index.d.ts +103 -15
  241. package/dist/types/onchain/accounts/intents/math.d.ts +11 -3
  242. package/dist/types/onchain/accounts/intents/maxBorrow.d.ts +54 -0
  243. package/dist/types/onchain/accounts/intents/maxWithdrawCollateral.d.ts +3 -8
  244. package/dist/types/onchain/accounts/intents/open-strategy.d.ts +3 -17
  245. package/dist/types/onchain/accounts/intents/testing/sdk-mock.d.ts +2 -0
  246. package/dist/types/onchain/accounts/intents/tests/open-strategy.fixtures.d.ts +2 -2
  247. package/dist/types/onchain/accounts/intents/types.d.ts +51 -6
  248. package/dist/types/onchain/accounts/intents/utils/common.d.ts +15 -1
  249. package/dist/types/onchain/accounts/intents/utils/credit-account-slice.d.ts +14 -1
  250. package/dist/types/onchain/accounts/intents/utils/index.d.ts +3 -3
  251. package/dist/types/onchain/accounts/intents/utils/price-impact.d.ts +4 -1
  252. package/dist/types/onchain/accounts/intents/utils/router-path.d.ts +2 -5
  253. package/dist/types/onchain/accounts/intents/withdraw-limits.d.ts +80 -0
  254. package/dist/types/onchain/accounts/types.d.ts +4 -2
  255. package/dist/types/onchain/constants/address-provider.d.ts +1 -2
  256. package/dist/types/onchain/constants/index.d.ts +2 -2
  257. package/dist/types/onchain/index.d.ts +40 -31
  258. package/dist/types/onchain/market/adapters/contracts/AbstractAdapter.d.ts +6 -0
  259. package/dist/types/onchain/market/adapters/contracts/MidasGatewayAdapterContract.d.ts +20 -4
  260. package/dist/types/onchain/market/adapters/types.d.ts +8 -0
  261. package/dist/types/onchain/market/credit/CreditSuite.d.ts +13 -3
  262. package/dist/types/onchain/market/index.d.ts +29 -24
  263. package/dist/types/onchain/market/oracle/PriceOracleBaseContract.d.ts +2 -1
  264. package/dist/types/onchain/market/oracle/types.d.ts +2 -1
  265. package/dist/types/onchain/market/pool/types.d.ts +1 -1
  266. package/dist/types/onchain/market/pricefeeds/AbstractPriceFeed.d.ts +1 -2
  267. package/dist/types/onchain/market/pricefeeds/PriceFeedRegistry.d.ts +60 -0
  268. package/dist/types/onchain/market/pricefeeds/feeds/BalancerStablePriceFeed.d.ts +12 -0
  269. package/dist/types/onchain/market/pricefeeds/{BalancerWeightedPriceFeed.d.ts → feeds/BalancerWeightedPriceFeed.d.ts} +7 -7
  270. package/dist/types/onchain/market/pricefeeds/feeds/BoundedPriceFeed.d.ts +15 -0
  271. package/dist/types/onchain/market/pricefeeds/{CompositePriceFeed.d.ts → feeds/CompositePriceFeed.d.ts} +6 -6
  272. package/dist/types/onchain/market/pricefeeds/{ConstantPriceFeed.d.ts → feeds/ConstantPriceFeed.d.ts} +6 -6
  273. package/dist/types/onchain/market/pricefeeds/feeds/CurveCryptoPriceFeed.d.ts +12 -0
  274. package/dist/types/onchain/market/pricefeeds/feeds/CurveStablePriceFeed.d.ts +12 -0
  275. package/dist/types/onchain/market/pricefeeds/feeds/CurveUSDPriceFeed.d.ts +12 -0
  276. package/dist/types/onchain/market/pricefeeds/feeds/Erc4626PriceFeed.d.ts +12 -0
  277. package/dist/types/onchain/market/pricefeeds/feeds/ExternalPriceFeed.d.ts +11 -0
  278. package/dist/types/onchain/market/pricefeeds/feeds/MellowLRTPriceFeed.d.ts +12 -0
  279. package/dist/types/onchain/market/pricefeeds/{PendleTWAPPTPriceFeed.d.ts → feeds/PendleTWAPPTPriceFeed.d.ts} +3 -3
  280. package/dist/types/onchain/market/pricefeeds/{PythPriceFeed.d.ts → feeds/PythPriceFeed.d.ts} +3 -3
  281. package/dist/types/onchain/market/pricefeeds/{RedstonePriceFeed.d.ts → feeds/RedstonePriceFeed.d.ts} +9 -9
  282. package/dist/types/onchain/market/pricefeeds/feeds/WstETHPriceFeed.d.ts +12 -0
  283. package/dist/types/onchain/market/pricefeeds/feeds/YearnPriceFeed.d.ts +12 -0
  284. package/dist/types/onchain/market/pricefeeds/feeds/ZeroPriceFeed.d.ts +11 -0
  285. package/dist/types/onchain/market/pricefeeds/feeds/index.d.ts +18 -0
  286. package/dist/types/onchain/market/pricefeeds/index.d.ts +28 -22
  287. package/dist/types/onchain/market/pricefeeds/types.d.ts +1 -31
  288. package/dist/types/onchain/market/pricefeeds/updates/RedstoneUpdater.d.ts +1 -1
  289. package/dist/types/onchain/market/pricefeeds/updates/UpdatablePriceFeedRegistry.d.ts +106 -0
  290. package/dist/types/onchain/market/pricefeeds/updates/getRawPriceUpdates.d.ts +6 -0
  291. package/dist/types/onchain/market/pricefeeds/updates/index.d.ts +7 -3
  292. package/dist/types/onchain/market/pricefeeds/updates/isUpdatablePriceFeed.d.ts +6 -0
  293. package/dist/types/onchain/market/pricefeeds/updates/types.d.ts +56 -2
  294. package/dist/types/onchain/market/pricefeeds/updates/updatableDependencies.d.ts +10 -0
  295. package/dist/types/onchain/market/rwa/RWARegistry.d.ts +2 -1
  296. package/dist/types/onchain/market/rwa/index.d.ts +3 -3
  297. package/dist/types/onchain/market/rwa/midas/MidasDegenNFT.d.ts +19 -4
  298. package/dist/types/onchain/market/rwa/securitize/SecuritizeDegenNFT.d.ts +24 -4
  299. package/dist/types/onchain/market/rwa/securitize/SecuritizeRWAFactory.d.ts +2 -14
  300. package/dist/types/onchain/market/rwa/types.d.ts +39 -37
  301. package/dist/types/onchain/opportunities/MultichainOpportunitiesService.d.ts +5 -1
  302. package/dist/types/onchain/opportunities/OpportunitiesService.d.ts +10 -3
  303. package/dist/types/onchain/opportunities/types.d.ts +6 -1
  304. package/dist/types/onchain/pools/PoolService.d.ts +5 -0
  305. package/dist/types/onchain/pools/types.d.ts +9 -2
  306. package/dist/types/onchain/preview/index.d.ts +2 -1
  307. package/dist/types/onchain/preview/preview/index.d.ts +2 -1
  308. package/dist/types/onchain/preview/preview/midasGreenlistsAccount.d.ts +13 -0
  309. package/dist/types/onchain/preview/preview/previewOpenStrategyPosition.d.ts +5 -3
  310. package/dist/types/onchain/preview/preview/replayMulticall.d.ts +8 -7
  311. package/dist/types/onchain/validation/bundles/checkCreditOperation.d.ts +5 -4
  312. package/dist/types/onchain/validation/bundles/{checkDraw.d.ts → checkIncreaseDebt.d.ts} +7 -7
  313. package/dist/types/onchain/validation/bundles/{checkQuotasAsked.d.ts → checkIncreaseQuota.d.ts} +3 -3
  314. package/dist/types/onchain/validation/bundles/checkMidasAccountGreenlist.d.ts +22 -0
  315. package/dist/types/onchain/validation/bundles/checkPoolOperation.d.ts +1 -7
  316. package/dist/types/onchain/validation/bundles/checkRWAOpenRequirements.d.ts +2 -2
  317. package/dist/types/onchain/validation/bundles/checkRWAOpening.d.ts +9 -7
  318. package/dist/types/onchain/validation/bundles/index.d.ts +5 -4
  319. package/dist/types/onchain/validation/checks/checkBorrowLimit.d.ts +1 -1
  320. package/dist/types/onchain/validation/checks/checkDebtLimits.d.ts +2 -2
  321. package/dist/types/onchain/validation/checks/checkPoolLiquidity.d.ts +1 -8
  322. package/dist/types/onchain/validation/checks/checkReservePriceLimited.d.ts +31 -0
  323. package/dist/types/onchain/validation/checks/index.d.ts +2 -1
  324. package/dist/types/onchain/validation/index.d.ts +6 -4
  325. package/dist/types/onchain/validation/raise.d.ts +2 -2
  326. package/dist/types/sdk/execute/index.d.ts +2 -2
  327. package/dist/types/sdk/execute/types.d.ts +48 -6
  328. package/dist/types/sdk/index.d.ts +5 -4
  329. package/dist/types/sdk/opportunities/OpportunitiesNamespace.d.ts +5 -1
  330. package/dist/types/sdk/opportunities/types.d.ts +9 -3
  331. package/dist/types/sdk/prepare/PrepareApi.d.ts +16 -4
  332. package/dist/types/sdk/prepare/index.d.ts +4 -3
  333. package/dist/types/sdk/prepare/types.d.ts +200 -66
  334. package/package.json +1 -1
  335. package/dist/cjs/onchain/accounts/utils/midasUtils.js +0 -70
  336. package/dist/cjs/onchain/market/pricefeeds/PriceFeedsRegister.js +0 -301
  337. package/dist/cjs/plugins/degen-distributors/DegenDistributorsPlugin.js +0 -61
  338. package/dist/cjs/plugins/degen-distributors/index.js +0 -4
  339. package/dist/cjs/plugins/degen-distributors/package.json +0 -1
  340. package/dist/cjs/plugins/degen-distributors/types.js +0 -1
  341. package/dist/cjs/plugins/delayed-withdrawal/DelayedWithdrawalPlugin.js +0 -114
  342. package/dist/cjs/plugins/delayed-withdrawal/index.js +0 -4
  343. package/dist/cjs/plugins/delayed-withdrawal/package.json +0 -1
  344. package/dist/cjs/plugins/delayed-withdrawal/types.js +0 -1
  345. package/dist/esm/onchain/accounts/utils/midasUtils.js +0 -69
  346. package/dist/esm/onchain/market/pricefeeds/PriceFeedsRegister.js +0 -300
  347. package/dist/esm/onchain/validation/bundles/checkDraw.js +0 -27
  348. package/dist/esm/plugins/degen-distributors/DegenDistributorsPlugin.js +0 -60
  349. package/dist/esm/plugins/degen-distributors/index.js +0 -3
  350. package/dist/esm/plugins/degen-distributors/package.json +0 -1
  351. package/dist/esm/plugins/degen-distributors/types.js +0 -1
  352. package/dist/esm/plugins/delayed-withdrawal/DelayedWithdrawalPlugin.js +0 -113
  353. package/dist/esm/plugins/delayed-withdrawal/index.js +0 -3
  354. package/dist/esm/plugins/delayed-withdrawal/package.json +0 -1
  355. package/dist/esm/plugins/delayed-withdrawal/types.js +0 -1
  356. package/dist/types/onchain/accounts/utils/midasUtils.d.ts +0 -38
  357. package/dist/types/onchain/market/pricefeeds/BalancerStablePriceFeed.d.ts +0 -12
  358. package/dist/types/onchain/market/pricefeeds/BoundedPriceFeed.d.ts +0 -15
  359. package/dist/types/onchain/market/pricefeeds/CurveCryptoPriceFeed.d.ts +0 -12
  360. package/dist/types/onchain/market/pricefeeds/CurveStablePriceFeed.d.ts +0 -12
  361. package/dist/types/onchain/market/pricefeeds/CurveUSDPriceFeed.d.ts +0 -12
  362. package/dist/types/onchain/market/pricefeeds/Erc4626PriceFeed.d.ts +0 -12
  363. package/dist/types/onchain/market/pricefeeds/ExternalPriceFeed.d.ts +0 -11
  364. package/dist/types/onchain/market/pricefeeds/MellowLRTPriceFeed.d.ts +0 -12
  365. package/dist/types/onchain/market/pricefeeds/PriceFeedsRegister.d.ts +0 -180
  366. package/dist/types/onchain/market/pricefeeds/WstETHPriceFeed.d.ts +0 -12
  367. package/dist/types/onchain/market/pricefeeds/YearnPriceFeed.d.ts +0 -12
  368. package/dist/types/onchain/market/pricefeeds/ZeroPriceFeed.d.ts +0 -11
  369. package/dist/types/onchain/market/pricefeeds/getRawPriceUpdates.d.ts +0 -5
  370. package/dist/types/onchain/market/pricefeeds/isUpdatablePriceFeed.d.ts +0 -5
  371. package/dist/types/plugins/degen-distributors/DegenDistributorsPlugin.d.ts +0 -25
  372. package/dist/types/plugins/degen-distributors/index.d.ts +0 -3
  373. package/dist/types/plugins/degen-distributors/types.d.ts +0 -8
  374. package/dist/types/plugins/delayed-withdrawal/DelayedWithdrawalPlugin.d.ts +0 -25
  375. package/dist/types/plugins/delayed-withdrawal/index.d.ts +0 -3
  376. package/dist/types/plugins/delayed-withdrawal/types.d.ts +0 -10
@@ -6,6 +6,7 @@ import { checkCreditManagerPaused } from "../../validation/checks/checkCreditMan
6
6
  import { checkForbiddenToken } from "../../validation/checks/checkForbiddenToken.js";
7
7
  import { checkMarketExpired } from "../../validation/checks/checkMarketExpired.js";
8
8
  import { checkQuotaLimit } from "../../validation/checks/checkQuotaLimit.js";
9
+ import { checkReservePriceLimited } from "../../validation/checks/checkReservePriceLimited.js";
9
10
  import { raise } from "../../validation/raise.js";
10
11
  import "../../validation/index.js";
11
12
  import { eq } from "./utils/common.js";
@@ -111,13 +112,24 @@ function assertGrowthAllowed(args) {
111
112
  * whose reserve feed the SDK cannot read keeps its main price, so a plan can
112
113
  * still be refused on-chain after passing here.
113
114
  */
114
- function assertCollateralised(healthFactorBps, safePrices) {
115
+ function assertCollateralised(healthFactorBps, safePrices, atSafePrices) {
115
116
  const healthFactorThreshold = MIN_HEALTH_FACTOR_FACADE;
116
- raise(checkCollateralised({
117
+ const errors = checkCollateralised({
117
118
  healthFactor: healthFactorBps,
118
119
  healthFactorThreshold,
119
120
  safePrices
120
- }), `the account would end at a health factor of ${healthFactorBps}, below ${healthFactorThreshold}`);
121
+ });
122
+ if (errors.length === 0) return;
123
+ if (safePrices && atSafePrices) {
124
+ const { atMainPrices, withdrawable } = atSafePrices();
125
+ raise(checkReservePriceLimited({
126
+ healthFactor: healthFactorBps,
127
+ atMainPrices,
128
+ healthFactorThreshold,
129
+ withdrawable
130
+ }), `the account covers its debt at ${atMainPrices} on the main feed and only ${healthFactorBps} at the reserve one, below ${healthFactorThreshold}`);
131
+ }
132
+ raise(errors, `the account would end at a health factor of ${healthFactorBps}, below ${healthFactorThreshold}`);
121
133
  }
122
134
  /**
123
135
  * A quota can only be raised as far as the market still has room for: past the
@@ -7,14 +7,16 @@ import { IntentPreviewError } from "../../validation/raise.js";
7
7
  import "../../validation/index.js";
8
8
  import { isPhantomToken } from "./utils/pick-token.js";
9
9
  import { assertMarketOperable } from "./guards.js";
10
+ import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
11
+ import { buildBorrowState } from "./borrow.js";
10
12
  import { calcLeverageBand } from "./leverage-band.js";
11
- import { maxProportionalWithdrawal } from "./math.js";
13
+ import { maxBorrow } from "./maxBorrow.js";
12
14
  import { maxWithdrawCollateral } from "./maxWithdrawCollateral.js";
13
- import { fetchCreditAccountSlice, toCreditAccountSlice } from "./utils/credit-account-slice.js";
14
15
  import { buildOpenStrategyState } from "./open-strategy.js";
15
16
  import { planAddCollateral, planAdjustLeverage, planAdjustLeverageDelayed, planDeposit, planRepay, planWithdraw, planWithdrawAsset, planWithdrawDelayed } from "./plan.js";
16
- import { realize } from "./realize.js";
17
17
  import { accountView } from "./view.js";
18
+ import { withdrawLimits } from "./withdraw-limits.js";
19
+ import { realize } from "./realize.js";
18
20
  import { planTail, projectTail } from "./tail.js";
19
21
  //#region src/onchain/accounts/intents/index.ts
20
22
  /**
@@ -50,26 +52,29 @@ var CreditAccountOperationsService = class extends SDKConstruct {
50
52
  }
51
53
  /**
52
54
  * Both ends of what a `WITHDRAW` can take out, in underlying: the largest
53
- * partial withdrawal that keeps leverage and stays inside the facade's
54
- * `debtLimits`, and the net value an exit hands over. They are reported together
55
- * because a withdraw form needs both — the range it may offer, and the one
56
- * amount past it that is allowed — and because the distance between them is
57
- * the account's own, not a constant a caller could assume.
55
+ * partial withdrawal that keeps leverage, and the net value an exit hands
56
+ * over. They are reported together because a withdraw form needs both — the
57
+ * range it may offer, and the one amount past it that is allowed — and
58
+ * because the distance between them is the account's own, not a constant a
59
+ * caller could assume.
58
60
  *
59
- * Takes no target health factor, unlike {@link maxWithdrawCollateral}: a
60
- * proportional withdrawal leaves the factor where it found it, and the
61
- * facade's `minDebt` is what bounds it.
61
+ * Two rules bound the partial end and both are reported: the facade's
62
+ * `debtLimits` as `partial`, and the safe-price collateral check on top of
63
+ * it as `safePartial`. The second is the one to offer — see
64
+ * {@link WithdrawCeilings}.
62
65
  *
63
- * @param props - Account slice and the SDK holding its market
64
- * @returns The two ceilings, see {@link WithdrawCeilings} for the gap between
65
- * them
66
+ * Takes no target health factor, unlike {@link maxWithdrawCollateral}. A
67
+ * proportional withdrawal leaves the factor where it found it, so there is
68
+ * no room to choose: what these answer to is the facade's own threshold,
69
+ * which is also what {@link startIntent} refuses against.
70
+ *
71
+ * @param props - Account slice, the SDK holding its market, and optionally
72
+ * the collateral the withdrawal would be funded from
73
+ * @returns The three limits, see {@link WithdrawCeilings} for the gap
74
+ * between them
66
75
  */
67
76
  maxWithdraw(props) {
68
- const view = accountView(props.creditAccount, props.sdk);
69
- return {
70
- partial: maxProportionalWithdrawal(view, view.debtLimits),
71
- exit: view.collateral > 0n ? view.collateral : 0n
72
- };
77
+ return withdrawLimits(props);
73
78
  }
74
79
  /**
75
80
  * Debt a `REPAY` would have to cover to settle the account, in underlying
@@ -129,6 +134,34 @@ var CreditAccountOperationsService = class extends SDKConstruct {
129
134
  });
130
135
  }
131
136
  /**
137
+ * Largest loan a given collateral supports at `targetHF`, in the payout
138
+ * token's units — the ceiling a borrow form should offer.
139
+ *
140
+ * Reads no account, like {@link leverageBand}: the borrow opens one. The
141
+ * collateral is valued the way the transaction will be judged, at safe
142
+ * prices and under the quota the borrow buys, and the answer is then held to
143
+ * what the market will lend.
144
+ *
145
+ * A ceiling, not a verdict: the facade's `minDebt` is a floor and is not
146
+ * applied here, so collateral too small for this market still answers with
147
+ * what it carries and {@link borrowIntent} is the one that refuses the loan.
148
+ *
149
+ * The default is {@link MIN_HF_LIMITED}, the threshold a form holds an
150
+ * account to.
151
+ *
152
+ * @param props - The manager, the SDK holding its market, the collateral put
153
+ * up, the token to be paid in, and optionally the health factor to land at
154
+ * @returns Amount in the payout token's units; `0n` where no loan of this
155
+ * shape can be funded at any size
156
+ */
157
+ maxBorrow(props) {
158
+ const { targetHF = MIN_HF_LIMITED, ...rest } = props;
159
+ return maxBorrow({
160
+ ...rest,
161
+ targetHF: targetHF + 2n
162
+ });
163
+ }
164
+ /**
132
165
  * Previews the same operation when its source only redeems through its
133
166
  * issuer: a Securitize dsToken, a Mellow share.
134
167
  *
@@ -179,7 +212,10 @@ var CreditAccountOperationsService = class extends SDKConstruct {
179
212
  });
180
213
  return {
181
214
  ...result,
182
- state: tail.state,
215
+ state: {
216
+ ...tail.state,
217
+ executionCost: result.state.executionCost
218
+ },
183
219
  delayed
184
220
  };
185
221
  } catch (e) {
@@ -271,6 +307,26 @@ var CreditAccountOperationsService = class extends SDKConstruct {
271
307
  };
272
308
  }
273
309
  /**
310
+ * Previews opening an account that holds nothing.
311
+ *
312
+ * Nothing is put up, drawn or routed, so there is no state to build and no
313
+ * guard to run beyond the market's own: a paused or expired facade takes no
314
+ * multicall, and an opening is a multicall like any other. Answers the same
315
+ * envelope its two neighbours do so a caller branches on `ok` throughout.
316
+ *
317
+ * @param props - The SDK holding the market, and the manager to open in
318
+ * @returns `{ ok: true }`, or `{ ok: false, error }` when the market takes
319
+ * no transaction right now
320
+ */
321
+ async openEmptyAccountIntent(props) {
322
+ try {
323
+ assertMarketOperable(props.sdk.marketRegister.findCreditManager(props.creditManager));
324
+ return { ok: true };
325
+ } catch (e) {
326
+ return asSDKError(e);
327
+ }
328
+ }
329
+ /**
274
330
  * Previews opening a brand-new leveraged position.
275
331
  *
276
332
  * Sits apart from {@link startIntent} because there is no account yet: nothing
@@ -292,6 +348,37 @@ var CreditAccountOperationsService = class extends SDKConstruct {
292
348
  return asSDKError(e);
293
349
  }
294
350
  }
351
+ /**
352
+ * Previews taking a loan against collateral, on an account this same
353
+ * transaction opens.
354
+ *
355
+ * Sits beside {@link openStrategyIntent} rather than under
356
+ * {@link startIntent} for the same reason: there is no account yet, and the
357
+ * output feeds `sdk.accounts.openCA`. What sets it apart from an opening is
358
+ * where the loan goes — out to the wallet rather than into a position — so
359
+ * the debt is named outright instead of following from a leverage, and the
360
+ * collateral is the only thing the account is left holding.
361
+ *
362
+ * `creditAccount` draws the loan on one the wallet already holds instead of
363
+ * opening another, as an opening takes one.
364
+ *
365
+ * @param props - Credit manager, the collateral the wallet puts up and the
366
+ * payout it asks for
367
+ * @returns Debt, the payout's two branches and the projection the account
368
+ * lands in, or `{ ok: false, error }` when the loan is not viable — a debt
369
+ * outside the facade's limits, collateral that cannot carry it, a payout the
370
+ * router has no path to
371
+ */
372
+ async borrowIntent(props) {
373
+ try {
374
+ return {
375
+ ok: true,
376
+ state: await buildBorrowState(props)
377
+ };
378
+ } catch (e) {
379
+ return asSDKError(e);
380
+ }
381
+ }
295
382
  /** Plan → realise → wrap. Unviable requests become `{ ok: false }`. */
296
383
  async #preview(props, plan) {
297
384
  try {
@@ -1,5 +1,6 @@
1
1
  import { BigIntMath } from "../../utils/bigint-math.js";
2
2
  import { LEVERAGE_DECIMALS } from "../../constants/math.js";
3
+ import { resolveCreditManager } from "./utils/common.js";
3
4
  //#region src/onchain/accounts/intents/leverage-band.ts
4
5
  /**
5
6
  * The leverages this market will actually fund for a position of this size.
@@ -29,7 +30,7 @@ import { LEVERAGE_DECIMALS } from "../../constants/math.js";
29
30
  * ```
30
31
  **/
31
32
  function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
32
- const found = resolve(sdk, creditManager);
33
+ const found = resolveCreditManager(sdk, creditManager);
33
34
  if (!found) return;
34
35
  const { suite, market } = found;
35
36
  const target = suite.strategyTargetCollateral;
@@ -54,16 +55,5 @@ function calcLeverageBand({ sdk, creditManager, collateral, targetHF }) {
54
55
  max
55
56
  };
56
57
  }
57
- /** The manager's suite and market, or nothing while they cannot be resolved. */
58
- function resolve(sdk, creditManager) {
59
- try {
60
- return {
61
- suite: sdk.marketRegister.findCreditManager(creditManager),
62
- market: sdk.marketRegister.findByCreditManager(creditManager)
63
- };
64
- } catch {
65
- return;
66
- }
67
- }
68
58
  //#endregion
69
59
  export { calcLeverageBand };
@@ -1,5 +1,5 @@
1
1
  import { BigIntMath } from "../../utils/bigint-math.js";
2
- import { LEVERAGE_DECIMALS } from "../../constants/math.js";
2
+ import { LEVERAGE_DECIMALS, PERCENTAGE_FACTOR } from "../../constants/math.js";
3
3
  import { insufficientBalance } from "../../../model/errors/operation-errors.js";
4
4
  import "../../../model/index.js";
5
5
  import { toToken } from "../../validation/helpers/token.js";
@@ -24,19 +24,27 @@ function proportionalDebt(position, collateralDelta) {
24
24
  return position.debt * collateralDelta / position.collateral;
25
25
  }
26
26
  /**
27
+ * Headroom on top of the debt read, in `PERCENTAGE_FACTOR`: enough interest for
28
+ * the transaction to sit in the mempool for hours at any sane borrow rate,
29
+ * small enough not to matter to the wallet that fronts it.
30
+ */
31
+ const SETTLE_MARGIN = 10n;
32
+ /**
27
33
  * Largest withdrawal (in underlying) that {@link proportionalDebt} can still
28
- * pay for: the repayment it implies leaves debt at or above `minDebt`, and
34
+ * pay for: the repayment it implies leaves debt at or above `minDebt` plus
35
+ * {@link SETTLE_MARGIN} of the debt, so the figure survives the interest of the
36
+ * blocks before it is sent, and
29
37
  * strictly less than the collateral goes — the last unit closes the account
30
38
  * rather than shrinks it. `0n` when the debt already sits below `minDebt`.
31
39
  *
32
- * Solves `floor(D0 · W / C0) ≤ D0 − minDebt` for `W`.
40
+ * Solves `floor(D0 · W / C0) ≤ D0 − minDebt − margin` for `W`.
33
41
  */
34
42
  function maxProportionalWithdrawal(position, debtLimits) {
35
43
  const { debt, collateral } = position;
36
44
  if (collateral <= 0n) return 0n;
37
45
  const allButLast = collateral - 1n;
38
46
  if (debt === 0n) return allButLast;
39
- const repayable = debt - debtLimits.minDebt;
47
+ const repayable = debt - debtLimits.minDebt - debt * SETTLE_MARGIN / PERCENTAGE_FACTOR;
40
48
  if (repayable < 0n) return 0n;
41
49
  const bound = BigIntMath.ceilDiv(collateral * (repayable + 1n), debt) - 1n;
42
50
  return bound < allButLast ? bound : allButLast;
@@ -62,4 +70,4 @@ function assertDebtLimits(sdk, debt, debtLimits, underlying) {
62
70
  }), debt > debtLimits.maxDebt ? `debt ${debt} exceeds maxDebt ${debtLimits.maxDebt}` : `debt ${debt} is below minDebt ${debtLimits.minDebt}`);
63
71
  }
64
72
  //#endregion
65
- export { assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage, maxProportionalWithdrawal, proportionalDebt };
73
+ export { SETTLE_MARGIN, assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage, maxProportionalWithdrawal, proportionalDebt };
@@ -0,0 +1,87 @@
1
+ import { BigIntMath } from "../../utils/bigint-math.js";
2
+ import "../../constants/math.js";
3
+ import "../../utils/index.js";
4
+ import { eq, resolveCreditManager, toTargetDecimals } from "./utils/common.js";
5
+ import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
6
+ import "./utils/index.js";
7
+ import { borrowCollateralQuota } from "./borrow.js";
8
+ import { collateralValuation } from "./collateral-valuation.js";
9
+ //#region src/onchain/accounts/intents/maxBorrow.ts
10
+ /**
11
+ * Largest loan this collateral supports at `targetHF` — the ceiling a borrow
12
+ * form should offer, in the payout token's units.
13
+ *
14
+ * The inverse of a borrow rather than a search for one: the loan leaves the
15
+ * account entirely, so the collateral is the whole of what backs the debt, and
16
+ * the health factor is one division away from the amount. Solving it the other
17
+ * way round costs a division too, and no iteration.
18
+ *
19
+ * Collateral is valued the way the transaction will be judged — at safe
20
+ * prices, under its liquidation threshold, capped by the quota the borrow
21
+ * buys for it, all of which is {@link collateralValuation}'s business. The ceiling
22
+ * is then held to what the market will actually lend: the pool's free
23
+ * liquidity, the manager's own allowance and the facade's `maxDebt`, whichever
24
+ * binds first.
25
+ *
26
+ * The facade's `minDebt` is deliberately not applied. It is a floor, and a
27
+ * ceiling answered as `0n` because the collateral is too small for this market
28
+ * would tell a form nothing about what it is holding — the number a user needs
29
+ * to see is the one they are short of. Collateral that carries something
30
+ * therefore answers with it, whether or not the market would lend that little;
31
+ * a loan under the floor is refused by `borrow` itself, with `debtOutOfRange`
32
+ * naming both ends.
33
+ *
34
+ * Nothing is fetched or simulated — the account does not exist yet and every
35
+ * input is loaded market state, so a form can call this on each keystroke.
36
+ *
37
+ * @param props - {@link MaxBorrowProps}
38
+ * @returns Amount in the payout token's units; `0n` where no loan of this
39
+ * shape exists at any size — a collateral that backs nothing at safe prices, a
40
+ * market with nothing left to lend, and a manager the SDK does not hold yet
41
+ **/
42
+ function maxBorrow(props) {
43
+ const { sdk, creditManager, collateralAmount, targetHF, quotaReserve } = props;
44
+ const found = resolveCreditManager(sdk, creditManager);
45
+ if (!found) return 0n;
46
+ const { suite, market } = found;
47
+ const { priceOracle } = market;
48
+ const underlying = market.pool.underlying.toLowerCase();
49
+ const collateralToken = props.collateralToken.toLowerCase();
50
+ const borrowToken = props.borrowToken.toLowerCase();
51
+ const rwaAsset = sdk.tokensMeta.rwaUnderlyings.get(underlying)?.asset?.toLowerCase();
52
+ if (eq(collateralToken, borrowToken)) return 0n;
53
+ if (rwaAsset && eq(borrowToken, underlying)) return 0n;
54
+ if (collateralAmount <= 10n || targetHF <= 0n) return 0n;
55
+ const quotas = borrowCollateralQuota({
56
+ sdk,
57
+ creditManager,
58
+ assets: [{
59
+ token: collateralToken,
60
+ balance: collateralAmount
61
+ }],
62
+ quotaReserve
63
+ });
64
+ const holding = {
65
+ token: collateralToken,
66
+ balance: collateralAmount,
67
+ quota: quotas.find((q) => eq(q.token, collateralToken))?.balance ?? 0n,
68
+ mask: 0n,
69
+ success: true
70
+ };
71
+ const valuation = collateralValuation({
72
+ ...unopenedAccountSlice({
73
+ creditManager,
74
+ creditFacade: suite.creditFacade.address,
75
+ underlying
76
+ }),
77
+ tokens: [holding]
78
+ }, sdk);
79
+ const weighted = valuation.checkedUsd(holding) * valuation.lt(collateralToken);
80
+ const backed = quotas.some((q) => eq(q.token, collateralToken)) ? BigIntMath.min(valuation.quotaValue(holding), weighted) : weighted;
81
+ if (backed <= 0n) return 0n;
82
+ const ceiling = BigIntMath.min(priceOracle.safeConvertFromUSD(underlying, backed / targetHF).value, suite.maxBorrowAmount().amount.value);
83
+ const unwrapsPayout = !!rwaAsset && eq(borrowToken, rwaAsset);
84
+ return eq(borrowToken, underlying) ? ceiling : unwrapsPayout ? toTargetDecimals(ceiling, underlying, borrowToken, sdk) : priceOracle.safeConvert(underlying, borrowToken, ceiling).value;
85
+ }
86
+ //#endregion
87
+ export { maxBorrow };
@@ -1,21 +1,17 @@
1
1
  import { BigIntMath } from "../../utils/bigint-math.js";
2
- import { PERCENTAGE_FACTOR } from "../../constants/math.js";
2
+ import "../../constants/math.js";
3
3
  import "../../utils/index.js";
4
4
  import { eq } from "./utils/common.js";
5
+ import { collateralValuation } from "./collateral-valuation.js";
5
6
  //#region src/onchain/accounts/intents/maxWithdrawCollateral.ts
6
7
  /**
7
8
  * Largest amount of one collateral the account can withdraw while its health
8
9
  * factor stays at or above `targetHF`.
9
10
  *
10
11
  * This is the collateral check solved for one balance, and it counts what that
11
- * check counts: a holding backed by a quota contributes the lesser of the
12
- * quota and its threshold-weighted value, an unquoted one — the underlying —
13
- * its weighted value alone, and dust or a disabled balance nothing at all.
14
- * Collateral is valued at the protocol safe price (`min` of the two feeds,
15
- * 0 when there is no reserve), the way the facade values a call that hands
16
- * funds over; the underlying is exempt and is valued at the main feed, as
17
- * `CreditManagerV3._safeConvertToUSD` does. The debt is valued at the main
18
- * feed, as the check does. Zero debt frees the whole balance.
12
+ * check counts — see {@link collateralValuation} for it, safe prices included.
13
+ * The debt is valued at the main feed, as the check does. Zero debt frees the
14
+ * whole balance.
19
15
  *
20
16
  * Rounding always favours the account, so the answer clears the check rather
21
17
  * than landing a wei short of it.
@@ -26,49 +22,27 @@ import { eq } from "./utils/common.js";
26
22
  **/
27
23
  function maxWithdrawCollateral(props) {
28
24
  const { creditAccount, sdk, token, targetHF } = props;
29
- const { market, creditManager } = sdk.marketRegister.findCreditManager(creditAccount.creditManager);
30
- const { priceOracle } = market;
31
- const { pqk } = market.pool;
32
- const underlying = market.pool.underlying;
33
25
  const target = creditAccount.tokens.find((t) => eq(t.token, token));
34
26
  if (!target || target.balance <= 10n) return 0n;
35
27
  if (creditAccount.totalDebt === 0n) return target.balance;
36
- const masked = creditAccount.enabledTokensMask !== 0n;
37
- const counts = (t) => t.balance > 10n && (!masked || (t.mask & creditAccount.enabledTokensMask) !== 0n);
38
- /** What a holding backs, in the check's units: USD × PERCENTAGE_FACTOR. */
39
- const weigh = (t) => {
40
- const lt = BigInt(creditManager.liquidationThresholds.get(t.token) ?? 0);
41
- const weighted = (eq(t.token, underlying) ? usd(priceOracle, t.token, t.balance) ?? 0n : priceOracle.safeConvertMinUSD(t.token, t.balance).value) * lt;
42
- if (t.quota === 0n) return weighted;
43
- return BigIntMath.min(quotaUsd(t) * PERCENTAGE_FACTOR, weighted);
44
- };
45
- /** A quota is underlying-denominated, and a closed market backs nothing. */
46
- const quotaUsd = (t) => pqk.hasActiveQuota(t.token) ? usd(priceOracle, underlying, t.quota) ?? 0n : 0n;
47
- let otherMoney = 0n;
28
+ const valuation = collateralValuation(creditAccount, sdk);
29
+ let otherValue = 0n;
48
30
  for (const t of creditAccount.tokens) {
49
- if (eq(t.token, token) || !counts(t)) continue;
50
- otherMoney += weigh(t);
31
+ if (eq(t.token, token) || !valuation.counts(t)) continue;
32
+ otherValue += valuation.weigh(t);
51
33
  }
52
- const borrowed = usd(priceOracle, underlying, creditAccount.totalDebt);
34
+ const borrowed = valuation.mainUsd(valuation.underlying, creditAccount.totalDebt);
53
35
  if (borrowed === void 0 || borrowed <= 0n) return 0n;
54
36
  const required = borrowed * targetHF;
55
- if (required <= otherMoney) return target.balance;
56
- const shortfall = required - otherMoney;
57
- if (target.quota > 0n && quotaUsd(target) * 10000n < shortfall) return 0n;
58
- const targetLt = BigInt(creditManager.liquidationThresholds.get(target.token) ?? 0);
59
- const targetUsd = eq(target.token, underlying) ? usd(priceOracle, target.token, target.balance) ?? 0n : priceOracle.safeConvertMinUSD(target.token, target.balance).value;
37
+ if (required <= otherValue) return target.balance;
38
+ const shortfall = required - otherValue;
39
+ if (target.quota > 0n && valuation.quotaValue(target) < shortfall) return 0n;
40
+ const targetLt = valuation.lt(target.token);
41
+ const targetUsd = valuation.checkedUsd(target);
60
42
  if (targetLt === 0n || targetUsd === 0n) return 0n;
61
43
  const keptUsd = BigIntMath.ceilDiv(shortfall, targetLt);
62
44
  const kept = BigIntMath.ceilDiv(target.balance * keptUsd, targetUsd);
63
45
  return kept >= target.balance ? 0n : target.balance - kept;
64
46
  }
65
- /** USD value at the main feed, or `undefined` when the token has no price. */
66
- function usd(oracle, token, amount) {
67
- try {
68
- return oracle.convertToUSD(token, amount);
69
- } catch {
70
- return;
71
- }
72
- }
73
47
  //#endregion
74
48
  export { maxWithdrawCollateral };
@@ -3,17 +3,13 @@ import "../../../model/index.js";
3
3
  import { IntentPreviewError } from "../../validation/raise.js";
4
4
  import { assertCanBorrow, assertCollateralised, assertGrowthAllowed, assertMarketOperable, assertQuotaAvailable } from "./guards.js";
5
5
  import { assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage } from "./math.js";
6
+ import { unopenedAccountSlice } from "./utils/credit-account-slice.js";
6
7
  import { collectPriceImpact } from "./utils/price-impact.js";
7
8
  import { getQuotasForUpdate } from "./utils/quotas-for-update.js";
8
9
  import { createRouterPaths } from "./utils/router-path.js";
9
10
  import "./utils/index.js";
10
11
  //#region src/onchain/accounts/intents/open-strategy.ts
11
12
  /**
12
- * Stand-in account address, used when the opening creates its own account:
13
- * nothing exists on chain until the tx lands.
14
- */
15
- const NO_ACCOUNT = "0x0000000000000000000000000000000000000000";
16
- /**
17
13
  * Builds the state opening a leveraged position out of wallet collateral would
18
14
  * reach.
19
15
  *
@@ -26,7 +22,6 @@ const NO_ACCOUNT = "0x0000000000000000000000000000000000000000";
26
22
  * `sdk.accounts.openCA`.
27
23
  */
28
24
  async function buildOpenStrategyState(props) {
29
- if (props.empty) return emptyOpenState(props);
30
25
  const { sdk, creditManager, collateral, targetToken, leverage, slippage = 0, quotaReserve, leftoverBalances = [], creditAccount: existing } = props;
31
26
  assertLeverageAtLeastOne(leverage);
32
27
  const suite = sdk.marketRegister.findCreditManager(creditManager);
@@ -37,16 +32,11 @@ async function buildOpenStrategyState(props) {
37
32
  const margin = collateral.reduce((acc, a) => acc + convert(a.token, underlying, a.balance), 0n);
38
33
  if (margin <= 0n) throw new IntentPreviewError(insufficientBalance(), "openStrategy: collateral is worth nothing in underlying");
39
34
  const debt = debtForLeverage(margin, leverage);
40
- const account = existing ?? {
41
- creditAccount: NO_ACCOUNT,
42
- creditManager: creditManager.toLowerCase(),
43
- creditFacade: suite.creditFacade.address.toLowerCase(),
44
- underlying,
45
- enabledTokensMask: 0n,
46
- totalDebtUSD: 0n,
47
- totalDebt: 0n,
48
- tokens: []
49
- };
35
+ const account = existing ?? unopenedAccountSlice({
36
+ creditManager,
37
+ creditFacade: suite.creditFacade.address,
38
+ underlying
39
+ });
50
40
  assertDebtLimits(sdk, debt, suite.creditFacade, underlying);
51
41
  assertCanBorrow(sdk, suite, debt);
52
42
  const paths = createRouterPaths({
@@ -96,7 +86,8 @@ async function buildOpenStrategyState(props) {
96
86
  const priceImpact = await collectPriceImpact(leg.probe ? [leg.probe] : [], {
97
87
  totalValue: margin + debt,
98
88
  netValue: margin,
99
- toUnderlying: (from, amount) => convert(from, underlying, amount)
89
+ toUnderlying: (from, amount) => convert(from, underlying, amount),
90
+ toUnderlyingAmount: market.toUnderlyingAmount
100
91
  });
101
92
  return {
102
93
  ...projection,
@@ -110,35 +101,6 @@ async function buildOpenStrategyState(props) {
110
101
  creditAccount: existing?.creditAccount
111
102
  };
112
103
  }
113
- /**
114
- * The opening that holds an account and nothing else.
115
- *
116
- * Taken before the walk rather than threaded through it: the router has no
117
- * guard for an empty basket and would still make its `eth_call`, and every
118
- * assertion below reads amounts that are not there.
119
- */
120
- async function emptyOpenState(props) {
121
- const { sdk, creditManager } = props;
122
- assertMarketOperable(sdk.marketRegister.findCreditManager(creditManager));
123
- const snapshot = {
124
- creditManager,
125
- assets: [],
126
- quotas: [],
127
- totalDebt: 0n,
128
- totalValue: 0n
129
- };
130
- const { assets: _assets, quotas: _quotas, ...projection } = sdk.positions.projection(snapshot, { availableLiquidityChange: 0n });
131
- return {
132
- ...projection,
133
- currentPrice: sdk.positions.currentPrice(snapshot),
134
- priceImpact: void 0,
135
- averageAssets: [],
136
- minAssets: [],
137
- averageQuota: [],
138
- minQuota: [],
139
- calls: []
140
- };
141
- }
142
104
  /** Collateral plus the borrowed underlying, folded into one balance per token. */
143
105
  function mergeExpectedBalances(collateral, underlying, debt) {
144
106
  const merged = /* @__PURE__ */ new Map();
@@ -54,7 +54,6 @@ function buildSwapOperation(input) {
54
54
  * underlying comes out.
55
55
  */
56
56
  function buildCloseSwapOperation(input) {
57
- if (input.calls.length === 0) throw new Error("swap: missing router calls");
58
57
  return {
59
58
  type: "swap",
60
59
  from: input.from,
@@ -6,7 +6,7 @@ import "../../../model/index.js";
6
6
  import { toToken, toTokenAmount } from "../../validation/helpers/token.js";
7
7
  import { IntentPreviewError } from "../../validation/raise.js";
8
8
  import { eq } from "./utils/common.js";
9
- import { assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage, proportionalDebt } from "./math.js";
9
+ import { SETTLE_MARGIN, assertDebtLimits, assertLeverageAtLeastOne, debtForLeverage, proportionalDebt } from "./math.js";
10
10
  //#region src/onchain/accounts/intents/plan.ts
11
11
  /** Whatever the previous convert produced. */
12
12
  const RAISED = { raised: true };
@@ -360,13 +360,6 @@ const claim = (claimable) => ({
360
360
  claimable
361
361
  });
362
362
  const clearQuotas = () => ({ kind: "clearQuotas" });
363
- /**
364
- * Headroom a settlement raises on top of the debt it read, in
365
- * `PERCENTAGE_FACTOR`: enough interest for the transaction to sit in the
366
- * mempool for hours at any sane borrow rate, small enough not to matter to the
367
- * wallet that fronts it.
368
- */
369
- const SETTLE_MARGIN = 10n;
370
363
  const withMargin = (debt) => debt + debt * SETTLE_MARGIN / PERCENTAGE_FACTOR;
371
364
  /** The amount that asks for all of it, whatever "all" turns out to be. */
372
365
  const everything = (amount) => amount >= MAX_UINT256;