@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,240 @@
1
+ import { AccrualPosition, MarketParams, MathLib, } from "@morpho-org/blue-sdk";
2
+ import { deepFreeze, Time } from "@morpho-org/morpho-ts";
3
+ import { blueWithdrawCollateral } from "../../actions/blue/withdrawCollateral.js";
4
+ import { normalizeBundlesCommonParams } from "../../actions/bundles/common.js";
5
+ import { DEFAULT_LLTV_BUFFER } from "../../helpers/constant.js";
6
+ import { validatePositionHealthAfterWithdraw, validateUint256Field, } from "../../helpers/validate.js";
7
+ import { NonPositiveInputError, } from "../../types/index.js";
8
+ import { IncompleteTransactionPlanError, TransactionPlanSignatureMismatchError, } from "../error.js";
9
+ import { getPlanObject, validatePlanField, validatePlanFields, } from "../validation.js";
10
+ import { validateMorphoAuthorizationRequest } from "./authorization.js";
11
+ import { prepareBlue, } from "./prepare.js";
12
+ /**
13
+ * Prepares a BlueBundlesV1 collateral withdrawal with direct or inline signed Morpho authorization.
14
+ * Health is checked with the same two-hour accrual horizon and LLTV buffer as the entity handle.
15
+ * No token allowance or Permit2 prerequisite is read or produced.
16
+ * @param client - Viem client used for registered contract-code and Morpho authorization reads.
17
+ * @param params - Intent and matching market and account position snapshots.
18
+ * @param params.chainId - Chain containing the market and registered BlueBundlesV1 contract.
19
+ * @param params.account - Non-zero owner of the collateral position, authorization signer and transaction sender.
20
+ * @param params.marketId - Market ID that both snapshots and their parameter tuples must describe.
21
+ * @param params.marketData.chainId - Chain from which the market snapshot was fetched; must equal `chainId`.
22
+ * @param params.marketData.market - Caller-fetched `Market` providing the market tuple and LLTV.
23
+ * @param params.positionData.chainId - Chain from which the position snapshot was fetched; must equal `chainId`.
24
+ * @param params.positionData.position - Caller-fetched `AccrualPosition` for `account` and `marketId`, used for the two-hour accrued health check.
25
+ * @param params.collateralAssets - Positive collateral withdrawal in token base units, not exceeding the position's collateral.
26
+ * @param params.referralFee.bps - Optional integer referral fee in basis points; defaults to zero and must be below 10,000.
27
+ * @param params.referralFee.recipient - Non-zero fee recipient required when the optional fee is positive.
28
+ * @param params.supportSignature - Optional Morpho authorization signature preference, defaulting to `false`; otherwise prepares a direct authorization transaction when needed.
29
+ * @param params.now - Optional reference timestamp in Unix seconds, normally the latest block timestamp; defaults to the device clock.
30
+ * @param params.expiresAt - Optional safe-integer Unix expiry later than `now`; defaults to `now + 2h` and governs every deadline.
31
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended verbatim to every built transaction.
32
+ * @param params.deployless - Optional shared intent field; unused because this operation reads no token metadata or allowances.
33
+ * @returns A deep-frozen, data-only `TransactionPlan` with chain, account, expiry, withdrawal step,
34
+ * and any preceding Morpho authorization step and signature request. The caller signs; the SDK never does.
35
+ * @throws {BlueSnapshotChainMismatchError} when either snapshot's chain differs from `chainId`.
36
+ * @throws {MarketIdMismatchError} when either snapshot describes another market or a market ID does not hash from its tuple.
37
+ * @throws {AccrualPositionUserMismatchError} when the position belongs to another account.
38
+ * @throws {ZeroAccountError} when `account` is the zero address.
39
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
40
+ * @throws {NonPositiveInputError} when `expiresAt` or `collateralAssets` is not positive.
41
+ * @throws {ExpiredDeadlineError} when `expiresAt` is at or before `now`.
42
+ * @throws {NegativeInputError} when `referralFee.bps` is negative.
43
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `collateralAssets` exceeds uint256.
44
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
45
+ * @throws {ReferralFeePctExceededError} when `referralFee.bps` equals 10,000.
46
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no non-zero recipient.
47
+ * @throws {UnsupportedMarketIrmError} when projecting an indebted position requires an unsupported IRM without rate data.
48
+ * @throws {WithdrawExceedsCollateralError} when `collateralAssets` exceeds the position's collateral.
49
+ * @throws {MissingMarketPriceError} when the position carries debt but its market price is missing or zero.
50
+ * @throws {WithdrawMakesPositionUnhealthyError} when the accrued remaining position would breach LLTV minus the default buffer.
51
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
52
+ * @throws {UnknownAddressError} when Morpho or BlueBundlesV1 is not registered on the target chain.
53
+ * @throws {MissingContractCodeError} when Morpho or BlueBundlesV1 has no deployed bytecode on the endpoint's chain.
54
+ * @throws {ChainIdMismatchError} when the client declares or its RPC reports another chain.
55
+ * @throws {viem.BaseError} when a contract-code, chain ID, authorization or nonce RPC read fails.
56
+ * @example
57
+ * ```ts
58
+ * import assert from "node:assert/strict";
59
+ * import { markets } from "@morpho-org/morpho-test";
60
+ * import { fetchAccrualPosition } from "@morpho-org/morpho-sdk/blue/fetch";
61
+ * import {
62
+ * applySignatures, buildTransactions, getPendingSignatureRequests,
63
+ * prepareBlueWithdrawCollateral,
64
+ * } from "@morpho-org/morpho-sdk";
65
+ * import { createPublicClient, createWalletClient, custom, type EIP1193Provider, http } from "viem";
66
+ * import { mainnet } from "viem/chains";
67
+ *
68
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
69
+ * const { ethereum } = window as Window & { ethereum?: EIP1193Provider };
70
+ * if (!ethereum) throw new Error("Install an Ethereum wallet to continue.");
71
+ * const wallet = createWalletClient({ chain: mainnet, transport: custom(ethereum) });
72
+ * const [account] = await wallet.requestAddresses();
73
+ * assert(account, "Connect a wallet holding collateral in this market.");
74
+ * const market = markets[mainnet.id].usdc_wbtc;
75
+ * const position = await fetchAccrualPosition(account, market.id, client);
76
+ * const plan = await prepareBlueWithdrawCollateral(client, {
77
+ * chainId: mainnet.id, account, marketId: market.id,
78
+ * marketData: { chainId: mainnet.id, market: position.market },
79
+ * positionData: { chainId: mainnet.id, position },
80
+ * collateralAssets: 1_000_000n, supportSignature: true,
81
+ * now: (await client.getBlock()).timestamp,
82
+ * });
83
+ * // plan satisfies TransactionPlan; no token approval or Permit2 request is included.
84
+ * const signatures = await Promise.all(getPendingSignatureRequests(plan).map(
85
+ * async ({ id, typedData }) => ({ id, signature: await wallet.signTypedData({ ...typedData, account }) }),
86
+ * ));
87
+ * const transactions = buildTransactions(applySignatures(plan, signatures));
88
+ * // transactions satisfies readonly Readonly<Transaction>[]; submit them in order from account.
89
+ * ```
90
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
91
+ */
92
+ export async function prepareBlueWithdrawCollateral(client, params) {
93
+ const now = params.now ?? Time.timestamp();
94
+ const { chainId, account, collateralAssets, marketId } = params;
95
+ const { loanToken, collateralToken, oracle, irm, lltv } = params.marketData.market.params;
96
+ const marketParams = { loanToken, collateralToken, oracle, irm, lltv };
97
+ const { intent, steps, signatureRequests, morphoAuthorizationRequestId } = await prepareBlue({ client, params: { ...params, now } }, (resolvedIntent) => {
98
+ // Reject invalid fees and deadlines before authorization reads.
99
+ normalizeBundlesCommonParams(resolvedIntent);
100
+ if (collateralAssets <= 0n) {
101
+ throw new NonPositiveInputError("collateralAssets", collateralAssets);
102
+ }
103
+ // Reject amounts outside the ABI range before reading authorization state.
104
+ validateUint256Field("collateralAssets", collateralAssets);
105
+ const position = params.positionData.position;
106
+ // Validate health against the same accrual horizon used by the existing handle.
107
+ validatePositionHealthAfterWithdraw({
108
+ positionData: position.borrowShares === 0n
109
+ ? new AccrualPosition(position, position.market)
110
+ : position.accrueInterest(MathLib.max(now, position.market.lastUpdate) +
111
+ Time.s.from.h(2n)),
112
+ withdrawAmount: collateralAssets,
113
+ lltv,
114
+ marketId,
115
+ });
116
+ return { id: "blueWithdrawCollateral", needsAuthorization: true };
117
+ });
118
+ return deepFreeze({
119
+ version: 2,
120
+ chainId,
121
+ account,
122
+ expiresAt: intent.expiresAt,
123
+ ...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
124
+ steps: [
125
+ ...steps,
126
+ {
127
+ id: "blueWithdrawCollateral",
128
+ label: "Withdraw Blue collateral",
129
+ action: {
130
+ type: "blueWithdrawCollateral",
131
+ signatureRequestIds: morphoAuthorizationRequestId === undefined
132
+ ? {}
133
+ : { morphoAuthorization: morphoAuthorizationRequestId },
134
+ inputs: {
135
+ chainId,
136
+ account,
137
+ collateralAssets,
138
+ ...(morphoAuthorizationRequestId === undefined
139
+ ? {}
140
+ : {
141
+ authorizationNonce: signatureRequests.find(({ id }) => id === morphoAuthorizationRequestId)?.args.nonce,
142
+ }),
143
+ marketParams,
144
+ maxLtv: MathLib.zeroFloorSub(lltv, DEFAULT_LLTV_BUFFER),
145
+ ...normalizeBundlesCommonParams(intent),
146
+ },
147
+ },
148
+ },
149
+ ],
150
+ signatureRequests,
151
+ });
152
+ }
153
+ /** @internal Binds an inline authorization to the collateral withdrawal that consumes it. */
154
+ export function validateBlueWithdrawCollateralAuthorizationRequest(request, action) {
155
+ if (action.signatureRequestIds.morphoAuthorization !== request.id ||
156
+ action.inputs.authorizationNonce === undefined) {
157
+ throw new TransactionPlanSignatureMismatchError(request.id, "reference");
158
+ }
159
+ // Pin the signature to the prepared collateral withdrawal's nonce and deadline.
160
+ validateMorphoAuthorizationRequest(request, {
161
+ ...action.inputs,
162
+ nonce: action.inputs.authorizationNonce,
163
+ });
164
+ }
165
+ /** @internal Encodes the self-contained collateral withdrawal recipe. */
166
+ export function buildBlueWithdrawCollateral(action, requests) {
167
+ const { chainId, account, marketParams, authorizationNonce: _authorizationNonce, ...args } = action.inputs;
168
+ const id = action.signatureRequestIds.morphoAuthorization;
169
+ const request = id === undefined
170
+ ? undefined
171
+ : requests.find((candidate) => candidate.id === id);
172
+ if (id !== undefined &&
173
+ (request?.kind !== "morphoAuthorization" || request.signature === undefined)) {
174
+ throw new IncompleteTransactionPlanError(id);
175
+ }
176
+ if (request?.kind === "morphoAuthorization") {
177
+ validateBlueWithdrawCollateralAuthorizationRequest(request, action);
178
+ }
179
+ return blueWithdrawCollateral({
180
+ market: { chainId, marketParams: new MarketParams(marketParams) },
181
+ args: {
182
+ ...args,
183
+ userAddress: account,
184
+ authorizationSignature: request?.kind === "morphoAuthorization" &&
185
+ request.signature !== undefined
186
+ ? {
187
+ action: {
188
+ type: "authorization",
189
+ args: {
190
+ authorized: request.args.authorized,
191
+ isAuthorized: true,
192
+ deadline: request.args.deadline,
193
+ },
194
+ typedData: request.typedData,
195
+ },
196
+ args: {
197
+ ...request.args,
198
+ isAuthorized: true,
199
+ signature: request.signature,
200
+ },
201
+ }
202
+ : undefined,
203
+ },
204
+ });
205
+ }
206
+ /** @internal Validates the stored collateral withdrawal's structural inputs. */
207
+ export function validateBlueWithdrawCollateralPlanAction(action, path) {
208
+ const inputs = getPlanObject(action.inputs, `${path}.inputs`);
209
+ const ids = getPlanObject(action.signatureRequestIds, `${path}.signatureRequestIds`);
210
+ if (ids.morphoAuthorization !== undefined) {
211
+ validatePlanField(ids.morphoAuthorization, {
212
+ path: `${path}.signatureRequestIds.morphoAuthorization`,
213
+ type: "string",
214
+ });
215
+ validatePlanField(inputs.authorizationNonce, {
216
+ path: `${path}.inputs.authorizationNonce`,
217
+ type: "uint256 bigint",
218
+ });
219
+ }
220
+ validatePlanFields(inputs, {
221
+ path: `${path}.inputs`,
222
+ fields: {
223
+ collateralAssets: "uint256 bigint",
224
+ maxLtv: "uint256 bigint",
225
+ deadline: "uint256 bigint",
226
+ referralFeePct: "uint256 bigint",
227
+ referralFeeRecipient: "address",
228
+ },
229
+ });
230
+ validatePlanFields(getPlanObject(inputs.marketParams, `${path}.inputs.marketParams`), {
231
+ path: `${path}.inputs.marketParams`,
232
+ fields: {
233
+ loanToken: "address",
234
+ collateralToken: "address",
235
+ oracle: "address",
236
+ irm: "address",
237
+ lltv: "uint256 bigint",
238
+ },
239
+ });
240
+ }
@@ -8,7 +8,7 @@ import { validateNativeVaultAsset, validateSlippageTolerance, validateUint256Fie
8
8
  import { NonPositiveInputError, } from "../types/index.js";
9
9
  import { InvalidTransactionPlanError } from "./error.js";
10
10
  import { resolveIntent } from "./intent.js";
11
- import { buildApprovalStep, buildPermitSignatureRequest, getTokenRequirements, } from "./requirements.js";
11
+ import { getTokenRequirements } from "./requirements.js";
12
12
  import { validatePlanField, validatePlanFields, validateVaultPlanAction, } from "./validation.js";
13
13
  /** @internal Validates the stored Vault V1 or V2 deposit action's input shape. */
14
14
  export function validateDepositPlanAction(action, path) {
@@ -66,9 +66,10 @@ export async function prepareVaultDeposit(client, params) {
66
66
  const now = params.now ?? Time.timestamp();
67
67
  const { intent, native, common, asset, maxSharePrice } = resolveDepositInputs(params, now);
68
68
  const spender = getChainAddress(chainId, "bundles.vaultBundlesV1");
69
+ const tokenPermitRequestId = `${params.type}:tokenPermit`;
69
70
  const [requirements] = await Promise.all([
70
71
  validateClientChainId(client, chainId).then(() => native
71
- ? []
72
+ ? undefined
72
73
  : getTokenRequirements(client, {
73
74
  token: asset,
74
75
  spender,
@@ -79,29 +80,17 @@ export async function prepareVaultDeposit(client, params) {
79
80
  now,
80
81
  supportSignature: intent.supportSignature,
81
82
  deployless: intent.deployless,
83
+ permitId: tokenPermitRequestId,
84
+ approvalId: (index) => index === 0
85
+ ? `${params.type}:approval`
86
+ : `${params.type}:approval:${index + 1}`,
82
87
  })),
83
88
  assertRegistryTargetsHaveCode(client, chainId, [
84
89
  { role: "bundles.vaultBundlesV1", address: spender },
85
90
  ]),
86
91
  ]);
87
- const approvals = [];
88
- const signatureRequests = [];
89
- const tokenPermitRequestId = `${params.type}:tokenPermit`;
90
- for (const requirement of requirements) {
91
- if ("sign" in requirement) {
92
- signatureRequests.push(buildPermitSignatureRequest(requirement, tokenPermitRequestId));
93
- }
94
- else {
95
- approvals.push(buildApprovalStep(requirement, {
96
- id: approvals.length === 0
97
- ? `${params.type}:approval`
98
- : `${params.type}:approval:${approvals.length + 1}`,
99
- chainId,
100
- account,
101
- denomination: "assets",
102
- }));
103
- }
104
- }
92
+ const approvals = requirements?.approvals ?? [];
93
+ const signatureRequests = requirements?.permit === undefined ? [] : [requirements.permit];
105
94
  return deepFreeze(structuredClone({
106
95
  version: 2,
107
96
  account,
@@ -1,4 +1,54 @@
1
1
  import type { Address } from "viem";
2
+ /**
3
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
4
+ * A caller-provided Blue market or position snapshot was read on a different chain.
5
+ * @example
6
+ * ```ts
7
+ * import { BlueSnapshotChainMismatchError } from "@morpho-org/morpho-sdk";
8
+ * const error = new BlueSnapshotChainMismatchError(8453, 1);
9
+ * ```
10
+ */
11
+ export declare class BlueSnapshotChainMismatchError extends Error {
12
+ readonly snapshotChainId: number;
13
+ readonly chainId: number;
14
+ /**
15
+ * @param snapshotChainId - Chain the snapshot was read from.
16
+ * @param chainId - Chain the operation targets.
17
+ */
18
+ constructor(snapshotChainId: number, chainId: number);
19
+ }
20
+ /**
21
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
22
+ * A caller-provided Blue market snapshot describes a different market state than the market
23
+ * embedded in the position snapshot, so quotes and health checks would mix two states.
24
+ * @example
25
+ * ```ts
26
+ * import { BlueSnapshotStateMismatchError } from "@morpho-org/morpho-sdk";
27
+ * const error = new BlueSnapshotStateMismatchError({
28
+ * field: "totalBorrowAssets",
29
+ * positionValue: 100n,
30
+ * marketValue: 200n,
31
+ * });
32
+ * ```
33
+ */
34
+ export declare class BlueSnapshotStateMismatchError extends Error {
35
+ /** Market state field that differs between the snapshots. */
36
+ readonly field: string;
37
+ /** Value in the market embedded in the position snapshot. */
38
+ readonly positionValue: bigint | undefined;
39
+ /** Value in the market snapshot. */
40
+ readonly marketValue: bigint | undefined;
41
+ /**
42
+ * @param params.field - Market state field that differs between the snapshots.
43
+ * @param params.positionValue - Value in the market embedded in the position snapshot.
44
+ * @param params.marketValue - Value in the market snapshot.
45
+ */
46
+ constructor({ field, positionValue, marketValue, }: {
47
+ readonly field: string;
48
+ readonly positionValue: bigint | undefined;
49
+ readonly marketValue: bigint | undefined;
50
+ });
51
+ }
2
52
  /**
3
53
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
4
54
  * Thrown when an operation's account is the zero address.
@@ -1,3 +1,60 @@
1
+ /**
2
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
3
+ * A caller-provided Blue market or position snapshot was read on a different chain.
4
+ * @example
5
+ * ```ts
6
+ * import { BlueSnapshotChainMismatchError } from "@morpho-org/morpho-sdk";
7
+ * const error = new BlueSnapshotChainMismatchError(8453, 1);
8
+ * ```
9
+ */
10
+ export class BlueSnapshotChainMismatchError extends Error {
11
+ snapshotChainId;
12
+ chainId;
13
+ /**
14
+ * @param snapshotChainId - Chain the snapshot was read from.
15
+ * @param chainId - Chain the operation targets.
16
+ */
17
+ constructor(snapshotChainId, chainId) {
18
+ super(`Expected a Blue snapshot on chain "${chainId}", got "${snapshotChainId}". Fetch the snapshot on the operation chain.`);
19
+ this.snapshotChainId = snapshotChainId;
20
+ this.chainId = chainId;
21
+ this.name = "BlueSnapshotChainMismatchError";
22
+ }
23
+ }
24
+ /**
25
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
26
+ * A caller-provided Blue market snapshot describes a different market state than the market
27
+ * embedded in the position snapshot, so quotes and health checks would mix two states.
28
+ * @example
29
+ * ```ts
30
+ * import { BlueSnapshotStateMismatchError } from "@morpho-org/morpho-sdk";
31
+ * const error = new BlueSnapshotStateMismatchError({
32
+ * field: "totalBorrowAssets",
33
+ * positionValue: 100n,
34
+ * marketValue: 200n,
35
+ * });
36
+ * ```
37
+ */
38
+ export class BlueSnapshotStateMismatchError extends Error {
39
+ /** Market state field that differs between the snapshots. */
40
+ field;
41
+ /** Value in the market embedded in the position snapshot. */
42
+ positionValue;
43
+ /** Value in the market snapshot. */
44
+ marketValue;
45
+ /**
46
+ * @param params.field - Market state field that differs between the snapshots.
47
+ * @param params.positionValue - Value in the market embedded in the position snapshot.
48
+ * @param params.marketValue - Value in the market snapshot.
49
+ */
50
+ constructor({ field, positionValue, marketValue, }) {
51
+ super(`Expected market snapshot ${field} "${positionValue}" from the position snapshot, got "${marketValue}". Fetch the market and position snapshots from the same market state.`);
52
+ this.field = field;
53
+ this.positionValue = positionValue;
54
+ this.marketValue = marketValue;
55
+ this.name = "BlueSnapshotStateMismatchError";
56
+ }
57
+ }
1
58
  /**
2
59
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
3
60
  * Thrown when an operation's account is the zero address.
@@ -1,11 +1,20 @@
1
- import { type Client } from "viem";
2
- import type { GetBundlesTokenRequirementsParams } from "../entities/requirements/getBundlesTokenRequirements.js";
3
- import type { Erc2612RequirementSignature, Requirement } from "../types/index.js";
1
+ import { type Address, type Client } from "viem";
2
+ import type { SignatureRequest } from "./types.js";
4
3
  /**
5
- * @internal Builds an ERC-2612 permit requirement, or returns undefined when the token has no
6
- * usable permit: DAI's non-standard permit, a reverting or undecodable `nonces()`, or no known
7
- * compatible permit domain and matching DOMAIN_SEPARATOR. Transport failures propagate.
4
+ * @internal Prepares an unsigned ERC-2612 request when the nonce and domain are usable.
5
+ * DAI's nonstandard permit is excluded; failed contract probes fall back to approval, but
6
+ * transport failures propagate.
8
7
  */
9
- export declare function getTokenPermit(client: Client, params: Pick<GetBundlesTokenRequirementsParams, "token" | "spender" | "amount" | "owner" | "chainId" | "deadline" | "supportDeployless"> & {
8
+ export declare function getTokenPermit(client: Client, params: {
9
+ readonly id: string;
10
+ readonly token: Address;
11
+ readonly spender: Address;
12
+ readonly amount: bigint;
13
+ readonly owner: Address;
14
+ readonly chainId: number;
15
+ readonly deadline: bigint;
10
16
  readonly now: bigint;
11
- }): Promise<Requirement<Erc2612RequirementSignature> | undefined>;
17
+ readonly supportDeployless: boolean | undefined;
18
+ }): Promise<Extract<SignatureRequest, {
19
+ kind: "permit";
20
+ }> | undefined>;
@@ -1,16 +1,44 @@
1
1
  import { getChainAddresses } from "@morpho-org/blue-sdk";
2
+ import { fetchToken, getPermitTypedData } from "@morpho-org/blue-sdk-viem";
2
3
  import { isDefined } from "@morpho-org/morpho-ts";
3
4
  import { isAddressEqual } from "viem";
4
- import { getErc2612Permit } from "../entities/requirements/getErc2612Permit.js";
5
+ import { readErc2612Permit, validateErc2612Permit, } from "../reads/readErc2612Permit.js";
5
6
  /**
6
- * @internal Builds an ERC-2612 permit requirement, or returns undefined when the token has no
7
- * usable permit: DAI's non-standard permit, a reverting or undecodable `nonces()`, or no known
8
- * compatible permit domain and matching DOMAIN_SEPARATOR. Transport failures propagate.
7
+ * @internal Prepares an unsigned ERC-2612 request when the nonce and domain are usable.
8
+ * DAI's nonstandard permit is excluded; failed contract probes fall back to approval, but
9
+ * transport failures propagate.
9
10
  */
10
11
  export async function getTokenPermit(client, params) {
11
- const { dai } = getChainAddresses(params.chainId);
12
- if (isDefined(dai) && isAddressEqual(params.token, dai)) {
12
+ const { id, token, spender, amount, owner, chainId, supportDeployless } = params;
13
+ const { dai } = getChainAddresses(chainId);
14
+ if (isDefined(dai) && isAddressEqual(token, dai)) {
13
15
  return undefined;
14
16
  }
15
- return getErc2612Permit(client, params);
17
+ return readErc2612Permit(client, {
18
+ token,
19
+ owner,
20
+ resolve: async (nonce) => {
21
+ const deadline = await validateErc2612Permit(client, params);
22
+ const typedData = getPermitTypedData({
23
+ erc20: await fetchToken(token, client, {
24
+ deployless: supportDeployless,
25
+ }),
26
+ owner,
27
+ spender,
28
+ allowance: amount,
29
+ nonce,
30
+ deadline,
31
+ }, chainId);
32
+ const domain = { ...typedData.domain };
33
+ return {
34
+ domain,
35
+ result: {
36
+ id,
37
+ kind: "permit",
38
+ typedData: { ...typedData, domain },
39
+ args: { spender, amount, deadline, nonce },
40
+ },
41
+ };
42
+ },
43
+ });
16
44
  }
@@ -1,4 +1,24 @@
1
- export { IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
1
+ export type { BlueBorrowPlanParams } from "./blue/borrow.js";
2
+ export { prepareBlueBorrow } from "./blue/borrow.js";
3
+ export type { BlueMarketSnapshot, BluePositionSnapshot, } from "./blue/prepare.js";
4
+ export { validateBlueMarketSnapshot } from "./blue/prepare.js";
5
+ export type { BlueRefinancePlanParams } from "./blue/refinance.js";
6
+ export { prepareBlueRefinance } from "./blue/refinance.js";
7
+ export type { BlueRepayPlanParams } from "./blue/repay.js";
8
+ export { prepareBlueRepay } from "./blue/repay.js";
9
+ export type { BlueRepayWithdrawCollateralPlanParams } from "./blue/repayWithdrawCollateral.js";
10
+ export { prepareBlueRepayWithdrawCollateral } from "./blue/repayWithdrawCollateral.js";
11
+ export type { BlueSupplyPlanParams } from "./blue/supply.js";
12
+ export { prepareBlueSupply } from "./blue/supply.js";
13
+ export type { BlueSupplyCollateralPlanParams } from "./blue/supplyCollateral.js";
14
+ export { prepareBlueSupplyCollateral } from "./blue/supplyCollateral.js";
15
+ export type { BlueSupplyCollateralBorrowPlanParams } from "./blue/supplyCollateralBorrow.js";
16
+ export { prepareBlueSupplyCollateralBorrow } from "./blue/supplyCollateralBorrow.js";
17
+ export type { BlueWithdrawPlanParams } from "./blue/withdraw.js";
18
+ export { prepareBlueWithdraw } from "./blue/withdraw.js";
19
+ export type { BlueWithdrawCollateralPlanParams } from "./blue/withdrawCollateral.js";
20
+ export { prepareBlueWithdrawCollateral } from "./blue/withdrawCollateral.js";
21
+ export { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
2
22
  export type { Funding, IntentParams, ReferralFee, } from "./intent.js";
3
23
  export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, } from "./plan.js";
4
24
  export { parseTransactionPlan, serializeTransactionPlan } from "./serde.js";
@@ -1,4 +1,14 @@
1
- export { IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
1
+ export { prepareBlueBorrow } from "./blue/borrow.js";
2
+ export { validateBlueMarketSnapshot } from "./blue/prepare.js";
3
+ export { prepareBlueRefinance } from "./blue/refinance.js";
4
+ export { prepareBlueRepay } from "./blue/repay.js";
5
+ export { prepareBlueRepayWithdrawCollateral } from "./blue/repayWithdrawCollateral.js";
6
+ export { prepareBlueSupply } from "./blue/supply.js";
7
+ export { prepareBlueSupplyCollateral } from "./blue/supplyCollateral.js";
8
+ export { prepareBlueSupplyCollateralBorrow } from "./blue/supplyCollateralBorrow.js";
9
+ export { prepareBlueWithdraw } from "./blue/withdraw.js";
10
+ export { prepareBlueWithdrawCollateral } from "./blue/withdrawCollateral.js";
11
+ export { BlueSnapshotChainMismatchError, BlueSnapshotStateMismatchError, IncompleteTransactionPlanError, InvalidCalldataOriginError, InvalidTransactionPlanError, NonIntegerInputError, TransactionPlanSignatureMismatchError, UnsupportedTransactionPlanActionError, UnsupportedTransactionPlanVersionError, ZeroAccountError, } from "./error.js";
2
12
  export { applySignatures, buildTransaction, buildTransactions, getPendingSignatureRequests, } from "./plan.js";
3
13
  export { parseTransactionPlan, serializeTransactionPlan } from "./serde.js";
4
14
  export { prepareVaultV1Deposit } from "./vaultv1/deposit.js";
@@ -1,7 +1,7 @@
1
1
  import { type Address, type Hex } from "viem";
2
2
  /**
3
3
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
4
- * Which balance pays a deposit: the vault asset, or native currency the bundle wraps.
4
+ * Which balance funds an operation: the ERC-20 token, or native currency the bundle wraps.
5
5
  */
6
6
  export type Funding = {
7
7
  readonly type: "erc20";
@@ -29,7 +29,7 @@ export interface IntentParams {
29
29
  readonly supportSignature?: boolean;
30
30
  /** Unix seconds. Defaults to two hours from now. */
31
31
  readonly expiresAt?: number;
32
- /** Optional attribution bytes appended verbatim to every built transaction's calldata. */
32
+ /** Optional attribution bytes (at most 1 MiB) appended verbatim to every built transaction's calldata. */
33
33
  readonly calldataOrigin?: Hex;
34
34
  /** Whether token metadata reads for permits may use deployless aggregation. */
35
35
  readonly deployless?: boolean;
@@ -2,6 +2,7 @@ import { MathLib, Time } from "@morpho-org/morpho-ts";
2
2
  import { isHex, zeroAddress } from "viem";
3
3
  import { ExpiredDeadlineError, InputExceedsMaxError, NegativeInputError, NonPositiveInputError, } from "../types/index.js";
4
4
  import { InvalidCalldataOriginError, NonIntegerInputError, ZeroAccountError, } from "./error.js";
5
+ import { validateCalldataOriginLength, validatePlanField, } from "./validation.js";
5
6
  const BASIS_POINTS = 10000n;
6
7
  const WAD_PER_BASIS_POINT = MathLib.WAD / BASIS_POINTS;
7
8
  function toSafeInteger(field, value) {
@@ -18,6 +19,7 @@ export function resolveIntent(params, now) {
18
19
  if (params.account === zeroAddress) {
19
20
  throw new ZeroAccountError(params.account);
20
21
  }
22
+ validatePlanField(params.account, { path: "$.account", type: "address" });
21
23
  const expiresAt = params.expiresAt ?? Number(now + Time.s.from.h(2n));
22
24
  const deadline = toSafeInteger("expiresAt", expiresAt);
23
25
  if (deadline <= 0n) {
@@ -40,11 +42,13 @@ export function resolveIntent(params, now) {
40
42
  });
41
43
  }
42
44
  const { calldataOrigin } = params;
43
- if (calldataOrigin !== undefined &&
44
- (!isHex(calldataOrigin, { strict: true }) ||
45
+ if (calldataOrigin !== undefined) {
46
+ if (!isHex(calldataOrigin, { strict: true }) ||
45
47
  calldataOrigin.length <= 2 ||
46
- calldataOrigin.length % 2 !== 0)) {
47
- throw new InvalidCalldataOriginError(calldataOrigin);
48
+ calldataOrigin.length % 2 !== 0) {
49
+ throw new InvalidCalldataOriginError(calldataOrigin);
50
+ }
51
+ validateCalldataOriginLength(calldataOrigin);
48
52
  }
49
53
  return {
50
54
  expiresAt: Number(deadline),
@@ -4,10 +4,24 @@ import type { Action, SignatureRequest } from "./types.js";
4
4
  /** @internal Validates the stored ERC-2612 request shape without verifying its signature. */
5
5
  export declare function validatePermitPlanRequest(request: Record<string, unknown>, path: string): void;
6
6
  /** @internal Checks a permit's signing payload against its referencing action and encoding arguments. */
7
- export declare function validateSignatureRequest(request: SignatureRequest, action: Action): void;
7
+ export declare function validateVaultPermitRequest(request: SignatureRequest, action: Action): void;
8
+ /** @internal Binds the signing payload and encoding arguments to a registered bundle's token pull. */
9
+ export declare function validateTokenPermitRequest(request: Extract<SignatureRequest, {
10
+ kind: "permit";
11
+ }>, pull: {
12
+ readonly chainId: number;
13
+ readonly account: Address;
14
+ readonly deadline: bigint | undefined;
15
+ readonly bundler: "bundles.vaultBundlesV1" | "bundles.vaultExitBundlesV1" | "bundles.blueBundlesV1";
16
+ readonly asset: Address;
17
+ readonly amount: bigint | undefined;
18
+ readonly exact: boolean;
19
+ }): void;
8
20
  /** @internal Rebuilds a token permit from the action's account/asset and its resolved signature requests. */
9
- export declare function getVaultPermit(requests: readonly SignatureRequest[], { id, asset, owner, }: {
21
+ export declare function getSignedTokenPermit(requests: readonly SignatureRequest[], { id, asset, owner, }: {
10
22
  readonly id: string | undefined;
11
23
  readonly asset: Address;
12
24
  readonly owner: Address;
13
25
  }): Erc2612RequirementSignature | undefined;
26
+ /** @internal Alias for existing Vault V2 plan builders. */
27
+ export { getSignedTokenPermit as getVaultPermit };