@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
@@ -5,9 +5,20 @@ import { publicKeyToAddress } from "viem/accounts";
5
5
  import { normalizeBundlesSignature } from "../actions/bundles/common.js";
6
6
  import { encodeErc20Approval } from "../actions/index.js";
7
7
  import { InvalidSignatureError } from "../types/error.js";
8
+ import { buildMorphoAuthorization, validateMorphoAuthorizationRequest, } from "./blue/authorization.js";
9
+ import { buildBlueBorrow } from "./blue/borrow.js";
10
+ import { buildBlueRefinance } from "./blue/refinance.js";
11
+ import { buildBlueRepay, validateBlueRepayPermit } from "./blue/repay.js";
12
+ import { buildBlueRepayWithdrawCollateral, validateRepayWithdrawCollateralRequest, } from "./blue/repayWithdrawCollateral.js";
13
+ import { buildBlueSupply, validateBlueSupplyPermitRequest, } from "./blue/supply.js";
14
+ import { buildBlueSupplyCollateral, validateSupplyCollateralPermitRequest, } from "./blue/supplyCollateral.js";
15
+ import { buildBlueSupplyCollateralBorrow, validateSupplyCollateralBorrowRequest, } from "./blue/supplyCollateralBorrow.js";
16
+ import { buildBlueWithdraw, validateBlueWithdrawAuthorizationRequest, } from "./blue/withdraw.js";
17
+ import { buildBlueWithdrawCollateral, validateBlueWithdrawCollateralAuthorizationRequest, } from "./blue/withdrawCollateral.js";
8
18
  import { IncompleteTransactionPlanError, TransactionPlanSignatureMismatchError, } from "./error.js";
9
- import { validateSignatureRequest } from "./permit.js";
19
+ import { validateVaultPermitRequest } from "./permit.js";
10
20
  import { validateTransactionPlanActions } from "./validateActions.js";
21
+ import { validateTransactionPlanHeader } from "./validation.js";
11
22
  import { buildVaultV1Deposit } from "./vaultv1/deposit.js";
12
23
  import { buildVaultV1InKindRedeem } from "./vaultv1/inKindRedeem.js";
13
24
  import { buildVaultV1MigrateToV2 } from "./vaultv1/migrateToV2.js";
@@ -24,11 +35,13 @@ import { validateTransactionPlanVersion } from "./version.js";
24
35
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
25
36
  * Validates every request against its actions, verifies supplied ECDSA signatures synchronously,
26
37
  * and attaches serialized signatures by request ID. No client or RPC is used; the EIP-712 domain
27
- * binds the signature to its chain. Only low-s compact or serialized ECDSA permits are supported.
38
+ * binds the signature to its chain. Only low-s compact or serialized ECDSA signatures are supported.
28
39
  * Contract wallets should use `supportSignature: false` for direct approvals: deployed bundles
29
40
  * consume ECDSA `v/r/s`, not arbitrary ERC-1271 or ERC-6492 signatures.
30
41
  * Stored inputs remain trusted; verification does not establish the integrator's intent or protect
31
- * a plan changed afterwards. Builders do not reverify signatures in restored plans.
42
+ * unsigned fields from tampering. Stored signatures are reverified offline at parse, inspection and build.
43
+ * Permits bind owner, token, spender, value, nonce, deadline and chain; Morpho authorizations bind
44
+ * owner, authorized address, nonce, deadline and chain, not operation amounts, markets or referral fees/recipients.
32
45
  * @param plan - Plan to update without mutating its requests or steps.
33
46
  * @param signatures - Compact or serialized ECDSA signatures, each naming a unique existing request ID.
34
47
  * @returns A new plan sharing steps and unpatched requests; omitted IDs are preserved. Empty input validates all requests and returns the original plan.
@@ -36,7 +49,8 @@ import { validateTransactionPlanVersion } from "./version.js";
36
49
  * @throws {UnsupportedTransactionPlanActionError} If any plan step names an unsupported action type, before reading requests or updates.
37
50
  * @throws {TransactionPlanSignatureMismatchError} If a request disagrees with its actions, an ID is unknown, or an input ID is duplicated (`field: "duplicate"`).
38
51
  * @throws {BundlesPermitMismatchError} If a supplied signature cannot be parsed by the bundle permit builders.
39
- * @throws {InvalidSignatureError} If a signature has high s, cannot recover a public key, or does not match the permit owner and typed data.
52
+ * @throws {InvalidTransactionPlanError} If the plan header, action context, IDs or deadlines are inconsistent.
53
+ * @throws {InvalidSignatureError} If a signature has high s, cannot recover a public key, or does not match the request owner and typed data.
40
54
  * @example
41
55
  * ```ts
42
56
  * import { applySignatures, type TransactionPlan } from "@morpho-org/morpho-sdk";
@@ -50,13 +64,15 @@ export function applySignatures(plan, signatures) {
50
64
  validateTransactionPlanVersion(plan.version);
51
65
  // Reject unknown actions before reading signature requests or updates.
52
66
  validateTransactionPlanActions(plan.steps);
53
- const requests = getPendingSignatureRequests({
67
+ const updatedIds = new Set(signatures.map(({ id }) => id));
68
+ // Validate all requests and stored signatures that are not being replaced.
69
+ getPendingSignatureRequests({
54
70
  ...plan,
55
- signatureRequests: plan.signatureRequests.map((request) => ({
56
- ...request,
57
- signature: undefined,
58
- })),
71
+ signatureRequests: plan.signatureRequests.map((request) => updatedIds.has(request.id)
72
+ ? { ...request, signature: undefined }
73
+ : request),
59
74
  });
75
+ const requests = plan.signatureRequests;
60
76
  const updates = new Map();
61
77
  for (const { id, signature } of signatures) {
62
78
  if (!requests.some((request) => request.id === id)) {
@@ -75,25 +91,7 @@ export function applySignatures(plan, signatures) {
75
91
  if (request === undefined) {
76
92
  throw new TransactionPlanSignatureMismatchError(id, "reference");
77
93
  }
78
- const normalized = normalizeBundlesSignature(signature);
79
- let recovered;
80
- try {
81
- const ecdsa = new secp256k1.Signature(BigInt(normalized.r), BigInt(normalized.s));
82
- if (ecdsa.hasHighS()) {
83
- throw new InvalidSignatureError();
84
- }
85
- const publicKey = ecdsa
86
- .addRecoveryBit(normalized.v - 27)
87
- .recoverPublicKey(hashTypedData(request.typedData).slice(2));
88
- recovered = publicKeyToAddress(toHex(publicKey.toRawBytes(false)));
89
- }
90
- catch {
91
- throw new InvalidSignatureError();
92
- }
93
- if (!isAddressEqual(recovered, request.typedData.message.owner)) {
94
- throw new InvalidSignatureError();
95
- }
96
- updates.set(id, serializeSignature({ ...normalized, v: BigInt(normalized.v) }));
94
+ updates.set(id, verifyPlanSignature(request, signature));
97
95
  }
98
96
  return {
99
97
  ...plan,
@@ -103,6 +101,31 @@ export function applySignatures(plan, signatures) {
103
101
  }),
104
102
  };
105
103
  }
104
+ /** @internal Verifies and normalizes a signature offline after the request has been validated against its action. */
105
+ export function verifyPlanSignature(request, signature) {
106
+ const normalized = normalizeBundlesSignature(signature);
107
+ let recovered;
108
+ try {
109
+ const ecdsa = new secp256k1.Signature(BigInt(normalized.r), BigInt(normalized.s));
110
+ if (ecdsa.hasHighS()) {
111
+ throw new InvalidSignatureError();
112
+ }
113
+ const publicKey = ecdsa
114
+ .addRecoveryBit(normalized.v - 27)
115
+ .recoverPublicKey(hashTypedData(request.typedData).slice(2));
116
+ recovered = publicKeyToAddress(toHex(publicKey.toRawBytes(false)));
117
+ }
118
+ catch {
119
+ throw new InvalidSignatureError();
120
+ }
121
+ const signer = request.kind === "permit"
122
+ ? request.typedData.message.owner
123
+ : request.args.owner;
124
+ if (!isAddressEqual(recovered, signer)) {
125
+ throw new InvalidSignatureError();
126
+ }
127
+ return serializeSignature({ ...normalized, v: BigInt(normalized.v) });
128
+ }
106
129
  /** @internal Lists the signature request IDs a step's action names, in role order. */
107
130
  function getStepSignatureRequestIds(step) {
108
131
  const { action } = step;
@@ -111,16 +134,131 @@ function getStepSignatureRequestIds(step) {
111
134
  }
112
135
  return Object.values(action.signatureRequestIds).filter((id) => id !== undefined);
113
136
  }
137
+ function actionDataKeys(value) {
138
+ const keys = Object.keys(value);
139
+ return Array.isArray(value)
140
+ ? keys
141
+ : keys.filter((key) => value[key] !== undefined);
142
+ }
143
+ function equalActionData(left, right) {
144
+ const pending = [[left, right]];
145
+ const compared = new WeakMap();
146
+ for (const [a, b] of pending) {
147
+ if (Object.is(a, b)) {
148
+ continue;
149
+ }
150
+ if (typeof a !== "object" ||
151
+ a === null ||
152
+ typeof b !== "object" ||
153
+ b === null) {
154
+ return false;
155
+ }
156
+ if (Array.isArray(a) || Array.isArray(b)) {
157
+ if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) {
158
+ return false;
159
+ }
160
+ }
161
+ else {
162
+ const prototype = Object.getPrototypeOf(a);
163
+ if ((prototype !== Object.prototype && prototype !== null) ||
164
+ prototype !== Object.getPrototypeOf(b)) {
165
+ return false;
166
+ }
167
+ }
168
+ const matches = compared.get(a) ?? new WeakSet();
169
+ if (matches.has(b)) {
170
+ continue;
171
+ }
172
+ matches.add(b);
173
+ compared.set(a, matches);
174
+ const aFields = a;
175
+ const bFields = b;
176
+ const keys = actionDataKeys(aFields);
177
+ if (keys.length !== actionDataKeys(bFields).length) {
178
+ return false;
179
+ }
180
+ for (const key of keys) {
181
+ if (!Object.prototype.propertyIsEnumerable.call(b, key)) {
182
+ return false;
183
+ }
184
+ pending.push([aFields[key], bFields[key]]);
185
+ }
186
+ }
187
+ return true;
188
+ }
189
+ function validateSignatureRequest(request, action) {
190
+ if (action.type === "blueSupplyCollateralBorrow") {
191
+ return validateSupplyCollateralBorrowRequest(request, action);
192
+ }
193
+ if (request.kind === "morphoAuthorization" &&
194
+ action.type === "blueWithdraw") {
195
+ return validateBlueWithdrawAuthorizationRequest(request, action);
196
+ }
197
+ if (request.kind === "morphoAuthorization" &&
198
+ action.type === "blueWithdrawCollateral") {
199
+ return validateBlueWithdrawCollateralAuthorizationRequest(request, action);
200
+ }
201
+ if (request.kind === "morphoAuthorization" &&
202
+ action.type === "blueBorrow" &&
203
+ action.signatureRequestIds.morphoAuthorization === request.id) {
204
+ return validateMorphoAuthorizationRequest(request, {
205
+ ...action.inputs,
206
+ nonce: action.inputs.authorizationNonce,
207
+ });
208
+ }
209
+ if (request.kind === "permit" && action.type === "blueSupplyCollateral") {
210
+ return validateSupplyCollateralPermitRequest(request, action);
211
+ }
212
+ if (request.kind === "permit" &&
213
+ action.type === "blueSupply" &&
214
+ action.signatureRequestIds.tokenPermit === request.id) {
215
+ return validateBlueSupplyPermitRequest(request, action);
216
+ }
217
+ if (request.kind === "permit" && action.type === "blueRepay") {
218
+ return validateBlueRepayPermit(request, action);
219
+ }
220
+ if (action.type === "blueRepayWithdrawCollateral") {
221
+ return validateRepayWithdrawCollateralRequest(request, action);
222
+ }
223
+ if (request.kind === "morphoAuthorization" &&
224
+ action.type === "blueRefinance" &&
225
+ action.signatureRequestIds.morphoAuthorization === request.id &&
226
+ action.inputs.authorizationNonce !== undefined) {
227
+ return validateMorphoAuthorizationRequest(request, {
228
+ ...action.inputs,
229
+ nonce: action.inputs.authorizationNonce,
230
+ });
231
+ }
232
+ if (request.kind === "permit" &&
233
+ (action.type === "vaultV2Deposit" ||
234
+ action.type === "vaultV1Deposit" ||
235
+ action.type === "vaultV1Withdraw" ||
236
+ action.type === "vaultV2Withdraw" ||
237
+ action.type === "vaultV2Redeem" ||
238
+ action.type === "vaultV1Redeem" ||
239
+ action.type === "vaultV2ForceWithdraw" ||
240
+ action.type === "vaultV1MigrateToV2" ||
241
+ action.type === "vaultV2InKindRedeem" ||
242
+ action.type === "vaultV1InKindRedeem")) {
243
+ validateVaultPermitRequest(request, action);
244
+ return;
245
+ }
246
+ throw new TransactionPlanSignatureMismatchError(request.id, "reference");
247
+ }
114
248
  /**
115
249
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
116
- * Lists pending signature requests once per request ID after checking each against every referencing action.
250
+ * Lists pending signature requests once per request ID and validates them against their referencing actions.
251
+ * Signed requests are also checked and their signers recovered offline.
117
252
  * Sign each request's typed data with your wallet stack, then verify and attach the results with
118
253
  * {@link applySignatures}.
119
254
  * @param plan - Plan to inspect without changing it.
120
255
  * @returns Pending requests in first-reference order, each carrying its `id`, `kind` and validated `typedData`. Dangling IDs are omitted. The SDK never signs.
256
+ * @throws {InvalidTransactionPlanError} If the plan header, action context, IDs or deadlines are inconsistent.
257
+ * @throws {InvalidSignatureError} If a stored signature has high s, cannot recover a public key or does not match the request owner.
258
+ * @throws {BundlesPermitMismatchError} If a stored signature cannot be parsed as a compact or serialized ECDSA signature.
121
259
  * @throws {UnsupportedTransactionPlanVersionError} If the plan version is unsupported, including empty plans.
122
260
  * @throws {UnsupportedTransactionPlanActionError} If any plan step names an unsupported action type, before reading requests.
123
- * @throws {TransactionPlanSignatureMismatchError} If a pending permit disagrees with its action or arguments, including the action deadline, or any request has no referencing step.
261
+ * @throws {TransactionPlanSignatureMismatchError} If a pending request or Morpho authorization disagrees with its action or arguments, or any request has no referencing step.
124
262
  * @example
125
263
  * ```ts
126
264
  * import { getPendingSignatureRequests, type TransactionPlan } from "@morpho-org/morpho-sdk";
@@ -133,9 +271,14 @@ export function getPendingSignatureRequests(plan) {
133
271
  validateTransactionPlanVersion(plan.version);
134
272
  // Reject unknown actions before exposing signature requests.
135
273
  validateTransactionPlanActions(plan.steps);
274
+ // Validate shared context before resolving requests.
275
+ validateTransactionPlanHeader(plan);
136
276
  const referenced = new Map();
137
277
  for (const step of plan.steps) {
138
278
  for (const id of getStepSignatureRequestIds(step)) {
279
+ if (referenced.has(id)) {
280
+ throw new TransactionPlanSignatureMismatchError(id, "reference");
281
+ }
139
282
  referenced.set(id, [...(referenced.get(id) ?? []), step.action]);
140
283
  }
141
284
  }
@@ -144,14 +287,12 @@ export function getPendingSignatureRequests(plan) {
144
287
  if (actions === undefined) {
145
288
  throw new TransactionPlanSignatureMismatchError(request.id, "reference");
146
289
  }
147
- if (request.signature === undefined) {
148
- for (const action of actions) {
149
- validateSignatureRequest(request, action);
150
- if ("signatureRequestIds" in action &&
151
- request.args.deadline !== action.inputs.deadline) {
152
- throw new TransactionPlanSignatureMismatchError(request.id, "args.deadline");
153
- }
154
- }
290
+ for (const action of actions) {
291
+ validateSignatureRequest(request, action);
292
+ }
293
+ if (request.signature !== undefined) {
294
+ // Recover only after the request has been bound to its action account.
295
+ verifyPlanSignature(request, request.signature);
155
296
  }
156
297
  }
157
298
  return [...referenced.keys()].flatMap((id) => {
@@ -167,6 +308,24 @@ function encodeStep(action, requests) {
167
308
  return buildVaultV1MigrateToV2(action, requests);
168
309
  case "vaultV1InKindRedeem":
169
310
  return buildVaultV1InKindRedeem(action, requests);
311
+ case "blueSupply":
312
+ return buildBlueSupply(action, requests);
313
+ case "blueSupplyCollateral":
314
+ return buildBlueSupplyCollateral(action, requests);
315
+ case "blueBorrow":
316
+ return buildBlueBorrow(action, requests);
317
+ case "blueSupplyCollateralBorrow":
318
+ return buildBlueSupplyCollateralBorrow(action, requests);
319
+ case "blueRepay":
320
+ return buildBlueRepay(action, requests);
321
+ case "blueWithdraw":
322
+ return buildBlueWithdraw(action, requests);
323
+ case "blueWithdrawCollateral":
324
+ return buildBlueWithdrawCollateral(action, requests);
325
+ case "blueRepayWithdrawCollateral":
326
+ return buildBlueRepayWithdrawCollateral(action, requests);
327
+ case "blueRefinance":
328
+ return buildBlueRefinance(action, requests);
170
329
  case "erc20Approval":
171
330
  return encodeErc20Approval({
172
331
  ...action.inputs,
@@ -174,6 +333,8 @@ function encodeStep(action, requests) {
174
333
  });
175
334
  case "vaultV1Deposit":
176
335
  return buildVaultV1Deposit(action, requests);
336
+ case "morphoAuthorization":
337
+ return buildMorphoAuthorization(action);
177
338
  case "vaultV2Deposit":
178
339
  return buildVaultV2Deposit(action, requests);
179
340
  case "vaultV2Withdraw":
@@ -196,23 +357,47 @@ function encodeStep(action, requests) {
196
357
  * Plans are trusted as given, whether restored or supplied directly. Signature checks establish
197
358
  * only request/action consistency; they do not validate stored fees, recipients, share-price bounds,
198
359
  * vaults or amounts against the intended operation. Integrators must protect stored plans from tampering.
199
- * This builder does not verify signature ownership; use {@link applySignatures} to verify and attach signatures.
360
+ * Stored signatures are verified offline. Permits bind owner, token, spender, value, nonce, deadline
361
+ * and chain; Morpho authorizations bind owner, authorized address, nonce, deadline and chain,
362
+ * not operation amounts, market parameters or referral fees/recipients. Protect those unsigned fields.
200
363
  * @param plan - Plan supplying referenced signature requests and the calldata origin; chain and account come from the action inputs.
201
364
  * @param step - Recipe to encode; missing signatures on unrelated supported steps do not block it.
202
365
  * @returns A frozen `{ to, data, value, action }`, ready to simulate or submit. `data` ends with the plan's `calldataOrigin` when one was set.
366
+ * @throws {InvalidTransactionPlanError} If the plan header, action context, IDs or deadlines are inconsistent.
367
+ * @throws {InvalidSignatureError} If a stored signature has high s, cannot recover a public key or does not match the request owner.
203
368
  * @throws {UnsupportedTransactionPlanVersionError} If the plan version is unsupported.
204
369
  * @throws {UnsupportedTransactionPlanActionError} If any plan step or the selected step names an unsupported action type.
205
370
  * @throws {UnsupportedErc20ApprovalSpenderError} If an approval names an unregistered spender.
206
371
  * @throws {SameVaultMigrationError} If a migration's source and destination vaults are identical.
207
372
  * @throws {AmountAndSharesExclusiveError} If a migration supplies both `assets` and `shares`, or neither.
208
- * @throws {NonPositiveInputError} If a deposit, withdrawal or migration amount, a deposit or migration destination share-price bound, a deadline, force-redeem shares or deallocation amount is not positive.
373
+ * @throws {NonPositiveInputError} If a deposit, withdrawal or migration amount, a deposit or migration destination share-price bound, a Blue collateral amount, a deadline, force-redeem shares or deallocation amount is not positive.
374
+ * @throws {MarketIdMismatchError} If a Blue collateral step's market ID doesn't match its market parameters.
375
+ * @throws {NativeAmountOnNonWNativeAssetError} If a native-funded Blue collateral step targets a token other than wNative.
376
+ * @throws {ChainWNativeMissingError} If a native-funded Blue collateral step targets a chain without registered wNative.
209
377
  * @throws {EmptyDeallocationsError} If a force-redeem step has no deallocations.
210
378
  * @throws {EmptyMarketParamsListError} If a Vault V1 in-kind redemption step has no markets.
211
379
  * @throws {ReferralFeePctExceededError} If the action's referral fee is at least WAD.
212
380
  * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no nonzero recipient.
213
381
  * @throws {IncompleteTransactionPlanError} If a referenced signature request or its signature is missing.
214
- * @throws {TransactionPlanSignatureMismatchError} If a referenced permit disagrees with the step's action or its encoding arguments.
215
- * @throws {BundlesPermitMismatchError} If a signed permit's spender, amount or deadline doesn't match the step.
382
+ * @throws {TransactionPlanSignatureMismatchError} If a referenced request disagrees with the step's action or its encoding arguments.
383
+ * @throws {BundlesPermitMismatchError} If a stored signature cannot be parsed or a signed permit's encoding arguments do not match the step.
384
+ * @throws {MarketIdMismatchError} If a Blue market ID differs from its parameter tuple.
385
+ * @throws {NegativeInputError} If a Blue amount, native value, LTV bound or referral fee is negative.
386
+ * @throws {InputExceedsMaxError} If a Blue amount, bound or deadline exceeds uint256, or withdrawal-only funding is nonzero.
387
+ * @throws {MutuallyExclusiveRepayAmountsError} If a Blue repayment specifies both nonzero assets and shares.
388
+ * @throws {MaxRepayAssetsBelowRepayAssetsError} If exact-asset funding cannot cover repayment plus referral fees.
389
+ * @throws {NativeFundingAmountMismatchError} If Blue native funding does not equal the full repayment cap.
390
+ * @throws {ChainWNativeMissingError} If native funding targets a chain without wNative.
391
+ * @throws {NativeAmountOnNonWNativeAssetError} If native funding targets a loan token other than wNative.
392
+ * @throws {UnexpectedRequirementSignatureError} If a Blue signature targets an inactive leg or native-funded token pull.
393
+ * @throws {DepositOwnerMismatchError} If a Blue signature belongs to another account.
394
+ * @throws {DepositAssetMismatchError} If a token signature names another loan token.
395
+ * @throws {DepositAmountMismatchError} If a token signature does not cover the repayment cap.
396
+ * @throws {DepositSpenderMismatchError} If a token signature names another spender.
397
+ * @throws {UnsupportedRequirementSignatureError} If a token signature has an unsupported action type.
398
+ * @throws {BundlesRequirementSignatureMismatchError} If a Blue signature cannot be bound or parsed safely.
399
+ * @throws {UnsupportedChainIdError} If a Blue action's chain is absent from the registry.
400
+ * @throws {UnknownAddressError} If BlueBundlesV1 is not registered on the action's chain.
216
401
  * @example
217
402
  * ```ts
218
403
  * import { buildTransaction, parseTransactionPlan } from "@morpho-org/morpho-sdk";
@@ -226,13 +411,37 @@ export function buildTransaction(plan, step) {
226
411
  // Reject unknown formats before interpreting stored fields.
227
412
  validateTransactionPlanVersion(plan.version);
228
413
  // Check the whole plan and any separately selected step before reading requests.
229
- validateTransactionPlanActions([...plan.steps, step]);
414
+ const isOriginalStep = plan.steps.includes(step);
415
+ const steps = isOriginalStep ? plan.steps : [...plan.steps, step];
416
+ validateTransactionPlanActions(steps);
417
+ // Validate the plan and the separately selected step without requiring unrelated signatures.
418
+ validateTransactionPlanHeader(plan);
419
+ const referencedIds = new Set(plan.steps.flatMap(getStepSignatureRequestIds));
420
+ getPendingSignatureRequests({
421
+ ...plan,
422
+ signatureRequests: plan.signatureRequests.filter((request) => referencedIds.has(request.id)),
423
+ });
424
+ if (!isOriginalStep &&
425
+ !plan.steps.some((candidate) => candidate.id === step.id &&
426
+ equalActionData(candidate.action, step.action))) {
427
+ for (const id of getStepSignatureRequestIds(step)) {
428
+ if (referencedIds.has(id)) {
429
+ throw new TransactionPlanSignatureMismatchError(id, "reference");
430
+ }
431
+ referencedIds.add(id);
432
+ }
433
+ }
434
+ validateTransactionPlanHeader({ ...plan, steps: [step] });
230
435
  const requests = getStepSignatureRequestIds(step).map((id) => {
231
436
  const request = plan.signatureRequests.find((candidate) => candidate.id === id);
232
437
  if (request === undefined) {
233
438
  throw new IncompleteTransactionPlanError(id);
234
439
  }
235
440
  validateSignatureRequest(request, step.action);
441
+ if (request.signature !== undefined) {
442
+ // The selected step may not be present in the plan's step list.
443
+ verifyPlanSignature(request, request.signature);
444
+ }
236
445
  return request;
237
446
  });
238
447
  const { to, value, data, action } = encodeStep(step.action, requests);
@@ -250,19 +459,41 @@ export function buildTransaction(plan, step) {
250
459
  * Builds every step of the plan in order.
251
460
  * @param plan - Plan whose referenced signature requests all carry a signature.
252
461
  * @returns Frozen SDK transactions in step order; discriminate on `action.type` for per-step handling.
462
+ * @throws {InvalidTransactionPlanError} If the plan header, action context, IDs or deadlines are inconsistent.
463
+ * @throws {InvalidSignatureError} If a stored signature has high s, cannot recover a public key or does not match the request owner.
253
464
  * @throws {UnsupportedTransactionPlanVersionError} If the plan version is unsupported, including empty plans.
254
465
  * @throws {UnsupportedTransactionPlanActionError} If any plan step names an unsupported action type, before reading requests.
255
466
  * @throws {UnsupportedErc20ApprovalSpenderError} If an approval names an unregistered spender.
256
467
  * @throws {SameVaultMigrationError} If a migration's source and destination vaults are identical.
257
468
  * @throws {AmountAndSharesExclusiveError} If a migration supplies both `assets` and `shares`, or neither.
258
- * @throws {NonPositiveInputError} If a deposit, withdrawal or migration amount, a deposit or migration destination share-price bound, a deadline, force-redeem shares or deallocation amount is not positive.
469
+ * @throws {NonPositiveInputError} If a deposit, withdrawal or migration amount, a deposit or migration destination share-price bound, a Blue collateral amount, a deadline, force-redeem shares or deallocation amount is not positive.
470
+ * @throws {MarketIdMismatchError} If a Blue collateral step's market ID doesn't match its market parameters.
471
+ * @throws {NativeAmountOnNonWNativeAssetError} If a native-funded Blue collateral step targets a token other than wNative.
472
+ * @throws {ChainWNativeMissingError} If a native-funded Blue collateral step targets a chain without registered wNative.
259
473
  * @throws {EmptyDeallocationsError} If a force-redeem step has no deallocations.
260
474
  * @throws {EmptyMarketParamsListError} If a Vault V1 in-kind redemption step has no markets.
261
475
  * @throws {ReferralFeePctExceededError} If an action's referral fee is at least WAD.
262
476
  * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no nonzero recipient.
263
477
  * @throws {IncompleteTransactionPlanError} If any step references a signature request or signature that is missing.
264
- * @throws {TransactionPlanSignatureMismatchError} If a referenced permit disagrees with its action or encoding arguments.
265
- * @throws {BundlesPermitMismatchError} If a signed permit's spender, amount or deadline doesn't match the step.
478
+ * @throws {TransactionPlanSignatureMismatchError} If a referenced request disagrees with its action or encoding arguments.
479
+ * @throws {BundlesPermitMismatchError} If a stored signature cannot be parsed or a signed permit's encoding arguments do not match the step.
480
+ * @throws {MarketIdMismatchError} If a Blue market ID differs from its parameter tuple.
481
+ * @throws {NegativeInputError} If a Blue amount, native value, LTV bound or referral fee is negative.
482
+ * @throws {InputExceedsMaxError} If a Blue amount, bound or deadline exceeds uint256, or withdrawal-only funding is nonzero.
483
+ * @throws {MutuallyExclusiveRepayAmountsError} If a Blue repayment specifies both nonzero assets and shares.
484
+ * @throws {MaxRepayAssetsBelowRepayAssetsError} If exact-asset funding cannot cover repayment plus referral fees.
485
+ * @throws {NativeFundingAmountMismatchError} If Blue native funding does not equal the full repayment cap.
486
+ * @throws {ChainWNativeMissingError} If native funding targets a chain without wNative.
487
+ * @throws {NativeAmountOnNonWNativeAssetError} If native funding targets a loan token other than wNative.
488
+ * @throws {UnexpectedRequirementSignatureError} If a Blue signature targets an inactive leg or native-funded token pull.
489
+ * @throws {DepositOwnerMismatchError} If a Blue signature belongs to another account.
490
+ * @throws {DepositAssetMismatchError} If a token signature names another loan token.
491
+ * @throws {DepositAmountMismatchError} If a token signature does not cover the repayment cap.
492
+ * @throws {DepositSpenderMismatchError} If a token signature names another spender.
493
+ * @throws {UnsupportedRequirementSignatureError} If a token signature has an unsupported action type.
494
+ * @throws {BundlesRequirementSignatureMismatchError} If a Blue signature cannot be bound or parsed safely.
495
+ * @throws {UnsupportedChainIdError} If a Blue action's chain is absent from the registry.
496
+ * @throws {UnknownAddressError} If BlueBundlesV1 is not registered on the action's chain.
266
497
  * @example
267
498
  * ```ts
268
499
  * import { buildTransactions, type TransactionPlan } from "@morpho-org/morpho-sdk";
@@ -275,5 +506,7 @@ export function buildTransactions(plan) {
275
506
  validateTransactionPlanVersion(plan.version);
276
507
  // Validate every action before the first step can interpret requests.
277
508
  validateTransactionPlanActions(plan.steps);
509
+ // Reject malformed headers even for empty plans.
510
+ validateTransactionPlanHeader(plan);
278
511
  return plan.steps.map((step) => buildTransaction(plan, step));
279
512
  }
@@ -8,7 +8,9 @@ import type { Action, SignatureRequest, Step } from "./types.js";
8
8
  * @returns The unsigned request with a concrete nonce.
9
9
  * @throws {UnexpectedRequirementSignatureError} If the permit requirement has no nonce.
10
10
  */
11
- export declare function buildPermitSignatureRequest(requirement: Pick<Requirement<Erc2612RequirementSignature>, "action">, id: string): SignatureRequest;
11
+ export declare function buildPermitSignatureRequest(requirement: Pick<Requirement<Erc2612RequirementSignature>, "action">, id: string): Extract<SignatureRequest, {
12
+ kind: "permit";
13
+ }>;
12
14
  /**
13
15
  * @internal Converts an approval transaction into a step with prepared chain/account inputs.
14
16
  * @param requirement - Direct token approval prerequisite.
@@ -23,8 +25,6 @@ export declare function buildApprovalStep(requirement: Readonly<Transaction<ERC2
23
25
  }): Step<Extract<Action, {
24
26
  type: "erc20Approval";
25
27
  }>>;
26
- /** @internal Token pull prerequisites: direct approvals or an ERC-2612 permit. */
27
- type TokenRequirement = Readonly<Transaction<ERC20ApprovalAction>> | Requirement<Erc2612RequirementSignature>;
28
28
  interface TokenRequirementsParams {
29
29
  readonly token: Address;
30
30
  readonly spender: Address;
@@ -35,11 +35,20 @@ interface TokenRequirementsParams {
35
35
  readonly now: bigint;
36
36
  readonly supportSignature: boolean;
37
37
  readonly deployless: boolean | undefined;
38
+ readonly permitId: string;
39
+ readonly approvalId: (index: number) => string;
38
40
  }
39
41
  /**
40
- * @internal Resolves the token prerequisite of a VaultBundlesV1 pull without Permit2. A sufficient
42
+ * @internal Resolves the token prerequisite of a bundles pull without Permit2. A sufficient
41
43
  * direct allowance yields nothing. Otherwise signature support prefers an ERC-2612 permit when
42
44
  * available and falls back to a direct unlimited approval. Without signature support, always approve.
43
45
  */
44
- export declare function getTokenRequirements(client: Client, params: TokenRequirementsParams): Promise<readonly TokenRequirement[]>;
46
+ export declare function getTokenRequirements(client: Client, params: TokenRequirementsParams): Promise<{
47
+ readonly approvals: Step<Extract<Action, {
48
+ type: "erc20Approval";
49
+ }>>[];
50
+ readonly permit?: Extract<SignatureRequest, {
51
+ kind: "permit";
52
+ }>;
53
+ }>;
45
54
  export {};
@@ -1,6 +1,6 @@
1
1
  import { erc20Abi } from "viem";
2
2
  import { readContract } from "viem/actions";
3
- import { getRequirementsApproval } from "../actions/requirements/getRequirementsApproval.js";
3
+ import { capTokenApproval, getTokenApprovalAmounts, } from "../helpers/tokenApproval.js";
4
4
  import { UnexpectedRequirementSignatureError } from "../types/error.js";
5
5
  import { getTokenPermit } from "./getTokenPermit.js";
6
6
  /**
@@ -47,34 +47,52 @@ export function buildApprovalStep(requirement, { id, chainId, account, denominat
47
47
  };
48
48
  }
49
49
  /**
50
- * @internal Resolves the token prerequisite of a VaultBundlesV1 pull without Permit2. A sufficient
50
+ * @internal Resolves the token prerequisite of a bundles pull without Permit2. A sufficient
51
51
  * direct allowance yields nothing. Otherwise signature support prefers an ERC-2612 permit when
52
52
  * available and falls back to a direct unlimited approval. Without signature support, always approve.
53
53
  */
54
54
  export async function getTokenRequirements(client, params) {
55
+ const { token, spender, amount, owner, chainId, permitId, approvalId } = params;
55
56
  // The allowance is trusted as returned by the RPC. See THREAT_MODEL.md, RPC.
56
57
  const allowance = await readContract(client, {
57
58
  abi: erc20Abi,
58
- address: params.token,
59
+ address: token,
59
60
  functionName: "allowance",
60
- args: [params.owner, params.spender],
61
+ args: [owner, spender],
61
62
  });
62
- if (allowance >= params.amount) {
63
- return [];
63
+ if (allowance >= amount) {
64
+ return { approvals: [] };
64
65
  }
65
66
  if (params.supportSignature) {
66
67
  const permit = await getTokenPermit(client, {
67
68
  ...params,
69
+ id: permitId,
68
70
  supportDeployless: params.deployless,
69
71
  });
70
72
  if (permit !== undefined) {
71
- return [permit];
73
+ return { approvals: [], permit };
72
74
  }
73
75
  }
74
- return getRequirementsApproval({
75
- address: params.token,
76
- chainId: params.chainId,
77
- args: { spendAmount: params.amount, spender: params.spender },
78
- allowances: allowance,
76
+ const amounts = getTokenApprovalAmounts({
77
+ token,
78
+ chainId,
79
+ allowance,
80
+ spendAmount: amount,
79
81
  });
82
+ return {
83
+ approvals: amounts.map((approvalAmount, index) => ({
84
+ id: approvalId(index),
85
+ label: "Approve token spending",
86
+ action: {
87
+ type: "erc20Approval",
88
+ inputs: {
89
+ token,
90
+ spender,
91
+ assets: capTokenApproval({ token, chainId, amount: approvalAmount }),
92
+ chainId,
93
+ account: owner,
94
+ },
95
+ },
96
+ })),
97
+ };
80
98
  }
@@ -14,11 +14,14 @@ export declare function serializeTransactionPlan(plan: TransactionPlan): string;
14
14
  /**
15
15
  * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
16
16
  * Restores bigint fields and validates version, action/request shapes, uint256 ranges, unique IDs,
17
- * references, per-action chain/account and permit/action consistency, including signed requests.
18
- * Extra keys are allowed. No clock or RPC is used: expiry, live state, signature ownership and
19
- * action-layer business constraints are not checked. Parsing does not prove authenticity or intent;
17
+ * references, per-action chain/account and signature-request consistency, including signed requests.
18
+ * Extra keys are allowed. No clock or RPC is used: current expiry, live state and
19
+ * action-layer business constraints are not checked. Stored signatures are recovered offline.
20
+ * Permits bind owner, token, spender, value, nonce, deadline and chain; Morpho authorizations bind
21
+ * owner, authorized address, nonce, deadline and chain, not operation amounts, markets or referral fees/recipients.
22
+ * Parsing does not prove authenticity or intent for unsigned fields;
20
23
  * tampered but well-formed, internally consistent plans pass. Integrators must protect stored plans.
21
- * Use `applySignatures` to verify new signatures; existing restored signatures remain trusted.
24
+ * Integrators must protect unsigned stored fields even when all signatures verify.
22
25
  * @param json - JSON previously returned by `serializeTransactionPlan`.
23
26
  * @returns The restored plan.
24
27
  * @throws {InvalidTransactionPlanError} At the first malformed JSON, field shape or consistency failure, exposing its JSON `path` and `reason`.