@morpho-org/morpho-sdk 9.6.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 (83) hide show
  1. package/MIGRATION-v6-to-v7.md +1 -1
  2. package/README.md +64 -3
  3. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +12 -46
  4. package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +7 -0
  5. package/lib/cjs/entities/requirements/getErc2612Permit.js +60 -0
  6. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
  7. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +3 -3
  8. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +2 -2
  9. package/lib/cjs/helpers/validateMidnightCollateralBatch.d.ts +1 -0
  10. package/lib/cjs/helpers/validateMidnightCollateralBatch.js +1 -0
  11. package/lib/cjs/index.d.ts +2 -0
  12. package/lib/cjs/index.js +18 -1
  13. package/lib/cjs/transactionPlan/approval.d.ts +2 -0
  14. package/lib/cjs/transactionPlan/approval.js +16 -0
  15. package/lib/cjs/transactionPlan/error.d.ts +145 -0
  16. package/lib/cjs/transactionPlan/error.js +186 -0
  17. package/lib/cjs/transactionPlan/getTokenPermit.d.ts +11 -0
  18. package/lib/cjs/transactionPlan/getTokenPermit.js +18 -0
  19. package/lib/cjs/transactionPlan/index.d.ts +9 -0
  20. package/lib/cjs/transactionPlan/index.js +24 -0
  21. package/lib/cjs/transactionPlan/intent.d.ts +51 -0
  22. package/lib/cjs/transactionPlan/intent.js +54 -0
  23. package/lib/cjs/transactionPlan/permit.d.ts +13 -0
  24. package/lib/cjs/transactionPlan/permit.js +145 -0
  25. package/lib/cjs/transactionPlan/plan.d.ts +99 -0
  26. package/lib/cjs/transactionPlan/plan.js +232 -0
  27. package/lib/cjs/transactionPlan/requirements.d.ts +44 -0
  28. package/lib/cjs/transactionPlan/requirements.js +79 -0
  29. package/lib/cjs/transactionPlan/serde.d.ts +33 -0
  30. package/lib/cjs/transactionPlan/serde.js +205 -0
  31. package/lib/cjs/transactionPlan/types.d.ts +91 -0
  32. package/lib/cjs/transactionPlan/types.js +2 -0
  33. package/lib/cjs/transactionPlan/validateActions.d.ts +8 -0
  34. package/lib/cjs/transactionPlan/validateActions.js +19 -0
  35. package/lib/cjs/transactionPlan/validation.d.ts +17 -0
  36. package/lib/cjs/transactionPlan/validation.js +70 -0
  37. package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +81 -0
  38. package/lib/cjs/transactionPlan/vaultv2/deposit.js +211 -0
  39. package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +77 -0
  40. package/lib/cjs/transactionPlan/vaultv2/withdraw.js +190 -0
  41. package/lib/cjs/transactionPlan/version.d.ts +2 -0
  42. package/lib/cjs/transactionPlan/version.js +9 -0
  43. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +14 -48
  44. package/lib/esm/entities/requirements/getErc2612Permit.d.ts +7 -0
  45. package/lib/esm/entities/requirements/getErc2612Permit.js +57 -0
  46. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
  47. package/lib/esm/entities/vaultV1/vaultV1.d.ts +3 -3
  48. package/lib/esm/entities/vaultV2/vaultV2.d.ts +2 -2
  49. package/lib/esm/helpers/validateMidnightCollateralBatch.d.ts +1 -0
  50. package/lib/esm/helpers/validateMidnightCollateralBatch.js +1 -0
  51. package/lib/esm/index.d.ts +2 -0
  52. package/lib/esm/index.js +1 -0
  53. package/lib/esm/transactionPlan/approval.d.ts +2 -0
  54. package/lib/esm/transactionPlan/approval.js +13 -0
  55. package/lib/esm/transactionPlan/error.d.ts +145 -0
  56. package/lib/esm/transactionPlan/error.js +175 -0
  57. package/lib/esm/transactionPlan/getTokenPermit.d.ts +11 -0
  58. package/lib/esm/transactionPlan/getTokenPermit.js +15 -0
  59. package/lib/esm/transactionPlan/index.d.ts +9 -0
  60. package/lib/esm/transactionPlan/index.js +5 -0
  61. package/lib/esm/transactionPlan/intent.d.ts +51 -0
  62. package/lib/esm/transactionPlan/intent.js +51 -0
  63. package/lib/esm/transactionPlan/permit.d.ts +13 -0
  64. package/lib/esm/transactionPlan/permit.js +140 -0
  65. package/lib/esm/transactionPlan/plan.d.ts +99 -0
  66. package/lib/esm/transactionPlan/plan.js +226 -0
  67. package/lib/esm/transactionPlan/requirements.d.ts +44 -0
  68. package/lib/esm/transactionPlan/requirements.js +74 -0
  69. package/lib/esm/transactionPlan/serde.d.ts +33 -0
  70. package/lib/esm/transactionPlan/serde.js +201 -0
  71. package/lib/esm/transactionPlan/types.d.ts +91 -0
  72. package/lib/esm/transactionPlan/types.js +1 -0
  73. package/lib/esm/transactionPlan/validateActions.d.ts +8 -0
  74. package/lib/esm/transactionPlan/validateActions.js +16 -0
  75. package/lib/esm/transactionPlan/validation.d.ts +17 -0
  76. package/lib/esm/transactionPlan/validation.js +64 -0
  77. package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +81 -0
  78. package/lib/esm/transactionPlan/vaultv2/deposit.js +206 -0
  79. package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +77 -0
  80. package/lib/esm/transactionPlan/vaultv2/withdraw.js +185 -0
  81. package/lib/esm/transactionPlan/version.d.ts +2 -0
  82. package/lib/esm/transactionPlan/version.js +6 -0
  83. package/package.json +6 -5
@@ -0,0 +1,226 @@
1
+ import { deepFreeze } from "@morpho-org/morpho-ts";
2
+ import { secp256k1 } from "@noble/curves/secp256k1";
3
+ import { concatHex, hashTypedData, isAddressEqual, serializeSignature, toHex, } from "viem";
4
+ import { publicKeyToAddress } from "viem/accounts";
5
+ import { normalizeBundlesSignature } from "../actions/bundles/common.js";
6
+ import { encodeErc20Approval } from "../actions/index.js";
7
+ import { InvalidSignatureError } from "../types/error.js";
8
+ import { IncompleteTransactionPlanError, TransactionPlanSignatureMismatchError, } from "./error.js";
9
+ import { validateSignatureRequest } from "./permit.js";
10
+ import { validateTransactionPlanActions } from "./validateActions.js";
11
+ import { buildVaultV2Deposit } from "./vaultv2/deposit.js";
12
+ import { buildVaultV2Withdraw } from "./vaultv2/withdraw.js";
13
+ import { validateTransactionPlanVersion } from "./version.js";
14
+ /**
15
+ * Validates every request against its actions, verifies supplied ECDSA signatures synchronously,
16
+ * and attaches serialized signatures by request ID. No client or RPC is used; the EIP-712 domain
17
+ * binds the signature to its chain. Only low-s compact or serialized ECDSA permits are supported.
18
+ * Contract wallets should use `supportSignature: false` for direct approvals: deployed bundles
19
+ * consume ECDSA `v/r/s`, not arbitrary ERC-1271 or ERC-6492 signatures.
20
+ * Stored inputs remain trusted; verification does not establish the integrator's intent or protect
21
+ * a plan changed afterwards. Builders do not reverify signatures in restored plans.
22
+ * @param plan - Plan to update without mutating its requests or steps.
23
+ * @param signatures - Compact or serialized ECDSA signatures, each naming a unique existing request ID.
24
+ * @returns A new plan sharing steps and unpatched requests; omitted IDs are preserved. Empty input validates all requests and returns the original plan.
25
+ * @throws {UnsupportedTransactionPlanVersionError} If the plan version is unsupported, including when no signatures are supplied.
26
+ * @throws {UnsupportedTransactionPlanActionError} If any plan step names an unsupported action type, before reading requests or updates.
27
+ * @throws {TransactionPlanSignatureMismatchError} If a request disagrees with its actions, an ID is unknown, or an input ID is duplicated (`field: "duplicate"`).
28
+ * @throws {BundlesPermitMismatchError} If a supplied signature cannot be parsed by the bundle permit builders.
29
+ * @throws {InvalidSignatureError} If a signature has high s, cannot recover a public key, or does not match the permit owner and typed data.
30
+ * @example
31
+ * ```ts
32
+ * import { applySignatures, type TransactionPlan } from "@morpho-org/morpho-sdk";
33
+ * import type { Hex } from "viem";
34
+ * const complete = (plan: TransactionPlan, signature: Hex) =>
35
+ * applySignatures(plan, [{ id: "vaultV2Deposit:tokenPermit", signature }]);
36
+ * ```
37
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
38
+ */
39
+ export function applySignatures(plan, signatures) {
40
+ // Reject unknown formats before interpreting stored fields or signature updates.
41
+ validateTransactionPlanVersion(plan.version);
42
+ // Reject unknown actions before reading signature requests or updates.
43
+ validateTransactionPlanActions(plan.steps);
44
+ const requests = getPendingSignatureRequests({
45
+ ...plan,
46
+ signatureRequests: plan.signatureRequests.map((request) => ({
47
+ ...request,
48
+ signature: undefined,
49
+ })),
50
+ });
51
+ const updates = new Map();
52
+ for (const { id, signature } of signatures) {
53
+ if (!requests.some((request) => request.id === id))
54
+ throw new TransactionPlanSignatureMismatchError(id, "reference");
55
+ if (updates.has(id))
56
+ throw new TransactionPlanSignatureMismatchError(id, "duplicate");
57
+ updates.set(id, signature);
58
+ }
59
+ if (updates.size === 0)
60
+ return plan;
61
+ for (const [id, signature] of updates) {
62
+ const request = requests.find((candidate) => candidate.id === id);
63
+ const normalized = normalizeBundlesSignature(signature);
64
+ let recovered;
65
+ try {
66
+ const ecdsa = new secp256k1.Signature(BigInt(normalized.r), BigInt(normalized.s));
67
+ if (ecdsa.hasHighS())
68
+ throw new InvalidSignatureError();
69
+ const publicKey = ecdsa
70
+ .addRecoveryBit(normalized.v - 27)
71
+ .recoverPublicKey(hashTypedData(request.typedData).slice(2));
72
+ recovered = publicKeyToAddress(toHex(publicKey.toRawBytes(false)));
73
+ }
74
+ catch {
75
+ throw new InvalidSignatureError();
76
+ }
77
+ if (!isAddressEqual(recovered, request.typedData.message.owner))
78
+ throw new InvalidSignatureError();
79
+ updates.set(id, serializeSignature({ ...normalized, v: BigInt(normalized.v) }));
80
+ }
81
+ return {
82
+ ...plan,
83
+ signatureRequests: plan.signatureRequests.map((request) => updates.has(request.id)
84
+ ? { ...request, signature: updates.get(request.id) }
85
+ : request),
86
+ };
87
+ }
88
+ /** @internal Lists the signature request IDs a step's action names, in role order. */
89
+ function getStepSignatureRequestIds(step) {
90
+ const { action } = step;
91
+ if (!("signatureRequestIds" in action))
92
+ return [];
93
+ return Object.values(action.signatureRequestIds).filter((id) => id !== undefined);
94
+ }
95
+ /**
96
+ * Lists pending signature requests once per request ID after checking each against every referencing action.
97
+ * Sign each request's typed data with your wallet stack, then verify and attach the results with
98
+ * {@link applySignatures}.
99
+ * @param plan - Plan to inspect without changing it.
100
+ * @returns Pending requests in first-reference order, each carrying its `id`, `kind` and validated `typedData`. Dangling IDs are omitted. The SDK never signs.
101
+ * @throws {UnsupportedTransactionPlanVersionError} If the plan version is unsupported, including empty plans.
102
+ * @throws {UnsupportedTransactionPlanActionError} If any plan step names an unsupported action type, before reading requests.
103
+ * @throws {TransactionPlanSignatureMismatchError} If a pending permit disagrees with its action or arguments, including the action deadline, or any request has no referencing step.
104
+ * @example
105
+ * ```ts
106
+ * import { getPendingSignatureRequests, type TransactionPlan } from "@morpho-org/morpho-sdk";
107
+ * const prompts = (plan: TransactionPlan) =>
108
+ * getPendingSignatureRequests(plan).map(({ id, kind, typedData }) => ({ id, kind, typedData }));
109
+ * ```
110
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
111
+ */
112
+ export function getPendingSignatureRequests(plan) {
113
+ // Reject unknown formats before interpreting stored fields.
114
+ validateTransactionPlanVersion(plan.version);
115
+ // Reject unknown actions before exposing signature requests.
116
+ validateTransactionPlanActions(plan.steps);
117
+ const referenced = new Map();
118
+ for (const step of plan.steps) {
119
+ for (const id of getStepSignatureRequestIds(step)) {
120
+ referenced.set(id, [...(referenced.get(id) ?? []), step.action]);
121
+ }
122
+ }
123
+ for (const request of plan.signatureRequests) {
124
+ const actions = referenced.get(request.id);
125
+ if (actions === undefined)
126
+ throw new TransactionPlanSignatureMismatchError(request.id, "reference");
127
+ if (request.signature === undefined) {
128
+ for (const action of actions) {
129
+ validateSignatureRequest(request, action);
130
+ if (action.type !== "erc20Approval" &&
131
+ request.args.deadline !== action.inputs.deadline)
132
+ throw new TransactionPlanSignatureMismatchError(request.id, "args.deadline");
133
+ }
134
+ }
135
+ }
136
+ return [...referenced.keys()].flatMap((id) => {
137
+ const request = plan.signatureRequests.find((candidate) => candidate.id === id);
138
+ return request && request.signature === undefined ? [request] : [];
139
+ });
140
+ }
141
+ function encodeStep(action, requests) {
142
+ switch (action.type) {
143
+ case "erc20Approval":
144
+ return encodeErc20Approval(action.inputs);
145
+ case "vaultV2Deposit":
146
+ return buildVaultV2Deposit(action, requests);
147
+ case "vaultV2Withdraw":
148
+ return buildVaultV2Withdraw(action, requests);
149
+ }
150
+ }
151
+ /**
152
+ * Builds one transaction from a step, its fixed inputs and the signatures its action names.
153
+ * Plans are trusted as given, whether restored or supplied directly. Signature checks establish
154
+ * only request/action consistency; they do not validate stored fees, recipients, share-price bounds,
155
+ * vaults or amounts against the intended operation. Integrators must protect stored plans from tampering.
156
+ * This builder does not verify signature ownership; use {@link applySignatures} to verify and attach signatures.
157
+ * @param plan - Plan supplying referenced signature requests and the calldata origin; chain and account come from the action inputs.
158
+ * @param step - Recipe to encode; missing signatures on unrelated supported steps do not block it.
159
+ * @returns A frozen `{ to, data, value, action }`, ready to simulate or submit. `data` ends with the plan's `calldataOrigin` when one was set.
160
+ * @throws {UnsupportedTransactionPlanVersionError} If the plan version is unsupported.
161
+ * @throws {UnsupportedTransactionPlanActionError} If any plan step or the selected step names an unsupported action type.
162
+ * @throws {UnsupportedErc20ApprovalSpenderError} If an approval names an unregistered spender.
163
+ * @throws {NonPositiveInputError} If a deposit or withdrawal amount, deposit share-price bound or deadline is not positive.
164
+ * @throws {ReferralFeePctExceededError} If the action's referral fee is at least WAD.
165
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no nonzero recipient.
166
+ * @throws {IncompleteTransactionPlanError} If a referenced signature request or its signature is missing.
167
+ * @throws {TransactionPlanSignatureMismatchError} If a referenced permit disagrees with the step's action or its encoding arguments.
168
+ * @example
169
+ * ```ts
170
+ * import { buildTransaction, parseTransactionPlan } from "@morpho-org/morpho-sdk";
171
+ * const resume = (saved: string) => {
172
+ * const plan = parseTransactionPlan(saved);
173
+ * return plan.steps.map((step) => buildTransaction(plan, step));
174
+ * };
175
+ * ```
176
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
177
+ */
178
+ export function buildTransaction(plan, step) {
179
+ // Reject unknown formats before interpreting stored fields.
180
+ validateTransactionPlanVersion(plan.version);
181
+ // Check the whole plan and any separately selected step before reading requests.
182
+ validateTransactionPlanActions([...plan.steps, step]);
183
+ const requests = getStepSignatureRequestIds(step).map((id) => {
184
+ const request = plan.signatureRequests.find((candidate) => candidate.id === id);
185
+ if (request === undefined)
186
+ throw new IncompleteTransactionPlanError(id);
187
+ validateSignatureRequest(request, step.action);
188
+ return request;
189
+ });
190
+ const { to, value, data, action } = encodeStep(step.action, requests);
191
+ return deepFreeze({
192
+ to,
193
+ value,
194
+ data: plan.calldataOrigin === undefined
195
+ ? data
196
+ : concatHex([data, plan.calldataOrigin]),
197
+ action,
198
+ });
199
+ }
200
+ /**
201
+ * Builds every step of the plan in order.
202
+ * @param plan - Plan whose referenced signature requests all carry a signature.
203
+ * @returns Frozen SDK transactions in step order; discriminate on `action.type` for per-step handling.
204
+ * @throws {UnsupportedTransactionPlanVersionError} If the plan version is unsupported, including empty plans.
205
+ * @throws {UnsupportedTransactionPlanActionError} If any plan step names an unsupported action type, before reading requests.
206
+ * @throws {UnsupportedErc20ApprovalSpenderError} If an approval names an unregistered spender.
207
+ * @throws {NonPositiveInputError} If a deposit or withdrawal amount, deposit share-price bound or deadline is not positive.
208
+ * @throws {ReferralFeePctExceededError} If an action's referral fee is at least WAD.
209
+ * @throws {ReferralFeeRecipientMissingError} If a positive referral fee has no nonzero recipient.
210
+ * @throws {IncompleteTransactionPlanError} If any step references a signature request or signature that is missing.
211
+ * @throws {TransactionPlanSignatureMismatchError} If a referenced permit disagrees with its action or encoding arguments.
212
+ * @example
213
+ * ```ts
214
+ * import { buildTransactions, type TransactionPlan } from "@morpho-org/morpho-sdk";
215
+ * const submit = (plan: TransactionPlan) => buildTransactions(plan);
216
+ * // Simulate and send in order from plan.account on plan.chainId.
217
+ * ```
218
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
219
+ */
220
+ export function buildTransactions(plan) {
221
+ // Reject unknown formats even when there are no steps to build.
222
+ validateTransactionPlanVersion(plan.version);
223
+ // Validate every action before the first step can interpret requests.
224
+ validateTransactionPlanActions(plan.steps);
225
+ return plan.steps.map((step) => buildTransaction(plan, step));
226
+ }
@@ -0,0 +1,44 @@
1
+ import { type Address, type Client } from "viem";
2
+ import type { ERC20ApprovalAction, Erc2612RequirementSignature, Requirement, Transaction } from "../types/index.js";
3
+ import type { Action, SignatureRequest, Step } from "./types.js";
4
+ /**
5
+ * @internal Converts an ERC-2612 requirement into a plan-local signature request.
6
+ * @param requirement - Permit requirement carrying its typed data and encoding arguments.
7
+ * @param id - Signature request ID selected by the preparer.
8
+ * @returns The unsigned request with a concrete nonce.
9
+ * @throws {UnexpectedRequirementSignatureError} If the permit requirement has no nonce.
10
+ */
11
+ export declare function buildPermitSignatureRequest(requirement: Requirement<Erc2612RequirementSignature>, id: string): SignatureRequest;
12
+ /**
13
+ * @internal Converts an approval transaction into a step with prepared chain/account inputs.
14
+ * @param requirement - Direct token approval prerequisite.
15
+ * @param params - Step ID, chain and account selected by the preparer.
16
+ * @returns The approval recipe labeled for token spending.
17
+ */
18
+ export declare function buildApprovalStep(requirement: Readonly<Transaction<ERC20ApprovalAction>>, { id, chainId, account, }: {
19
+ readonly id: string;
20
+ readonly chainId: number;
21
+ readonly account: Address;
22
+ }): Step<Extract<Action, {
23
+ type: "erc20Approval";
24
+ }>>;
25
+ /** @internal Token pull prerequisites: direct approvals or an ERC-2612 permit. */
26
+ type TokenRequirement = Readonly<Transaction<ERC20ApprovalAction>> | Requirement<Erc2612RequirementSignature>;
27
+ interface TokenRequirementsParams {
28
+ readonly token: Address;
29
+ readonly spender: Address;
30
+ readonly amount: bigint;
31
+ readonly owner: Address;
32
+ readonly chainId: number;
33
+ readonly deadline: bigint;
34
+ readonly now: bigint;
35
+ readonly supportSignature: boolean;
36
+ readonly deployless: boolean | undefined;
37
+ }
38
+ /**
39
+ * @internal Resolves the token prerequisite of a VaultBundlesV1 pull without Permit2. A sufficient
40
+ * direct allowance yields nothing. Otherwise signature support prefers an ERC-2612 permit when
41
+ * available and falls back to a direct unlimited approval. Without signature support, always approve.
42
+ */
43
+ export declare function getTokenRequirements(client: Client, params: TokenRequirementsParams): Promise<readonly TokenRequirement[]>;
44
+ export {};
@@ -0,0 +1,74 @@
1
+ import { erc20Abi } from "viem";
2
+ import { readContract } from "viem/actions";
3
+ import { getRequirementsApproval } from "../actions/requirements/getRequirementsApproval.js";
4
+ import { UnexpectedRequirementSignatureError } from "../types/error.js";
5
+ import { getTokenPermit } from "./getTokenPermit.js";
6
+ /**
7
+ * @internal Converts an ERC-2612 requirement into a plan-local signature request.
8
+ * @param requirement - Permit requirement carrying its typed data and encoding arguments.
9
+ * @param id - Signature request ID selected by the preparer.
10
+ * @returns The unsigned request with a concrete nonce.
11
+ * @throws {UnexpectedRequirementSignatureError} If the permit requirement has no nonce.
12
+ */
13
+ export function buildPermitSignatureRequest(requirement, id) {
14
+ const { nonce, ...args } = requirement.action.args;
15
+ if (nonce === undefined)
16
+ throw new UnexpectedRequirementSignatureError(requirement.action.type);
17
+ return {
18
+ id,
19
+ kind: "permit",
20
+ typedData: requirement.action.typedData,
21
+ args: { ...args, nonce },
22
+ };
23
+ }
24
+ /**
25
+ * @internal Converts an approval transaction into a step with prepared chain/account inputs.
26
+ * @param requirement - Direct token approval prerequisite.
27
+ * @param params - Step ID, chain and account selected by the preparer.
28
+ * @returns The approval recipe labeled for token spending.
29
+ */
30
+ export function buildApprovalStep(requirement, { id, chainId, account, }) {
31
+ return {
32
+ id,
33
+ label: "Approve token spending",
34
+ action: {
35
+ type: "erc20Approval",
36
+ inputs: {
37
+ token: requirement.to,
38
+ ...requirement.action.args,
39
+ chainId,
40
+ account,
41
+ },
42
+ },
43
+ };
44
+ }
45
+ /**
46
+ * @internal Resolves the token prerequisite of a VaultBundlesV1 pull without Permit2. A sufficient
47
+ * direct allowance yields nothing. Otherwise signature support prefers an ERC-2612 permit when
48
+ * available and falls back to a direct unlimited approval. Without signature support, always approve.
49
+ */
50
+ export async function getTokenRequirements(client, params) {
51
+ // The allowance is trusted as returned by the RPC. See THREAT_MODEL.md, RPC.
52
+ const allowance = await readContract(client, {
53
+ abi: erc20Abi,
54
+ address: params.token,
55
+ functionName: "allowance",
56
+ args: [params.owner, params.spender],
57
+ });
58
+ if (allowance >= params.amount)
59
+ return [];
60
+ if (params.supportSignature) {
61
+ const permit = await getTokenPermit(client, {
62
+ ...params,
63
+ supportDeployless: params.deployless,
64
+ });
65
+ if (permit !== undefined)
66
+ return [permit];
67
+ }
68
+ return getRequirementsApproval({
69
+ address: params.token,
70
+ chainId: params.chainId,
71
+ args: { spendAmount: params.amount, spender: params.spender },
72
+ allowances: allowance,
73
+ });
74
+ }
@@ -0,0 +1,33 @@
1
+ import type { TransactionPlan } from "./types.js";
2
+ /**
3
+ * Serializes plan data with a bigint replacer. No validation is performed.
4
+ * @param plan - Plan to save.
5
+ * @returns JSON with `$bigint` tags for bigint quantities.
6
+ * @example
7
+ * ```ts
8
+ * import { serializeTransactionPlan, type TransactionPlan } from "@morpho-org/morpho-sdk";
9
+ * const save = (plan: TransactionPlan) => serializeTransactionPlan(plan);
10
+ * ```
11
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
12
+ */
13
+ export declare function serializeTransactionPlan(plan: TransactionPlan): string;
14
+ /**
15
+ * Restores bigint fields and validates version, action/request shapes, uint256 ranges, unique IDs,
16
+ * references, per-action chain/account and permit/action consistency, including signed requests.
17
+ * Extra keys are allowed. No clock or RPC is used: expiry, live state, signature ownership and
18
+ * action-layer business constraints are not checked. Parsing does not prove authenticity or intent;
19
+ * tampered but well-formed, internally consistent plans pass. Integrators must protect stored plans.
20
+ * Use `applySignatures` to verify new signatures; existing restored signatures remain trusted.
21
+ * @param json - JSON previously returned by `serializeTransactionPlan`.
22
+ * @returns The restored plan.
23
+ * @throws {InvalidTransactionPlanError} At the first malformed JSON, field shape or consistency failure, exposing its JSON `path` and `reason`.
24
+ * @throws {UnsupportedTransactionPlanVersionError} If the stored integer version is unsupported.
25
+ * @throws {UnsupportedTransactionPlanActionError} If a step names an unsupported action type.
26
+ * @example
27
+ * ```ts
28
+ * import { parseTransactionPlan } from "@morpho-org/morpho-sdk";
29
+ * const restore = (saved: string) => parseTransactionPlan(saved);
30
+ * ```
31
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
32
+ */
33
+ export declare function parseTransactionPlan(json: string): TransactionPlan;
@@ -0,0 +1,201 @@
1
+ import { isAddressEqual } from "viem";
2
+ import { validateApprovalPlanAction } from "./approval.js";
3
+ import { InvalidTransactionPlanError, TransactionPlanSignatureMismatchError, } from "./error.js";
4
+ import { validatePermitPlanRequest } from "./permit.js";
5
+ import { getPendingSignatureRequests } from "./plan.js";
6
+ import { validateTransactionPlanActions } from "./validateActions.js";
7
+ import { getPlanObject, validatePlanField, validatePlanFields, } from "./validation.js";
8
+ import { validateDepositPlanAction } from "./vaultv2/deposit.js";
9
+ import { validateWithdrawPlanAction } from "./vaultv2/withdraw.js";
10
+ import { validateTransactionPlanVersion } from "./version.js";
11
+ const actionValidators = {
12
+ erc20Approval: validateApprovalPlanAction,
13
+ vaultV2Deposit: validateDepositPlanAction,
14
+ vaultV2Withdraw: validateWithdrawPlanAction,
15
+ };
16
+ /**
17
+ * Serializes plan data with a bigint replacer. No validation is performed.
18
+ * @param plan - Plan to save.
19
+ * @returns JSON with `$bigint` tags for bigint quantities.
20
+ * @example
21
+ * ```ts
22
+ * import { serializeTransactionPlan, type TransactionPlan } from "@morpho-org/morpho-sdk";
23
+ * const save = (plan: TransactionPlan) => serializeTransactionPlan(plan);
24
+ * ```
25
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
26
+ */
27
+ export function serializeTransactionPlan(plan) {
28
+ return JSON.stringify(plan, function (key) {
29
+ // Read the original value even when the host has installed BigInt.prototype.toJSON.
30
+ const value = this[key];
31
+ return typeof value === "bigint" ? { $bigint: value.toString() } : value;
32
+ });
33
+ }
34
+ /**
35
+ * Restores bigint fields and validates version, action/request shapes, uint256 ranges, unique IDs,
36
+ * references, per-action chain/account and permit/action consistency, including signed requests.
37
+ * Extra keys are allowed. No clock or RPC is used: expiry, live state, signature ownership and
38
+ * action-layer business constraints are not checked. Parsing does not prove authenticity or intent;
39
+ * tampered but well-formed, internally consistent plans pass. Integrators must protect stored plans.
40
+ * Use `applySignatures` to verify new signatures; existing restored signatures remain trusted.
41
+ * @param json - JSON previously returned by `serializeTransactionPlan`.
42
+ * @returns The restored plan.
43
+ * @throws {InvalidTransactionPlanError} At the first malformed JSON, field shape or consistency failure, exposing its JSON `path` and `reason`.
44
+ * @throws {UnsupportedTransactionPlanVersionError} If the stored integer version is unsupported.
45
+ * @throws {UnsupportedTransactionPlanActionError} If a step names an unsupported action type.
46
+ * @example
47
+ * ```ts
48
+ * import { parseTransactionPlan } from "@morpho-org/morpho-sdk";
49
+ * const restore = (saved: string) => parseTransactionPlan(saved);
50
+ * ```
51
+ * @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
52
+ */
53
+ export function parseTransactionPlan(json) {
54
+ let restored;
55
+ try {
56
+ restored = JSON.parse(json, (_key, field) => typeof field === "object" &&
57
+ field !== null &&
58
+ "$bigint" in field &&
59
+ typeof field.$bigint === "string"
60
+ ? BigInt(field.$bigint)
61
+ : field);
62
+ }
63
+ catch (cause) {
64
+ throw new InvalidTransactionPlanError({
65
+ path: "$",
66
+ reason: "expected JSON with valid bigint tags",
67
+ cause,
68
+ });
69
+ }
70
+ const plan = getPlanObject(restored, "$");
71
+ validatePlanField(plan.version, { path: "$.version", type: "safe integer" });
72
+ validateTransactionPlanVersion(plan.version);
73
+ validatePlanFields(plan, {
74
+ path: "$",
75
+ fields: {
76
+ chainId: "positive safe integer",
77
+ account: "address",
78
+ expiresAt: "safe integer",
79
+ steps: "array",
80
+ signatureRequests: "array",
81
+ },
82
+ });
83
+ if (plan.calldataOrigin !== undefined)
84
+ validatePlanField(plan.calldataOrigin, {
85
+ path: "$.calldataOrigin",
86
+ type: "hex",
87
+ });
88
+ const steps = plan.steps;
89
+ const requests = plan.signatureRequests;
90
+ const stepIds = new Set();
91
+ for (const [index, value] of steps.entries()) {
92
+ const path = `$.steps[${index}]`;
93
+ const step = getPlanObject(value, path);
94
+ validatePlanFields(step, {
95
+ path,
96
+ fields: { id: "string", label: "string" },
97
+ });
98
+ if (stepIds.has(step.id))
99
+ throw new InvalidTransactionPlanError({
100
+ path: `${path}.id`,
101
+ reason: "expected a unique step ID",
102
+ });
103
+ stepIds.add(step.id);
104
+ const action = getPlanObject(step.action, `${path}.action`);
105
+ validatePlanField(action.type, {
106
+ path: `${path}.action.type`,
107
+ type: "string",
108
+ });
109
+ }
110
+ // Preserve the existing action-type guard before dispatching action schemas.
111
+ validateTransactionPlanActions(steps);
112
+ for (const [index, step] of steps.entries()) {
113
+ const path = `$.steps[${index}].action`;
114
+ const action = getPlanObject(step.action, path);
115
+ const inputs = getPlanObject(action.inputs, `${path}.inputs`);
116
+ validatePlanFields(inputs, {
117
+ path: `${path}.inputs`,
118
+ fields: { chainId: "positive safe integer", account: "address" },
119
+ });
120
+ actionValidators[step.action.type](action, path);
121
+ if (inputs.chainId !== plan.chainId)
122
+ throw new InvalidTransactionPlanError({
123
+ path: `${path}.inputs.chainId`,
124
+ reason: "expected the plan chainId",
125
+ });
126
+ if (!isAddressEqual(inputs.account, plan.account))
127
+ throw new InvalidTransactionPlanError({
128
+ path: `${path}.inputs.account`,
129
+ reason: "expected the plan account",
130
+ });
131
+ }
132
+ const requestIds = new Set();
133
+ for (const [index, value] of requests.entries()) {
134
+ const path = `$.signatureRequests[${index}]`;
135
+ const request = getPlanObject(value, path);
136
+ validatePlanFields(request, {
137
+ path,
138
+ fields: { id: "string", kind: "string" },
139
+ });
140
+ if (requestIds.has(request.id))
141
+ throw new InvalidTransactionPlanError({
142
+ path: `${path}.id`,
143
+ reason: "expected a unique signature request ID",
144
+ });
145
+ requestIds.add(request.id);
146
+ if (request.kind !== "permit")
147
+ throw new InvalidTransactionPlanError({
148
+ path: `${path}.kind`,
149
+ reason: "expected a supported signature request kind (permit)",
150
+ });
151
+ validatePermitPlanRequest(request, path);
152
+ }
153
+ for (const [index, step] of steps.entries()) {
154
+ if (!("signatureRequestIds" in step.action))
155
+ continue;
156
+ const path = `$.steps[${index}].action.signatureRequestIds`;
157
+ const ids = getPlanObject(step.action.signatureRequestIds, path);
158
+ for (const [role, id] of Object.entries(ids)) {
159
+ validatePlanField(id, { path: `${path}.${role}`, type: "string" });
160
+ if (!requestIds.has(id))
161
+ throw new InvalidTransactionPlanError({
162
+ path: `${path}.${role}`,
163
+ reason: "expected an existing signature request ID",
164
+ });
165
+ }
166
+ }
167
+ const result = restored;
168
+ try {
169
+ // Clear signatures so the existing pure consistency check validates every request.
170
+ getPendingSignatureRequests({
171
+ ...result,
172
+ signatureRequests: result.signatureRequests.map((request) => ({
173
+ ...request,
174
+ signature: undefined,
175
+ })),
176
+ });
177
+ }
178
+ catch (cause) {
179
+ if (cause instanceof TransactionPlanSignatureMismatchError) {
180
+ const index = result.signatureRequests.findIndex((request) => request.id === cause.id);
181
+ const field = cause.field === "reference"
182
+ ? "id"
183
+ : cause.field === "value"
184
+ ? "args.amount"
185
+ : cause.field.startsWith("args.")
186
+ ? cause.field
187
+ : `typedData.${cause.field}`;
188
+ throw new InvalidTransactionPlanError({
189
+ path: `$.signatureRequests[${index}].${field}`,
190
+ reason: "expected agreement with every referencing action",
191
+ cause,
192
+ });
193
+ }
194
+ throw new InvalidTransactionPlanError({
195
+ path: "$.signatureRequests",
196
+ reason: "expected requests consistent with supported action chains",
197
+ cause,
198
+ });
199
+ }
200
+ return result;
201
+ }
@@ -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 @@
1
+ export {};