@morpho-org/morpho-sdk 10.0.1 → 10.1.0-next.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 (250) hide show
  1. package/README.md +31 -10
  2. package/lib/cjs/abis.d.ts +1 -1
  3. package/lib/cjs/abis.js +5 -1
  4. package/lib/cjs/actions/blue/refinance.d.ts +1 -1
  5. package/lib/cjs/actions/blue/refinance.js +3 -8
  6. package/lib/cjs/actions/blue/refinanceValidation.d.ts +19 -0
  7. package/lib/cjs/actions/blue/refinanceValidation.js +46 -0
  8. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  9. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -7
  10. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +1 -1
  11. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +4 -20
  12. package/lib/cjs/actions/requirements/getRequirementsApproval.js +7 -21
  13. package/lib/cjs/actions/requirements/validateClientChainId.d.ts +1 -26
  14. package/lib/cjs/actions/requirements/validateClientChainId.js +2 -31
  15. package/lib/cjs/actions/vaultV2/forceRedeem.d.ts +2 -1
  16. package/lib/cjs/actions/vaultV2/forceRedeem.js +20 -2
  17. package/lib/cjs/blue/abis.d.ts +1 -1
  18. package/lib/cjs/blue/abis.js +5 -1
  19. package/lib/cjs/blue/entities.d.ts +4 -4
  20. package/lib/cjs/blue/entities.js +3 -1
  21. package/lib/cjs/blue/errors.d.ts +2 -2
  22. package/lib/cjs/blue/errors.js +5 -1
  23. package/lib/cjs/blue/fetch.d.ts +2 -2
  24. package/lib/cjs/blue/fetch.js +3 -1
  25. package/lib/cjs/blue/utils.d.ts +1 -1
  26. package/lib/cjs/blue/utils.js +2 -1
  27. package/lib/cjs/entities/blue/blue.js +24 -55
  28. package/lib/cjs/entities/index.d.ts +4 -4
  29. package/lib/cjs/entities/index.js +3 -1
  30. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +2 -5
  31. package/lib/cjs/entities/requirements/getErc2612Permit.js +9 -58
  32. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
  33. package/lib/cjs/entities/vaultV2/vaultV2.js +39 -1
  34. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -2
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.js +6 -2
  36. package/lib/cjs/errors.d.ts +4 -4
  37. package/lib/cjs/errors.js +7 -5
  38. package/lib/cjs/fetch.d.ts +2 -2
  39. package/lib/cjs/fetch.js +3 -1
  40. package/lib/cjs/helpers/deadShares.js +3 -0
  41. package/lib/cjs/helpers/quoteBlueRepay.d.ts +16 -0
  42. package/lib/cjs/helpers/quoteBlueRepay.js +46 -0
  43. package/lib/cjs/helpers/tokenApproval.d.ts +14 -0
  44. package/lib/cjs/helpers/tokenApproval.js +20 -0
  45. package/lib/cjs/helpers/validate.d.ts +1 -1
  46. package/lib/cjs/helpers/validate.js +2 -2
  47. package/lib/cjs/index.d.ts +2 -2
  48. package/lib/cjs/index.js +13 -1
  49. package/lib/cjs/midnight/errors.d.ts +2 -1
  50. package/lib/cjs/midnight/errors.js +5 -4
  51. package/lib/cjs/reads/readErc2612Permit.d.ts +22 -0
  52. package/lib/cjs/reads/readErc2612Permit.js +77 -0
  53. package/lib/cjs/reads/validateClientChainId.d.ts +26 -0
  54. package/lib/cjs/reads/validateClientChainId.js +34 -0
  55. package/lib/cjs/transactionPlan/blue/authorization.d.ts +23 -0
  56. package/lib/cjs/transactionPlan/blue/authorization.js +128 -0
  57. package/lib/cjs/transactionPlan/blue/borrow.d.ts +80 -0
  58. package/lib/cjs/transactionPlan/blue/borrow.js +248 -0
  59. package/lib/cjs/transactionPlan/blue/prepare.d.ts +102 -0
  60. package/lib/cjs/transactionPlan/blue/prepare.js +191 -0
  61. package/lib/cjs/transactionPlan/blue/refinance.d.ts +93 -0
  62. package/lib/cjs/transactionPlan/blue/refinance.js +281 -0
  63. package/lib/cjs/transactionPlan/blue/refinanceValidation.d.ts +11 -0
  64. package/lib/cjs/transactionPlan/blue/refinanceValidation.js +20 -0
  65. package/lib/cjs/transactionPlan/blue/repay.d.ts +80 -0
  66. package/lib/cjs/transactionPlan/blue/repay.js +229 -0
  67. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.d.ts +98 -0
  68. package/lib/cjs/transactionPlan/blue/repayWithdrawCollateral.js +379 -0
  69. package/lib/cjs/transactionPlan/blue/supply.d.ts +181 -0
  70. package/lib/cjs/transactionPlan/blue/supply.js +238 -0
  71. package/lib/cjs/transactionPlan/blue/supplyCollateral.d.ts +97 -0
  72. package/lib/cjs/transactionPlan/blue/supplyCollateral.js +231 -0
  73. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.d.ts +102 -0
  74. package/lib/cjs/transactionPlan/blue/supplyCollateralBorrow.js +395 -0
  75. package/lib/cjs/transactionPlan/blue/withdraw.d.ts +136 -0
  76. package/lib/cjs/transactionPlan/blue/withdraw.js +340 -0
  77. package/lib/cjs/transactionPlan/blue/withdrawCollateral.d.ts +123 -0
  78. package/lib/cjs/transactionPlan/blue/withdrawCollateral.js +246 -0
  79. package/lib/cjs/transactionPlan/deposit.js +8 -19
  80. package/lib/cjs/transactionPlan/error.d.ts +50 -0
  81. package/lib/cjs/transactionPlan/error.js +60 -1
  82. package/lib/cjs/transactionPlan/getTokenPermit.d.ts +17 -8
  83. package/lib/cjs/transactionPlan/getTokenPermit.js +35 -7
  84. package/lib/cjs/transactionPlan/index.d.ts +21 -1
  85. package/lib/cjs/transactionPlan/index.js +27 -5
  86. package/lib/cjs/transactionPlan/intent.d.ts +2 -2
  87. package/lib/cjs/transactionPlan/intent.js +8 -4
  88. package/lib/cjs/transactionPlan/permit.d.ts +16 -2
  89. package/lib/cjs/transactionPlan/permit.js +77 -45
  90. package/lib/cjs/transactionPlan/plan.d.ts +67 -12
  91. package/lib/cjs/transactionPlan/plan.js +284 -50
  92. package/lib/cjs/transactionPlan/requirements.d.ts +14 -5
  93. package/lib/cjs/transactionPlan/requirements.js +30 -12
  94. package/lib/cjs/transactionPlan/serde.d.ts +7 -4
  95. package/lib/cjs/transactionPlan/serde.js +80 -61
  96. package/lib/cjs/transactionPlan/types.d.ts +141 -13
  97. package/lib/cjs/transactionPlan/validateActions.js +11 -1
  98. package/lib/cjs/transactionPlan/validation.d.ts +8 -0
  99. package/lib/cjs/transactionPlan/validation.js +90 -0
  100. package/lib/cjs/transactionPlan/vaultv1/deposit.d.ts +1 -0
  101. package/lib/cjs/transactionPlan/vaultv1/deposit.js +1 -0
  102. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.d.ts +1 -0
  103. package/lib/cjs/transactionPlan/vaultv1/inKindRedeem.js +1 -0
  104. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.d.ts +1 -0
  105. package/lib/cjs/transactionPlan/vaultv1/migrateToV2.js +1 -0
  106. package/lib/cjs/transactionPlan/vaultv1/redeem.d.ts +1 -0
  107. package/lib/cjs/transactionPlan/vaultv1/redeem.js +1 -0
  108. package/lib/cjs/transactionPlan/vaultv1/withdraw.d.ts +1 -0
  109. package/lib/cjs/transactionPlan/vaultv1/withdraw.js +1 -0
  110. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +1 -0
  111. package/lib/cjs/transactionPlan/vaultv2/deposit.js +1 -0
  112. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.d.ts +1 -0
  113. package/lib/cjs/transactionPlan/vaultv2/forceRedeem.js +1 -0
  114. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.d.ts +1 -0
  115. package/lib/cjs/transactionPlan/vaultv2/forceWithdraw.js +1 -0
  116. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.d.ts +1 -0
  117. package/lib/cjs/transactionPlan/vaultv2/inKindRedeem.js +1 -0
  118. package/lib/cjs/transactionPlan/vaultv2/redeem.d.ts +1 -0
  119. package/lib/cjs/transactionPlan/vaultv2/redeem.js +1 -0
  120. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +1 -0
  121. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +1 -0
  122. package/lib/cjs/utils.d.ts +2 -2
  123. package/lib/cjs/utils.js +4 -2
  124. package/lib/cjs/version.d.ts +1 -1
  125. package/lib/cjs/version.js +1 -1
  126. package/lib/esm/abis.d.ts +1 -1
  127. package/lib/esm/abis.js +1 -1
  128. package/lib/esm/actions/blue/refinance.d.ts +1 -1
  129. package/lib/esm/actions/blue/refinance.js +4 -9
  130. package/lib/esm/actions/blue/refinanceValidation.d.ts +19 -0
  131. package/lib/esm/actions/blue/refinanceValidation.js +41 -0
  132. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  133. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +4 -8
  134. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +1 -1
  135. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -21
  136. package/lib/esm/actions/requirements/getRequirementsApproval.js +7 -21
  137. package/lib/esm/actions/requirements/validateClientChainId.d.ts +1 -26
  138. package/lib/esm/actions/requirements/validateClientChainId.js +1 -30
  139. package/lib/esm/actions/vaultV2/forceRedeem.d.ts +2 -1
  140. package/lib/esm/actions/vaultV2/forceRedeem.js +20 -2
  141. package/lib/esm/blue/abis.d.ts +1 -1
  142. package/lib/esm/blue/abis.js +1 -1
  143. package/lib/esm/blue/entities.d.ts +4 -4
  144. package/lib/esm/blue/entities.js +2 -2
  145. package/lib/esm/blue/errors.d.ts +2 -2
  146. package/lib/esm/blue/errors.js +2 -2
  147. package/lib/esm/blue/fetch.d.ts +2 -2
  148. package/lib/esm/blue/fetch.js +2 -2
  149. package/lib/esm/blue/utils.d.ts +1 -1
  150. package/lib/esm/blue/utils.js +1 -1
  151. package/lib/esm/entities/blue/blue.js +26 -57
  152. package/lib/esm/entities/index.d.ts +4 -4
  153. package/lib/esm/entities/index.js +2 -2
  154. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +2 -5
  155. package/lib/esm/entities/requirements/getErc2612Permit.js +9 -58
  156. package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
  157. package/lib/esm/entities/vaultV2/vaultV2.js +40 -2
  158. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -2
  159. package/lib/esm/entities/vaultV2BlueReallocationData.js +6 -2
  160. package/lib/esm/errors.d.ts +4 -4
  161. package/lib/esm/errors.js +4 -4
  162. package/lib/esm/fetch.d.ts +2 -2
  163. package/lib/esm/fetch.js +2 -2
  164. package/lib/esm/helpers/deadShares.js +4 -1
  165. package/lib/esm/helpers/quoteBlueRepay.d.ts +16 -0
  166. package/lib/esm/helpers/quoteBlueRepay.js +42 -0
  167. package/lib/esm/helpers/tokenApproval.d.ts +14 -0
  168. package/lib/esm/helpers/tokenApproval.js +16 -0
  169. package/lib/esm/helpers/validate.d.ts +1 -1
  170. package/lib/esm/helpers/validate.js +3 -3
  171. package/lib/esm/index.d.ts +2 -2
  172. package/lib/esm/index.js +1 -1
  173. package/lib/esm/midnight/errors.d.ts +2 -1
  174. package/lib/esm/midnight/errors.js +2 -1
  175. package/lib/esm/reads/readErc2612Permit.d.ts +22 -0
  176. package/lib/esm/reads/readErc2612Permit.js +73 -0
  177. package/lib/esm/reads/validateClientChainId.d.ts +26 -0
  178. package/lib/esm/reads/validateClientChainId.js +30 -0
  179. package/lib/esm/transactionPlan/blue/authorization.d.ts +23 -0
  180. package/lib/esm/transactionPlan/blue/authorization.js +122 -0
  181. package/lib/esm/transactionPlan/blue/borrow.d.ts +80 -0
  182. package/lib/esm/transactionPlan/blue/borrow.js +243 -0
  183. package/lib/esm/transactionPlan/blue/prepare.d.ts +102 -0
  184. package/lib/esm/transactionPlan/blue/prepare.js +187 -0
  185. package/lib/esm/transactionPlan/blue/refinance.d.ts +93 -0
  186. package/lib/esm/transactionPlan/blue/refinance.js +276 -0
  187. package/lib/esm/transactionPlan/blue/refinanceValidation.d.ts +11 -0
  188. package/lib/esm/transactionPlan/blue/refinanceValidation.js +17 -0
  189. package/lib/esm/transactionPlan/blue/repay.d.ts +80 -0
  190. package/lib/esm/transactionPlan/blue/repay.js +223 -0
  191. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.d.ts +98 -0
  192. package/lib/esm/transactionPlan/blue/repayWithdrawCollateral.js +373 -0
  193. package/lib/esm/transactionPlan/blue/supply.d.ts +181 -0
  194. package/lib/esm/transactionPlan/blue/supply.js +232 -0
  195. package/lib/esm/transactionPlan/blue/supplyCollateral.d.ts +97 -0
  196. package/lib/esm/transactionPlan/blue/supplyCollateral.js +225 -0
  197. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.d.ts +102 -0
  198. package/lib/esm/transactionPlan/blue/supplyCollateralBorrow.js +389 -0
  199. package/lib/esm/transactionPlan/blue/withdraw.d.ts +136 -0
  200. package/lib/esm/transactionPlan/blue/withdraw.js +334 -0
  201. package/lib/esm/transactionPlan/blue/withdrawCollateral.d.ts +123 -0
  202. package/lib/esm/transactionPlan/blue/withdrawCollateral.js +240 -0
  203. package/lib/esm/transactionPlan/deposit.js +9 -20
  204. package/lib/esm/transactionPlan/error.d.ts +50 -0
  205. package/lib/esm/transactionPlan/error.js +57 -0
  206. package/lib/esm/transactionPlan/getTokenPermit.d.ts +17 -8
  207. package/lib/esm/transactionPlan/getTokenPermit.js +35 -7
  208. package/lib/esm/transactionPlan/index.d.ts +21 -1
  209. package/lib/esm/transactionPlan/index.js +11 -1
  210. package/lib/esm/transactionPlan/intent.d.ts +2 -2
  211. package/lib/esm/transactionPlan/intent.js +8 -4
  212. package/lib/esm/transactionPlan/permit.d.ts +16 -2
  213. package/lib/esm/transactionPlan/permit.js +76 -44
  214. package/lib/esm/transactionPlan/plan.d.ts +67 -12
  215. package/lib/esm/transactionPlan/plan.js +279 -46
  216. package/lib/esm/transactionPlan/requirements.d.ts +14 -5
  217. package/lib/esm/transactionPlan/requirements.js +30 -12
  218. package/lib/esm/transactionPlan/serde.d.ts +7 -4
  219. package/lib/esm/transactionPlan/serde.js +73 -54
  220. package/lib/esm/transactionPlan/types.d.ts +141 -13
  221. package/lib/esm/transactionPlan/validateActions.js +11 -1
  222. package/lib/esm/transactionPlan/validation.d.ts +8 -0
  223. package/lib/esm/transactionPlan/validation.js +88 -1
  224. package/lib/esm/transactionPlan/vaultv1/deposit.d.ts +1 -0
  225. package/lib/esm/transactionPlan/vaultv1/deposit.js +1 -0
  226. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.d.ts +1 -0
  227. package/lib/esm/transactionPlan/vaultv1/inKindRedeem.js +1 -0
  228. package/lib/esm/transactionPlan/vaultv1/migrateToV2.d.ts +1 -0
  229. package/lib/esm/transactionPlan/vaultv1/migrateToV2.js +1 -0
  230. package/lib/esm/transactionPlan/vaultv1/redeem.d.ts +1 -0
  231. package/lib/esm/transactionPlan/vaultv1/redeem.js +1 -0
  232. package/lib/esm/transactionPlan/vaultv1/withdraw.d.ts +1 -0
  233. package/lib/esm/transactionPlan/vaultv1/withdraw.js +1 -0
  234. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +1 -0
  235. package/lib/esm/transactionPlan/vaultv2/deposit.js +1 -0
  236. package/lib/esm/transactionPlan/vaultv2/forceRedeem.d.ts +1 -0
  237. package/lib/esm/transactionPlan/vaultv2/forceRedeem.js +1 -0
  238. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.d.ts +1 -0
  239. package/lib/esm/transactionPlan/vaultv2/forceWithdraw.js +1 -0
  240. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.d.ts +1 -0
  241. package/lib/esm/transactionPlan/vaultv2/inKindRedeem.js +1 -0
  242. package/lib/esm/transactionPlan/vaultv2/redeem.d.ts +1 -0
  243. package/lib/esm/transactionPlan/vaultv2/redeem.js +1 -0
  244. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +1 -0
  245. package/lib/esm/transactionPlan/vaultv2/withdraw.js +1 -0
  246. package/lib/esm/utils.d.ts +2 -2
  247. package/lib/esm/utils.js +2 -2
  248. package/lib/esm/version.d.ts +1 -1
  249. package/lib/esm/version.js +1 -1
  250. package/package.json +7 -7
@@ -0,0 +1,334 @@
1
+ import { AccrualPosition, MarketParams, } from "@morpho-org/blue-sdk";
2
+ import { deepFreeze } from "@morpho-org/morpho-ts";
3
+ import { zeroAddress } from "viem";
4
+ import { getBlueBundlesV1PenaltyAssets } from "../../actions/blue/common.js";
5
+ import { blueWithdraw } from "../../actions/blue/withdraw.js";
6
+ import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
7
+ import { validateVaultV2BlueReallocations, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/validate.js";
8
+ import { InputExceedsMaxError, MissingAccrualPositionError, } from "../../types/index.js";
9
+ import { IncompleteTransactionPlanError, InvalidTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
10
+ import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
11
+ import { validateMorphoAuthorizationRequest } from "./authorization.js";
12
+ import { prepareBlue, } from "./prepare.js";
13
+ /**
14
+ * Prepares a BlueBundlesV1 withdrawal with only Morpho authorization prerequisites, never token approvals.
15
+ * The caller supplies market and position snapshots; the SDK reads authorization but never signs.
16
+ * Share-based withdrawals have no minimum-proceeds guard.
17
+ * @param client - Viem client on the requested chain.
18
+ * @param params.chainId - Chain containing the market and registered BlueBundlesV1 contract.
19
+ * @param params.account - Non-zero account whose supply position is withdrawn and which sends every plan transaction.
20
+ * @param params.marketId - Market ID matching the caller-fetched snapshot and its market tuple.
21
+ * @param params.marketData.chainId - Chain on which the market snapshot was fetched; must equal `chainId`.
22
+ * @param params.marketData.market - Caller-fetched `Market` snapshot, used to fix the market tuple and quote share-mode penalty coverage; never stored in the plan.
23
+ * @param params.positionData.chainId - Position snapshot's chain; must match `chainId`.
24
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` belonging to `account` and `marketId`; validates the withdrawal against supplied assets or shares.
25
+ * @param params.assets - Exact positive gross loan assets withdrawn in base units; exclusive with `shares`.
26
+ * @param params.shares - Exact positive supply shares burned; exclusive with `assets`, with no full-close sentinel or minimum-proceeds guarantee.
27
+ * @param params.reallocations - Optional ordered Vault V2 BluePublicAllocator inputs; defaults to an empty list. Penalties reduce withdrawal proceeds.
28
+ * @param params.reallocations[].vault - Vault whose liquidity the allocator moves.
29
+ * @param params.reallocations[].from.type - Source discriminator: `market` or `idle`.
30
+ * @param params.reallocations[].from.adapter - Source adapter, required only for a `market` source.
31
+ * @param params.reallocations[].from.marketParams.loanToken - Source market loan token, required only for a `market` source; must match the target loan token.
32
+ * @param params.reallocations[].from.marketParams.collateralToken - Source market collateral token, required only for a `market` source.
33
+ * @param params.reallocations[].from.marketParams.oracle - Source market oracle, required only for a `market` source.
34
+ * @param params.reallocations[].from.marketParams.irm - Source market interest-rate model, required only for a `market` source.
35
+ * @param params.reallocations[].from.marketParams.lltv - Source market WAD-scaled liquidation LTV, required only for a `market` source.
36
+ * @param params.reallocations[].to.adapter - Target adapter supplying the enclosing withdrawal market.
37
+ * @param params.reallocations[].assets - Positive reallocated assets in loan-token base units, bounded by uint128.
38
+ * @param params.reallocations[].penalty - Vault-configured WAD-scaled penalty, bounded by uint64 and applied with upward rounding per allocation.
39
+ * @param params.referralFee.bps - Optional integer referral fee in basis points of gross proceeds after allocator penalties; defaults to zero and must be below 10,000.
40
+ * @param params.referralFee.recipient - Optional fee recipient; required and non-zero when `referralFee.bps` is positive.
41
+ * @param params.supportSignature - Optional Morpho authorization signature preference; defaults to `false`, selecting a direct authorization transaction when needed. Neither mode requests a token allowance or Permit2 signature.
42
+ * @param params.now - Optional reference timestamp in seconds, normally the latest block timestamp; defaults to the device clock.
43
+ * @param params.expiresAt - Optional Unix expiry in safe-integer seconds, later than `now`; defaults to `now + 2h`.
44
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to every built transaction; omitted by default.
45
+ * @param params.deployless - Optional shared intent field; unused because withdrawal reads no token metadata.
46
+ * @returns A deep-frozen, data-only `{ version, chainId, account, expiresAt, steps, signatureRequests, calldataOrigin? }` plan with a withdrawal step. Direct Morpho authorization is a preceding step; signed authorization is consumed inline by the withdrawal. Attach signatures before building.
47
+ * @throws {ChainIdMismatchError} when the client declares or its transport serves another chain.
48
+ * @throws {UnsupportedChainIdError} when `chainId` is absent from the registry.
49
+ * @throws {UnknownAddressError} when Blue or BlueBundlesV1 is not registered on `chainId`.
50
+ * @throws {BlueSnapshotChainMismatchError} when a market or supplied position snapshot's chain differs from `chainId`.
51
+ * @throws {MarketIdMismatchError} when a market or supplied position snapshot's ID differs from `marketId` or does not hash from its market tuple.
52
+ * @throws {AccrualPositionUserMismatchError} when a supplied position belongs to another account.
53
+ * @throws {ZeroAccountError} when `account` is the zero address.
54
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
55
+ * @throws {NonPositiveInputError} when expiry, the selected withdrawal amount, or a reallocation amount is not positive.
56
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
57
+ * @throws {NegativeInputError} when the referral fee, a withdrawal amount, or a reallocation penalty is negative.
58
+ * @throws {InputExceedsMaxError} when referral basis points exceed 10,000, an encoded amount or penalty exceeds its ABI bound, or aggregate allocator penalties exceed withdrawn assets (the snapshot's downward-rounded asset quote in shares mode).
59
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
60
+ * @throws {InvalidVaultV2BlueReallocationShapeError} when a reallocation entry is not an object or has a legacy Vault V1 shape.
61
+ * @throws {InvalidReallocationAddressError} when a reallocation vault or adapter address is malformed.
62
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source discriminator or source market tuple is malformed.
63
+ * @throws {InconsistentReallocationPenaltyError} when allocations from one vault specify different penalties.
64
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation source is the withdrawal market.
65
+ * @throws {MutuallyExclusiveWithdrawAmountsError} when both withdrawal modes are nonzero.
66
+ * @throws {ReferralFeePctExceededError} when `referralFee.bps` equals 10,000.
67
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no non-zero recipient.
68
+ * @throws {ReallocationLoanTokenMismatchError} when a source market uses another loan token.
69
+ * @throws {MissingAccrualPositionError} when the required position snapshot is missing.
70
+ * @throws {WithdrawExceedsSupplyError} when `assets` exceeds the position's supplied assets.
71
+ * @throws {WithdrawSharesExceedSupplyError} when `shares` exceeds the position's supply shares.
72
+ * @throws {MissingContractCodeError} when registered BlueBundlesV1 or Blue has no deployed code.
73
+ * @throws {viem.BaseError} when a chain, bytecode, authorization or nonce RPC read fails, or ABI encoding rejects malformed input.
74
+ * @throws {UnexpectedRequirementSignatureError} when an authorization requirement returns a nonce that is not a bigint.
75
+ * @throws {TransactionPlanSignatureMismatchError} when the authorization requirement does not match the prepared account, chain, nonce or deadline.
76
+ * @example
77
+ * ```ts
78
+ * import { markets } from "@morpho-org/morpho-test";
79
+ * import { prepareBlueWithdraw, type TransactionPlan } from "@morpho-org/morpho-sdk";
80
+ * import { fetchBlueAccrualPosition } from "@morpho-org/morpho-sdk/fetch";
81
+ * import { createPublicClient, type Address, http } from "viem";
82
+ * import { mainnet } from "viem/chains";
83
+ *
84
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
85
+ * declare const account: Address; // Connected wallet holding a Blue supply position.
86
+ * const position = await fetchBlueAccrualPosition(account, markets[mainnet.id].usdc_wbtc.id, client);
87
+ * const market = position.market;
88
+ * const plan: TransactionPlan = await prepareBlueWithdraw(client, {
89
+ * chainId: mainnet.id, account, marketId: market.id,
90
+ * marketData: { chainId: mainnet.id, market }, assets: 1_000_000n,
91
+ * positionData: { chainId: mainnet.id, position },
92
+ * now: (await client.getBlock()).timestamp,
93
+ * });
94
+ * // plan: { version: 1, chainId, account, expiresAt, steps, signatureRequests }
95
+ * // Sign any pending Morpho authorization request, then build and submit each step in order.
96
+ * ```
97
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
98
+ */
99
+ export async function prepareBlueWithdraw(client, params) {
100
+ await validateClientChainId(client, params.chainId);
101
+ const { positionData: snapshot } = params;
102
+ if (snapshot == null) {
103
+ throw new MissingAccrualPositionError(params.marketId);
104
+ }
105
+ const withdrawals = [];
106
+ const { intent: resolvedIntent, steps, signatureRequests, } = await prepareBlue({ client, params }, (intent) => {
107
+ const inputs = {
108
+ chainId: params.chainId,
109
+ account: params.account,
110
+ marketParams: {
111
+ loanToken: params.marketData.market.params.loanToken,
112
+ collateralToken: params.marketData.market.params.collateralToken,
113
+ oracle: params.marketData.market.params.oracle,
114
+ irm: params.marketData.market.params.irm,
115
+ lltv: params.marketData.market.params.lltv,
116
+ },
117
+ withdrawAssets: "assets" in params ? (params.assets ?? 0n) : 0n,
118
+ withdrawShares: "shares" in params ? (params.shares ?? 0n) : 0n,
119
+ reallocations: params.reallocations ?? [],
120
+ deadline: intent.deadline,
121
+ referralFeePct: intent.referralFeePct,
122
+ referralFeeRecipient: intent.referralFeeRecipient ?? zeroAddress,
123
+ };
124
+ // Validate all encoding constraints before authorization reads.
125
+ buildBlueWithdraw({
126
+ type: "blueWithdraw",
127
+ inputs,
128
+ signatureRequestIds: {},
129
+ });
130
+ const max = inputs.withdrawAssets > 0n
131
+ ? inputs.withdrawAssets
132
+ : params.marketData.market.toSupplyAssets(inputs.withdrawShares, "Down");
133
+ const penalty = getBlueBundlesV1PenaltyAssets(inputs.reallocations);
134
+ if (penalty > max) {
135
+ throw new InputExceedsMaxError({
136
+ field: "reallocationPenaltyAssets",
137
+ value: penalty,
138
+ max,
139
+ });
140
+ }
141
+ const positionData = new AccrualPosition(snapshot.position, snapshot.position.market);
142
+ const validateWithdrawal = inputs.withdrawShares > 0n
143
+ ? validateWithdrawShares
144
+ : validateWithdrawAmount;
145
+ // Reject over-withdrawals before requesting Morpho authorization.
146
+ validateWithdrawal({
147
+ positionData,
148
+ withdrawShares: inputs.withdrawShares,
149
+ withdrawAssets: inputs.withdrawAssets,
150
+ marketId: params.marketId,
151
+ });
152
+ withdrawals.push({
153
+ id: "blueWithdraw",
154
+ label: "Withdraw from Blue",
155
+ action: { type: "blueWithdraw", inputs, signatureRequestIds: {} },
156
+ });
157
+ return { id: "blueWithdraw", needsAuthorization: true };
158
+ });
159
+ return deepFreeze(structuredClone({
160
+ version: 2,
161
+ chainId: params.chainId,
162
+ account: params.account,
163
+ expiresAt: resolvedIntent.expiresAt,
164
+ ...(resolvedIntent.calldataOrigin && {
165
+ calldataOrigin: resolvedIntent.calldataOrigin,
166
+ }),
167
+ steps: [
168
+ ...steps,
169
+ ...withdrawals.map((step) => {
170
+ const authorization = signatureRequests.find((request) => request.kind === "morphoAuthorization");
171
+ return authorization === undefined
172
+ ? step
173
+ : {
174
+ ...step,
175
+ action: {
176
+ ...step.action,
177
+ inputs: {
178
+ ...step.action.inputs,
179
+ authorizationNonce: authorization.args.nonce,
180
+ },
181
+ signatureRequestIds: {
182
+ morphoAuthorization: authorization.id,
183
+ },
184
+ },
185
+ };
186
+ }),
187
+ ],
188
+ signatureRequests,
189
+ }));
190
+ }
191
+ /** @internal Binds an inline authorization to the withdrawal that consumes it. */
192
+ export function validateBlueWithdrawAuthorizationRequest(request, action) {
193
+ if (action.signatureRequestIds.morphoAuthorization !== request.id ||
194
+ action.inputs.authorizationNonce === undefined) {
195
+ throw new TransactionPlanSignatureMismatchError(request.id, "reference");
196
+ }
197
+ // Pin the signature to the prepared withdrawal's account, nonce and deadline.
198
+ validateMorphoAuthorizationRequest(request, {
199
+ chainId: action.inputs.chainId,
200
+ account: action.inputs.account,
201
+ nonce: action.inputs.authorizationNonce,
202
+ deadline: action.inputs.deadline,
203
+ });
204
+ }
205
+ /** @internal Encodes the self-contained withdrawal recipe and its inline authorization, if requested. */
206
+ export function buildBlueWithdraw(action, requests = []) {
207
+ const { chainId, account, marketParams, authorizationNonce: _authorizationNonce, ...args } = action.inputs;
208
+ let authorizationSignature;
209
+ const id = action.signatureRequestIds.morphoAuthorization;
210
+ if (id !== undefined) {
211
+ const request = requests.find((candidate) => candidate.id === id);
212
+ if (request?.signature === undefined) {
213
+ throw new IncompleteTransactionPlanError(id);
214
+ }
215
+ if (request.kind !== "morphoAuthorization") {
216
+ throw new TransactionPlanSignatureMismatchError(id, "reference");
217
+ }
218
+ // Reject mismatches before encoding signed authorization into the withdrawal.
219
+ validateBlueWithdrawAuthorizationRequest(request, action);
220
+ authorizationSignature = {
221
+ action: {
222
+ type: "authorization",
223
+ args: {
224
+ authorized: request.args.authorized,
225
+ isAuthorized: true,
226
+ deadline: request.args.deadline,
227
+ },
228
+ typedData: request.typedData,
229
+ },
230
+ args: {
231
+ ...request.args,
232
+ isAuthorized: true,
233
+ signature: request.signature,
234
+ },
235
+ };
236
+ }
237
+ const targetMarketParams = new MarketParams(marketParams);
238
+ // Reject malformed entries with typed errors before reading their source fields.
239
+ validateVaultV2BlueReallocations(args.reallocations, targetMarketParams.id);
240
+ const reallocations = args.reallocations.map((entry) => ({
241
+ ...entry,
242
+ from: entry.from.type === "market"
243
+ ? {
244
+ ...entry.from,
245
+ marketParams: new MarketParams(entry.from.marketParams),
246
+ }
247
+ : entry.from,
248
+ }));
249
+ return blueWithdraw({
250
+ market: { chainId, marketParams: targetMarketParams },
251
+ args: {
252
+ ...args,
253
+ reallocations,
254
+ userAddress: account,
255
+ authorizationSignature,
256
+ },
257
+ });
258
+ }
259
+ /** @internal Validates stored withdrawal scalars and allocator input shapes. */
260
+ export function validateBlueWithdrawPlanAction(action, path) {
261
+ const inputs = getPlanObject(action.inputs, `${path}.inputs`);
262
+ const roles = getPlanObject(action.signatureRequestIds, `${path}.signatureRequestIds`);
263
+ if (roles.morphoAuthorization !== undefined) {
264
+ validatePlanField(roles.morphoAuthorization, {
265
+ path: `${path}.signatureRequestIds.morphoAuthorization`,
266
+ type: "string",
267
+ });
268
+ validatePlanField(inputs.authorizationNonce, {
269
+ path: `${path}.inputs.authorizationNonce`,
270
+ type: "uint256 bigint",
271
+ });
272
+ }
273
+ validatePlanFields(inputs, {
274
+ path: `${path}.inputs`,
275
+ fields: {
276
+ withdrawAssets: "uint256 bigint",
277
+ withdrawShares: "uint256 bigint",
278
+ deadline: "uint256 bigint",
279
+ referralFeePct: "uint256 bigint",
280
+ referralFeeRecipient: "address",
281
+ reallocations: "array",
282
+ },
283
+ });
284
+ validatePlanFields(getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`), {
285
+ path: `${path}.inputs.marketParams`,
286
+ fields: {
287
+ loanToken: "address",
288
+ collateralToken: "address",
289
+ oracle: "address",
290
+ irm: "address",
291
+ lltv: "uint256 bigint",
292
+ },
293
+ });
294
+ for (const [index, value] of inputs.reallocations.entries()) {
295
+ const entryPath = `${path}.inputs.reallocations[${index}]`;
296
+ const entry = getPlanObject(value, entryPath);
297
+ validatePlanFields(entry, {
298
+ path: entryPath,
299
+ fields: {
300
+ vault: "address",
301
+ assets: "uint256 bigint",
302
+ penalty: "uint256 bigint",
303
+ },
304
+ });
305
+ validatePlanFields(getPlanObject(entry.to, `${entryPath}.to`), {
306
+ path: `${entryPath}.to`,
307
+ fields: { adapter: "address" },
308
+ });
309
+ const from = getPlanObject(entry.from, `${entryPath}.from`);
310
+ if (from.type === "idle") {
311
+ continue;
312
+ }
313
+ if (from.type !== "market") {
314
+ throw new InvalidTransactionPlanError({
315
+ path: `${entryPath}.from.type`,
316
+ reason: "expected market or idle",
317
+ });
318
+ }
319
+ validatePlanFields(from, {
320
+ path: `${entryPath}.from`,
321
+ fields: { adapter: "address" },
322
+ });
323
+ validatePlanFields(getPlanObject(from.marketParams, `${entryPath}.from.marketParams`), {
324
+ path: `${entryPath}.from.marketParams`,
325
+ fields: {
326
+ loanToken: "address",
327
+ collateralToken: "address",
328
+ oracle: "address",
329
+ irm: "address",
330
+ lltv: "uint256 bigint",
331
+ },
332
+ });
333
+ }
334
+ }
@@ -0,0 +1,123 @@
1
+ import { type MarketId } from "@morpho-org/blue-sdk";
2
+ import type { Client } from "viem";
3
+ import { type ReferenceTimestampParams } from "../../types/index.js";
4
+ import type { IntentParams } from "../intent.js";
5
+ import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
6
+ import { type BlueMarketSnapshot, type BluePositionSnapshot } from "./prepare.js";
7
+ /**
8
+ * Represents caller intent and caller-fetched snapshots for a Blue collateral withdrawal.
9
+ * The snapshots are validated and used to fix the withdrawal's buffered LTV cap before any
10
+ * authorization read; they are not stored in the resulting plan.
11
+ * @example
12
+ * ```ts
13
+ * import type { BlueWithdrawCollateralPlanParams } from "@morpho-org/morpho-sdk";
14
+ * const withdrawal = {
15
+ * collateralAssets: 1_000_000n,
16
+ * supportSignature: true,
17
+ * } satisfies Pick<BlueWithdrawCollateralPlanParams, "collateralAssets" | "supportSignature">;
18
+ * ```
19
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
20
+ */
21
+ export interface BlueWithdrawCollateralPlanParams extends IntentParams, ReferenceTimestampParams {
22
+ /** ID derived from both snapshots' market parameter tuples. */
23
+ readonly marketId: MarketId;
24
+ /** Caller-fetched market and the chain it was read from. */
25
+ readonly marketData: BlueMarketSnapshot;
26
+ /** Caller-fetched accrual position for `account` and the chain it was read from. */
27
+ readonly positionData: BluePositionSnapshot;
28
+ /** Positive collateral amount in token base units. */
29
+ readonly collateralAssets: bigint;
30
+ }
31
+ /**
32
+ * Prepares a BlueBundlesV1 collateral withdrawal with direct or inline signed Morpho authorization.
33
+ * Health is checked with the same two-hour accrual horizon and LLTV buffer as the entity handle.
34
+ * No token allowance or Permit2 prerequisite is read or produced.
35
+ * @param client - Viem client used for registered contract-code and Morpho authorization reads.
36
+ * @param params - Intent and matching market and account position snapshots.
37
+ * @param params.chainId - Chain containing the market and registered BlueBundlesV1 contract.
38
+ * @param params.account - Non-zero owner of the collateral position, authorization signer and transaction sender.
39
+ * @param params.marketId - Market ID that both snapshots and their parameter tuples must describe.
40
+ * @param params.marketData.chainId - Chain from which the market snapshot was fetched; must equal `chainId`.
41
+ * @param params.marketData.market - Caller-fetched `Market` providing the market tuple and LLTV.
42
+ * @param params.positionData.chainId - Chain from which the position snapshot was fetched; must equal `chainId`.
43
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` for `account` and `marketId`, used for the two-hour accrued health check.
44
+ * @param params.collateralAssets - Positive collateral withdrawal in token base units, not exceeding the position's collateral.
45
+ * @param params.referralFee.bps - Optional integer referral fee in basis points; defaults to zero and must be below 10,000.
46
+ * @param params.referralFee.recipient - Non-zero fee recipient required when the optional fee is positive.
47
+ * @param params.supportSignature - Optional Morpho authorization signature preference, defaulting to `false`; otherwise prepares a direct authorization transaction when needed.
48
+ * @param params.now - Optional reference timestamp in Unix seconds, normally the latest block timestamp; defaults to the device clock.
49
+ * @param params.expiresAt - Optional safe-integer Unix expiry later than `now`; defaults to `now + 2h` and governs every deadline.
50
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended verbatim to every built transaction.
51
+ * @param params.deployless - Optional shared intent field; unused because this operation reads no token metadata or allowances.
52
+ * @returns A deep-frozen, data-only `TransactionPlan` with chain, account, expiry, withdrawal step,
53
+ * and any preceding Morpho authorization step and signature request. The caller signs; the SDK never does.
54
+ * @throws {BlueSnapshotChainMismatchError} when either snapshot's chain differs from `chainId`.
55
+ * @throws {MarketIdMismatchError} when either snapshot describes another market or a market ID does not hash from its tuple.
56
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another account.
57
+ * @throws {ZeroAccountError} when `account` is the zero address.
58
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
59
+ * @throws {NonPositiveInputError} when `expiresAt` or `collateralAssets` is not positive.
60
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
61
+ * @throws {NegativeInputError} when `referralFee.bps` is negative.
62
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `collateralAssets` exceeds uint256.
63
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
64
+ * @throws {ReferralFeePctExceededError} when `referralFee.bps` equals 10,000.
65
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no non-zero recipient.
66
+ * @throws {UnsupportedMarketIrmError} when projecting an indebted position requires an unsupported IRM without rate data.
67
+ * @throws {WithdrawExceedsCollateralError} when `collateralAssets` exceeds the position's collateral.
68
+ * @throws {MissingMarketPriceError} when the position carries debt but its market price is missing or zero.
69
+ * @throws {WithdrawMakesPositionUnhealthyError} when the accrued remaining position would breach LLTV minus the default buffer.
70
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
71
+ * @throws {UnknownAddressError} when Morpho or BlueBundlesV1 is not registered on the target chain.
72
+ * @throws {MissingContractCodeError} when Morpho or BlueBundlesV1 has no deployed bytecode on the endpoint's chain.
73
+ * @throws {ChainIdMismatchError} when the client declares or its RPC reports another chain.
74
+ * @throws {viem.BaseError} when a contract-code, chain ID, authorization or nonce RPC read fails.
75
+ * @example
76
+ * ```ts
77
+ * import assert from "node:assert/strict";
78
+ * import { markets } from "@morpho-org/morpho-test";
79
+ * import { fetchAccrualPosition } from "@morpho-org/morpho-sdk/blue/fetch";
80
+ * import {
81
+ * applySignatures, buildTransactions, getPendingSignatureRequests,
82
+ * prepareBlueWithdrawCollateral,
83
+ * } from "@morpho-org/morpho-sdk";
84
+ * import { createPublicClient, createWalletClient, custom, type EIP1193Provider, http } from "viem";
85
+ * import { mainnet } from "viem/chains";
86
+ *
87
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
88
+ * const { ethereum } = window as Window & { ethereum?: EIP1193Provider };
89
+ * if (!ethereum) throw new Error("Install an Ethereum wallet to continue.");
90
+ * const wallet = createWalletClient({ chain: mainnet, transport: custom(ethereum) });
91
+ * const [account] = await wallet.requestAddresses();
92
+ * assert(account, "Connect a wallet holding collateral in this market.");
93
+ * const market = markets[mainnet.id].usdc_wbtc;
94
+ * const position = await fetchAccrualPosition(account, market.id, client);
95
+ * const plan = await prepareBlueWithdrawCollateral(client, {
96
+ * chainId: mainnet.id, account, marketId: market.id,
97
+ * marketData: { chainId: mainnet.id, market: position.market },
98
+ * positionData: { chainId: mainnet.id, position },
99
+ * collateralAssets: 1_000_000n, supportSignature: true,
100
+ * now: (await client.getBlock()).timestamp,
101
+ * });
102
+ * // plan satisfies TransactionPlan; no token approval or Permit2 request is included.
103
+ * const signatures = await Promise.all(getPendingSignatureRequests(plan).map(
104
+ * async ({ id, typedData }) => ({ id, signature: await wallet.signTypedData({ ...typedData, account }) }),
105
+ * ));
106
+ * const transactions = buildTransactions(applySignatures(plan, signatures));
107
+ * // transactions satisfies readonly Readonly<Transaction>[]; submit them in order from account.
108
+ * ```
109
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
110
+ */
111
+ export declare function prepareBlueWithdrawCollateral(client: Client, params: BlueWithdrawCollateralPlanParams): Promise<TransactionPlan>;
112
+ /** @internal Binds an inline authorization to the collateral withdrawal that consumes it. */
113
+ export declare function validateBlueWithdrawCollateralAuthorizationRequest(request: Extract<SignatureRequest, {
114
+ kind: "morphoAuthorization";
115
+ }>, action: Extract<Action, {
116
+ type: "blueWithdrawCollateral";
117
+ }>): void;
118
+ /** @internal Encodes the self-contained collateral withdrawal recipe. */
119
+ export declare function buildBlueWithdrawCollateral(action: Extract<Action, {
120
+ type: "blueWithdrawCollateral";
121
+ }>, requests: readonly SignatureRequest[]): Readonly<import("../../types/action.js").Transaction<import("../../types/action.js").BlueWithdrawCollateralAction>>;
122
+ /** @internal Validates the stored collateral withdrawal's structural inputs. */
123
+ export declare function validateBlueWithdrawCollateralPlanAction(action: Record<string, unknown>, path: string): void;