@morpho-org/morpho-sdk 1.2.1 → 2.0.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 (58) hide show
  1. package/README.md +12 -11
  2. package/lib/cjs/actions/marketV1/repay.js +1 -1
  3. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.js +1 -1
  4. package/lib/cjs/actions/marketV1/supplyCollateral.js +1 -1
  5. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +1 -1
  6. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +4 -7
  7. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2.js +4 -7
  8. package/lib/cjs/actions/requirements/getRequirementsAction.d.ts +5 -5
  9. package/lib/cjs/actions/requirements/getRequirementsAction.js +6 -8
  10. package/lib/cjs/actions/vaultV1/deposit.js +1 -1
  11. package/lib/cjs/actions/vaultV1/migrateToV2.js +1 -1
  12. package/lib/cjs/actions/vaultV2/deposit.js +1 -1
  13. package/lib/cjs/actions/vaultV2/forceWithdraw.js +5 -4
  14. package/lib/cjs/client/morphoClient.d.ts +48 -9
  15. package/lib/cjs/client/morphoClient.js +48 -9
  16. package/lib/cjs/client/morphoViemExtension.d.ts +2 -2
  17. package/lib/cjs/client/morphoViemExtension.js +2 -2
  18. package/lib/cjs/entities/marketV1/marketV1.js +0 -6
  19. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +6 -6
  20. package/lib/cjs/entities/vaultV1/vaultV1.js +8 -9
  21. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +5 -5
  22. package/lib/cjs/entities/vaultV2/vaultV2.js +8 -8
  23. package/lib/cjs/helpers/computeReallocations.d.ts +1 -0
  24. package/lib/cjs/helpers/computeReallocations.js +15 -0
  25. package/lib/cjs/helpers/validate.d.ts +10 -6
  26. package/lib/cjs/helpers/validate.js +13 -9
  27. package/lib/cjs/types/action.d.ts +3 -3
  28. package/lib/cjs/types/error.d.ts +20 -0
  29. package/lib/cjs/types/error.js +16 -1
  30. package/lib/esm/actions/marketV1/repay.js +1 -1
  31. package/lib/esm/actions/marketV1/repayWithdrawCollateral.js +1 -1
  32. package/lib/esm/actions/marketV1/supplyCollateral.js +1 -1
  33. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +1 -1
  34. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -8
  35. package/lib/esm/actions/requirements/encode/encodeErc20Permit2.js +5 -8
  36. package/lib/esm/actions/requirements/getRequirementsAction.d.ts +5 -5
  37. package/lib/esm/actions/requirements/getRequirementsAction.js +6 -8
  38. package/lib/esm/actions/vaultV1/deposit.js +1 -1
  39. package/lib/esm/actions/vaultV1/migrateToV2.js +1 -1
  40. package/lib/esm/actions/vaultV2/deposit.js +1 -1
  41. package/lib/esm/actions/vaultV2/forceWithdraw.js +5 -4
  42. package/lib/esm/client/morphoClient.d.ts +48 -9
  43. package/lib/esm/client/morphoClient.js +48 -9
  44. package/lib/esm/client/morphoViemExtension.d.ts +2 -2
  45. package/lib/esm/client/morphoViemExtension.js +2 -2
  46. package/lib/esm/entities/marketV1/marketV1.js +1 -7
  47. package/lib/esm/entities/vaultV1/vaultV1.d.ts +6 -6
  48. package/lib/esm/entities/vaultV1/vaultV1.js +9 -10
  49. package/lib/esm/entities/vaultV2/vaultV2.d.ts +5 -5
  50. package/lib/esm/entities/vaultV2/vaultV2.js +8 -8
  51. package/lib/esm/helpers/computeReallocations.d.ts +1 -0
  52. package/lib/esm/helpers/computeReallocations.js +16 -1
  53. package/lib/esm/helpers/validate.d.ts +10 -6
  54. package/lib/esm/helpers/validate.js +11 -7
  55. package/lib/esm/types/action.d.ts +3 -3
  56. package/lib/esm/types/error.d.ts +20 -0
  57. package/lib/esm/types/error.js +14 -0
  58. package/package.json +11 -11
@@ -83,9 +83,9 @@ export const vaultV1MigrateToV2 = ({ vault: { chainId, address: sourceVault, ass
83
83
  // Without: plain erc20TransferFrom for the specified shares amount.
84
84
  if (requirementSignature) {
85
85
  actions.push(...getRequirementsAction({
86
- chainId,
87
86
  asset: sourceVault,
88
87
  amount: shares,
88
+ recipient: generalAdapter1,
89
89
  requirementSignature,
90
90
  }));
91
91
  }
@@ -92,9 +92,9 @@ export const vaultV2Deposit = ({ vault: { chainId, address: vaultAddress, asset
92
92
  if (amount > 0n) {
93
93
  if (requirementSignature) {
94
94
  actions.push(...getRequirementsAction({
95
- chainId,
96
95
  asset,
97
96
  amount,
97
+ recipient: generalAdapter1,
98
98
  requirementSignature,
99
99
  }));
100
100
  }
@@ -48,7 +48,8 @@ export const vaultV2ForceWithdraw = ({ vault: { address: vaultAddress }, args: {
48
48
  if (deallocations.length === 0) {
49
49
  throw new EmptyDeallocationsError(vaultAddress);
50
50
  }
51
- if (withdraw.amount <= 0n) {
51
+ const { amount: withdrawAmount, recipient: withdrawRecipient } = withdraw;
52
+ if (withdrawAmount <= 0n) {
52
53
  throw new NonPositiveAssetAmountError(vaultAddress);
53
54
  }
54
55
  const calls = [];
@@ -58,7 +59,7 @@ export const vaultV2ForceWithdraw = ({ vault: { address: vaultAddress }, args: {
58
59
  calls.push(encodeFunctionData({
59
60
  abi: vaultV2Abi,
60
61
  functionName: "withdraw",
61
- args: [withdraw.amount, withdraw.recipient, onBehalf],
62
+ args: [withdrawAmount, withdrawRecipient, onBehalf],
62
63
  }));
63
64
  let tx = {
64
65
  to: vaultAddress,
@@ -80,8 +81,8 @@ export const vaultV2ForceWithdraw = ({ vault: { address: vaultAddress }, args: {
80
81
  vault: vaultAddress,
81
82
  deallocations: deallocations.map((d) => ({ ...d })),
82
83
  withdraw: {
83
- amount: withdraw.amount,
84
- recipient: withdraw.recipient,
84
+ amount: withdrawAmount,
85
+ recipient: withdrawRecipient,
85
86
  },
86
87
  onBehalf,
87
88
  },
@@ -8,6 +8,42 @@ import { type Metadata, type MorphoClientType } from "../types/index.js";
8
8
  *
9
9
  * Holds no state beyond configuration: no cache, no `init()`, no warm-up. Each factory call
10
10
  * (`vaultV1`, `vaultV2`, `marketV1`) returns a fresh entity bound to this client.
11
+ *
12
+ * @deprecated Use {@link morphoViemExtension} instead. Extending your viem client keeps a single
13
+ * transport / chain / account on the integrator side and exposes the same factories under
14
+ * `client.morpho`, so reads and writes share one client. `MorphoClient` will be removed in the
15
+ * next major release.
16
+ *
17
+ * @example
18
+ * ```ts
19
+ * // Before — wrapping a viem client in MorphoClient:
20
+ * import { createPublicClient, http } from "viem";
21
+ * import { mainnet } from "viem/chains";
22
+ * import { MorphoClient } from "@morpho-org/morpho-sdk";
23
+ *
24
+ * const publicClient = createPublicClient({ chain: mainnet, transport: http() });
25
+ * const morpho = new MorphoClient(publicClient);
26
+ *
27
+ * const vault = morpho.vaultV1(vaultAddress, 1);
28
+ * const vaultData = await vault.getData();
29
+ * ```
30
+ *
31
+ * @example
32
+ * ```ts
33
+ * // After — extend the public client directly:
34
+ * import { createPublicClient, http } from "viem";
35
+ * import { mainnet } from "viem/chains";
36
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
37
+ *
38
+ * const client = createPublicClient({ chain: mainnet, transport: http() }).extend(
39
+ * morphoViemExtension(),
40
+ * );
41
+ *
42
+ * // Native viem reads and Morpho factories share the same client:
43
+ * const block = await client.getBlockNumber();
44
+ * const vault = client.morpho.vaultV1(vaultAddress, 1);
45
+ * const vaultData = await vault.getData();
46
+ * ```
11
47
  */
12
48
  export declare class MorphoClient implements MorphoClientType {
13
49
  readonly viemClient: Client;
@@ -31,16 +67,19 @@ export declare class MorphoClient implements MorphoClientType {
31
67
  * @param _options.supportDeployless - Whether entity fetchers may use deployless multicall.
32
68
  * @param _options.metadata - Optional analytics metadata applied to every transaction this
33
69
  * client builds.
70
+ * @deprecated Prefer {@link morphoViemExtension} so the SDK rides on top of a viem client the
71
+ * integrator already owns (public or wallet). Will be removed in the next major release.
34
72
  * @example
35
73
  * ```ts
36
- * import { createWalletClient, http } from "viem";
74
+ * import { createPublicClient, http } from "viem";
37
75
  * import { mainnet } from "viem/chains";
38
- * import { MorphoClient } from "@morpho-org/morpho-sdk";
76
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
39
77
  *
40
- * const client = new MorphoClient(
41
- * createWalletClient({ chain: mainnet, transport: http(), account: user }),
42
- * { supportSignature: true },
78
+ * const client = createPublicClient({ chain: mainnet, transport: http() }).extend(
79
+ * morphoViemExtension({ supportSignature: true }),
43
80
  * );
81
+ *
82
+ * const vault = client.morpho.vaultV1(vaultAddress, 1);
44
83
  * ```
45
84
  */
46
85
  constructor(viemClient: Client, _options?: {
@@ -57,11 +96,11 @@ export declare class MorphoClient implements MorphoClientType {
57
96
  * @example
58
97
  * ```ts
59
98
  * const vault = client.vaultV1(vaultAddress, 1);
60
- * const accrualVault = await vault.getData();
99
+ * const vaultData = await vault.getData();
61
100
  * const { buildTx } = vault.deposit({
62
101
  * amount: 1_000_000n,
63
102
  * userAddress: depositor,
64
- * accrualVault,
103
+ * vaultData,
65
104
  * });
66
105
  * const tx = buildTx();
67
106
  * ```
@@ -76,11 +115,11 @@ export declare class MorphoClient implements MorphoClientType {
76
115
  * @example
77
116
  * ```ts
78
117
  * const vault = client.vaultV2(vaultAddress, 1);
79
- * const accrualVault = await vault.getData();
118
+ * const vaultData = await vault.getData();
80
119
  * const { buildTx } = vault.deposit({
81
120
  * amount: 1_000_000n,
82
121
  * userAddress: depositor,
83
- * accrualVault,
122
+ * vaultData,
84
123
  * });
85
124
  * const tx = buildTx();
86
125
  * ```
@@ -7,6 +7,42 @@ import { MarketIdMismatchError, } from "../types/index.js";
7
7
  *
8
8
  * Holds no state beyond configuration: no cache, no `init()`, no warm-up. Each factory call
9
9
  * (`vaultV1`, `vaultV2`, `marketV1`) returns a fresh entity bound to this client.
10
+ *
11
+ * @deprecated Use {@link morphoViemExtension} instead. Extending your viem client keeps a single
12
+ * transport / chain / account on the integrator side and exposes the same factories under
13
+ * `client.morpho`, so reads and writes share one client. `MorphoClient` will be removed in the
14
+ * next major release.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * // Before — wrapping a viem client in MorphoClient:
19
+ * import { createPublicClient, http } from "viem";
20
+ * import { mainnet } from "viem/chains";
21
+ * import { MorphoClient } from "@morpho-org/morpho-sdk";
22
+ *
23
+ * const publicClient = createPublicClient({ chain: mainnet, transport: http() });
24
+ * const morpho = new MorphoClient(publicClient);
25
+ *
26
+ * const vault = morpho.vaultV1(vaultAddress, 1);
27
+ * const vaultData = await vault.getData();
28
+ * ```
29
+ *
30
+ * @example
31
+ * ```ts
32
+ * // After — extend the public client directly:
33
+ * import { createPublicClient, http } from "viem";
34
+ * import { mainnet } from "viem/chains";
35
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
36
+ *
37
+ * const client = createPublicClient({ chain: mainnet, transport: http() }).extend(
38
+ * morphoViemExtension(),
39
+ * );
40
+ *
41
+ * // Native viem reads and Morpho factories share the same client:
42
+ * const block = await client.getBlockNumber();
43
+ * const vault = client.morpho.vaultV1(vaultAddress, 1);
44
+ * const vaultData = await vault.getData();
45
+ * ```
10
46
  */
11
47
  export class MorphoClient {
12
48
  viemClient;
@@ -22,16 +58,19 @@ export class MorphoClient {
22
58
  * @param _options.supportDeployless - Whether entity fetchers may use deployless multicall.
23
59
  * @param _options.metadata - Optional analytics metadata applied to every transaction this
24
60
  * client builds.
61
+ * @deprecated Prefer {@link morphoViemExtension} so the SDK rides on top of a viem client the
62
+ * integrator already owns (public or wallet). Will be removed in the next major release.
25
63
  * @example
26
64
  * ```ts
27
- * import { createWalletClient, http } from "viem";
65
+ * import { createPublicClient, http } from "viem";
28
66
  * import { mainnet } from "viem/chains";
29
- * import { MorphoClient } from "@morpho-org/morpho-sdk";
67
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
30
68
  *
31
- * const client = new MorphoClient(
32
- * createWalletClient({ chain: mainnet, transport: http(), account: user }),
33
- * { supportSignature: true },
69
+ * const client = createPublicClient({ chain: mainnet, transport: http() }).extend(
70
+ * morphoViemExtension({ supportSignature: true }),
34
71
  * );
72
+ *
73
+ * const vault = client.morpho.vaultV1(vaultAddress, 1);
35
74
  * ```
36
75
  */
37
76
  constructor(viemClient, _options) {
@@ -52,11 +91,11 @@ export class MorphoClient {
52
91
  * @example
53
92
  * ```ts
54
93
  * const vault = client.vaultV1(vaultAddress, 1);
55
- * const accrualVault = await vault.getData();
94
+ * const vaultData = await vault.getData();
56
95
  * const { buildTx } = vault.deposit({
57
96
  * amount: 1_000_000n,
58
97
  * userAddress: depositor,
59
- * accrualVault,
98
+ * vaultData,
60
99
  * });
61
100
  * const tx = buildTx();
62
101
  * ```
@@ -73,11 +112,11 @@ export class MorphoClient {
73
112
  * @example
74
113
  * ```ts
75
114
  * const vault = client.vaultV2(vaultAddress, 1);
76
- * const accrualVault = await vault.getData();
115
+ * const vaultData = await vault.getData();
77
116
  * const { buildTx } = vault.deposit({
78
117
  * amount: 1_000_000n,
79
118
  * userAddress: depositor,
80
- * accrualVault,
119
+ * vaultData,
81
120
  * });
82
121
  * const tx = buildTx();
83
122
  * ```
@@ -27,11 +27,11 @@ import { MorphoClient } from "./morphoClient.js";
27
27
  * }).extend(morphoViemExtension({ supportSignature: true }));
28
28
  *
29
29
  * const vault = client.morpho.vaultV1(vaultAddress, 1);
30
- * const accrualVault = await vault.getData();
30
+ * const vaultData = await vault.getData();
31
31
  * const { buildTx } = vault.deposit({
32
32
  * amount: 1_000_000n,
33
33
  * userAddress: user,
34
- * accrualVault,
34
+ * vaultData,
35
35
  * });
36
36
  * const tx = buildTx();
37
37
  * ```
@@ -25,11 +25,11 @@ import { MorphoClient } from "./morphoClient.js";
25
25
  * }).extend(morphoViemExtension({ supportSignature: true }));
26
26
  *
27
27
  * const vault = client.morpho.vaultV1(vaultAddress, 1);
28
- * const accrualVault = await vault.getData();
28
+ * const vaultData = await vault.getData();
29
29
  * const { buildTx } = vault.deposit({
30
30
  * amount: 1_000_000n,
31
31
  * userAddress: user,
32
- * accrualVault,
32
+ * vaultData,
33
33
  * });
34
34
  * const tx = buildTx();
35
35
  * ```
@@ -3,7 +3,7 @@ import { fetchAccrualPosition, fetchHolding, fetchMarket, fetchPosition, fetchVa
3
3
  import { Time } from "@morpho-org/morpho-ts";
4
4
  import { SimulationState } from "@morpho-org/simulation-sdk";
5
5
  import { getMorphoAuthorizationRequirement, getRequirements, marketV1Borrow, marketV1Repay, marketV1RepayWithdrawCollateral, marketV1SupplyCollateral, marketV1SupplyCollateralBorrow, marketV1WithdrawCollateral, } from "../../actions/index.js";
6
- import { computeMaxRepaySharePrice, computeMinBorrowSharePrice, computeReallocations, validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "../../helpers/index.js";
6
+ import { computeMaxRepaySharePrice, computeMinBorrowSharePrice, computeReallocations, validateAccrualPosition, validateChainId, validateNativeCollateral, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateSlippageTolerance, } from "../../helpers/index.js";
7
7
  import { MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, NegativeNativeAmountError, NonPositiveAssetAmountError, NonPositiveBorrowAmountError, NonPositiveRepayAmountError, NonPositiveWithdrawCollateralAmountError, WithdrawExceedsCollateralError, ZeroCollateralAmountError, } from "../../types/index.js";
8
8
  export class MorphoMarketV1 {
9
9
  client;
@@ -33,7 +33,6 @@ export class MorphoMarketV1 {
33
33
  }
34
34
  supplyCollateral({ amount = 0n, userAddress, nativeAmount, }) {
35
35
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
36
- validateUserAddress(this.client.viemClient.account?.address, userAddress);
37
36
  if (amount < 0n) {
38
37
  throw new NonPositiveAssetAmountError(this.marketParams.collateralToken);
39
38
  }
@@ -73,7 +72,6 @@ export class MorphoMarketV1 {
73
72
  }
74
73
  borrow({ amount, userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
75
74
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
76
- validateUserAddress(this.client.viemClient.account?.address, userAddress);
77
75
  if (amount <= 0n) {
78
76
  throw new NonPositiveBorrowAmountError(this.marketParams.id);
79
77
  }
@@ -124,7 +122,6 @@ export class MorphoMarketV1 {
124
122
  }
125
123
  repay(params) {
126
124
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
127
- validateUserAddress(this.client.viemClient.account?.address, params.userAddress);
128
125
  const { userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, } = params;
129
126
  if ("assets" in params && "shares" in params) {
130
127
  throw new MutuallyExclusiveRepayAmountsError(this.marketParams.id);
@@ -210,7 +207,6 @@ export class MorphoMarketV1 {
210
207
  }
211
208
  withdrawCollateral({ userAddress, amount, positionData, }) {
212
209
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
213
- validateUserAddress(this.client.viemClient.account?.address, userAddress);
214
210
  if (amount <= 0n) {
215
211
  throw new NonPositiveWithdrawCollateralAmountError(this.marketParams.id);
216
212
  }
@@ -252,7 +248,6 @@ export class MorphoMarketV1 {
252
248
  }
253
249
  repayWithdrawCollateral(params) {
254
250
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
255
- validateUserAddress(this.client.viemClient.account?.address, params.userAddress);
256
251
  const { userAddress, withdrawAmount, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, } = params;
257
252
  if ("assets" in params && "shares" in params) {
258
253
  throw new MutuallyExclusiveRepayAmountsError(this.marketParams.id);
@@ -367,7 +362,6 @@ export class MorphoMarketV1 {
367
362
  }
368
363
  supplyCollateralBorrow({ amount = 0n, userAddress, positionData, borrowAmount, nativeAmount, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
369
364
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
370
- validateUserAddress(this.client.viemClient.account?.address, userAddress);
371
365
  if (amount < 0n) {
372
366
  throw new NonPositiveAssetAmountError(this.marketParams.collateralToken);
373
367
  }
@@ -8,26 +8,26 @@ export interface VaultV1Actions {
8
8
  * Fetches the latest vault data with accrued interest.
9
9
  *
10
10
  * @param {FetchParameters} [parameters] - Optional fetch parameters (block number, state overrides, etc.).
11
- * @returns {Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>} The latest accrued vault data.
11
+ * @returns {Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>} The latest vault data.
12
12
  */
13
13
  getData: (parameters?: FetchParameters) => Promise<Awaited<ReturnType<typeof fetchAccrualVault>>>;
14
14
  /**
15
15
  * Prepares a deposit into a VaultV1 (MetaMorpho) contract.
16
16
  *
17
- * Uses pre-fetched accrual vault data to compute `maxSharePrice` with slippage tolerance,
17
+ * Uses pre-fetched vault data to compute `maxSharePrice` with slippage tolerance,
18
18
  * then returns `buildTx` and `getRequirements` for lazy evaluation.
19
19
  *
20
20
  * @param {Object} params - The deposit parameters.
21
21
  * @param {bigint} params.amount - Amount of assets to deposit.
22
22
  * @param {Address} params.userAddress - User address initiating the deposit.
23
- * @param {AccrualVault} params.accrualVault - Pre-fetched vault data with asset address and share conversion.
23
+ * @param {AccrualVault} params.vaultData - Pre-fetched vault data with asset address and share conversion.
24
24
  * @param {bigint} [params.slippageTolerance=DEFAULT_SLIPPAGE_TOLERANCE] - Slippage tolerance (default 0.03%, max 10%).
25
25
  * @param {bigint} [params.nativeAmount] - Amount of native ETH to wrap into WETH. Vault asset must be wNative.
26
26
  * @returns {Object} Object with `buildTx` and `getRequirements`.
27
27
  */
28
28
  deposit: (params: {
29
29
  userAddress: Address;
30
- accrualVault: AccrualVault;
30
+ vaultData: AccrualVault;
31
31
  slippageTolerance?: bigint;
32
32
  } & DepositAmountArgs) => {
33
33
  buildTx: (requirementSignature?: RequirementSignature) => Readonly<Transaction<VaultV1DepositAction>>;
@@ -94,9 +94,9 @@ export declare class MorphoVaultV1 implements VaultV1Actions {
94
94
  private readonly chainId;
95
95
  constructor(client: MorphoClientType, vault: Address, chainId: number);
96
96
  getData(parameters?: FetchParameters): Promise<AccrualVault>;
97
- deposit({ amount, userAddress, accrualVault, slippageTolerance, nativeAmount, }: {
97
+ deposit({ amount, userAddress, vaultData, slippageTolerance, nativeAmount, }: {
98
98
  userAddress: Address;
99
- accrualVault: AccrualVault;
99
+ vaultData: AccrualVault;
100
100
  slippageTolerance?: bigint;
101
101
  } & DepositAmountArgs): {
102
102
  getRequirements: (params?: {
@@ -3,7 +3,7 @@ import { fetchAccrualVault } from "@morpho-org/blue-sdk-viem";
3
3
  import { isAddressEqual } from "viem";
4
4
  import { getRequirements, vaultV1Deposit, vaultV1MigrateToV2, vaultV1Redeem, vaultV1Withdraw, } from "../../actions/index.js";
5
5
  import { MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, } from "../../helpers/constant.js";
6
- import { validateChainId, validateUserAddress } from "../../helpers/index.js";
6
+ import { validateChainId } from "../../helpers/index.js";
7
7
  import { ChainIdMismatchError, ChainWNativeMissingError, ExcessiveSlippageToleranceError, NativeAmountOnNonWNativeVaultError, NegativeNativeAmountError, NegativeSlippageToleranceError, NonPositiveAssetAmountError, NonPositiveSharesAmountError, VaultAddressMismatchError, VaultAssetMismatchError, } from "../../types/index.js";
8
8
  export class MorphoVaultV1 {
9
9
  client;
@@ -26,12 +26,12 @@ export class MorphoVaultV1 {
26
26
  deployless: this.client.options.supportDeployless,
27
27
  });
28
28
  }
29
- deposit({ amount = 0n, userAddress, accrualVault, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
29
+ deposit({ amount = 0n, userAddress, vaultData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
30
30
  if (this.client.viemClient.chain?.id !== this.chainId) {
31
31
  throw new ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
32
32
  }
33
- if (!isAddressEqual(accrualVault.address, this.vault)) {
34
- throw new VaultAddressMismatchError(this.vault, accrualVault.address);
33
+ if (!isAddressEqual(vaultData.address, this.vault)) {
34
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
35
35
  }
36
36
  if (amount < 0n) {
37
37
  throw new NonPositiveAssetAmountError(this.vault);
@@ -53,19 +53,19 @@ export class MorphoVaultV1 {
53
53
  throw new ExcessiveSlippageToleranceError(slippageTolerance);
54
54
  }
55
55
  if (nativeAmount && wNative) {
56
- if (!isAddressEqual(accrualVault.asset, wNative)) {
57
- throw new NativeAmountOnNonWNativeVaultError(accrualVault.asset, wNative);
56
+ if (!isAddressEqual(vaultData.asset, wNative)) {
57
+ throw new NativeAmountOnNonWNativeVaultError(vaultData.asset, wNative);
58
58
  }
59
59
  }
60
60
  const totalAssets = amount + (nativeAmount ?? 0n);
61
- const shares = accrualVault.toShares(totalAssets);
61
+ const shares = vaultData.toShares(totalAssets);
62
62
  if (shares <= 0n) {
63
63
  throw new NonPositiveSharesAmountError(this.vault);
64
64
  }
65
65
  const maxSharePrice = MathLib.min(MathLib.mulDivUp(totalAssets, MathLib.wToRay(MathLib.WAD + slippageTolerance), shares), MAX_ABSOLUTE_SHARE_PRICE);
66
66
  return {
67
67
  getRequirements: async (params) => await getRequirements(this.client.viemClient, {
68
- address: accrualVault.asset,
68
+ address: vaultData.asset,
69
69
  chainId: this.chainId,
70
70
  supportSignature: this.client.options.supportSignature,
71
71
  supportDeployless: this.client.options.supportDeployless,
@@ -79,7 +79,7 @@ export class MorphoVaultV1 {
79
79
  vault: {
80
80
  chainId: this.chainId,
81
81
  address: this.vault,
82
- asset: accrualVault.asset,
82
+ asset: vaultData.asset,
83
83
  },
84
84
  args: {
85
85
  amount,
@@ -126,7 +126,6 @@ export class MorphoVaultV1 {
126
126
  }
127
127
  migrateToV2({ userAddress, sourceVault, targetVault, shares, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, }) {
128
128
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
129
- validateUserAddress(this.client.viemClient.account?.address, userAddress);
130
129
  if (!isAddressEqual(sourceVault.address, this.vault)) {
131
130
  throw new VaultAddressMismatchError(this.vault, sourceVault.address);
132
131
  }
@@ -17,14 +17,14 @@ export interface VaultV2Actions {
17
17
  * Prepares a deposit transaction for the VaultV2 contract.
18
18
  *
19
19
  * This function constructs the transaction data required to deposit a specified amount of assets into the vault.
20
- * Uses pre-fetched accrual vault data for accurate calculations of slippage and asset address,
20
+ * Uses pre-fetched vault data for accurate calculations of slippage and asset address,
21
21
  * then returns the prepared deposit transaction and a function for retrieving all required approval transactions.
22
22
  * Bundler Integration: This flow uses the bundler to atomically execute the user's asset transfer and vault deposit in a single transaction for slippage protection.
23
23
  *
24
24
  * @param {Object} params - The deposit parameters.
25
25
  * @param {bigint} [params.amount=0n] - Amount of ERC-20 assets to deposit. At least one of amount or nativeAmount must be provided.
26
26
  * @param {Address} params.userAddress - User address initiating the deposit.
27
- * @param {AccrualVaultV2} params.accrualVault - Pre-fetched vault data with asset address and share conversion.
27
+ * @param {AccrualVaultV2} params.vaultData - Pre-fetched vault data with asset address and share conversion.
28
28
  * @param {bigint} [params.slippageTolerance=DEFAULT_SLIPPAGE_TOLERANCE] - Optional slippage tolerance value. Default is 0.03%. Slippage tolerance must be less than 10%.
29
29
  * @param {bigint} [params.nativeAmount] - Amount of native token to wrap into wNative. Vault asset must be wNative.
30
30
  * @returns {Object} The result object.
@@ -33,7 +33,7 @@ export interface VaultV2Actions {
33
33
  */
34
34
  deposit: (params: {
35
35
  userAddress: Address;
36
- accrualVault: AccrualVaultV2;
36
+ vaultData: AccrualVaultV2;
37
37
  slippageTolerance?: bigint;
38
38
  } & DepositAmountArgs) => {
39
39
  buildTx: (requirementSignature?: RequirementSignature) => Readonly<Transaction<VaultV2DepositAction>>;
@@ -137,9 +137,9 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
137
137
  private readonly chainId;
138
138
  constructor(client: MorphoClientType, vault: Address, chainId: number);
139
139
  getData(parameters?: FetchParameters): Promise<AccrualVaultV2>;
140
- deposit({ amount, userAddress, accrualVault, slippageTolerance, nativeAmount, }: {
140
+ deposit({ amount, userAddress, vaultData, slippageTolerance, nativeAmount, }: {
141
141
  userAddress: Address;
142
- accrualVault: AccrualVaultV2;
142
+ vaultData: AccrualVaultV2;
143
143
  slippageTolerance?: bigint;
144
144
  } & DepositAmountArgs): {
145
145
  getRequirements: (params?: {
@@ -25,12 +25,12 @@ export class MorphoVaultV2 {
25
25
  deployless: this.client.options.supportDeployless,
26
26
  });
27
27
  }
28
- deposit({ amount = 0n, userAddress, accrualVault, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
28
+ deposit({ amount = 0n, userAddress, vaultData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
29
29
  if (this.client.viemClient.chain?.id !== this.chainId) {
30
30
  throw new ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
31
31
  }
32
- if (!isAddressEqual(accrualVault.address, this.vault)) {
33
- throw new VaultAddressMismatchError(this.vault, accrualVault.address);
32
+ if (!isAddressEqual(vaultData.address, this.vault)) {
33
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
34
34
  }
35
35
  if (amount < 0n) {
36
36
  throw new NonPositiveAssetAmountError(this.vault);
@@ -52,19 +52,19 @@ export class MorphoVaultV2 {
52
52
  throw new ExcessiveSlippageToleranceError(slippageTolerance);
53
53
  }
54
54
  if (nativeAmount && wNative) {
55
- if (!isAddressEqual(accrualVault.asset, wNative)) {
56
- throw new NativeAmountOnNonWNativeVaultError(accrualVault.asset, wNative);
55
+ if (!isAddressEqual(vaultData.asset, wNative)) {
56
+ throw new NativeAmountOnNonWNativeVaultError(vaultData.asset, wNative);
57
57
  }
58
58
  }
59
59
  const totalAssets = amount + (nativeAmount ?? 0n);
60
- const shares = accrualVault.toShares(totalAssets);
60
+ const shares = vaultData.toShares(totalAssets);
61
61
  if (shares <= 0n) {
62
62
  throw new NonPositiveSharesAmountError(this.vault);
63
63
  }
64
64
  const maxSharePrice = MathLib.min(MathLib.mulDivUp(totalAssets, MathLib.wToRay(MathLib.WAD + slippageTolerance), shares), MathLib.RAY * 100n);
65
65
  return {
66
66
  getRequirements: async (params) => await getRequirements(this.client.viemClient, {
67
- address: accrualVault.asset,
67
+ address: vaultData.asset,
68
68
  chainId: this.chainId,
69
69
  supportSignature: this.client.options.supportSignature,
70
70
  supportDeployless: this.client.options.supportDeployless,
@@ -78,7 +78,7 @@ export class MorphoVaultV2 {
78
78
  vault: {
79
79
  chainId: this.chainId,
80
80
  address: this.vault,
81
- asset: accrualVault.asset,
81
+ asset: vaultData.asset,
82
82
  },
83
83
  args: {
84
84
  amount,
@@ -14,6 +14,7 @@ import { type ReallocationComputeOptions, type VaultReallocation } from "../type
14
14
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
15
15
  * @param params.options - Optional reallocation computation options.
16
16
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
17
+ * @throws {InsufficientSharedLiquidityError} If shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
17
18
  */
18
19
  export declare const computeReallocations: ({ reallocationData: data, marketId, borrowAmount, options, }: {
19
20
  readonly reallocationData: SimulationState;
@@ -1,6 +1,6 @@
1
1
  import { MarketUtils, MathLib } from "@morpho-org/blue-sdk";
2
2
  import { DEFAULT_SUPPLY_TARGET_UTILIZATION } from "@morpho-org/bundler-sdk-viem";
3
- import { MissingPublicAllocatorConfigError, } from "../types/index.js";
3
+ import { InsufficientSharedLiquidityError, MissingPublicAllocatorConfigError, } from "../types/index.js";
4
4
  /**
5
5
  * Computes vault reallocations for a borrow operation on a target market.
6
6
  *
@@ -14,6 +14,7 @@ import { MissingPublicAllocatorConfigError, } from "../types/index.js";
14
14
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
15
15
  * @param params.options - Optional reallocation computation options.
16
16
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
17
+ * @throws {InsufficientSharedLiquidityError} If shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
17
18
  */
18
19
  export const computeReallocations = ({ reallocationData: data, marketId, borrowAmount, options, }) => {
19
20
  if (options?.enabled === false)
@@ -50,8 +51,13 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
50
51
  }
51
52
  if (requiredAssets <= 0n)
52
53
  return [];
54
+ // Liquidity strictly required for `morphoBorrow` to succeed onchain.
55
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
56
+ ? newTotalBorrowAssets - newTotalSupplyAssets
57
+ : 0n;
53
58
  // Group withdrawals by vault, capping total at requiredAssets.
54
59
  const reallocationsMap = {};
60
+ let totalReallocated = 0n;
55
61
  for (const { vault, ...withdrawal } of withdrawals) {
56
62
  const vaultReallocations = (reallocationsMap[vault] ??= []);
57
63
  const existing = vaultReallocations.find((item) => item.id === withdrawal.id);
@@ -68,9 +74,18 @@ export const computeReallocations = ({ reallocationData: data, marketId, borrowA
68
74
  });
69
75
  }
70
76
  requiredAssets -= reallocatedAssets;
77
+ totalReallocated += reallocatedAssets;
71
78
  if (requiredAssets === 0n)
72
79
  break;
73
80
  }
81
+ // Refuse fee-bearing partial plans for an unreachable borrow.
82
+ if (totalReallocated < absoluteShortfall) {
83
+ throw new InsufficientSharedLiquidityError({
84
+ marketId,
85
+ shortfall: absoluteShortfall,
86
+ available: totalReallocated,
87
+ });
88
+ }
74
89
  // Transform into VaultReallocation[] format.
75
90
  return Object.entries(reallocationsMap)
76
91
  .filter(([, vaultWithdrawals]) => vaultWithdrawals.length > 0)
@@ -2,13 +2,17 @@ import { type AccrualPosition, type MarketId } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
3
  import { type VaultReallocation } from "../types/index.js";
4
4
  /**
5
- * Validates that the client has a connected account AND that it matches
5
+ * Asserts that the client has a connected account AND that it matches
6
6
  * the provided user address.
7
7
  *
8
- * Enforces the builder = executor invariant: `userAddress` MUST equal the
9
- * connected client account. Some bundle actions (e.g. `erc20TransferFrom`,
10
- * `morphoWithdrawCollateral`) act implicitly on the initiator rather than
11
- * on `userAddress`, so a divergence can produce mixed-account bundles.
8
+ * Used internally by the signature requirements (`encodeErc20Permit`,
9
+ * `encodeErc20Permit2`) to enforce builder = signer at `sign()` time:
10
+ * the signing flow is the only path where an account/address mismatch
11
+ * is a real security concern (rather than just an integrator footgun).
12
+ *
13
+ * Transaction builders no longer call this helper — callers are
14
+ * responsible for keeping `userAddress` aligned with the signing account
15
+ * at the builder layer.
12
16
  *
13
17
  * Throws {@link MissingClientPropertyError} if the client has no account.
14
18
  * Throws {@link AddressMismatchError} if the client account differs from
@@ -18,7 +22,7 @@ import { type VaultReallocation } from "../types/index.js";
18
22
  * `MissingClientPropertyError` is thrown.
19
23
  * @param userAddress - The user address provided by the caller.
20
24
  */
21
- export declare const validateUserAddress: (clientAccountAddress: Address | undefined, userAddress: Address) => void;
25
+ export declare function validateUserAddress(clientAccountAddress: Address | undefined, userAddress: Address): asserts clientAccountAddress is Address;
22
26
  /**
23
27
  * Validates that the accrual position belongs to the expected market and user.
24
28
  * Throws {@link MarketIdMismatchError} if the position's market ID