@morpho-org/morpho-sdk 9.6.0-next.0 → 9.7.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 (211) hide show
  1. package/MIGRATION-v6-to-v7.md +1 -1
  2. package/README.md +123 -3
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +1 -5
  5. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +2 -2
  6. package/lib/cjs/actions/bundles/common.js +39 -32
  7. package/lib/cjs/actions/midnight/cancelAndMake.js +20 -98
  8. package/lib/cjs/actions/midnight/index.d.ts +2 -0
  9. package/lib/cjs/actions/midnight/index.js +2 -0
  10. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +5 -6
  11. package/lib/cjs/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  12. package/lib/cjs/actions/midnight/supplyCollateralBatch.js +91 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +31 -32
  14. package/lib/cjs/actions/midnight/takeBorrow.js +24 -23
  15. package/lib/cjs/actions/midnight/takeLend.js +24 -23
  16. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  17. package/lib/cjs/actions/midnight/takeWithdraw.js +24 -23
  18. package/lib/cjs/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  19. package/lib/cjs/actions/midnight/withdrawCollateralBatch.js +104 -0
  20. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  21. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  22. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  23. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +1 -0
  24. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  25. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  26. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  27. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  28. package/lib/cjs/actions/vaultV1/migrateToV2.js +7 -7
  29. package/lib/cjs/blue/abis.d.ts +1 -1
  30. package/lib/cjs/blue/abis.js +1 -5
  31. package/lib/cjs/blue/entities.d.ts +4 -4
  32. package/lib/cjs/blue/entities.js +1 -3
  33. package/lib/cjs/blue/errors.d.ts +2 -2
  34. package/lib/cjs/blue/errors.js +1 -5
  35. package/lib/cjs/blue/fetch.d.ts +2 -2
  36. package/lib/cjs/blue/fetch.js +1 -3
  37. package/lib/cjs/blue/utils.d.ts +1 -1
  38. package/lib/cjs/blue/utils.js +1 -2
  39. package/lib/cjs/entities/index.d.ts +5 -5
  40. package/lib/cjs/entities/index.js +1 -3
  41. package/lib/cjs/entities/midnight/midnight.d.ts +77 -3
  42. package/lib/cjs/entities/midnight/midnight.js +174 -0
  43. package/lib/cjs/entities/midnight/types.d.ts +16 -0
  44. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +12 -46
  45. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +7 -0
  46. package/lib/cjs/entities/requirements/getErc2612Permit.js +60 -0
  47. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
  48. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +3 -3
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +10 -35
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +1 -33
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +3 -5
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +3 -9
  53. package/lib/cjs/errors.d.ts +4 -4
  54. package/lib/cjs/errors.js +6 -7
  55. package/lib/cjs/fetch.d.ts +2 -2
  56. package/lib/cjs/fetch.js +1 -3
  57. package/lib/cjs/helpers/deadShares.js +0 -2
  58. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +1 -0
  59. package/lib/cjs/helpers/signAndVerifyTypedData.js +12 -5
  60. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  61. package/lib/cjs/helpers/validateMidnightCancelAndMakePublication.js +129 -0
  62. package/lib/cjs/helpers/validateMidnightCollateralBatch.d.ts +15 -0
  63. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +28 -0
  64. package/lib/cjs/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  65. package/lib/cjs/helpers/validateMidnightCollateralSupplies.js +28 -0
  66. package/lib/cjs/helpers/validatePositiveInput.d.ts +10 -0
  67. package/lib/cjs/helpers/validatePositiveInput.js +18 -0
  68. package/lib/cjs/index.d.ts +2 -0
  69. package/lib/cjs/index.js +18 -1
  70. package/lib/cjs/midnight/errors.d.ts +1 -2
  71. package/lib/cjs/midnight/errors.js +5 -5
  72. package/lib/cjs/transactionPlan/approval.d.ts +2 -0
  73. package/lib/cjs/transactionPlan/approval.js +16 -0
  74. package/lib/cjs/transactionPlan/error.d.ts +145 -0
  75. package/lib/cjs/transactionPlan/error.js +186 -0
  76. package/lib/cjs/transactionPlan/getTokenPermit.d.ts +11 -0
  77. package/lib/cjs/transactionPlan/getTokenPermit.js +18 -0
  78. package/lib/cjs/transactionPlan/index.d.ts +9 -0
  79. package/lib/cjs/transactionPlan/index.js +24 -0
  80. package/lib/cjs/transactionPlan/intent.d.ts +51 -0
  81. package/lib/cjs/transactionPlan/intent.js +54 -0
  82. package/lib/cjs/transactionPlan/permit.d.ts +13 -0
  83. package/lib/cjs/transactionPlan/permit.js +145 -0
  84. package/lib/cjs/transactionPlan/plan.d.ts +99 -0
  85. package/lib/cjs/transactionPlan/plan.js +232 -0
  86. package/lib/cjs/transactionPlan/requirements.d.ts +44 -0
  87. package/lib/cjs/transactionPlan/requirements.js +79 -0
  88. package/lib/cjs/transactionPlan/serde.d.ts +33 -0
  89. package/lib/cjs/transactionPlan/serde.js +205 -0
  90. package/lib/cjs/transactionPlan/types.d.ts +91 -0
  91. package/lib/cjs/transactionPlan/types.js +2 -0
  92. package/lib/cjs/transactionPlan/validateActions.d.ts +8 -0
  93. package/lib/cjs/transactionPlan/validateActions.js +19 -0
  94. package/lib/cjs/transactionPlan/validation.d.ts +17 -0
  95. package/lib/cjs/transactionPlan/validation.js +70 -0
  96. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +81 -0
  97. package/lib/cjs/transactionPlan/vaultv2/deposit.js +211 -0
  98. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +77 -0
  99. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +190 -0
  100. package/lib/cjs/transactionPlan/version.d.ts +2 -0
  101. package/lib/cjs/transactionPlan/version.js +9 -0
  102. package/lib/cjs/types/action.d.ts +18 -3
  103. package/lib/cjs/types/error.d.ts +23 -2
  104. package/lib/cjs/types/error.js +45 -5
  105. package/lib/cjs/utils.d.ts +2 -2
  106. package/lib/cjs/utils.js +2 -4
  107. package/lib/esm/abis.d.ts +1 -1
  108. package/lib/esm/abis.js +1 -1
  109. package/lib/esm/actions/blue/repayWithdrawCollateral.js +2 -2
  110. package/lib/esm/actions/bundles/common.js +39 -32
  111. package/lib/esm/actions/midnight/cancelAndMake.js +25 -103
  112. package/lib/esm/actions/midnight/index.d.ts +2 -0
  113. package/lib/esm/actions/midnight/index.js +2 -0
  114. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +5 -6
  115. package/lib/esm/actions/midnight/supplyCollateralBatch.d.ts +39 -0
  116. package/lib/esm/actions/midnight/supplyCollateralBatch.js +87 -0
  117. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +33 -34
  118. package/lib/esm/actions/midnight/takeBorrow.js +25 -24
  119. package/lib/esm/actions/midnight/takeLend.js +25 -24
  120. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +20 -19
  121. package/lib/esm/actions/midnight/takeWithdraw.js +25 -24
  122. package/lib/esm/actions/midnight/withdrawCollateralBatch.d.ts +44 -0
  123. package/lib/esm/actions/midnight/withdrawCollateralBatch.js +100 -0
  124. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +1 -0
  125. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +1 -0
  126. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +1 -0
  127. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +1 -0
  128. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +1 -0
  129. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +1 -0
  130. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -0
  131. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +1 -0
  132. package/lib/esm/actions/vaultV1/migrateToV2.js +8 -8
  133. package/lib/esm/blue/abis.d.ts +1 -1
  134. package/lib/esm/blue/abis.js +1 -1
  135. package/lib/esm/blue/entities.d.ts +4 -4
  136. package/lib/esm/blue/entities.js +2 -2
  137. package/lib/esm/blue/errors.d.ts +2 -2
  138. package/lib/esm/blue/errors.js +2 -2
  139. package/lib/esm/blue/fetch.d.ts +2 -2
  140. package/lib/esm/blue/fetch.js +2 -2
  141. package/lib/esm/blue/utils.d.ts +1 -1
  142. package/lib/esm/blue/utils.js +1 -1
  143. package/lib/esm/entities/index.d.ts +5 -5
  144. package/lib/esm/entities/index.js +2 -2
  145. package/lib/esm/entities/midnight/midnight.d.ts +77 -3
  146. package/lib/esm/entities/midnight/midnight.js +176 -2
  147. package/lib/esm/entities/midnight/types.d.ts +16 -0
  148. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +14 -48
  149. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +7 -0
  150. package/lib/esm/entities/requirements/getErc2612Permit.js +57 -0
  151. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
  152. package/lib/esm/entities/vaultV1/vaultV1.d.ts +3 -3
  153. package/lib/esm/entities/vaultV2/vaultV2.d.ts +10 -35
  154. package/lib/esm/entities/vaultV2/vaultV2.js +1 -33
  155. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +3 -5
  156. package/lib/esm/entities/vaultV2BlueReallocationData.js +3 -9
  157. package/lib/esm/errors.d.ts +4 -4
  158. package/lib/esm/errors.js +4 -4
  159. package/lib/esm/fetch.d.ts +2 -2
  160. package/lib/esm/fetch.js +2 -2
  161. package/lib/esm/helpers/deadShares.js +1 -3
  162. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +1 -0
  163. package/lib/esm/helpers/signAndVerifyTypedData.js +13 -6
  164. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.d.ts +68 -0
  165. package/lib/esm/helpers/validateMidnightCancelAndMakePublication.js +124 -0
  166. package/lib/esm/helpers/validateMidnightCollateralBatch.d.ts +15 -0
  167. package/lib/esm/helpers/validateMidnightCollateralBatch.js +25 -0
  168. package/lib/esm/helpers/validateMidnightCollateralSupplies.d.ts +17 -0
  169. package/lib/esm/helpers/validateMidnightCollateralSupplies.js +24 -0
  170. package/lib/esm/helpers/validatePositiveInput.d.ts +10 -0
  171. package/lib/esm/helpers/validatePositiveInput.js +14 -0
  172. package/lib/esm/index.d.ts +2 -0
  173. package/lib/esm/index.js +1 -0
  174. package/lib/esm/midnight/errors.d.ts +1 -2
  175. package/lib/esm/midnight/errors.js +1 -2
  176. package/lib/esm/transactionPlan/approval.d.ts +2 -0
  177. package/lib/esm/transactionPlan/approval.js +13 -0
  178. package/lib/esm/transactionPlan/error.d.ts +145 -0
  179. package/lib/esm/transactionPlan/error.js +175 -0
  180. package/lib/esm/transactionPlan/getTokenPermit.d.ts +11 -0
  181. package/lib/esm/transactionPlan/getTokenPermit.js +15 -0
  182. package/lib/esm/transactionPlan/index.d.ts +9 -0
  183. package/lib/esm/transactionPlan/index.js +5 -0
  184. package/lib/esm/transactionPlan/intent.d.ts +51 -0
  185. package/lib/esm/transactionPlan/intent.js +51 -0
  186. package/lib/esm/transactionPlan/permit.d.ts +13 -0
  187. package/lib/esm/transactionPlan/permit.js +140 -0
  188. package/lib/esm/transactionPlan/plan.d.ts +99 -0
  189. package/lib/esm/transactionPlan/plan.js +226 -0
  190. package/lib/esm/transactionPlan/requirements.d.ts +44 -0
  191. package/lib/esm/transactionPlan/requirements.js +74 -0
  192. package/lib/esm/transactionPlan/serde.d.ts +33 -0
  193. package/lib/esm/transactionPlan/serde.js +201 -0
  194. package/lib/esm/transactionPlan/types.d.ts +91 -0
  195. package/lib/esm/transactionPlan/types.js +1 -0
  196. package/lib/esm/transactionPlan/validateActions.d.ts +8 -0
  197. package/lib/esm/transactionPlan/validateActions.js +16 -0
  198. package/lib/esm/transactionPlan/validation.d.ts +17 -0
  199. package/lib/esm/transactionPlan/validation.js +64 -0
  200. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +81 -0
  201. package/lib/esm/transactionPlan/vaultv2/deposit.js +206 -0
  202. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +77 -0
  203. package/lib/esm/transactionPlan/vaultv2/withdraw.js +185 -0
  204. package/lib/esm/transactionPlan/version.d.ts +2 -0
  205. package/lib/esm/transactionPlan/version.js +6 -0
  206. package/lib/esm/types/action.d.ts +18 -3
  207. package/lib/esm/types/error.d.ts +23 -2
  208. package/lib/esm/types/error.js +40 -3
  209. package/lib/esm/utils.d.ts +2 -2
  210. package/lib/esm/utils.js +2 -2
  211. package/package.json +8 -7
@@ -0,0 +1,205 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.serializeTransactionPlan = serializeTransactionPlan;
4
+ exports.parseTransactionPlan = parseTransactionPlan;
5
+ const viem_1 = require("viem");
6
+ const approval_js_1 = require("./approval.js");
7
+ const error_js_1 = require("./error.js");
8
+ const permit_js_1 = require("./permit.js");
9
+ const plan_js_1 = require("./plan.js");
10
+ const validateActions_js_1 = require("./validateActions.js");
11
+ const validation_js_1 = require("./validation.js");
12
+ const deposit_js_1 = require("./vaultv2/deposit.js");
13
+ const withdraw_js_1 = require("./vaultv2/withdraw.js");
14
+ const version_js_1 = require("./version.js");
15
+ const actionValidators = {
16
+ erc20Approval: approval_js_1.validateApprovalPlanAction,
17
+ vaultV2Deposit: deposit_js_1.validateDepositPlanAction,
18
+ vaultV2Withdraw: withdraw_js_1.validateWithdrawPlanAction,
19
+ };
20
+ /**
21
+ * Serializes plan data with a bigint replacer. No validation is performed.
22
+ * @param plan - Plan to save.
23
+ * @returns JSON with `$bigint` tags for bigint quantities.
24
+ * @example
25
+ * ```ts
26
+ * import { serializeTransactionPlan, type TransactionPlan } from "@morpho-org/morpho-sdk";
27
+ * const save = (plan: TransactionPlan) => serializeTransactionPlan(plan);
28
+ * ```
29
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
30
+ */
31
+ function serializeTransactionPlan(plan) {
32
+ return JSON.stringify(plan, function (key) {
33
+ // Read the original value even when the host has installed BigInt.prototype.toJSON.
34
+ const value = this[key];
35
+ return typeof value === "bigint" ? { $bigint: value.toString() } : value;
36
+ });
37
+ }
38
+ /**
39
+ * Restores bigint fields and validates version, action/request shapes, uint256 ranges, unique IDs,
40
+ * references, per-action chain/account and permit/action consistency, including signed requests.
41
+ * Extra keys are allowed. No clock or RPC is used: expiry, live state, signature ownership and
42
+ * action-layer business constraints are not checked. Parsing does not prove authenticity or intent;
43
+ * tampered but well-formed, internally consistent plans pass. Integrators must protect stored plans.
44
+ * Use `applySignatures` to verify new signatures; existing restored signatures remain trusted.
45
+ * @param json - JSON previously returned by `serializeTransactionPlan`.
46
+ * @returns The restored plan.
47
+ * @throws {InvalidTransactionPlanError} At the first malformed JSON, field shape or consistency failure, exposing its JSON `path` and `reason`.
48
+ * @throws {UnsupportedTransactionPlanVersionError} If the stored integer version is unsupported.
49
+ * @throws {UnsupportedTransactionPlanActionError} If a step names an unsupported action type.
50
+ * @example
51
+ * ```ts
52
+ * import { parseTransactionPlan } from "@morpho-org/morpho-sdk";
53
+ * const restore = (saved: string) => parseTransactionPlan(saved);
54
+ * ```
55
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
56
+ */
57
+ function parseTransactionPlan(json) {
58
+ let restored;
59
+ try {
60
+ restored = JSON.parse(json, (_key, field) => typeof field === "object" &&
61
+ field !== null &&
62
+ "$bigint" in field &&
63
+ typeof field.$bigint === "string"
64
+ ? BigInt(field.$bigint)
65
+ : field);
66
+ }
67
+ catch (cause) {
68
+ throw new error_js_1.InvalidTransactionPlanError({
69
+ path: "$",
70
+ reason: "expected JSON with valid bigint tags",
71
+ cause,
72
+ });
73
+ }
74
+ const plan = (0, validation_js_1.getPlanObject)(restored, "$");
75
+ (0, validation_js_1.validatePlanField)(plan.version, { path: "$.version", type: "safe integer" });
76
+ (0, version_js_1.validateTransactionPlanVersion)(plan.version);
77
+ (0, validation_js_1.validatePlanFields)(plan, {
78
+ path: "$",
79
+ fields: {
80
+ chainId: "positive safe integer",
81
+ account: "address",
82
+ expiresAt: "safe integer",
83
+ steps: "array",
84
+ signatureRequests: "array",
85
+ },
86
+ });
87
+ if (plan.calldataOrigin !== undefined)
88
+ (0, validation_js_1.validatePlanField)(plan.calldataOrigin, {
89
+ path: "$.calldataOrigin",
90
+ type: "hex",
91
+ });
92
+ const steps = plan.steps;
93
+ const requests = plan.signatureRequests;
94
+ const stepIds = new Set();
95
+ for (const [index, value] of steps.entries()) {
96
+ const path = `$.steps[${index}]`;
97
+ const step = (0, validation_js_1.getPlanObject)(value, path);
98
+ (0, validation_js_1.validatePlanFields)(step, {
99
+ path,
100
+ fields: { id: "string", label: "string" },
101
+ });
102
+ if (stepIds.has(step.id))
103
+ throw new error_js_1.InvalidTransactionPlanError({
104
+ path: `${path}.id`,
105
+ reason: "expected a unique step ID",
106
+ });
107
+ stepIds.add(step.id);
108
+ const action = (0, validation_js_1.getPlanObject)(step.action, `${path}.action`);
109
+ (0, validation_js_1.validatePlanField)(action.type, {
110
+ path: `${path}.action.type`,
111
+ type: "string",
112
+ });
113
+ }
114
+ // Preserve the existing action-type guard before dispatching action schemas.
115
+ (0, validateActions_js_1.validateTransactionPlanActions)(steps);
116
+ for (const [index, step] of steps.entries()) {
117
+ const path = `$.steps[${index}].action`;
118
+ const action = (0, validation_js_1.getPlanObject)(step.action, path);
119
+ const inputs = (0, validation_js_1.getPlanObject)(action.inputs, `${path}.inputs`);
120
+ (0, validation_js_1.validatePlanFields)(inputs, {
121
+ path: `${path}.inputs`,
122
+ fields: { chainId: "positive safe integer", account: "address" },
123
+ });
124
+ actionValidators[step.action.type](action, path);
125
+ if (inputs.chainId !== plan.chainId)
126
+ throw new error_js_1.InvalidTransactionPlanError({
127
+ path: `${path}.inputs.chainId`,
128
+ reason: "expected the plan chainId",
129
+ });
130
+ if (!(0, viem_1.isAddressEqual)(inputs.account, plan.account))
131
+ throw new error_js_1.InvalidTransactionPlanError({
132
+ path: `${path}.inputs.account`,
133
+ reason: "expected the plan account",
134
+ });
135
+ }
136
+ const requestIds = new Set();
137
+ for (const [index, value] of requests.entries()) {
138
+ const path = `$.signatureRequests[${index}]`;
139
+ const request = (0, validation_js_1.getPlanObject)(value, path);
140
+ (0, validation_js_1.validatePlanFields)(request, {
141
+ path,
142
+ fields: { id: "string", kind: "string" },
143
+ });
144
+ if (requestIds.has(request.id))
145
+ throw new error_js_1.InvalidTransactionPlanError({
146
+ path: `${path}.id`,
147
+ reason: "expected a unique signature request ID",
148
+ });
149
+ requestIds.add(request.id);
150
+ if (request.kind !== "permit")
151
+ throw new error_js_1.InvalidTransactionPlanError({
152
+ path: `${path}.kind`,
153
+ reason: "expected a supported signature request kind (permit)",
154
+ });
155
+ (0, permit_js_1.validatePermitPlanRequest)(request, path);
156
+ }
157
+ for (const [index, step] of steps.entries()) {
158
+ if (!("signatureRequestIds" in step.action))
159
+ continue;
160
+ const path = `$.steps[${index}].action.signatureRequestIds`;
161
+ const ids = (0, validation_js_1.getPlanObject)(step.action.signatureRequestIds, path);
162
+ for (const [role, id] of Object.entries(ids)) {
163
+ (0, validation_js_1.validatePlanField)(id, { path: `${path}.${role}`, type: "string" });
164
+ if (!requestIds.has(id))
165
+ throw new error_js_1.InvalidTransactionPlanError({
166
+ path: `${path}.${role}`,
167
+ reason: "expected an existing signature request ID",
168
+ });
169
+ }
170
+ }
171
+ const result = restored;
172
+ try {
173
+ // Clear signatures so the existing pure consistency check validates every request.
174
+ (0, plan_js_1.getPendingSignatureRequests)({
175
+ ...result,
176
+ signatureRequests: result.signatureRequests.map((request) => ({
177
+ ...request,
178
+ signature: undefined,
179
+ })),
180
+ });
181
+ }
182
+ catch (cause) {
183
+ if (cause instanceof error_js_1.TransactionPlanSignatureMismatchError) {
184
+ const index = result.signatureRequests.findIndex((request) => request.id === cause.id);
185
+ const field = cause.field === "reference"
186
+ ? "id"
187
+ : cause.field === "value"
188
+ ? "args.amount"
189
+ : cause.field.startsWith("args.")
190
+ ? cause.field
191
+ : `typedData.${cause.field}`;
192
+ throw new error_js_1.InvalidTransactionPlanError({
193
+ path: `$.signatureRequests[${index}].${field}`,
194
+ reason: "expected agreement with every referencing action",
195
+ cause,
196
+ });
197
+ }
198
+ throw new error_js_1.InvalidTransactionPlanError({
199
+ path: "$.signatureRequests",
200
+ reason: "expected requests consistent with supported action chains",
201
+ cause,
202
+ });
203
+ }
204
+ return result;
205
+ }
@@ -0,0 +1,91 @@
1
+ import type { Address, Hex } from "viem";
2
+ import type { BundlesFundingArgs, PermitAction, RequirementTypedData } from "../types/index.js";
3
+ interface ActionInputs {
4
+ readonly chainId: number;
5
+ readonly account: Address;
6
+ }
7
+ interface VaultInputs extends ActionInputs {
8
+ readonly vault: Address;
9
+ readonly deadline: bigint;
10
+ readonly referralFeePct: bigint;
11
+ readonly referralFeeRecipient: Address;
12
+ }
13
+ /** Signature request roles a vault action selects by plan-local ID. */
14
+ type VaultSignatureRequestIds = {
15
+ /** Token permit consumed by the action; omitted when no permit is needed. */
16
+ readonly tokenPermit?: string;
17
+ };
18
+ /**
19
+ * Recipes supported by Vault V2 plans. Each `type` equals the `action.type` of the
20
+ * {@link TransactionAction} it builds.
21
+ * Snapshot-derived values such as the asset and the quote are fixed on `inputs` at preparation;
22
+ * each action also carries its own chain and account on `inputs`.
23
+ * the role map `signatureRequestIds` is a step's only request reference.
24
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
25
+ */
26
+ export type Action = {
27
+ readonly type: "erc20Approval";
28
+ readonly inputs: ActionInputs & {
29
+ readonly token: Address;
30
+ readonly spender: Address;
31
+ readonly amount: bigint;
32
+ };
33
+ } | {
34
+ readonly type: "vaultV2Deposit";
35
+ readonly inputs: VaultInputs & BundlesFundingArgs & {
36
+ /** Vault asset read from the snapshot. */
37
+ readonly asset: Address;
38
+ /** Deadline-accrued RAY-scaled bound quoted from the snapshot for the net deposit. */
39
+ readonly maxSharePrice: bigint;
40
+ };
41
+ readonly signatureRequestIds: VaultSignatureRequestIds;
42
+ } | {
43
+ readonly type: "vaultV2Withdraw";
44
+ readonly inputs: VaultInputs & {
45
+ readonly amount: bigint;
46
+ /** Minimum share allowance quoted from the snapshot for the gross withdrawal. */
47
+ readonly requiredShareAllowance: bigint;
48
+ };
49
+ readonly signatureRequestIds: VaultSignatureRequestIds;
50
+ };
51
+ /**
52
+ * A recipe with a plan-unique `id`; its request dependencies are the roles its action names.
53
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
54
+ */
55
+ export interface Step<TAction extends Action = Action> {
56
+ readonly id: string;
57
+ readonly label: string;
58
+ readonly action: TAction;
59
+ }
60
+ /**
61
+ * ERC-2612 permit request exposed as `{ id, kind, typedData }`. `signature` is undefined until the
62
+ * account signs `typedData`. Protocol milestones add further `kind`s such as Blue authorization.
63
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
64
+ */
65
+ export interface SignatureRequest {
66
+ readonly id: string;
67
+ readonly kind: "permit";
68
+ readonly typedData: RequirementTypedData;
69
+ readonly args: PermitAction["args"] & {
70
+ readonly nonce: bigint;
71
+ };
72
+ readonly signature?: Hex;
73
+ }
74
+ /**
75
+ * Data-only operation prepared for one chain and account from the caller's intent and a vault
76
+ * snapshot. Every step and signature request carries its own `id`, unique within the plan. Once
77
+ * prepared, a plan is static: only signatures are added before building.
78
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
79
+ */
80
+ export interface TransactionPlan {
81
+ readonly version: 1;
82
+ readonly chainId: number;
83
+ readonly account: Address;
84
+ /** Unix seconds. One expiry governs every step deadline and signature deadline. */
85
+ readonly expiresAt: number;
86
+ /** Appended verbatim to every built transaction's calldata. */
87
+ readonly calldataOrigin?: Hex;
88
+ readonly steps: readonly Step[];
89
+ readonly signatureRequests: readonly SignatureRequest[];
90
+ }
91
+ export {};
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,8 @@
1
+ import type { Step } from "./types.js";
2
+ /**
3
+ * @internal Rejects unknown action types before interpreting requests or updates.
4
+ * @param steps - Steps whose action discriminators must be supported.
5
+ * @returns Nothing when every action type is supported.
6
+ * @throws {UnsupportedTransactionPlanActionError} when any step names an unsupported action type.
7
+ */
8
+ export declare function validateTransactionPlanActions(steps: readonly Step[]): void;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateTransactionPlanActions = validateTransactionPlanActions;
4
+ const error_js_1 = require("./error.js");
5
+ /**
6
+ * @internal Rejects unknown action types before interpreting requests or updates.
7
+ * @param steps - Steps whose action discriminators must be supported.
8
+ * @returns Nothing when every action type is supported.
9
+ * @throws {UnsupportedTransactionPlanActionError} when any step names an unsupported action type.
10
+ */
11
+ function validateTransactionPlanActions(steps) {
12
+ for (const step of steps) {
13
+ const actionType = step.action.type;
14
+ if (actionType !== "erc20Approval" &&
15
+ actionType !== "vaultV2Deposit" &&
16
+ actionType !== "vaultV2Withdraw")
17
+ throw new error_js_1.UnsupportedTransactionPlanActionError(actionType);
18
+ }
19
+ }
@@ -0,0 +1,17 @@
1
+ /** @internal Scalar and collection shapes used by stored plan fields. */
2
+ type PlanFieldType = "string" | "address" | "hex" | "safe integer" | "positive safe integer" | "uint256 bigint" | "array";
3
+ /** @internal Validates one restored field without coercing it. */
4
+ export declare function validatePlanField(value: unknown, options: {
5
+ readonly path: string;
6
+ readonly type: PlanFieldType;
7
+ }): void;
8
+ /** @internal Requires a non-null, non-array JSON object. */
9
+ export declare function getPlanObject(value: unknown, path: string): Record<string, unknown>;
10
+ /** @internal Validates required fields while permitting additional keys. */
11
+ export declare function validatePlanFields(value: Record<string, unknown>, options: {
12
+ readonly path: string;
13
+ readonly fields: Readonly<Record<string, PlanFieldType>>;
14
+ }): void;
15
+ /** @internal Validates the shared stored vault-action fields and role map. */
16
+ export declare function validateVaultPlanAction(action: Record<string, unknown>, path: string): Record<string, unknown>;
17
+ export {};
@@ -0,0 +1,70 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validatePlanField = validatePlanField;
4
+ exports.getPlanObject = getPlanObject;
5
+ exports.validatePlanFields = validatePlanFields;
6
+ exports.validateVaultPlanAction = validateVaultPlanAction;
7
+ const viem_1 = require("viem");
8
+ const error_js_1 = require("./error.js");
9
+ /** @internal Validates one restored field without coercing it. */
10
+ function validatePlanField(value, options) {
11
+ const { path, type } = options;
12
+ let valid;
13
+ switch (type) {
14
+ case "string":
15
+ valid = typeof value === "string";
16
+ break;
17
+ case "address":
18
+ valid = typeof value === "string" && (0, viem_1.isAddress)(value);
19
+ break;
20
+ case "hex":
21
+ valid =
22
+ typeof value === "string" && /^0x(?:[0-9a-fA-F]{2})*$/.test(value);
23
+ break;
24
+ case "safe integer":
25
+ valid = typeof value === "number" && Number.isSafeInteger(value);
26
+ break;
27
+ case "positive safe integer":
28
+ valid =
29
+ typeof value === "number" && Number.isSafeInteger(value) && value > 0;
30
+ break;
31
+ case "uint256 bigint":
32
+ valid = typeof value === "bigint" && value >= 0n && value <= viem_1.maxUint256;
33
+ break;
34
+ case "array":
35
+ valid = Array.isArray(value);
36
+ break;
37
+ }
38
+ if (!valid)
39
+ throw new error_js_1.InvalidTransactionPlanError({ path, reason: `expected ${type}` });
40
+ }
41
+ /** @internal Requires a non-null, non-array JSON object. */
42
+ function getPlanObject(value, path) {
43
+ if (typeof value !== "object" || value === null || Array.isArray(value))
44
+ throw new error_js_1.InvalidTransactionPlanError({
45
+ path,
46
+ reason: "expected an object",
47
+ });
48
+ return value;
49
+ }
50
+ /** @internal Validates required fields while permitting additional keys. */
51
+ function validatePlanFields(value, options) {
52
+ for (const [key, type] of Object.entries(options.fields))
53
+ validatePlanField(value[key], { path: `${options.path}.${key}`, type });
54
+ }
55
+ /** @internal Validates the shared stored vault-action fields and role map. */
56
+ function validateVaultPlanAction(action, path) {
57
+ const inputs = getPlanObject(action.inputs, `${path}.inputs`);
58
+ validatePlanFields(inputs, {
59
+ path: `${path}.inputs`,
60
+ fields: {
61
+ vault: "address",
62
+ deadline: "uint256 bigint",
63
+ referralFeePct: "uint256 bigint",
64
+ referralFeeRecipient: "address",
65
+ },
66
+ });
67
+ // Vault actions require a role map even when no permit is needed.
68
+ getPlanObject(action.signatureRequestIds, `${path}.signatureRequestIds`);
69
+ return inputs;
70
+ }
@@ -0,0 +1,81 @@
1
+ import { type AccrualVaultV2 } from "@morpho-org/blue-sdk";
2
+ import { type Address, type Client } from "viem";
3
+ import { type Transaction, type VaultV2DepositAction } from "../../types/index.js";
4
+ import { type Funding, type IntentParams } from "../intent.js";
5
+ import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
6
+ /** @internal Validates the stored Vault V2 deposit action's input shape. */
7
+ export declare function validateDepositPlanAction(action: Record<string, unknown>, path: string): void;
8
+ /**
9
+ * Caller intent for a Vault V2 deposit, mirroring the Actions API deposit inputs, plus the snapshot.
10
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
11
+ */
12
+ export interface VaultV2DepositPlanParams extends IntentParams {
13
+ /** WAD-scaled tolerance for the share-price bound; defaults to `DEFAULT_SLIPPAGE_TOLERANCE`. */
14
+ readonly slippageTolerance?: bigint;
15
+ readonly vault: Address;
16
+ /** Gross amount the account pays, before the referral fee. */
17
+ readonly amount: bigint;
18
+ /** Defaults to `{ type: "erc20" }`. */
19
+ readonly funding?: Funding;
20
+ /**
21
+ * Accrual snapshot of `vault`, fetched by the caller with `fetchAccrualVaultV2`. The asset and
22
+ * the deadline-accrued `maxSharePrice` are derived from it at preparation; the snapshot itself is
23
+ * never stored in the plan.
24
+ */
25
+ readonly vaultData: AccrualVaultV2;
26
+ }
27
+ /**
28
+ * Prepares a deposit plan from caller intent and a vault snapshot, reading the token prerequisites
29
+ * directly. The quote is fixed on the deposit step at preparation, so the returned plan is static:
30
+ * only signatures are added before building.
31
+ * @param client - Viem client for `params.chainId`, used for allowance and permit metadata reads only.
32
+ * @param params.vault - Vault V2 contract receiving the net deposit.
33
+ * @param params.vaultData - Caller-fetched `AccrualVaultV2` snapshot of `vault`, used to derive the asset and deadline-accrued share-price bound.
34
+ * @param params.chainId - Chain containing the vault and registered VaultBundlesV1 contract.
35
+ * @param params.account - Non-zero account funding, signing and sending the deposit.
36
+ * @param params.amount - Positive gross deposit in asset base units, before referral fees.
37
+ * @param params.funding.type - Optional funding source: `"erc20"` (default) or `"native"`; native funding requires the vault asset to be wNative.
38
+ * @param params.referralFee.bps - Optional integer fee in basis points of the gross amount; defaults to zero and must be below 10,000.
39
+ * @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
40
+ * @param params.slippageTolerance - Optional WAD-scaled tolerance for the share-price bound; defaults to `DEFAULT_SLIPPAGE_TOLERANCE` and must not exceed `MAX_SLIPPAGE_TOLERANCE`.
41
+ * @param params.supportSignature - Optional ERC-2612 preference, defaulting to `false`; when enabled, falls back to direct approval if no permit is available.
42
+ * @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
43
+ * @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
44
+ * @param params.deployless - Optional permission to use deployless aggregation for token permit metadata reads.
45
+ * @returns A plan with approvals, concrete signature requests and the deposit step.
46
+ * @throws {ZeroAccountError} when `account` is the zero address.
47
+ * @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
48
+ * @throws {NonPositiveInputError} when `expiresAt`, `amount`, net assets or previewed shares are not positive.
49
+ * @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
50
+ * @throws {NegativeInputError} when `referralFee.bps` or `slippageTolerance` is negative.
51
+ * @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
52
+ * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds `MAX_SLIPPAGE_TOLERANCE`.
53
+ * @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
54
+ * @throws {ReferralFeePctExceededError} when `referralFee.bps` equals 10,000; the normalized fee must be below WAD.
55
+ * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient or a zero recipient.
56
+ * @throws {VaultAddressMismatchError} when `vaultData` describes another vault.
57
+ * @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a vault whose asset is not wNative.
58
+ * @throws {ChainIdMismatchError} when the client targets another chain.
59
+ * @throws {MissingContractCodeError} when the VaultBundlesV1 contract is absent.
60
+ * @see computeVaultMaxSharePrice for quote errors.
61
+ * @example
62
+ * ```ts
63
+ * import { prepareVaultV2Deposit } from "@morpho-org/morpho-sdk";
64
+ * import { fetchAccrualVaultV2 } from "@morpho-org/morpho-sdk/fetch";
65
+ * import { createPublicClient, http } from "viem";
66
+ * import { mainnet } from "viem/chains";
67
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
68
+ * const vault = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
69
+ * const plan = await prepareVaultV2Deposit(client, {
70
+ * vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
71
+ * vaultData: await fetchAccrualVaultV2(vault, client),
72
+ * });
73
+ * // Sign the pending requests, verify and attach with applySignatures, then build.
74
+ * ```
75
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
76
+ */
77
+ export declare function prepareVaultV2Deposit(client: Client, params: VaultV2DepositPlanParams): Promise<TransactionPlan>;
78
+ /** @internal Encodes the deposit from its self-contained inputs and resolved signature requests. */
79
+ export declare function buildVaultV2Deposit(action: Extract<Action, {
80
+ type: "vaultV2Deposit";
81
+ }>, requests: readonly SignatureRequest[]): Readonly<Transaction<VaultV2DepositAction>>;