@morpho-org/morpho-sdk 1.2.0 → 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 +25 -27
@@ -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?: {
@@ -29,12 +29,12 @@ class MorphoVaultV1 {
29
29
  deployless: this.client.options.supportDeployless,
30
30
  });
31
31
  }
32
- deposit({ amount = 0n, userAddress, accrualVault, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
32
+ deposit({ amount = 0n, userAddress, vaultData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
33
33
  if (this.client.viemClient.chain?.id !== this.chainId) {
34
34
  throw new index_js_3.ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
35
35
  }
36
- if (!(0, viem_1.isAddressEqual)(accrualVault.address, this.vault)) {
37
- throw new index_js_3.VaultAddressMismatchError(this.vault, accrualVault.address);
36
+ if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
37
+ throw new index_js_3.VaultAddressMismatchError(this.vault, vaultData.address);
38
38
  }
39
39
  if (amount < 0n) {
40
40
  throw new index_js_3.NonPositiveAssetAmountError(this.vault);
@@ -56,19 +56,19 @@ class MorphoVaultV1 {
56
56
  throw new index_js_3.ExcessiveSlippageToleranceError(slippageTolerance);
57
57
  }
58
58
  if (nativeAmount && wNative) {
59
- if (!(0, viem_1.isAddressEqual)(accrualVault.asset, wNative)) {
60
- throw new index_js_3.NativeAmountOnNonWNativeVaultError(accrualVault.asset, wNative);
59
+ if (!(0, viem_1.isAddressEqual)(vaultData.asset, wNative)) {
60
+ throw new index_js_3.NativeAmountOnNonWNativeVaultError(vaultData.asset, wNative);
61
61
  }
62
62
  }
63
63
  const totalAssets = amount + (nativeAmount ?? 0n);
64
- const shares = accrualVault.toShares(totalAssets);
64
+ const shares = vaultData.toShares(totalAssets);
65
65
  if (shares <= 0n) {
66
66
  throw new index_js_3.NonPositiveSharesAmountError(this.vault);
67
67
  }
68
68
  const maxSharePrice = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.mulDivUp(totalAssets, blue_sdk_1.MathLib.wToRay(blue_sdk_1.MathLib.WAD + slippageTolerance), shares), constant_js_1.MAX_ABSOLUTE_SHARE_PRICE);
69
69
  return {
70
70
  getRequirements: async (params) => await (0, index_js_1.getRequirements)(this.client.viemClient, {
71
- address: accrualVault.asset,
71
+ address: vaultData.asset,
72
72
  chainId: this.chainId,
73
73
  supportSignature: this.client.options.supportSignature,
74
74
  supportDeployless: this.client.options.supportDeployless,
@@ -82,7 +82,7 @@ class MorphoVaultV1 {
82
82
  vault: {
83
83
  chainId: this.chainId,
84
84
  address: this.vault,
85
- asset: accrualVault.asset,
85
+ asset: vaultData.asset,
86
86
  },
87
87
  args: {
88
88
  amount,
@@ -129,7 +129,6 @@ class MorphoVaultV1 {
129
129
  }
130
130
  migrateToV2({ userAddress, sourceVault, targetVault, shares, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, }) {
131
131
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
132
- (0, index_js_2.validateUserAddress)(this.client.viemClient.account?.address, userAddress);
133
132
  if (!(0, viem_1.isAddressEqual)(sourceVault.address, this.vault)) {
134
133
  throw new index_js_3.VaultAddressMismatchError(this.vault, sourceVault.address);
135
134
  }
@@ -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?: {
@@ -28,12 +28,12 @@ class MorphoVaultV2 {
28
28
  deployless: this.client.options.supportDeployless,
29
29
  });
30
30
  }
31
- deposit({ amount = 0n, userAddress, accrualVault, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
31
+ deposit({ amount = 0n, userAddress, vaultData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
32
32
  if (this.client.viemClient.chain?.id !== this.chainId) {
33
33
  throw new index_js_2.ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
34
34
  }
35
- if (!(0, viem_1.isAddressEqual)(accrualVault.address, this.vault)) {
36
- throw new index_js_2.VaultAddressMismatchError(this.vault, accrualVault.address);
35
+ if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
36
+ throw new index_js_2.VaultAddressMismatchError(this.vault, vaultData.address);
37
37
  }
38
38
  if (amount < 0n) {
39
39
  throw new index_js_2.NonPositiveAssetAmountError(this.vault);
@@ -55,19 +55,19 @@ class MorphoVaultV2 {
55
55
  throw new index_js_2.ExcessiveSlippageToleranceError(slippageTolerance);
56
56
  }
57
57
  if (nativeAmount && wNative) {
58
- if (!(0, viem_1.isAddressEqual)(accrualVault.asset, wNative)) {
59
- throw new index_js_2.NativeAmountOnNonWNativeVaultError(accrualVault.asset, wNative);
58
+ if (!(0, viem_1.isAddressEqual)(vaultData.asset, wNative)) {
59
+ throw new index_js_2.NativeAmountOnNonWNativeVaultError(vaultData.asset, wNative);
60
60
  }
61
61
  }
62
62
  const totalAssets = amount + (nativeAmount ?? 0n);
63
- const shares = accrualVault.toShares(totalAssets);
63
+ const shares = vaultData.toShares(totalAssets);
64
64
  if (shares <= 0n) {
65
65
  throw new index_js_2.NonPositiveSharesAmountError(this.vault);
66
66
  }
67
67
  const maxSharePrice = blue_sdk_1.MathLib.min(blue_sdk_1.MathLib.mulDivUp(totalAssets, blue_sdk_1.MathLib.wToRay(blue_sdk_1.MathLib.WAD + slippageTolerance), shares), blue_sdk_1.MathLib.RAY * 100n);
68
68
  return {
69
69
  getRequirements: async (params) => await (0, index_js_1.getRequirements)(this.client.viemClient, {
70
- address: accrualVault.asset,
70
+ address: vaultData.asset,
71
71
  chainId: this.chainId,
72
72
  supportSignature: this.client.options.supportSignature,
73
73
  supportDeployless: this.client.options.supportDeployless,
@@ -81,7 +81,7 @@ class MorphoVaultV2 {
81
81
  vault: {
82
82
  chainId: this.chainId,
83
83
  address: this.vault,
84
- asset: accrualVault.asset,
84
+ asset: vaultData.asset,
85
85
  },
86
86
  args: {
87
87
  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;
@@ -17,6 +17,7 @@ const index_js_1 = require("../types/index.js");
17
17
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
18
18
  * @param params.options - Optional reallocation computation options.
19
19
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
20
+ * @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.
20
21
  */
21
22
  const computeReallocations = ({ reallocationData: data, marketId, borrowAmount, options, }) => {
22
23
  if (options?.enabled === false)
@@ -53,8 +54,13 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
53
54
  }
54
55
  if (requiredAssets <= 0n)
55
56
  return [];
57
+ // Liquidity strictly required for `morphoBorrow` to succeed onchain.
58
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
59
+ ? newTotalBorrowAssets - newTotalSupplyAssets
60
+ : 0n;
56
61
  // Group withdrawals by vault, capping total at requiredAssets.
57
62
  const reallocationsMap = {};
63
+ let totalReallocated = 0n;
58
64
  for (const { vault, ...withdrawal } of withdrawals) {
59
65
  const vaultReallocations = (reallocationsMap[vault] ??= []);
60
66
  const existing = vaultReallocations.find((item) => item.id === withdrawal.id);
@@ -71,9 +77,18 @@ const computeReallocations = ({ reallocationData: data, marketId, borrowAmount,
71
77
  });
72
78
  }
73
79
  requiredAssets -= reallocatedAssets;
80
+ totalReallocated += reallocatedAssets;
74
81
  if (requiredAssets === 0n)
75
82
  break;
76
83
  }
84
+ // Refuse fee-bearing partial plans for an unreachable borrow.
85
+ if (totalReallocated < absoluteShortfall) {
86
+ throw new index_js_1.InsufficientSharedLiquidityError({
87
+ marketId,
88
+ shortfall: absoluteShortfall,
89
+ available: totalReallocated,
90
+ });
91
+ }
77
92
  // Transform into VaultReallocation[] format.
78
93
  return Object.entries(reallocationsMap)
79
94
  .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
@@ -1,19 +1,24 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeCollateral = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = exports.validateUserAddress = void 0;
3
+ exports.validateSlippageTolerance = exports.validateReallocations = exports.validateRepayParams = exports.validateRepayShares = exports.validateRepayAmount = exports.validatePositionHealthAfterWithdraw = exports.validateNativeCollateral = exports.validateChainId = exports.validatePositionHealth = exports.validateAccrualPosition = void 0;
4
+ exports.validateUserAddress = validateUserAddress;
4
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
6
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
7
  const viem_1 = require("viem");
7
8
  const index_js_1 = require("../types/index.js");
8
9
  const constant_js_1 = require("./constant.js");
9
10
  /**
10
- * Validates that the client has a connected account AND that it matches
11
+ * Asserts that the client has a connected account AND that it matches
11
12
  * the provided user address.
12
13
  *
13
- * Enforces the builder = executor invariant: `userAddress` MUST equal the
14
- * connected client account. Some bundle actions (e.g. `erc20TransferFrom`,
15
- * `morphoWithdrawCollateral`) act implicitly on the initiator rather than
16
- * on `userAddress`, so a divergence can produce mixed-account bundles.
14
+ * Used internally by the signature requirements (`encodeErc20Permit`,
15
+ * `encodeErc20Permit2`) to enforce builder = signer at `sign()` time:
16
+ * the signing flow is the only path where an account/address mismatch
17
+ * is a real security concern (rather than just an integrator footgun).
18
+ *
19
+ * Transaction builders no longer call this helper — callers are
20
+ * responsible for keeping `userAddress` aligned with the signing account
21
+ * at the builder layer.
17
22
  *
18
23
  * Throws {@link MissingClientPropertyError} if the client has no account.
19
24
  * Throws {@link AddressMismatchError} if the client account differs from
@@ -23,15 +28,14 @@ const constant_js_1 = require("./constant.js");
23
28
  * `MissingClientPropertyError` is thrown.
24
29
  * @param userAddress - The user address provided by the caller.
25
30
  */
26
- const validateUserAddress = (clientAccountAddress, userAddress) => {
31
+ function validateUserAddress(clientAccountAddress, userAddress) {
27
32
  if (clientAccountAddress === undefined) {
28
33
  throw new index_js_1.MissingClientPropertyError("account");
29
34
  }
30
35
  if (!(0, viem_1.isAddressEqual)(clientAccountAddress, userAddress)) {
31
36
  throw new index_js_1.AddressMismatchError(clientAccountAddress, userAddress);
32
37
  }
33
- };
34
- exports.validateUserAddress = validateUserAddress;
38
+ }
35
39
  /**
36
40
  * Validates that the accrual position belongs to the expected market and user.
37
41
  * Throws {@link MarketIdMismatchError} if the position's market ID
@@ -1,4 +1,4 @@
1
- import type { Address, Client, Hex } from "viem";
1
+ import type { Address, Hex, WalletClient } from "viem";
2
2
  import type { Deallocation } from "./deallocation.js";
3
3
  export interface BaseAction<TType extends string = string, TArgs extends Record<string, unknown> = Record<string, unknown>> {
4
4
  readonly type: TType;
@@ -10,7 +10,7 @@ export interface ERC20ApprovalAction extends BaseAction<"erc20Approval", {
10
10
  }> {
11
11
  }
12
12
  export interface ERC20PermitAction {
13
- sign: (client: Client, userAddress: Address) => Promise<Hex>;
13
+ sign: (client: WalletClient, userAddress: Address) => Promise<Hex>;
14
14
  }
15
15
  export interface VaultV2DepositAction extends BaseAction<"vaultV2Deposit", {
16
16
  vault: Address;
@@ -191,7 +191,7 @@ export interface Permit2Args {
191
191
  expiration: bigint;
192
192
  }
193
193
  export interface Requirement {
194
- sign: (client: Client, userAddress: Address) => Promise<RequirementSignature>;
194
+ sign: (client: WalletClient, userAddress: Address) => Promise<RequirementSignature>;
195
195
  action: PermitAction | Permit2Action;
196
196
  }
197
197
  export interface PermitAction extends BaseAction<"permit", {
@@ -1,3 +1,4 @@
1
+ import type { MarketId } from "@morpho-org/blue-sdk";
1
2
  import type { Address } from "viem";
2
3
  /** Thrown when an asset amount is required to be positive but is zero or negative. */
3
4
  export declare class NonPositiveAssetAmountError extends Error {
@@ -191,6 +192,25 @@ export declare class RepaySharesExceedDebtError extends Error {
191
192
  export declare class MissingPublicAllocatorConfigError extends Error {
192
193
  constructor(vault: string);
193
194
  }
195
+ /**
196
+ * Thrown when shared liquidity selected by `computeReallocations` cannot cover
197
+ * the absolute borrow shortfall on the target market — the resulting
198
+ * `morphoBorrow` would still revert onchain.
199
+ *
200
+ * Pattern-match on the class and inspect `params` to surface the gap to users.
201
+ */
202
+ export declare class InsufficientSharedLiquidityError extends Error {
203
+ readonly params: {
204
+ readonly marketId: MarketId;
205
+ readonly shortfall: bigint;
206
+ readonly available: bigint;
207
+ };
208
+ constructor(params: {
209
+ readonly marketId: MarketId;
210
+ readonly shortfall: bigint;
211
+ readonly available: bigint;
212
+ });
213
+ }
194
214
  /** Thrown when a market borrow's `minSharePrice` slippage bound is negative. */
195
215
  export declare class NonPositiveMinBorrowSharePriceError extends Error {
196
216
  constructor(market: string);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NegativeMinSharePriceError = exports.VaultAssetMismatchError = exports.NonPositiveMinBorrowSharePriceError = exports.MissingPublicAllocatorConfigError = exports.RepaySharesExceedDebtError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.ShareDivideByZeroError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.NonPositiveWithdrawCollateralAmountError = exports.NonPositiveRepayMaxSharePriceError = exports.NonPositiveRepayAmountError = exports.MutuallyExclusiveRepayAmountsError = exports.TransferAmountNotEqualToAssetsError = exports.NonPositiveTransferAmountError = exports.UnsortedReallocationWithdrawalsError = exports.ReallocationWithdrawalOnTargetMarketError = exports.NonPositiveReallocationAmountError = exports.EmptyReallocationWithdrawalsError = exports.NegativeReallocationFeeError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeCollateralError = exports.ZeroCollateralAmountError = exports.NonPositiveBorrowAmountError = exports.VaultAddressMismatchError = exports.ZeroDepositAmountError = exports.NegativeNativeAmountError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.DepositAssetMismatchError = exports.DepositAmountMismatchError = exports.EmptyDeallocationsError = exports.ExcessiveSlippageToleranceError = exports.MissingAccrualPositionError = exports.NegativeSlippageToleranceError = exports.ApprovalAmountLessThanSpendAmountError = exports.MissingClientPropertyError = exports.ChainIdMismatchError = exports.AddressMismatchError = exports.NonPositiveMaxSharePriceError = exports.NonPositiveSharesAmountError = exports.NonPositiveAssetAmountError = void 0;
3
+ exports.NegativeMinSharePriceError = exports.VaultAssetMismatchError = exports.NonPositiveMinBorrowSharePriceError = exports.InsufficientSharedLiquidityError = exports.MissingPublicAllocatorConfigError = exports.RepaySharesExceedDebtError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.ShareDivideByZeroError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.NonPositiveWithdrawCollateralAmountError = exports.NonPositiveRepayMaxSharePriceError = exports.NonPositiveRepayAmountError = exports.MutuallyExclusiveRepayAmountsError = exports.TransferAmountNotEqualToAssetsError = exports.NonPositiveTransferAmountError = exports.UnsortedReallocationWithdrawalsError = exports.ReallocationWithdrawalOnTargetMarketError = exports.NonPositiveReallocationAmountError = exports.EmptyReallocationWithdrawalsError = exports.NegativeReallocationFeeError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeCollateralError = exports.ZeroCollateralAmountError = exports.NonPositiveBorrowAmountError = exports.VaultAddressMismatchError = exports.ZeroDepositAmountError = exports.NegativeNativeAmountError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.DepositAssetMismatchError = exports.DepositAmountMismatchError = exports.EmptyDeallocationsError = exports.ExcessiveSlippageToleranceError = exports.MissingAccrualPositionError = exports.NegativeSlippageToleranceError = exports.ApprovalAmountLessThanSpendAmountError = exports.MissingClientPropertyError = exports.ChainIdMismatchError = exports.AddressMismatchError = exports.NonPositiveMaxSharePriceError = exports.NonPositiveSharesAmountError = exports.NonPositiveAssetAmountError = void 0;
4
4
  /** Thrown when an asset amount is required to be positive but is zero or negative. */
5
5
  class NonPositiveAssetAmountError extends Error {
6
6
  constructor(origin) {
@@ -302,6 +302,21 @@ class MissingPublicAllocatorConfigError extends Error {
302
302
  }
303
303
  }
304
304
  exports.MissingPublicAllocatorConfigError = MissingPublicAllocatorConfigError;
305
+ /**
306
+ * Thrown when shared liquidity selected by `computeReallocations` cannot cover
307
+ * the absolute borrow shortfall on the target market — the resulting
308
+ * `morphoBorrow` would still revert onchain.
309
+ *
310
+ * Pattern-match on the class and inspect `params` to surface the gap to users.
311
+ */
312
+ class InsufficientSharedLiquidityError extends Error {
313
+ params;
314
+ constructor(params) {
315
+ super(`Shared liquidity is insufficient to cover the borrow on market ${params.marketId}: shortfall "${params.shortfall}", available "${params.available}". Reduce the borrow amount or wait for additional vault liquidity.`);
316
+ this.params = params;
317
+ }
318
+ }
319
+ exports.InsufficientSharedLiquidityError = InsufficientSharedLiquidityError;
305
320
  /** Thrown when a market borrow's `minSharePrice` slippage bound is negative. */
306
321
  class NonPositiveMinBorrowSharePriceError extends Error {
307
322
  constructor(market) {
@@ -74,9 +74,9 @@ export const marketV1Repay = ({ market: { chainId, marketParams }, args: { asset
74
74
  const actions = [];
75
75
  if (requirementSignature) {
76
76
  actions.push(...getRequirementsAction({
77
- chainId,
78
77
  asset: marketParams.loanToken,
79
78
  amount: transferAmount,
79
+ recipient: generalAdapter1,
80
80
  requirementSignature,
81
81
  }));
82
82
  }
@@ -89,9 +89,9 @@ export const marketV1RepayWithdrawCollateral = ({ market: { chainId, marketParam
89
89
  const actions = [];
90
90
  if (requirementSignature) {
91
91
  actions.push(...getRequirementsAction({
92
- chainId,
93
92
  asset: marketParams.loanToken,
94
93
  amount: transferAmount,
94
+ recipient: generalAdapter1,
95
95
  requirementSignature,
96
96
  }));
97
97
  }
@@ -73,9 +73,9 @@ export const marketV1SupplyCollateral = ({ market: { chainId, marketParams }, ar
73
73
  if (amount > 0n) {
74
74
  if (requirementSignature) {
75
75
  actions.push(...getRequirementsAction({
76
- chainId,
77
76
  asset: marketParams.collateralToken,
78
77
  amount,
78
+ recipient: generalAdapter1,
79
79
  requirementSignature,
80
80
  }));
81
81
  }
@@ -106,9 +106,9 @@ export const marketV1SupplyCollateralBorrow = ({ market: { chainId, marketParams
106
106
  if (amount > 0n) {
107
107
  if (requirementSignature) {
108
108
  actions.push(...getRequirementsAction({
109
- chainId,
110
109
  asset: marketParams.collateralToken,
111
110
  amount,
111
+ recipient: generalAdapter1,
112
112
  requirementSignature,
113
113
  }));
114
114
  }
@@ -2,7 +2,8 @@ import { fetchToken, getPermitTypedData } from "@morpho-org/blue-sdk-viem";
2
2
  import { deepFreeze, Time } from "@morpho-org/morpho-ts";
3
3
  import { verifyTypedData } from "viem";
4
4
  import { signTypedData } from "viem/actions";
5
- import { AddressMismatchError, ChainIdMismatchError, InvalidSignatureError, MissingClientPropertyError, } from "../../../types/index.js";
5
+ import { validateUserAddress } from "../../../helpers/validate.js";
6
+ import { ChainIdMismatchError, InvalidSignatureError, } from "../../../types/index.js";
6
7
  /**
7
8
  * Builds an EIP-2612 permit `Requirement` that, once signed, lets `spender` pull `amount` of
8
9
  * `token`.
@@ -62,12 +63,8 @@ export const encodeErc20Permit = async (viemClient, params) => {
62
63
  return {
63
64
  action,
64
65
  async sign(client, userAddress) {
65
- if (!client.account?.address) {
66
- throw new MissingClientPropertyError("client.account.address");
67
- }
68
- if (client.account.address !== userAddress) {
69
- throw new AddressMismatchError(client.account.address, userAddress);
70
- }
66
+ const account = client.account;
67
+ validateUserAddress(account?.address, userAddress);
71
68
  const typedData = getPermitTypedData({
72
69
  erc20: tokenData,
73
70
  owner: userAddress,
@@ -78,7 +75,7 @@ export const encodeErc20Permit = async (viemClient, params) => {
78
75
  }, chainId);
79
76
  const signature = await signTypedData(client, {
80
77
  ...typedData,
81
- account: client.account,
78
+ account,
82
79
  });
83
80
  const isValid = await verifyTypedData({
84
81
  ...typedData,
@@ -3,7 +3,8 @@ import { getPermit2PermitTypedData } from "@morpho-org/blue-sdk-viem";
3
3
  import { deepFreeze, Time } from "@morpho-org/morpho-ts";
4
4
  import { verifyTypedData } from "viem";
5
5
  import { signTypedData } from "viem/actions";
6
- import { AddressMismatchError, InvalidSignatureError, MissingClientPropertyError, } from "../../../types/index.js";
6
+ import { validateUserAddress } from "../../../helpers/validate.js";
7
+ import { InvalidSignatureError, } from "../../../types/index.js";
7
8
  /**
8
9
  * Builds a Permit2 `Requirement` that, once signed, lets `GeneralAdapter1` pull `amount` of
9
10
  * `token` via the Permit2 contract.
@@ -53,12 +54,8 @@ export const encodeErc20Permit2 = (params) => {
53
54
  return {
54
55
  action,
55
56
  async sign(client, userAddress) {
56
- if (!client.account?.address) {
57
- throw new MissingClientPropertyError("client.account.address");
58
- }
59
- if (client.account.address !== userAddress) {
60
- throw new AddressMismatchError(client.account.address, userAddress);
61
- }
57
+ const account = client.account;
58
+ validateUserAddress(account?.address, userAddress);
62
59
  const typedData = getPermit2PermitTypedData({
63
60
  // Never permit any other address than the GeneralAdapter1 otherwise
64
61
  // the signature can be used independently.
@@ -71,7 +68,7 @@ export const encodeErc20Permit2 = (params) => {
71
68
  }, chainId);
72
69
  const signature = await signTypedData(client, {
73
70
  ...typedData,
74
- account: client.account,
71
+ account,
75
72
  });
76
73
  const isValid = await verifyTypedData({
77
74
  ...typedData,
@@ -2,9 +2,9 @@ import type { Action } from "@morpho-org/bundler-sdk-viem";
2
2
  import { type Address } from "viem";
3
3
  import { type Permit2Action, type PermitAction, type PermitArgs } from "../../types/index.js";
4
4
  interface GetRequirementsActionParams {
5
- chainId: number;
6
5
  asset: Address;
7
6
  amount: bigint;
7
+ recipient: Address;
8
8
  requirementSignature: {
9
9
  args: PermitArgs;
10
10
  action: PermitAction | Permit2Action;
@@ -12,7 +12,7 @@ interface GetRequirementsActionParams {
12
12
  }
13
13
  /**
14
14
  * Encodes the bundler actions that consume a pre-signed permit / permit2 requirement and pull
15
- * the asset into `GeneralAdapter1`.
15
+ * the asset to `recipient`.
16
16
  *
17
17
  * Permit2 path emits `approve2` + `transferFrom2`; classic permit path emits `permit` +
18
18
  * `erc20TransferFrom`. The signed `asset` and `amount` must match the pulled `asset` and
@@ -20,14 +20,14 @@ interface GetRequirementsActionParams {
20
20
  * wider-than-expected approval. Internal helper — consumed only by the action builders that
21
21
  * accept a `requirementSignature`; not re-exported on the public surface.
22
22
  *
23
- * @param params.chainId - The chain the bundle targets (used to resolve `GeneralAdapter1`).
24
- * @param params.asset - The ERC-20 to pull into the adapter.
23
+ * @param params.asset - The ERC-20 to pull.
25
24
  * @param params.amount - The amount to pull, in the asset's smallest unit.
25
+ * @param params.recipient - The address that receives the transfer.
26
26
  * @param params.requirementSignature - The signed permit / permit2 to apply before the transfer.
27
27
  * @returns A pair of bundler `Action`s: a permit / approve2 followed by the transfer.
28
28
  * @throws {DepositAssetMismatchError} when the signed asset differs from `asset`.
29
29
  * @throws {DepositAmountMismatchError} when the signed amount differs from `amount`.
30
30
  * @internal
31
31
  */
32
- export declare const getRequirementsAction: ({ chainId, asset, amount, requirementSignature, }: GetRequirementsActionParams) => Action[];
32
+ export declare const getRequirementsAction: ({ asset, amount, recipient, requirementSignature, }: GetRequirementsActionParams) => Action[];
33
33
  export {};
@@ -1,9 +1,8 @@
1
- import { getChainAddresses } from "@morpho-org/blue-sdk";
2
1
  import { isAddressEqual } from "viem";
3
2
  import { DepositAmountMismatchError, DepositAssetMismatchError, } from "../../types/index.js";
4
3
  /**
5
4
  * Encodes the bundler actions that consume a pre-signed permit / permit2 requirement and pull
6
- * the asset into `GeneralAdapter1`.
5
+ * the asset to `recipient`.
7
6
  *
8
7
  * Permit2 path emits `approve2` + `transferFrom2`; classic permit path emits `permit` +
9
8
  * `erc20TransferFrom`. The signed `asset` and `amount` must match the pulled `asset` and
@@ -11,23 +10,22 @@ import { DepositAmountMismatchError, DepositAssetMismatchError, } from "../../ty
11
10
  * wider-than-expected approval. Internal helper — consumed only by the action builders that
12
11
  * accept a `requirementSignature`; not re-exported on the public surface.
13
12
  *
14
- * @param params.chainId - The chain the bundle targets (used to resolve `GeneralAdapter1`).
15
- * @param params.asset - The ERC-20 to pull into the adapter.
13
+ * @param params.asset - The ERC-20 to pull.
16
14
  * @param params.amount - The amount to pull, in the asset's smallest unit.
15
+ * @param params.recipient - The address that receives the transfer.
17
16
  * @param params.requirementSignature - The signed permit / permit2 to apply before the transfer.
18
17
  * @returns A pair of bundler `Action`s: a permit / approve2 followed by the transfer.
19
18
  * @throws {DepositAssetMismatchError} when the signed asset differs from `asset`.
20
19
  * @throws {DepositAmountMismatchError} when the signed amount differs from `amount`.
21
20
  * @internal
22
21
  */
23
- export const getRequirementsAction = ({ chainId, asset, amount, requirementSignature, }) => {
22
+ export const getRequirementsAction = ({ asset, amount, recipient, requirementSignature, }) => {
24
23
  if (!isAddressEqual(requirementSignature.args.asset, asset)) {
25
24
  throw new DepositAssetMismatchError(asset, requirementSignature.args.asset);
26
25
  }
27
26
  if (requirementSignature.args.amount !== amount) {
28
27
  throw new DepositAmountMismatchError(amount, requirementSignature.args.amount);
29
28
  }
30
- const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
31
29
  if (requirementSignature.action.type === "permit2") {
32
30
  if (!("expiration" in requirementSignature.args)) {
33
31
  throw new Error("Expiration is not defined");
@@ -52,7 +50,7 @@ export const getRequirementsAction = ({ chainId, asset, amount, requirementSigna
52
50
  },
53
51
  {
54
52
  type: "transferFrom2",
55
- args: [asset, amount, generalAdapter1, false /* skipRevert */],
53
+ args: [asset, amount, recipient, false /* skipRevert */],
56
54
  },
57
55
  ];
58
56
  }
@@ -70,7 +68,7 @@ export const getRequirementsAction = ({ chainId, asset, amount, requirementSigna
70
68
  },
71
69
  {
72
70
  type: "erc20TransferFrom",
73
- args: [asset, amount, generalAdapter1, false /* skipRevert */],
71
+ args: [asset, amount, recipient, false /* skipRevert */],
74
72
  },
75
73
  ];
76
74
  };
@@ -92,9 +92,9 @@ export const vaultV1Deposit = ({ 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
  }