@morpho-org/morpho-sdk 1.2.1 → 2.1.1

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 (66) 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 +32 -8
  9. package/lib/cjs/actions/requirements/getRequirementsAction.js +34 -12
  10. package/lib/cjs/actions/requirements/index.d.ts +1 -0
  11. package/lib/cjs/actions/requirements/index.js +1 -0
  12. package/lib/cjs/actions/vaultV1/deposit.js +1 -1
  13. package/lib/cjs/actions/vaultV1/migrateToV2.js +1 -1
  14. package/lib/cjs/actions/vaultV2/deposit.js +1 -1
  15. package/lib/cjs/actions/vaultV2/forceWithdraw.js +5 -4
  16. package/lib/cjs/client/morphoClient.d.ts +48 -9
  17. package/lib/cjs/client/morphoClient.js +48 -9
  18. package/lib/cjs/client/morphoViemExtension.d.ts +2 -2
  19. package/lib/cjs/client/morphoViemExtension.js +2 -2
  20. package/lib/cjs/entities/marketV1/marketV1.js +18 -17
  21. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +6 -6
  22. package/lib/cjs/entities/vaultV1/vaultV1.js +14 -11
  23. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +5 -5
  24. package/lib/cjs/entities/vaultV2/vaultV2.js +13 -8
  25. package/lib/cjs/helpers/computeReallocations.d.ts +1 -0
  26. package/lib/cjs/helpers/computeReallocations.js +15 -0
  27. package/lib/cjs/helpers/metadata.d.ts +10 -0
  28. package/lib/cjs/helpers/metadata.js +20 -1
  29. package/lib/cjs/helpers/validate.d.ts +10 -6
  30. package/lib/cjs/helpers/validate.js +13 -9
  31. package/lib/cjs/types/action.d.ts +3 -3
  32. package/lib/cjs/types/error.d.ts +24 -0
  33. package/lib/cjs/types/error.js +23 -1
  34. package/lib/esm/actions/marketV1/repay.js +1 -1
  35. package/lib/esm/actions/marketV1/repayWithdrawCollateral.js +1 -1
  36. package/lib/esm/actions/marketV1/supplyCollateral.js +1 -1
  37. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +1 -1
  38. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -8
  39. package/lib/esm/actions/requirements/encode/encodeErc20Permit2.js +5 -8
  40. package/lib/esm/actions/requirements/getRequirementsAction.d.ts +32 -8
  41. package/lib/esm/actions/requirements/getRequirementsAction.js +35 -13
  42. package/lib/esm/actions/requirements/index.d.ts +1 -0
  43. package/lib/esm/actions/requirements/index.js +1 -0
  44. package/lib/esm/actions/vaultV1/deposit.js +1 -1
  45. package/lib/esm/actions/vaultV1/migrateToV2.js +1 -1
  46. package/lib/esm/actions/vaultV2/deposit.js +1 -1
  47. package/lib/esm/actions/vaultV2/forceWithdraw.js +5 -4
  48. package/lib/esm/client/morphoClient.d.ts +48 -9
  49. package/lib/esm/client/morphoClient.js +48 -9
  50. package/lib/esm/client/morphoViemExtension.d.ts +2 -2
  51. package/lib/esm/client/morphoViemExtension.js +2 -2
  52. package/lib/esm/entities/marketV1/marketV1.js +19 -18
  53. package/lib/esm/entities/vaultV1/vaultV1.d.ts +6 -6
  54. package/lib/esm/entities/vaultV1/vaultV1.js +15 -12
  55. package/lib/esm/entities/vaultV2/vaultV2.d.ts +5 -5
  56. package/lib/esm/entities/vaultV2/vaultV2.js +13 -8
  57. package/lib/esm/helpers/computeReallocations.d.ts +1 -0
  58. package/lib/esm/helpers/computeReallocations.js +16 -1
  59. package/lib/esm/helpers/metadata.d.ts +10 -0
  60. package/lib/esm/helpers/metadata.js +20 -1
  61. package/lib/esm/helpers/validate.d.ts +10 -6
  62. package/lib/esm/helpers/validate.js +11 -7
  63. package/lib/esm/types/action.d.ts +3 -3
  64. package/lib/esm/types/error.d.ts +24 -0
  65. package/lib/esm/types/error.js +20 -0
  66. package/package.json +12 -12
@@ -36,7 +36,6 @@ class MorphoMarketV1 {
36
36
  }
37
37
  supplyCollateral({ amount = 0n, userAddress, nativeAmount, }) {
38
38
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
39
- (0, index_js_2.validateUserAddress)(this.client.viemClient.account?.address, userAddress);
40
39
  if (amount < 0n) {
41
40
  throw new index_js_3.NonPositiveAssetAmountError(this.marketParams.collateralToken);
42
41
  }
@@ -76,7 +75,6 @@ class MorphoMarketV1 {
76
75
  }
77
76
  borrow({ amount, userAddress, positionData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
78
77
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
79
- (0, index_js_2.validateUserAddress)(this.client.viemClient.account?.address, userAddress);
80
78
  if (amount <= 0n) {
81
79
  throw new index_js_3.NonPositiveBorrowAmountError(this.marketParams.id);
82
80
  }
@@ -127,7 +125,6 @@ class MorphoMarketV1 {
127
125
  }
128
126
  repay(params) {
129
127
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
130
- (0, index_js_2.validateUserAddress)(this.client.viemClient.account?.address, params.userAddress);
131
128
  const { userAddress, positionData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, } = params;
132
129
  if ("assets" in params && "shares" in params) {
133
130
  throw new index_js_3.MutuallyExclusiveRepayAmountsError(this.marketParams.id);
@@ -155,6 +152,7 @@ class MorphoMarketV1 {
155
152
  let assets;
156
153
  let shares;
157
154
  let transferAmount;
155
+ let marketForRepay;
158
156
  if (isSharesMode) {
159
157
  (0, index_js_2.validateRepayShares)({
160
158
  positionData,
@@ -163,10 +161,12 @@ class MorphoMarketV1 {
163
161
  });
164
162
  assets = 0n;
165
163
  shares = params.shares;
166
- // Add slippage buffer to cover interest accrued between tx construction and execution.
167
- // Without this, the on-chain repay amount may exceed the pre-transferred ERC20 amount.
168
- const baseTransferAmount = positionData.market.toBorrowAssets(shares, "Up");
169
- transferAmount = blue_sdk_1.MathLib.wMulUp(baseTransferAmount, blue_sdk_1.MathLib.WAD + slippageTolerance);
164
+ // 2h forward accrual upper-bounds the on-chain repay price; bundle
165
+ // skims residual back to the receiver.
166
+ const accrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), positionData.market.lastUpdate) +
167
+ morpho_ts_1.Time.s.from.h(2n);
168
+ marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
169
+ transferAmount = marketForRepay.toBorrowAssets(shares, "Up");
170
170
  }
171
171
  else {
172
172
  (0, index_js_2.validateRepayAmount)({
@@ -177,11 +177,12 @@ class MorphoMarketV1 {
177
177
  assets = params.assets;
178
178
  shares = 0n;
179
179
  transferAmount = params.assets;
180
+ marketForRepay = positionData.market;
180
181
  }
181
182
  const maxSharePrice = (0, index_js_2.computeMaxRepaySharePrice)({
182
183
  repayAssets: assets,
183
184
  repayShares: shares,
184
- market: positionData.market,
185
+ market: marketForRepay,
185
186
  slippageTolerance,
186
187
  });
187
188
  return {
@@ -213,7 +214,6 @@ class MorphoMarketV1 {
213
214
  }
214
215
  withdrawCollateral({ userAddress, amount, positionData, }) {
215
216
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
216
- (0, index_js_2.validateUserAddress)(this.client.viemClient.account?.address, userAddress);
217
217
  if (amount <= 0n) {
218
218
  throw new index_js_3.NonPositiveWithdrawCollateralAmountError(this.marketParams.id);
219
219
  }
@@ -255,7 +255,6 @@ class MorphoMarketV1 {
255
255
  }
256
256
  repayWithdrawCollateral(params) {
257
257
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
258
- (0, index_js_2.validateUserAddress)(this.client.viemClient.account?.address, params.userAddress);
259
258
  const { userAddress, withdrawAmount, positionData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, } = params;
260
259
  if ("assets" in params && "shares" in params) {
261
260
  throw new index_js_3.MutuallyExclusiveRepayAmountsError(this.marketParams.id);
@@ -286,6 +285,11 @@ class MorphoMarketV1 {
286
285
  let assets;
287
286
  let shares;
288
287
  let transferAmount;
288
+ let marketForRepay;
289
+ // 2h forward accrual upper-bounds the on-chain repay price (shares
290
+ // mode) and the post-repay health check; bundle skims residual back.
291
+ const accrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), positionData.market.lastUpdate) +
292
+ morpho_ts_1.Time.s.from.h(2n);
289
293
  if (isSharesMode) {
290
294
  (0, index_js_2.validateRepayShares)({
291
295
  positionData,
@@ -294,8 +298,8 @@ class MorphoMarketV1 {
294
298
  });
295
299
  assets = 0n;
296
300
  shares = params.shares;
297
- const baseTransferAmount = positionData.market.toBorrowAssets(shares, "Up");
298
- transferAmount = blue_sdk_1.MathLib.wMulUp(baseTransferAmount, blue_sdk_1.MathLib.WAD + slippageTolerance);
301
+ marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
302
+ transferAmount = marketForRepay.toBorrowAssets(shares, "Up");
299
303
  }
300
304
  else {
301
305
  (0, index_js_2.validateRepayAmount)({
@@ -306,6 +310,7 @@ class MorphoMarketV1 {
306
310
  assets = params.assets;
307
311
  shares = 0n;
308
312
  transferAmount = params.assets;
313
+ marketForRepay = positionData.market;
309
314
  }
310
315
  if (withdrawAmount > positionData.collateral) {
311
316
  throw new index_js_3.WithdrawExceedsCollateralError({
@@ -314,9 +319,6 @@ class MorphoMarketV1 {
314
319
  market: positionData.marketId,
315
320
  });
316
321
  }
317
- // +10 min accrual buffer: residual debt grows between build and execute.
318
- const accrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), positionData.market.lastUpdate) +
319
- morpho_ts_1.Time.s.from.min(10n);
320
322
  const { position: positionAfterRepay } = positionData.repay(assets, shares, accrualTimestamp);
321
323
  (0, index_js_2.validatePositionHealthAfterWithdraw)({
322
324
  positionData: positionAfterRepay,
@@ -327,7 +329,7 @@ class MorphoMarketV1 {
327
329
  const maxSharePrice = (0, index_js_2.computeMaxRepaySharePrice)({
328
330
  repayAssets: assets,
329
331
  repayShares: shares,
330
- market: positionData.market,
332
+ market: marketForRepay,
331
333
  slippageTolerance,
332
334
  });
333
335
  return {
@@ -370,7 +372,6 @@ class MorphoMarketV1 {
370
372
  }
371
373
  supplyCollateralBorrow({ amount = 0n, userAddress, positionData, borrowAmount, nativeAmount, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
372
374
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
373
- (0, index_js_2.validateUserAddress)(this.client.viemClient.account?.address, userAddress);
374
375
  if (amount < 0n) {
375
376
  throw new index_js_3.NonPositiveAssetAmountError(this.marketParams.collateralToken);
376
377
  }
@@ -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,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MorphoVaultV1 = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
7
  const viem_1 = require("viem");
7
8
  const index_js_1 = require("../../actions/index.js");
8
9
  const constant_js_1 = require("../../helpers/constant.js");
@@ -29,12 +30,12 @@ class MorphoVaultV1 {
29
30
  deployless: this.client.options.supportDeployless,
30
31
  });
31
32
  }
32
- deposit({ amount = 0n, userAddress, accrualVault, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
33
+ deposit({ amount = 0n, userAddress, vaultData, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, nativeAmount, }) {
33
34
  if (this.client.viemClient.chain?.id !== this.chainId) {
34
35
  throw new index_js_3.ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
35
36
  }
36
- if (!(0, viem_1.isAddressEqual)(accrualVault.address, this.vault)) {
37
- throw new index_js_3.VaultAddressMismatchError(this.vault, accrualVault.address);
37
+ if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
38
+ throw new index_js_3.VaultAddressMismatchError(this.vault, vaultData.address);
38
39
  }
39
40
  if (amount < 0n) {
40
41
  throw new index_js_3.NonPositiveAssetAmountError(this.vault);
@@ -56,19 +57,19 @@ class MorphoVaultV1 {
56
57
  throw new index_js_3.ExcessiveSlippageToleranceError(slippageTolerance);
57
58
  }
58
59
  if (nativeAmount && wNative) {
59
- if (!(0, viem_1.isAddressEqual)(accrualVault.asset, wNative)) {
60
- throw new index_js_3.NativeAmountOnNonWNativeVaultError(accrualVault.asset, wNative);
60
+ if (!(0, viem_1.isAddressEqual)(vaultData.asset, wNative)) {
61
+ throw new index_js_3.NativeAmountOnNonWNativeVaultError(vaultData.asset, wNative);
61
62
  }
62
63
  }
63
64
  const totalAssets = amount + (nativeAmount ?? 0n);
64
- const shares = accrualVault.toShares(totalAssets);
65
+ const shares = vaultData.toShares(totalAssets);
65
66
  if (shares <= 0n) {
66
67
  throw new index_js_3.NonPositiveSharesAmountError(this.vault);
67
68
  }
68
69
  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
70
  return {
70
71
  getRequirements: async (params) => await (0, index_js_1.getRequirements)(this.client.viemClient, {
71
- address: accrualVault.asset,
72
+ address: vaultData.asset,
72
73
  chainId: this.chainId,
73
74
  supportSignature: this.client.options.supportSignature,
74
75
  supportDeployless: this.client.options.supportDeployless,
@@ -82,7 +83,7 @@ class MorphoVaultV1 {
82
83
  vault: {
83
84
  chainId: this.chainId,
84
85
  address: this.vault,
85
- asset: accrualVault.asset,
86
+ asset: vaultData.asset,
86
87
  },
87
88
  args: {
88
89
  amount,
@@ -129,7 +130,6 @@ class MorphoVaultV1 {
129
130
  }
130
131
  migrateToV2({ userAddress, sourceVault, targetVault, shares, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, }) {
131
132
  (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
133
  if (!(0, viem_1.isAddressEqual)(sourceVault.address, this.vault)) {
134
134
  throw new index_js_3.VaultAddressMismatchError(this.vault, sourceVault.address);
135
135
  }
@@ -148,8 +148,11 @@ class MorphoVaultV1 {
148
148
  // Compute minSharePriceVaultV1 for V1 redeem (slippage downward)
149
149
  const v1RefAssets = sourceVault.toAssets(shares);
150
150
  const minSharePriceVaultV1 = blue_sdk_1.MathLib.mulDivDown(v1RefAssets, blue_sdk_1.MathLib.wToRay(blue_sdk_1.MathLib.WAD - slippageTolerance), shares);
151
- // Compute maxSharePriceVaultV2 for V2 deposit (slippage upward)
152
- const v2RefShares = targetVault.toShares(v1RefAssets);
151
+ // Compute maxSharePriceVaultV2 for V2 deposit (slippage upward).
152
+ // Accrue VaultV2 interest forward to bound the on-chain share price at execution.
153
+ const targetAccrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), targetVault.lastUpdate) + morpho_ts_1.Time.s.from.h(2n);
154
+ const { vault: accruedTargetVault } = targetVault.accrueInterest(targetAccrualTimestamp);
155
+ const v2RefShares = accruedTargetVault.toShares(v1RefAssets);
153
156
  if (v2RefShares <= 0n) {
154
157
  throw new index_js_3.NonPositiveSharesAmountError(targetVault.address);
155
158
  }
@@ -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?: {
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MorphoVaultV2 = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
7
  const viem_1 = require("viem");
7
8
  const index_js_1 = require("../../actions/index.js");
8
9
  const constant_js_1 = require("../../helpers/constant.js");
@@ -28,12 +29,12 @@ class MorphoVaultV2 {
28
29
  deployless: this.client.options.supportDeployless,
29
30
  });
30
31
  }
31
- 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, }) {
32
33
  if (this.client.viemClient.chain?.id !== this.chainId) {
33
34
  throw new index_js_2.ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
34
35
  }
35
- if (!(0, viem_1.isAddressEqual)(accrualVault.address, this.vault)) {
36
- throw new index_js_2.VaultAddressMismatchError(this.vault, accrualVault.address);
36
+ if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
37
+ throw new index_js_2.VaultAddressMismatchError(this.vault, vaultData.address);
37
38
  }
38
39
  if (amount < 0n) {
39
40
  throw new index_js_2.NonPositiveAssetAmountError(this.vault);
@@ -55,19 +56,23 @@ class MorphoVaultV2 {
55
56
  throw new index_js_2.ExcessiveSlippageToleranceError(slippageTolerance);
56
57
  }
57
58
  if (nativeAmount && wNative) {
58
- if (!(0, viem_1.isAddressEqual)(accrualVault.asset, wNative)) {
59
- throw new index_js_2.NativeAmountOnNonWNativeVaultError(accrualVault.asset, wNative);
59
+ if (!(0, viem_1.isAddressEqual)(vaultData.asset, wNative)) {
60
+ throw new index_js_2.NativeAmountOnNonWNativeVaultError(vaultData.asset, wNative);
60
61
  }
61
62
  }
62
63
  const totalAssets = amount + (nativeAmount ?? 0n);
63
- const shares = accrualVault.toShares(totalAssets);
64
+ // Accrue interest forward to bound the on-chain share price at execution.
65
+ // Mirrors marketV1 repay's 2h forward-accrual buffer.
66
+ const accrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), vaultData.lastUpdate) + morpho_ts_1.Time.s.from.h(2n);
67
+ const { vault: accruedVault } = vaultData.accrueInterest(accrualTimestamp);
68
+ const shares = accruedVault.toShares(totalAssets);
64
69
  if (shares <= 0n) {
65
70
  throw new index_js_2.NonPositiveSharesAmountError(this.vault);
66
71
  }
67
72
  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
73
  return {
69
74
  getRequirements: async (params) => await (0, index_js_1.getRequirements)(this.client.viemClient, {
70
- address: accrualVault.asset,
75
+ address: vaultData.asset,
71
76
  chainId: this.chainId,
72
77
  supportSignature: this.client.options.supportSignature,
73
78
  supportDeployless: this.client.options.supportDeployless,
@@ -81,7 +86,7 @@ class MorphoVaultV2 {
81
86
  vault: {
82
87
  chainId: this.chainId,
83
88
  address: this.vault,
84
- asset: accrualVault.asset,
89
+ asset: vaultData.asset,
85
90
  },
86
91
  args: {
87
92
  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)
@@ -9,6 +9,16 @@ import type { Metadata } from "../types/index.js";
9
9
  * The function ensures that the transaction data is correctly formatted
10
10
  * and includes optional metadata elements if provided.
11
11
  *
12
+ * `metadata.origin` accepts either a raw hex string (`"cafe"`) or a
13
+ * 0x-prefixed hex string (`"0xcafe"` / `"0Xcafe"`); both produce the same
14
+ * appended 4-byte origin tag. The 0x/0X prefix is stripped case-insensitively
15
+ * before length-validation, so an origin of `"0xdeadbeef"` (10 chars
16
+ * including prefix, 8 raw hex chars) is accepted while `"0xdeadbeef00"`
17
+ * (10 raw hex chars) is rejected and a warning is logged. Odd-length raw
18
+ * fragments (e.g. `"abc"`, `"0xabc"`) are also rejected — concatenating
19
+ * a non-byte-aligned fragment would corrupt the trailing analytics byte
20
+ * once viem's `concatHex` pads it to a whole byte at broadcast time.
21
+ *
12
22
  * @param {Object} tx - The original transaction object.
13
23
  * @param {Hex} tx.data - The existing hex-encoded data for the transaction.
14
24
  * @param {bigint} tx.value - The value to be sent with the transaction.
@@ -12,6 +12,16 @@ const viem_1 = require("viem");
12
12
  * The function ensures that the transaction data is correctly formatted
13
13
  * and includes optional metadata elements if provided.
14
14
  *
15
+ * `metadata.origin` accepts either a raw hex string (`"cafe"`) or a
16
+ * 0x-prefixed hex string (`"0xcafe"` / `"0Xcafe"`); both produce the same
17
+ * appended 4-byte origin tag. The 0x/0X prefix is stripped case-insensitively
18
+ * before length-validation, so an origin of `"0xdeadbeef"` (10 chars
19
+ * including prefix, 8 raw hex chars) is accepted while `"0xdeadbeef00"`
20
+ * (10 raw hex chars) is rejected and a warning is logged. Odd-length raw
21
+ * fragments (e.g. `"abc"`, `"0xabc"`) are also rejected — concatenating
22
+ * a non-byte-aligned fragment would corrupt the trailing analytics byte
23
+ * once viem's `concatHex` pads it to a whole byte at broadcast time.
24
+ *
15
25
  * @param {Object} tx - The original transaction object.
16
26
  * @param {Hex} tx.data - The existing hex-encoded data for the transaction.
17
27
  * @param {bigint} tx.value - The value to be sent with the transaction.
@@ -34,11 +44,20 @@ function addTransactionMetadata(tx, metadata) {
34
44
  concatItems.push((0, viem_1.numberToHex)(morpho_ts_1.Time.timestamp(), { size: 4 }));
35
45
  }
36
46
  try {
37
- const origin = metadata.origin.replace(/^(?!0x)/, "");
47
+ // Strip a leading "0x" / "0X" case-insensitively so callers can pass
48
+ // "cafe", "0xcafe", or "0Xcafe" — all produce the same 4-byte appended
49
+ // origin. The case-insensitive form prevents "0Xcafe" from falling
50
+ // through to `isHex("0x0Xcafe")` and being silently dropped.
51
+ const origin = metadata.origin.replace(/^0x/i, "");
38
52
  if (!(0, viem_1.isHex)(`0x${origin}`))
39
53
  throw Error("Calldata origin must consists of only hex characters");
40
54
  if (origin.length > 8)
41
55
  throw Error("Calldata origin must be at most 8 characters long");
56
+ // Reject odd-length raw fragments. viem's `concatHex` would pad the
57
+ // stray nibble to a whole byte at broadcast, corrupting the trailing
58
+ // analytics byte on-chain.
59
+ if (origin.length % 2 !== 0)
60
+ throw Error("Calldata origin must have an even number of hex characters");
42
61
  concatItems.push(`0x${origin}`);
43
62
  }
44
63
  catch (error) {
@@ -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 {
@@ -51,6 +52,10 @@ export declare class DepositAmountMismatchError extends Error {
51
52
  export declare class DepositAssetMismatchError extends Error {
52
53
  constructor(depositAsset: Address, signatureAsset: Address);
53
54
  }
55
+ /** Thrown when a `permit2` requirement signature is missing the `expiration` field. */
56
+ export declare class Permit2ExpirationMissingError extends Error {
57
+ constructor();
58
+ }
54
59
  /** Thrown when a vault deposit uses `nativeAmount` but the vault asset is not the chain's wNative. */
55
60
  export declare class NativeAmountOnNonWNativeVaultError extends Error {
56
61
  constructor(vaultAsset: Address, wNative: Address);
@@ -191,6 +196,25 @@ export declare class RepaySharesExceedDebtError extends Error {
191
196
  export declare class MissingPublicAllocatorConfigError extends Error {
192
197
  constructor(vault: string);
193
198
  }
199
+ /**
200
+ * Thrown when shared liquidity selected by `computeReallocations` cannot cover
201
+ * the absolute borrow shortfall on the target market — the resulting
202
+ * `morphoBorrow` would still revert onchain.
203
+ *
204
+ * Pattern-match on the class and inspect `params` to surface the gap to users.
205
+ */
206
+ export declare class InsufficientSharedLiquidityError extends Error {
207
+ readonly params: {
208
+ readonly marketId: MarketId;
209
+ readonly shortfall: bigint;
210
+ readonly available: bigint;
211
+ };
212
+ constructor(params: {
213
+ readonly marketId: MarketId;
214
+ readonly shortfall: bigint;
215
+ readonly available: bigint;
216
+ });
217
+ }
194
218
  /** Thrown when a market borrow's `minSharePrice` slippage bound is negative. */
195
219
  export declare class NonPositiveMinBorrowSharePriceError extends Error {
196
220
  constructor(market: string);