@morpho-org/morpho-sdk 2.0.0 → 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.
@@ -17,8 +17,7 @@ interface GetRequirementsActionParams {
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
19
19
  * `amount` exactly, otherwise the function throws so the caller does not silently spend a
20
- * wider-than-expected approval. Internal helper — consumed only by the action builders that
21
- * accept a `requirementSignature`; not re-exported on the public surface.
20
+ * wider-than-expected approval.
22
21
  *
23
22
  * @param params.asset - The ERC-20 to pull.
24
23
  * @param params.amount - The amount to pull, in the asset's smallest unit.
@@ -27,7 +26,32 @@ interface GetRequirementsActionParams {
27
26
  * @returns A pair of bundler `Action`s: a permit / approve2 followed by the transfer.
28
27
  * @throws {DepositAssetMismatchError} when the signed asset differs from `asset`.
29
28
  * @throws {DepositAmountMismatchError} when the signed amount differs from `amount`.
30
- * @internal
29
+ * @throws {Permit2ExpirationMissingError} when `action.type === "permit2"` but `args.expiration` is missing.
30
+ * @example
31
+ * ```ts
32
+ * import { createWalletClient, http } from "viem";
33
+ * import { mainnet } from "viem/chains";
34
+ * import { getRequirementsAction } from "@morpho-org/morpho-sdk";
35
+ *
36
+ * const walletClient = createWalletClient({
37
+ * chain: mainnet,
38
+ * transport: http(),
39
+ * account: borrower,
40
+ * });
41
+ *
42
+ * // `requirement` comes from `getRequirements*` helpers; signing produces a `RequirementSignature`.
43
+ * const requirementSignature = await requirement.sign(walletClient, borrower);
44
+ *
45
+ * const actions = getRequirementsAction({
46
+ * asset: loanToken,
47
+ * amount: 1_000_000n,
48
+ * recipient: generalAdapter1,
49
+ * requirementSignature,
50
+ * });
51
+ * // actions satisfies Action[]
52
+ * // - permit2 path: [{ type: "approve2", ... }, { type: "transferFrom2", ... }]
53
+ * // - classic permit path: [{ type: "permit", ... }, { type: "erc20TransferFrom", ... }]
54
+ * ```
31
55
  */
32
56
  export declare const getRequirementsAction: ({ asset, amount, recipient, requirementSignature, }: GetRequirementsActionParams) => Action[];
33
57
  export {};
@@ -10,8 +10,7 @@ const index_js_1 = require("../../types/index.js");
10
10
  * Permit2 path emits `approve2` + `transferFrom2`; classic permit path emits `permit` +
11
11
  * `erc20TransferFrom`. The signed `asset` and `amount` must match the pulled `asset` and
12
12
  * `amount` exactly, otherwise the function throws so the caller does not silently spend a
13
- * wider-than-expected approval. Internal helper — consumed only by the action builders that
14
- * accept a `requirementSignature`; not re-exported on the public surface.
13
+ * wider-than-expected approval.
15
14
  *
16
15
  * @param params.asset - The ERC-20 to pull.
17
16
  * @param params.amount - The amount to pull, in the asset's smallest unit.
@@ -20,7 +19,32 @@ const index_js_1 = require("../../types/index.js");
20
19
  * @returns A pair of bundler `Action`s: a permit / approve2 followed by the transfer.
21
20
  * @throws {DepositAssetMismatchError} when the signed asset differs from `asset`.
22
21
  * @throws {DepositAmountMismatchError} when the signed amount differs from `amount`.
23
- * @internal
22
+ * @throws {Permit2ExpirationMissingError} when `action.type === "permit2"` but `args.expiration` is missing.
23
+ * @example
24
+ * ```ts
25
+ * import { createWalletClient, http } from "viem";
26
+ * import { mainnet } from "viem/chains";
27
+ * import { getRequirementsAction } from "@morpho-org/morpho-sdk";
28
+ *
29
+ * const walletClient = createWalletClient({
30
+ * chain: mainnet,
31
+ * transport: http(),
32
+ * account: borrower,
33
+ * });
34
+ *
35
+ * // `requirement` comes from `getRequirements*` helpers; signing produces a `RequirementSignature`.
36
+ * const requirementSignature = await requirement.sign(walletClient, borrower);
37
+ *
38
+ * const actions = getRequirementsAction({
39
+ * asset: loanToken,
40
+ * amount: 1_000_000n,
41
+ * recipient: generalAdapter1,
42
+ * requirementSignature,
43
+ * });
44
+ * // actions satisfies Action[]
45
+ * // - permit2 path: [{ type: "approve2", ... }, { type: "transferFrom2", ... }]
46
+ * // - classic permit path: [{ type: "permit", ... }, { type: "erc20TransferFrom", ... }]
47
+ * ```
24
48
  */
25
49
  const getRequirementsAction = ({ asset, amount, recipient, requirementSignature, }) => {
26
50
  if (!(0, viem_1.isAddressEqual)(requirementSignature.args.asset, asset)) {
@@ -31,7 +55,7 @@ const getRequirementsAction = ({ asset, amount, recipient, requirementSignature,
31
55
  }
32
56
  if (requirementSignature.action.type === "permit2") {
33
57
  if (!("expiration" in requirementSignature.args)) {
34
- throw new Error("Expiration is not defined");
58
+ throw new index_js_1.Permit2ExpirationMissingError();
35
59
  }
36
60
  return [
37
61
  {
@@ -1,6 +1,7 @@
1
1
  export * from "./encode/index.js";
2
2
  export * from "./getMorphoAuthorizationRequirement.js";
3
3
  export * from "./getRequirements.js";
4
+ export * from "./getRequirementsAction.js";
4
5
  export * from "./getRequirementsApproval.js";
5
6
  export * from "./getRequirementsPermit.js";
6
7
  export * from "./getRequirementsPermit2.js";
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./encode/index.js"), exports);
18
18
  __exportStar(require("./getMorphoAuthorizationRequirement.js"), exports);
19
19
  __exportStar(require("./getRequirements.js"), exports);
20
+ __exportStar(require("./getRequirementsAction.js"), exports);
20
21
  __exportStar(require("./getRequirementsApproval.js"), exports);
21
22
  __exportStar(require("./getRequirementsPermit.js"), exports);
22
23
  __exportStar(require("./getRequirementsPermit2.js"), exports);
@@ -152,6 +152,7 @@ class MorphoMarketV1 {
152
152
  let assets;
153
153
  let shares;
154
154
  let transferAmount;
155
+ let marketForRepay;
155
156
  if (isSharesMode) {
156
157
  (0, index_js_2.validateRepayShares)({
157
158
  positionData,
@@ -160,10 +161,12 @@ class MorphoMarketV1 {
160
161
  });
161
162
  assets = 0n;
162
163
  shares = params.shares;
163
- // Add slippage buffer to cover interest accrued between tx construction and execution.
164
- // Without this, the on-chain repay amount may exceed the pre-transferred ERC20 amount.
165
- const baseTransferAmount = positionData.market.toBorrowAssets(shares, "Up");
166
- 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");
167
170
  }
168
171
  else {
169
172
  (0, index_js_2.validateRepayAmount)({
@@ -174,11 +177,12 @@ class MorphoMarketV1 {
174
177
  assets = params.assets;
175
178
  shares = 0n;
176
179
  transferAmount = params.assets;
180
+ marketForRepay = positionData.market;
177
181
  }
178
182
  const maxSharePrice = (0, index_js_2.computeMaxRepaySharePrice)({
179
183
  repayAssets: assets,
180
184
  repayShares: shares,
181
- market: positionData.market,
185
+ market: marketForRepay,
182
186
  slippageTolerance,
183
187
  });
184
188
  return {
@@ -281,6 +285,11 @@ class MorphoMarketV1 {
281
285
  let assets;
282
286
  let shares;
283
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);
284
293
  if (isSharesMode) {
285
294
  (0, index_js_2.validateRepayShares)({
286
295
  positionData,
@@ -289,8 +298,8 @@ class MorphoMarketV1 {
289
298
  });
290
299
  assets = 0n;
291
300
  shares = params.shares;
292
- const baseTransferAmount = positionData.market.toBorrowAssets(shares, "Up");
293
- 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");
294
303
  }
295
304
  else {
296
305
  (0, index_js_2.validateRepayAmount)({
@@ -301,6 +310,7 @@ class MorphoMarketV1 {
301
310
  assets = params.assets;
302
311
  shares = 0n;
303
312
  transferAmount = params.assets;
313
+ marketForRepay = positionData.market;
304
314
  }
305
315
  if (withdrawAmount > positionData.collateral) {
306
316
  throw new index_js_3.WithdrawExceedsCollateralError({
@@ -309,9 +319,6 @@ class MorphoMarketV1 {
309
319
  market: positionData.marketId,
310
320
  });
311
321
  }
312
- // +10 min accrual buffer: residual debt grows between build and execute.
313
- const accrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), positionData.market.lastUpdate) +
314
- morpho_ts_1.Time.s.from.min(10n);
315
322
  const { position: positionAfterRepay } = positionData.repay(assets, shares, accrualTimestamp);
316
323
  (0, index_js_2.validatePositionHealthAfterWithdraw)({
317
324
  positionData: positionAfterRepay,
@@ -322,7 +329,7 @@ class MorphoMarketV1 {
322
329
  const maxSharePrice = (0, index_js_2.computeMaxRepaySharePrice)({
323
330
  repayAssets: assets,
324
331
  repayShares: shares,
325
- market: positionData.market,
332
+ market: marketForRepay,
326
333
  slippageTolerance,
327
334
  });
328
335
  return {
@@ -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");
@@ -147,8 +148,11 @@ class MorphoVaultV1 {
147
148
  // Compute minSharePriceVaultV1 for V1 redeem (slippage downward)
148
149
  const v1RefAssets = sourceVault.toAssets(shares);
149
150
  const minSharePriceVaultV1 = blue_sdk_1.MathLib.mulDivDown(v1RefAssets, blue_sdk_1.MathLib.wToRay(blue_sdk_1.MathLib.WAD - slippageTolerance), shares);
150
- // Compute maxSharePriceVaultV2 for V2 deposit (slippage upward)
151
- 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);
152
156
  if (v2RefShares <= 0n) {
153
157
  throw new index_js_3.NonPositiveSharesAmountError(targetVault.address);
154
158
  }
@@ -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");
@@ -60,7 +61,11 @@ class MorphoVaultV2 {
60
61
  }
61
62
  }
62
63
  const totalAssets = amount + (nativeAmount ?? 0n);
63
- const shares = vaultData.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
  }
@@ -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) {
@@ -52,6 +52,10 @@ export declare class DepositAmountMismatchError extends Error {
52
52
  export declare class DepositAssetMismatchError extends Error {
53
53
  constructor(depositAsset: Address, signatureAsset: Address);
54
54
  }
55
+ /** Thrown when a `permit2` requirement signature is missing the `expiration` field. */
56
+ export declare class Permit2ExpirationMissingError extends Error {
57
+ constructor();
58
+ }
55
59
  /** Thrown when a vault deposit uses `nativeAmount` but the vault asset is not the chain's wNative. */
56
60
  export declare class NativeAmountOnNonWNativeVaultError extends Error {
57
61
  constructor(vaultAsset: Address, wNative: Address);
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
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;
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.Permit2ExpirationMissingError = 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) {
@@ -92,6 +92,13 @@ class DepositAssetMismatchError extends Error {
92
92
  }
93
93
  }
94
94
  exports.DepositAssetMismatchError = DepositAssetMismatchError;
95
+ /** Thrown when a `permit2` requirement signature is missing the `expiration` field. */
96
+ class Permit2ExpirationMissingError extends Error {
97
+ constructor() {
98
+ super('Requirement signature with action.type === "permit2" must include args.expiration. Re-sign using the permit2 flow.');
99
+ }
100
+ }
101
+ exports.Permit2ExpirationMissingError = Permit2ExpirationMissingError;
95
102
  /** Thrown when a vault deposit uses `nativeAmount` but the vault asset is not the chain's wNative. */
96
103
  class NativeAmountOnNonWNativeVaultError extends Error {
97
104
  constructor(vaultAsset, wNative) {
@@ -17,8 +17,7 @@ interface GetRequirementsActionParams {
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
19
19
  * `amount` exactly, otherwise the function throws so the caller does not silently spend a
20
- * wider-than-expected approval. Internal helper — consumed only by the action builders that
21
- * accept a `requirementSignature`; not re-exported on the public surface.
20
+ * wider-than-expected approval.
22
21
  *
23
22
  * @param params.asset - The ERC-20 to pull.
24
23
  * @param params.amount - The amount to pull, in the asset's smallest unit.
@@ -27,7 +26,32 @@ interface GetRequirementsActionParams {
27
26
  * @returns A pair of bundler `Action`s: a permit / approve2 followed by the transfer.
28
27
  * @throws {DepositAssetMismatchError} when the signed asset differs from `asset`.
29
28
  * @throws {DepositAmountMismatchError} when the signed amount differs from `amount`.
30
- * @internal
29
+ * @throws {Permit2ExpirationMissingError} when `action.type === "permit2"` but `args.expiration` is missing.
30
+ * @example
31
+ * ```ts
32
+ * import { createWalletClient, http } from "viem";
33
+ * import { mainnet } from "viem/chains";
34
+ * import { getRequirementsAction } from "@morpho-org/morpho-sdk";
35
+ *
36
+ * const walletClient = createWalletClient({
37
+ * chain: mainnet,
38
+ * transport: http(),
39
+ * account: borrower,
40
+ * });
41
+ *
42
+ * // `requirement` comes from `getRequirements*` helpers; signing produces a `RequirementSignature`.
43
+ * const requirementSignature = await requirement.sign(walletClient, borrower);
44
+ *
45
+ * const actions = getRequirementsAction({
46
+ * asset: loanToken,
47
+ * amount: 1_000_000n,
48
+ * recipient: generalAdapter1,
49
+ * requirementSignature,
50
+ * });
51
+ * // actions satisfies Action[]
52
+ * // - permit2 path: [{ type: "approve2", ... }, { type: "transferFrom2", ... }]
53
+ * // - classic permit path: [{ type: "permit", ... }, { type: "erc20TransferFrom", ... }]
54
+ * ```
31
55
  */
32
56
  export declare const getRequirementsAction: ({ asset, amount, recipient, requirementSignature, }: GetRequirementsActionParams) => Action[];
33
57
  export {};
@@ -1,5 +1,5 @@
1
1
  import { isAddressEqual } from "viem";
2
- import { DepositAmountMismatchError, DepositAssetMismatchError, } from "../../types/index.js";
2
+ import { DepositAmountMismatchError, DepositAssetMismatchError, Permit2ExpirationMissingError, } from "../../types/index.js";
3
3
  /**
4
4
  * Encodes the bundler actions that consume a pre-signed permit / permit2 requirement and pull
5
5
  * the asset to `recipient`.
@@ -7,8 +7,7 @@ import { DepositAmountMismatchError, DepositAssetMismatchError, } from "../../ty
7
7
  * Permit2 path emits `approve2` + `transferFrom2`; classic permit path emits `permit` +
8
8
  * `erc20TransferFrom`. The signed `asset` and `amount` must match the pulled `asset` and
9
9
  * `amount` exactly, otherwise the function throws so the caller does not silently spend a
10
- * wider-than-expected approval. Internal helper — consumed only by the action builders that
11
- * accept a `requirementSignature`; not re-exported on the public surface.
10
+ * wider-than-expected approval.
12
11
  *
13
12
  * @param params.asset - The ERC-20 to pull.
14
13
  * @param params.amount - The amount to pull, in the asset's smallest unit.
@@ -17,7 +16,32 @@ import { DepositAmountMismatchError, DepositAssetMismatchError, } from "../../ty
17
16
  * @returns A pair of bundler `Action`s: a permit / approve2 followed by the transfer.
18
17
  * @throws {DepositAssetMismatchError} when the signed asset differs from `asset`.
19
18
  * @throws {DepositAmountMismatchError} when the signed amount differs from `amount`.
20
- * @internal
19
+ * @throws {Permit2ExpirationMissingError} when `action.type === "permit2"` but `args.expiration` is missing.
20
+ * @example
21
+ * ```ts
22
+ * import { createWalletClient, http } from "viem";
23
+ * import { mainnet } from "viem/chains";
24
+ * import { getRequirementsAction } from "@morpho-org/morpho-sdk";
25
+ *
26
+ * const walletClient = createWalletClient({
27
+ * chain: mainnet,
28
+ * transport: http(),
29
+ * account: borrower,
30
+ * });
31
+ *
32
+ * // `requirement` comes from `getRequirements*` helpers; signing produces a `RequirementSignature`.
33
+ * const requirementSignature = await requirement.sign(walletClient, borrower);
34
+ *
35
+ * const actions = getRequirementsAction({
36
+ * asset: loanToken,
37
+ * amount: 1_000_000n,
38
+ * recipient: generalAdapter1,
39
+ * requirementSignature,
40
+ * });
41
+ * // actions satisfies Action[]
42
+ * // - permit2 path: [{ type: "approve2", ... }, { type: "transferFrom2", ... }]
43
+ * // - classic permit path: [{ type: "permit", ... }, { type: "erc20TransferFrom", ... }]
44
+ * ```
21
45
  */
22
46
  export const getRequirementsAction = ({ asset, amount, recipient, requirementSignature, }) => {
23
47
  if (!isAddressEqual(requirementSignature.args.asset, asset)) {
@@ -28,7 +52,7 @@ export const getRequirementsAction = ({ asset, amount, recipient, requirementSig
28
52
  }
29
53
  if (requirementSignature.action.type === "permit2") {
30
54
  if (!("expiration" in requirementSignature.args)) {
31
- throw new Error("Expiration is not defined");
55
+ throw new Permit2ExpirationMissingError();
32
56
  }
33
57
  return [
34
58
  {
@@ -1,6 +1,7 @@
1
1
  export * from "./encode/index.js";
2
2
  export * from "./getMorphoAuthorizationRequirement.js";
3
3
  export * from "./getRequirements.js";
4
+ export * from "./getRequirementsAction.js";
4
5
  export * from "./getRequirementsApproval.js";
5
6
  export * from "./getRequirementsPermit.js";
6
7
  export * from "./getRequirementsPermit2.js";
@@ -1,6 +1,7 @@
1
1
  export * from "./encode/index.js";
2
2
  export * from "./getMorphoAuthorizationRequirement.js";
3
3
  export * from "./getRequirements.js";
4
+ export * from "./getRequirementsAction.js";
4
5
  export * from "./getRequirementsApproval.js";
5
6
  export * from "./getRequirementsPermit.js";
6
7
  export * from "./getRequirementsPermit2.js";
@@ -149,6 +149,7 @@ export class MorphoMarketV1 {
149
149
  let assets;
150
150
  let shares;
151
151
  let transferAmount;
152
+ let marketForRepay;
152
153
  if (isSharesMode) {
153
154
  validateRepayShares({
154
155
  positionData,
@@ -157,10 +158,12 @@ export class MorphoMarketV1 {
157
158
  });
158
159
  assets = 0n;
159
160
  shares = params.shares;
160
- // Add slippage buffer to cover interest accrued between tx construction and execution.
161
- // Without this, the on-chain repay amount may exceed the pre-transferred ERC20 amount.
162
- const baseTransferAmount = positionData.market.toBorrowAssets(shares, "Up");
163
- transferAmount = MathLib.wMulUp(baseTransferAmount, MathLib.WAD + slippageTolerance);
161
+ // 2h forward accrual upper-bounds the on-chain repay price; bundle
162
+ // skims residual back to the receiver.
163
+ const accrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
164
+ Time.s.from.h(2n);
165
+ marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
166
+ transferAmount = marketForRepay.toBorrowAssets(shares, "Up");
164
167
  }
165
168
  else {
166
169
  validateRepayAmount({
@@ -171,11 +174,12 @@ export class MorphoMarketV1 {
171
174
  assets = params.assets;
172
175
  shares = 0n;
173
176
  transferAmount = params.assets;
177
+ marketForRepay = positionData.market;
174
178
  }
175
179
  const maxSharePrice = computeMaxRepaySharePrice({
176
180
  repayAssets: assets,
177
181
  repayShares: shares,
178
- market: positionData.market,
182
+ market: marketForRepay,
179
183
  slippageTolerance,
180
184
  });
181
185
  return {
@@ -278,6 +282,11 @@ export class MorphoMarketV1 {
278
282
  let assets;
279
283
  let shares;
280
284
  let transferAmount;
285
+ let marketForRepay;
286
+ // 2h forward accrual upper-bounds the on-chain repay price (shares
287
+ // mode) and the post-repay health check; bundle skims residual back.
288
+ const accrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
289
+ Time.s.from.h(2n);
281
290
  if (isSharesMode) {
282
291
  validateRepayShares({
283
292
  positionData,
@@ -286,8 +295,8 @@ export class MorphoMarketV1 {
286
295
  });
287
296
  assets = 0n;
288
297
  shares = params.shares;
289
- const baseTransferAmount = positionData.market.toBorrowAssets(shares, "Up");
290
- transferAmount = MathLib.wMulUp(baseTransferAmount, MathLib.WAD + slippageTolerance);
298
+ marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
299
+ transferAmount = marketForRepay.toBorrowAssets(shares, "Up");
291
300
  }
292
301
  else {
293
302
  validateRepayAmount({
@@ -298,6 +307,7 @@ export class MorphoMarketV1 {
298
307
  assets = params.assets;
299
308
  shares = 0n;
300
309
  transferAmount = params.assets;
310
+ marketForRepay = positionData.market;
301
311
  }
302
312
  if (withdrawAmount > positionData.collateral) {
303
313
  throw new WithdrawExceedsCollateralError({
@@ -306,9 +316,6 @@ export class MorphoMarketV1 {
306
316
  market: positionData.marketId,
307
317
  });
308
318
  }
309
- // +10 min accrual buffer: residual debt grows between build and execute.
310
- const accrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
311
- Time.s.from.min(10n);
312
319
  const { position: positionAfterRepay } = positionData.repay(assets, shares, accrualTimestamp);
313
320
  validatePositionHealthAfterWithdraw({
314
321
  positionData: positionAfterRepay,
@@ -319,7 +326,7 @@ export class MorphoMarketV1 {
319
326
  const maxSharePrice = computeMaxRepaySharePrice({
320
327
  repayAssets: assets,
321
328
  repayShares: shares,
322
- market: positionData.market,
329
+ market: marketForRepay,
323
330
  slippageTolerance,
324
331
  });
325
332
  return {
@@ -1,5 +1,6 @@
1
1
  import { DEFAULT_SLIPPAGE_TOLERANCE, getChainAddresses, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualVault } from "@morpho-org/blue-sdk-viem";
3
+ import { Time } from "@morpho-org/morpho-ts";
3
4
  import { isAddressEqual } from "viem";
4
5
  import { getRequirements, vaultV1Deposit, vaultV1MigrateToV2, vaultV1Redeem, vaultV1Withdraw, } from "../../actions/index.js";
5
6
  import { MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, } from "../../helpers/constant.js";
@@ -144,8 +145,11 @@ export class MorphoVaultV1 {
144
145
  // Compute minSharePriceVaultV1 for V1 redeem (slippage downward)
145
146
  const v1RefAssets = sourceVault.toAssets(shares);
146
147
  const minSharePriceVaultV1 = MathLib.mulDivDown(v1RefAssets, MathLib.wToRay(MathLib.WAD - slippageTolerance), shares);
147
- // Compute maxSharePriceVaultV2 for V2 deposit (slippage upward)
148
- const v2RefShares = targetVault.toShares(v1RefAssets);
148
+ // Compute maxSharePriceVaultV2 for V2 deposit (slippage upward).
149
+ // Accrue VaultV2 interest forward to bound the on-chain share price at execution.
150
+ const targetAccrualTimestamp = MathLib.max(Time.timestamp(), targetVault.lastUpdate) + Time.s.from.h(2n);
151
+ const { vault: accruedTargetVault } = targetVault.accrueInterest(targetAccrualTimestamp);
152
+ const v2RefShares = accruedTargetVault.toShares(v1RefAssets);
149
153
  if (v2RefShares <= 0n) {
150
154
  throw new NonPositiveSharesAmountError(targetVault.address);
151
155
  }
@@ -1,5 +1,6 @@
1
1
  import { DEFAULT_SLIPPAGE_TOLERANCE, getChainAddresses, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
+ import { Time } from "@morpho-org/morpho-ts";
3
4
  import { isAddressEqual } from "viem";
4
5
  import { getRequirements, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
5
6
  import { MAX_SLIPPAGE_TOLERANCE } from "../../helpers/constant.js";
@@ -57,7 +58,11 @@ export class MorphoVaultV2 {
57
58
  }
58
59
  }
59
60
  const totalAssets = amount + (nativeAmount ?? 0n);
60
- const shares = vaultData.toShares(totalAssets);
61
+ // Accrue interest forward to bound the on-chain share price at execution.
62
+ // Mirrors marketV1 repay's 2h forward-accrual buffer.
63
+ const accrualTimestamp = MathLib.max(Time.timestamp(), vaultData.lastUpdate) + Time.s.from.h(2n);
64
+ const { vault: accruedVault } = vaultData.accrueInterest(accrualTimestamp);
65
+ const shares = accruedVault.toShares(totalAssets);
61
66
  if (shares <= 0n) {
62
67
  throw new NonPositiveSharesAmountError(this.vault);
63
68
  }
@@ -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.
@@ -9,6 +9,16 @@ import { concatHex, isHex, numberToHex } from "viem";
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.
@@ -31,11 +41,20 @@ export function addTransactionMetadata(tx, metadata) {
31
41
  concatItems.push(numberToHex(Time.timestamp(), { size: 4 }));
32
42
  }
33
43
  try {
34
- const origin = metadata.origin.replace(/^(?!0x)/, "");
44
+ // Strip a leading "0x" / "0X" case-insensitively so callers can pass
45
+ // "cafe", "0xcafe", or "0Xcafe" — all produce the same 4-byte appended
46
+ // origin. The case-insensitive form prevents "0Xcafe" from falling
47
+ // through to `isHex("0x0Xcafe")` and being silently dropped.
48
+ const origin = metadata.origin.replace(/^0x/i, "");
35
49
  if (!isHex(`0x${origin}`))
36
50
  throw Error("Calldata origin must consists of only hex characters");
37
51
  if (origin.length > 8)
38
52
  throw Error("Calldata origin must be at most 8 characters long");
53
+ // Reject odd-length raw fragments. viem's `concatHex` would pad the
54
+ // stray nibble to a whole byte at broadcast, corrupting the trailing
55
+ // analytics byte on-chain.
56
+ if (origin.length % 2 !== 0)
57
+ throw Error("Calldata origin must have an even number of hex characters");
39
58
  concatItems.push(`0x${origin}`);
40
59
  }
41
60
  catch (error) {
@@ -52,6 +52,10 @@ export declare class DepositAmountMismatchError extends Error {
52
52
  export declare class DepositAssetMismatchError extends Error {
53
53
  constructor(depositAsset: Address, signatureAsset: Address);
54
54
  }
55
+ /** Thrown when a `permit2` requirement signature is missing the `expiration` field. */
56
+ export declare class Permit2ExpirationMissingError extends Error {
57
+ constructor();
58
+ }
55
59
  /** Thrown when a vault deposit uses `nativeAmount` but the vault asset is not the chain's wNative. */
56
60
  export declare class NativeAmountOnNonWNativeVaultError extends Error {
57
61
  constructor(vaultAsset: Address, wNative: Address);
@@ -76,6 +76,12 @@ export class DepositAssetMismatchError extends Error {
76
76
  super(`Deposit asset ${depositAsset} does not match requirement signature asset ${signatureAsset}`);
77
77
  }
78
78
  }
79
+ /** Thrown when a `permit2` requirement signature is missing the `expiration` field. */
80
+ export class Permit2ExpirationMissingError extends Error {
81
+ constructor() {
82
+ super('Requirement signature with action.type === "permit2" must include args.expiration. Re-sign using the permit2 flow.');
83
+ }
84
+ }
79
85
  /** Thrown when a vault deposit uses `nativeAmount` but the vault asset is not the chain's wNative. */
80
86
  export class NativeAmountOnNonWNativeVaultError extends Error {
81
87
  constructor(vaultAsset, wNative) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@morpho-org/morpho-sdk",
3
3
  "description": "Abstraction layer for Morpho's complexity.",
4
- "version": "2.0.0",
4
+ "version": "2.1.1",
5
5
  "author": "Morpho Association <contact@morpho.org>",
6
6
  "contributors": [
7
7
  "Foulks-Plb <https://x.com/FoulkPlb>"
@@ -20,11 +20,11 @@
20
20
  ],
21
21
  "dependencies": {
22
22
  "zod": "^4.4.3",
23
- "@morpho-org/blue-sdk": "^5.23.3",
24
- "@morpho-org/bundler-sdk-viem": "^4.3.3",
23
+ "@morpho-org/blue-sdk": "^6.0.0",
24
+ "@morpho-org/blue-sdk-viem": "^5.0.0",
25
+ "@morpho-org/bundler-sdk-viem": "^5.0.0",
25
26
  "@morpho-org/morpho-ts": "^2.5.1",
26
- "@morpho-org/simulation-sdk": "^3.4.4",
27
- "@morpho-org/blue-sdk-viem": "^4.6.6"
27
+ "@morpho-org/simulation-sdk": "^4.0.0"
28
28
  },
29
29
  "peerDependencies": {
30
30
  "viem": "^2.0.0"
@@ -34,7 +34,7 @@
34
34
  "typescript": "^6.0.3",
35
35
  "viem": "^2.49.3",
36
36
  "vitest": "^4.1.6",
37
- "@morpho-org/test": "^2.7.3"
37
+ "@morpho-org/test": "^2.8.0"
38
38
  },
39
39
  "scripts": {
40
40
  "prepublish": "$npm_execpath build",