@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.
- package/MIGRATION-v6-to-v7.md +1 -1
- package/README.md +64 -3
- package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +12 -46
- package/lib/cjs/entities/requirements/getErc2612Permit.d.ts +7 -0
- package/lib/cjs/entities/requirements/getErc2612Permit.js +60 -0
- package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
- package/lib/cjs/entities/vaultV1/vaultV1.d.ts +3 -3
- package/lib/cjs/entities/vaultV2/vaultV2.d.ts +2 -2
- package/lib/cjs/helpers/validateMidnightCollateralBatch.d.ts +1 -0
- package/lib/cjs/helpers/validateMidnightCollateralBatch.js +1 -0
- package/lib/cjs/index.d.ts +2 -0
- package/lib/cjs/index.js +18 -1
- package/lib/cjs/transactionPlan/approval.d.ts +2 -0
- package/lib/cjs/transactionPlan/approval.js +16 -0
- package/lib/cjs/transactionPlan/error.d.ts +145 -0
- package/lib/cjs/transactionPlan/error.js +186 -0
- package/lib/cjs/transactionPlan/getTokenPermit.d.ts +11 -0
- package/lib/cjs/transactionPlan/getTokenPermit.js +18 -0
- package/lib/cjs/transactionPlan/index.d.ts +9 -0
- package/lib/cjs/transactionPlan/index.js +24 -0
- package/lib/cjs/transactionPlan/intent.d.ts +51 -0
- package/lib/cjs/transactionPlan/intent.js +54 -0
- package/lib/cjs/transactionPlan/permit.d.ts +13 -0
- package/lib/cjs/transactionPlan/permit.js +145 -0
- package/lib/cjs/transactionPlan/plan.d.ts +99 -0
- package/lib/cjs/transactionPlan/plan.js +232 -0
- package/lib/cjs/transactionPlan/requirements.d.ts +44 -0
- package/lib/cjs/transactionPlan/requirements.js +79 -0
- package/lib/cjs/transactionPlan/serde.d.ts +33 -0
- package/lib/cjs/transactionPlan/serde.js +205 -0
- package/lib/cjs/transactionPlan/types.d.ts +91 -0
- package/lib/cjs/transactionPlan/types.js +2 -0
- package/lib/cjs/transactionPlan/validateActions.d.ts +8 -0
- package/lib/cjs/transactionPlan/validateActions.js +19 -0
- package/lib/cjs/transactionPlan/validation.d.ts +17 -0
- package/lib/cjs/transactionPlan/validation.js +70 -0
- package/lib/cjs/transactionPlan/vaultv2/deposit.d.ts +81 -0
- package/lib/cjs/transactionPlan/vaultv2/deposit.js +211 -0
- package/lib/cjs/transactionPlan/vaultv2/withdraw.d.ts +77 -0
- package/lib/cjs/transactionPlan/vaultv2/withdraw.js +190 -0
- package/lib/cjs/transactionPlan/version.d.ts +2 -0
- package/lib/cjs/transactionPlan/version.js +9 -0
- package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +14 -48
- package/lib/esm/entities/requirements/getErc2612Permit.d.ts +7 -0
- package/lib/esm/entities/requirements/getErc2612Permit.js +57 -0
- package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +2 -2
- package/lib/esm/entities/vaultV1/vaultV1.d.ts +3 -3
- package/lib/esm/entities/vaultV2/vaultV2.d.ts +2 -2
- package/lib/esm/helpers/validateMidnightCollateralBatch.d.ts +1 -0
- package/lib/esm/helpers/validateMidnightCollateralBatch.js +1 -0
- package/lib/esm/index.d.ts +2 -0
- package/lib/esm/index.js +1 -0
- package/lib/esm/transactionPlan/approval.d.ts +2 -0
- package/lib/esm/transactionPlan/approval.js +13 -0
- package/lib/esm/transactionPlan/error.d.ts +145 -0
- package/lib/esm/transactionPlan/error.js +175 -0
- package/lib/esm/transactionPlan/getTokenPermit.d.ts +11 -0
- package/lib/esm/transactionPlan/getTokenPermit.js +15 -0
- package/lib/esm/transactionPlan/index.d.ts +9 -0
- package/lib/esm/transactionPlan/index.js +5 -0
- package/lib/esm/transactionPlan/intent.d.ts +51 -0
- package/lib/esm/transactionPlan/intent.js +51 -0
- package/lib/esm/transactionPlan/permit.d.ts +13 -0
- package/lib/esm/transactionPlan/permit.js +140 -0
- package/lib/esm/transactionPlan/plan.d.ts +99 -0
- package/lib/esm/transactionPlan/plan.js +226 -0
- package/lib/esm/transactionPlan/requirements.d.ts +44 -0
- package/lib/esm/transactionPlan/requirements.js +74 -0
- package/lib/esm/transactionPlan/serde.d.ts +33 -0
- package/lib/esm/transactionPlan/serde.js +201 -0
- package/lib/esm/transactionPlan/types.d.ts +91 -0
- package/lib/esm/transactionPlan/types.js +1 -0
- package/lib/esm/transactionPlan/validateActions.d.ts +8 -0
- package/lib/esm/transactionPlan/validateActions.js +16 -0
- package/lib/esm/transactionPlan/validation.d.ts +17 -0
- package/lib/esm/transactionPlan/validation.js +64 -0
- package/lib/esm/transactionPlan/vaultv2/deposit.d.ts +81 -0
- package/lib/esm/transactionPlan/vaultv2/deposit.js +206 -0
- package/lib/esm/transactionPlan/vaultv2/withdraw.d.ts +77 -0
- package/lib/esm/transactionPlan/vaultv2/withdraw.js +185 -0
- package/lib/esm/transactionPlan/version.d.ts +2 -0
- package/lib/esm/transactionPlan/version.js +6 -0
- package/package.json +6 -5
|
@@ -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,16 @@
|
|
|
1
|
+
import { UnsupportedTransactionPlanActionError } from "./error.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 function validateTransactionPlanActions(steps) {
|
|
9
|
+
for (const step of steps) {
|
|
10
|
+
const actionType = step.action.type;
|
|
11
|
+
if (actionType !== "erc20Approval" &&
|
|
12
|
+
actionType !== "vaultV2Deposit" &&
|
|
13
|
+
actionType !== "vaultV2Withdraw")
|
|
14
|
+
throw new UnsupportedTransactionPlanActionError(actionType);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -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,64 @@
|
|
|
1
|
+
import { isAddress, maxUint256 } from "viem";
|
|
2
|
+
import { InvalidTransactionPlanError } from "./error.js";
|
|
3
|
+
/** @internal Validates one restored field without coercing it. */
|
|
4
|
+
export function validatePlanField(value, options) {
|
|
5
|
+
const { path, type } = options;
|
|
6
|
+
let valid;
|
|
7
|
+
switch (type) {
|
|
8
|
+
case "string":
|
|
9
|
+
valid = typeof value === "string";
|
|
10
|
+
break;
|
|
11
|
+
case "address":
|
|
12
|
+
valid = typeof value === "string" && isAddress(value);
|
|
13
|
+
break;
|
|
14
|
+
case "hex":
|
|
15
|
+
valid =
|
|
16
|
+
typeof value === "string" && /^0x(?:[0-9a-fA-F]{2})*$/.test(value);
|
|
17
|
+
break;
|
|
18
|
+
case "safe integer":
|
|
19
|
+
valid = typeof value === "number" && Number.isSafeInteger(value);
|
|
20
|
+
break;
|
|
21
|
+
case "positive safe integer":
|
|
22
|
+
valid =
|
|
23
|
+
typeof value === "number" && Number.isSafeInteger(value) && value > 0;
|
|
24
|
+
break;
|
|
25
|
+
case "uint256 bigint":
|
|
26
|
+
valid = typeof value === "bigint" && value >= 0n && value <= maxUint256;
|
|
27
|
+
break;
|
|
28
|
+
case "array":
|
|
29
|
+
valid = Array.isArray(value);
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
if (!valid)
|
|
33
|
+
throw new InvalidTransactionPlanError({ path, reason: `expected ${type}` });
|
|
34
|
+
}
|
|
35
|
+
/** @internal Requires a non-null, non-array JSON object. */
|
|
36
|
+
export function getPlanObject(value, path) {
|
|
37
|
+
if (typeof value !== "object" || value === null || Array.isArray(value))
|
|
38
|
+
throw new InvalidTransactionPlanError({
|
|
39
|
+
path,
|
|
40
|
+
reason: "expected an object",
|
|
41
|
+
});
|
|
42
|
+
return value;
|
|
43
|
+
}
|
|
44
|
+
/** @internal Validates required fields while permitting additional keys. */
|
|
45
|
+
export function validatePlanFields(value, options) {
|
|
46
|
+
for (const [key, type] of Object.entries(options.fields))
|
|
47
|
+
validatePlanField(value[key], { path: `${options.path}.${key}`, type });
|
|
48
|
+
}
|
|
49
|
+
/** @internal Validates the shared stored vault-action fields and role map. */
|
|
50
|
+
export function validateVaultPlanAction(action, path) {
|
|
51
|
+
const inputs = getPlanObject(action.inputs, `${path}.inputs`);
|
|
52
|
+
validatePlanFields(inputs, {
|
|
53
|
+
path: `${path}.inputs`,
|
|
54
|
+
fields: {
|
|
55
|
+
vault: "address",
|
|
56
|
+
deadline: "uint256 bigint",
|
|
57
|
+
referralFeePct: "uint256 bigint",
|
|
58
|
+
referralFeeRecipient: "address",
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
// Vault actions require a role map even when no permit is needed.
|
|
62
|
+
getPlanObject(action.signatureRequestIds, `${path}.signatureRequestIds`);
|
|
63
|
+
return inputs;
|
|
64
|
+
}
|
|
@@ -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>>;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { DEFAULT_SLIPPAGE_TOLERANCE, } from "@morpho-org/blue-sdk";
|
|
2
|
+
import { deepFreeze, getChainAddress, Time } from "@morpho-org/morpho-ts";
|
|
3
|
+
import { isAddressEqual } from "viem";
|
|
4
|
+
import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, selectBundlesTokenRequirementSignature, } from "../../actions/bundles/common.js";
|
|
5
|
+
import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
|
|
6
|
+
import { vaultV2Deposit } from "../../actions/vaultV2/deposit.js";
|
|
7
|
+
import { assertRegistryTargetsHaveCode } from "../../entities/requirements/assertContractCode.js";
|
|
8
|
+
import { computeVaultMaxSharePrice } from "../../helpers/index.js";
|
|
9
|
+
import { validateNativeVaultAsset, validateSlippageTolerance, validateUint256Field, } from "../../helpers/validate.js";
|
|
10
|
+
import { NonPositiveInputError, VaultAddressMismatchError, } from "../../types/index.js";
|
|
11
|
+
import { InvalidTransactionPlanError } from "../error.js";
|
|
12
|
+
import { resolveIntent } from "../intent.js";
|
|
13
|
+
import { getVaultPermit } from "../permit.js";
|
|
14
|
+
import { buildApprovalStep, buildPermitSignatureRequest, getTokenRequirements, } from "../requirements.js";
|
|
15
|
+
import { validatePlanField, validatePlanFields, validateVaultPlanAction, } from "../validation.js";
|
|
16
|
+
/** @internal Validates the stored Vault V2 deposit action's input shape. */
|
|
17
|
+
export function validateDepositPlanAction(action, path) {
|
|
18
|
+
const inputs = validateVaultPlanAction(action, path);
|
|
19
|
+
validatePlanFields(inputs, {
|
|
20
|
+
path: `${path}.inputs`,
|
|
21
|
+
fields: { asset: "address", maxSharePrice: "uint256 bigint" },
|
|
22
|
+
});
|
|
23
|
+
if ((inputs.amount === undefined) === (inputs.nativeAmount === undefined))
|
|
24
|
+
throw new InvalidTransactionPlanError({
|
|
25
|
+
path: `${path}.inputs`,
|
|
26
|
+
reason: "expected exactly one of amount or nativeAmount",
|
|
27
|
+
});
|
|
28
|
+
const field = inputs.amount === undefined ? "nativeAmount" : "amount";
|
|
29
|
+
validatePlanField(inputs[field], {
|
|
30
|
+
path: `${path}.inputs.${field}`,
|
|
31
|
+
type: "uint256 bigint",
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function resolveDepositInputs(params, now) {
|
|
35
|
+
const { vault, chainId, amount, vaultData } = params;
|
|
36
|
+
const intent = resolveIntent(params, now);
|
|
37
|
+
const slippageTolerance = params.slippageTolerance ?? DEFAULT_SLIPPAGE_TOLERANCE;
|
|
38
|
+
validateSlippageTolerance(slippageTolerance);
|
|
39
|
+
const native = (params.funding ?? { type: "erc20" }).type === "native";
|
|
40
|
+
if (amount <= 0n)
|
|
41
|
+
throw new NonPositiveInputError("amount", amount);
|
|
42
|
+
// Reject amounts that cannot be encoded as uint256 before making RPC requests.
|
|
43
|
+
validateUint256Field("amount", amount);
|
|
44
|
+
const common = normalizeBundlesCommonParams({
|
|
45
|
+
deadline: intent.deadline,
|
|
46
|
+
referralFeePct: intent.referralFeePct,
|
|
47
|
+
referralFeeRecipient: intent.referralFeeRecipient,
|
|
48
|
+
});
|
|
49
|
+
if (!isAddressEqual(vaultData.address, vault))
|
|
50
|
+
throw new VaultAddressMismatchError(vaultData.address, vault);
|
|
51
|
+
const { asset } = vaultData;
|
|
52
|
+
// Native funding must target the chain's wrapped-native vault asset.
|
|
53
|
+
if (native)
|
|
54
|
+
validateNativeVaultAsset(chainId, asset);
|
|
55
|
+
// The quote depends only on the snapshot and the intent, so it is fixed before any read.
|
|
56
|
+
const maxSharePrice = computeVaultMaxSharePrice({
|
|
57
|
+
vaultData,
|
|
58
|
+
deadline: intent.deadline,
|
|
59
|
+
assets: amount - getBundlesReferralFeeAssets(amount, common.referralFeePct),
|
|
60
|
+
slippageTolerance,
|
|
61
|
+
});
|
|
62
|
+
return { intent, native, common, asset, maxSharePrice };
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Prepares a deposit plan from caller intent and a vault snapshot, reading the token prerequisites
|
|
66
|
+
* directly. The quote is fixed on the deposit step at preparation, so the returned plan is static:
|
|
67
|
+
* only signatures are added before building.
|
|
68
|
+
* @param client - Viem client for `params.chainId`, used for allowance and permit metadata reads only.
|
|
69
|
+
* @param params.vault - Vault V2 contract receiving the net deposit.
|
|
70
|
+
* @param params.vaultData - Caller-fetched `AccrualVaultV2` snapshot of `vault`, used to derive the asset and deadline-accrued share-price bound.
|
|
71
|
+
* @param params.chainId - Chain containing the vault and registered VaultBundlesV1 contract.
|
|
72
|
+
* @param params.account - Non-zero account funding, signing and sending the deposit.
|
|
73
|
+
* @param params.amount - Positive gross deposit in asset base units, before referral fees.
|
|
74
|
+
* @param params.funding.type - Optional funding source: `"erc20"` (default) or `"native"`; native funding requires the vault asset to be wNative.
|
|
75
|
+
* @param params.referralFee.bps - Optional integer fee in basis points of the gross amount; defaults to zero and must be below 10,000.
|
|
76
|
+
* @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
|
|
77
|
+
* @param params.slippageTolerance - Optional WAD-scaled tolerance for the share-price bound; defaults to `DEFAULT_SLIPPAGE_TOLERANCE` and must not exceed `MAX_SLIPPAGE_TOLERANCE`.
|
|
78
|
+
* @param params.supportSignature - Optional ERC-2612 preference, defaulting to `false`; when enabled, falls back to direct approval if no permit is available.
|
|
79
|
+
* @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
|
|
80
|
+
* @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
|
|
81
|
+
* @param params.deployless - Optional permission to use deployless aggregation for token permit metadata reads.
|
|
82
|
+
* @returns A plan with approvals, concrete signature requests and the deposit step.
|
|
83
|
+
* @throws {ZeroAccountError} when `account` is the zero address.
|
|
84
|
+
* @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
|
|
85
|
+
* @throws {NonPositiveInputError} when `expiresAt`, `amount`, net assets or previewed shares are not positive.
|
|
86
|
+
* @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
|
|
87
|
+
* @throws {NegativeInputError} when `referralFee.bps` or `slippageTolerance` is negative.
|
|
88
|
+
* @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
|
|
89
|
+
* @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds `MAX_SLIPPAGE_TOLERANCE`.
|
|
90
|
+
* @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
|
|
91
|
+
* @throws {ReferralFeePctExceededError} when `referralFee.bps` equals 10,000; the normalized fee must be below WAD.
|
|
92
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient or a zero recipient.
|
|
93
|
+
* @throws {VaultAddressMismatchError} when `vaultData` describes another vault.
|
|
94
|
+
* @throws {NativeAmountOnNonWNativeVaultError} when native funding targets a vault whose asset is not wNative.
|
|
95
|
+
* @throws {ChainIdMismatchError} when the client targets another chain.
|
|
96
|
+
* @throws {MissingContractCodeError} when the VaultBundlesV1 contract is absent.
|
|
97
|
+
* @see computeVaultMaxSharePrice for quote errors.
|
|
98
|
+
* @example
|
|
99
|
+
* ```ts
|
|
100
|
+
* import { prepareVaultV2Deposit } from "@morpho-org/morpho-sdk";
|
|
101
|
+
* import { fetchAccrualVaultV2 } from "@morpho-org/morpho-sdk/fetch";
|
|
102
|
+
* import { createPublicClient, http } from "viem";
|
|
103
|
+
* import { mainnet } from "viem/chains";
|
|
104
|
+
* const client = createPublicClient({ chain: mainnet, transport: http() });
|
|
105
|
+
* const vault = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
|
|
106
|
+
* const plan = await prepareVaultV2Deposit(client, {
|
|
107
|
+
* vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
|
|
108
|
+
* vaultData: await fetchAccrualVaultV2(vault, client),
|
|
109
|
+
* });
|
|
110
|
+
* // Sign the pending requests, verify and attach with applySignatures, then build.
|
|
111
|
+
* ```
|
|
112
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
113
|
+
*/
|
|
114
|
+
export async function prepareVaultV2Deposit(client, params) {
|
|
115
|
+
const { vault, chainId, account, amount } = params;
|
|
116
|
+
const now = Time.timestamp();
|
|
117
|
+
const { intent, native, common, asset, maxSharePrice } = resolveDepositInputs(params, now);
|
|
118
|
+
const spender = getChainAddress(chainId, "bundles.vaultBundlesV1");
|
|
119
|
+
const [requirements] = await Promise.all([
|
|
120
|
+
validateClientChainId(client, chainId).then(() => native
|
|
121
|
+
? []
|
|
122
|
+
: getTokenRequirements(client, {
|
|
123
|
+
token: asset,
|
|
124
|
+
spender,
|
|
125
|
+
amount,
|
|
126
|
+
owner: account,
|
|
127
|
+
chainId,
|
|
128
|
+
deadline: intent.deadline,
|
|
129
|
+
now,
|
|
130
|
+
supportSignature: intent.supportSignature,
|
|
131
|
+
deployless: intent.deployless,
|
|
132
|
+
})),
|
|
133
|
+
assertRegistryTargetsHaveCode(client, chainId, [
|
|
134
|
+
{ role: "bundles.vaultBundlesV1", address: spender },
|
|
135
|
+
]),
|
|
136
|
+
]);
|
|
137
|
+
const approvals = [];
|
|
138
|
+
const signatureRequests = [];
|
|
139
|
+
const tokenPermitRequestId = "vaultV2Deposit:tokenPermit";
|
|
140
|
+
for (const requirement of requirements) {
|
|
141
|
+
if ("sign" in requirement) {
|
|
142
|
+
signatureRequests.push(buildPermitSignatureRequest(requirement, tokenPermitRequestId));
|
|
143
|
+
}
|
|
144
|
+
else {
|
|
145
|
+
approvals.push(buildApprovalStep(requirement, {
|
|
146
|
+
id: approvals.length === 0
|
|
147
|
+
? "vaultV2Deposit:approval"
|
|
148
|
+
: `vaultV2Deposit:approval:${approvals.length + 1}`,
|
|
149
|
+
chainId,
|
|
150
|
+
account,
|
|
151
|
+
}));
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return deepFreeze(structuredClone({
|
|
155
|
+
version: 1,
|
|
156
|
+
account,
|
|
157
|
+
chainId,
|
|
158
|
+
expiresAt: intent.expiresAt,
|
|
159
|
+
...(intent.calldataOrigin && { calldataOrigin: intent.calldataOrigin }),
|
|
160
|
+
steps: [
|
|
161
|
+
...approvals,
|
|
162
|
+
{
|
|
163
|
+
id: "vaultV2Deposit",
|
|
164
|
+
label: "Deposit into vault",
|
|
165
|
+
action: {
|
|
166
|
+
type: "vaultV2Deposit",
|
|
167
|
+
inputs: {
|
|
168
|
+
chainId,
|
|
169
|
+
account,
|
|
170
|
+
vault,
|
|
171
|
+
asset,
|
|
172
|
+
maxSharePrice,
|
|
173
|
+
...(native ? { nativeAmount: amount } : { amount }),
|
|
174
|
+
...common,
|
|
175
|
+
},
|
|
176
|
+
signatureRequestIds: signatureRequests.length > 0
|
|
177
|
+
? { tokenPermit: tokenPermitRequestId }
|
|
178
|
+
: {},
|
|
179
|
+
},
|
|
180
|
+
},
|
|
181
|
+
],
|
|
182
|
+
signatureRequests,
|
|
183
|
+
}));
|
|
184
|
+
}
|
|
185
|
+
/** @internal Encodes the deposit from its self-contained inputs and resolved signature requests. */
|
|
186
|
+
export function buildVaultV2Deposit(action, requests) {
|
|
187
|
+
const { asset, chainId, account, ...args } = action.inputs;
|
|
188
|
+
const signature = getVaultPermit(requests, {
|
|
189
|
+
id: action.signatureRequestIds.tokenPermit,
|
|
190
|
+
asset,
|
|
191
|
+
owner: account,
|
|
192
|
+
});
|
|
193
|
+
const requirementSignature = selectBundlesTokenRequirementSignature(signature ? [signature] : [], {
|
|
194
|
+
spender: getChainAddress(chainId, "bundles.vaultBundlesV1"),
|
|
195
|
+
amount: action.inputs.amount ?? action.inputs.nativeAmount,
|
|
196
|
+
deadline: action.inputs.deadline,
|
|
197
|
+
});
|
|
198
|
+
return vaultV2Deposit({
|
|
199
|
+
vault: { chainId, address: action.inputs.vault, asset },
|
|
200
|
+
args: {
|
|
201
|
+
...args,
|
|
202
|
+
userAddress: account,
|
|
203
|
+
requirementSignature,
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
}
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { type AccrualVaultV2 } from "@morpho-org/blue-sdk";
|
|
2
|
+
import { type Address, type Client } from "viem";
|
|
3
|
+
import { type Transaction, type VaultV2WithdrawAction } from "../../types/index.js";
|
|
4
|
+
import { type IntentParams } from "../intent.js";
|
|
5
|
+
import type { Action, SignatureRequest, TransactionPlan } from "../types.js";
|
|
6
|
+
/** @internal Validates the stored Vault V2 withdrawal action's input shape. */
|
|
7
|
+
export declare function validateWithdrawPlanAction(action: Record<string, unknown>, path: string): void;
|
|
8
|
+
/**
|
|
9
|
+
* Caller intent for a Vault V2 asset withdrawal, mirroring the Actions API withdraw inputs, plus the snapshot.
|
|
10
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
11
|
+
*/
|
|
12
|
+
export interface VaultV2WithdrawPlanParams extends IntentParams {
|
|
13
|
+
readonly vault: Address;
|
|
14
|
+
/** Gross assets withdrawn, before the referral fee. */
|
|
15
|
+
readonly amount: bigint;
|
|
16
|
+
/**
|
|
17
|
+
* Accrual snapshot of `vault`, fetched by the caller with `fetchAccrualVaultV2`. The required
|
|
18
|
+
* share allowance is derived from it at preparation; the snapshot itself is never stored.
|
|
19
|
+
*/
|
|
20
|
+
readonly vaultData: AccrualVaultV2;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Prepares a withdrawal plan from caller intent and a vault snapshot. The share quote is fixed on
|
|
24
|
+
* the withdrawal step at preparation, because the required share allowance decides the approval or
|
|
25
|
+
* permit prerequisite, so the returned plan is static: only signatures are added before building.
|
|
26
|
+
* When allowance is insufficient, both direct share approvals and ERC-2612 share permits authorize
|
|
27
|
+
* `maxUint256`, not the quote. Later withdrawals reuse that allowance without another signature.
|
|
28
|
+
* The share-allowance quote uses `DEFAULT_SLIPPAGE_TOLERANCE` internally. The withdrawal has no
|
|
29
|
+
* on-chain share-price or max-shares bound and accepts no slippage tolerance input.
|
|
30
|
+
* @param client - Viem client for `params.chainId`, used for allowance and nonce reads only.
|
|
31
|
+
* @param params.vault - Vault V2 contract whose shares are burned for the withdrawal.
|
|
32
|
+
* @param params.vaultData - Caller-fetched `AccrualVaultV2` snapshot of `vault`, used to derive the required share allowance.
|
|
33
|
+
* @param params.chainId - Chain containing the vault and registered VaultBundlesV1 contract.
|
|
34
|
+
* @param params.account - Non-zero account approving or permitting shares and sending the withdrawal.
|
|
35
|
+
* @param params.amount - Positive gross withdrawal in asset base units, before referral fees.
|
|
36
|
+
* @param params.referralFee.bps - Optional integer fee in basis points of the gross amount; defaults to zero and must be below 10,000.
|
|
37
|
+
* @param params.referralFee.recipient - Recipient of the optional fee; must be non-zero when the fee is positive.
|
|
38
|
+
* @param params.supportSignature - Optional unlimited share-permit preference, defaulting to `false`; otherwise uses unlimited direct share approval when allowance is insufficient.
|
|
39
|
+
* @param params.expiresAt - Optional future Unix timestamp in seconds as a safe integer; defaults to two hours from preparation.
|
|
40
|
+
* @param params.calldataOrigin - Optional non-empty, even-length hex bytes appended to each built transaction's calldata.
|
|
41
|
+
* @param params.deployless - Optional shared intent field; unused by withdrawal share-permit reads.
|
|
42
|
+
* @returns A plan with the withdrawal step and any required share approval or signature request.
|
|
43
|
+
* @throws {ZeroAccountError} when `account` is the zero address.
|
|
44
|
+
* @throws {NonIntegerInputError} when `expiresAt` or `referralFee.bps` is not a safe integer.
|
|
45
|
+
* @throws {NonPositiveInputError} when `expiresAt`, `amount` or the computed required shares are not positive.
|
|
46
|
+
* @throws {ExpiredDeadlineError} when `expiresAt` is not in the future.
|
|
47
|
+
* @throws {NegativeInputError} when `referralFee.bps` is negative.
|
|
48
|
+
* @throws {InputExceedsMaxError} when `referralFee.bps` exceeds 10,000 or `amount` exceeds uint256.
|
|
49
|
+
* @throws {InvalidCalldataOriginError} when `calldataOrigin` is empty, malformed or has an odd number of hex digits.
|
|
50
|
+
* @throws {ReferralFeePctExceededError} when `referralFee.bps` equals 10,000; the normalized fee must be below WAD.
|
|
51
|
+
* @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient or a zero recipient.
|
|
52
|
+
* @throws {VaultAddressMismatchError} when `vaultData` describes another vault.
|
|
53
|
+
* @throws {ChainIdMismatchError} when the client targets another chain.
|
|
54
|
+
* @throws {MissingContractCodeError} when the VaultBundlesV1 contract is absent.
|
|
55
|
+
* @see computeVaultMaxShareAllowance for quote errors.
|
|
56
|
+
* @see getVaultBundlesSharesRequirements for allowance and nonce reads.
|
|
57
|
+
* @example
|
|
58
|
+
* ```ts
|
|
59
|
+
* import { prepareVaultV2Withdraw } from "@morpho-org/morpho-sdk";
|
|
60
|
+
* import { fetchAccrualVaultV2 } from "@morpho-org/morpho-sdk/fetch";
|
|
61
|
+
* import { createPublicClient, http } from "viem";
|
|
62
|
+
* import { mainnet } from "viem/chains";
|
|
63
|
+
* const client = createPublicClient({ chain: mainnet, transport: http() });
|
|
64
|
+
* const vault = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
|
|
65
|
+
* const plan = await prepareVaultV2Withdraw(client, {
|
|
66
|
+
* vault, chainId: 1, account: "0x0000000000000000000000000000000000000001", amount: 1_000_000n, supportSignature: true,
|
|
67
|
+
* vaultData: await fetchAccrualVaultV2(vault, client),
|
|
68
|
+
* });
|
|
69
|
+
* // Sign the pending requests, verify and attach with applySignatures, then build.
|
|
70
|
+
* ```
|
|
71
|
+
* @experimental TransactionPlan is in beta; breaking changes may ship in minor releases.
|
|
72
|
+
*/
|
|
73
|
+
export declare function prepareVaultV2Withdraw(client: Client, params: VaultV2WithdrawPlanParams): Promise<TransactionPlan>;
|
|
74
|
+
/** @internal Encodes the withdrawal from its self-contained inputs and resolved signature requests. */
|
|
75
|
+
export declare function buildVaultV2Withdraw(action: Extract<Action, {
|
|
76
|
+
type: "vaultV2Withdraw";
|
|
77
|
+
}>, requests: readonly SignatureRequest[]): Readonly<Transaction<VaultV2WithdrawAction>>;
|