@morpho-org/morpho-sdk 5.0.0 → 5.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 (51) hide show
  1. package/README.md +4 -4
  2. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +47 -0
  3. package/lib/cjs/actions/blue/buildAssetFundingActions.js +63 -0
  4. package/lib/cjs/actions/blue/repay.d.ts +39 -39
  5. package/lib/cjs/actions/blue/repay.js +65 -46
  6. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +37 -37
  7. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +64 -41
  8. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +69 -0
  9. package/lib/cjs/actions/blue/resolveRepayFunding.js +82 -0
  10. package/lib/cjs/actions/blue/supply.d.ts +1 -1
  11. package/lib/cjs/actions/blue/supply.js +8 -22
  12. package/lib/cjs/actions/blue/supplyCollateral.d.ts +1 -1
  13. package/lib/cjs/actions/blue/supplyCollateral.js +8 -22
  14. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +1 -1
  15. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +8 -21
  16. package/lib/cjs/entities/blue/blue.js +161 -87
  17. package/lib/cjs/helpers/index.d.ts +1 -1
  18. package/lib/cjs/helpers/index.js +1 -2
  19. package/lib/cjs/helpers/validate.d.ts +0 -18
  20. package/lib/cjs/helpers/validate.js +1 -38
  21. package/lib/cjs/types/action.d.ts +51 -3
  22. package/lib/cjs/types/error.d.ts +24 -2
  23. package/lib/cjs/types/error.js +26 -5
  24. package/lib/cjs/utils.d.ts +1 -1
  25. package/lib/cjs/utils.js +2 -3
  26. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +47 -0
  27. package/lib/esm/actions/blue/buildAssetFundingActions.js +59 -0
  28. package/lib/esm/actions/blue/repay.d.ts +39 -39
  29. package/lib/esm/actions/blue/repay.js +66 -47
  30. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +37 -37
  31. package/lib/esm/actions/blue/repayWithdrawCollateral.js +65 -42
  32. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +69 -0
  33. package/lib/esm/actions/blue/resolveRepayFunding.js +78 -0
  34. package/lib/esm/actions/blue/supply.d.ts +1 -1
  35. package/lib/esm/actions/blue/supply.js +9 -23
  36. package/lib/esm/actions/blue/supplyCollateral.d.ts +1 -1
  37. package/lib/esm/actions/blue/supplyCollateral.js +9 -23
  38. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +1 -1
  39. package/lib/esm/actions/blue/supplyCollateralBorrow.js +9 -22
  40. package/lib/esm/entities/blue/blue.js +162 -88
  41. package/lib/esm/helpers/index.d.ts +1 -1
  42. package/lib/esm/helpers/index.js +1 -1
  43. package/lib/esm/helpers/validate.d.ts +0 -18
  44. package/lib/esm/helpers/validate.js +1 -37
  45. package/lib/esm/types/action.d.ts +51 -3
  46. package/lib/esm/types/error.d.ts +24 -2
  47. package/lib/esm/types/error.js +23 -3
  48. package/lib/esm/utils.d.ts +1 -1
  49. package/lib/esm/utils.js +1 -1
  50. package/package.json +19 -18
  51. package/src/index.ts +0 -4
@@ -6,4 +6,4 @@ export { bigIntComparator, createGetValue, createHasValue, deepFreeze, entries,
6
6
  export { computeReallocations } from "./helpers/computeReallocations.js";
7
7
  export { addTransactionMetadata } from "./helpers/metadata.js";
8
8
  export { computeMaxRepaySharePrice, computeMinBorrowSharePrice, } from "./helpers/slippage.js";
9
- export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayParams, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";
9
+ export { validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, } from "./helpers/validate.js";
package/lib/cjs/utils.js CHANGED
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateRepayParams = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.computeReallocations = exports.values = exports.transformValue = exports.Time = exports.retryPromiseLinearBackoff = exports.mergeEntries = exports.keys = exports.isNotUndefined = exports.isNotNull = exports.isDefined = exports.hasValue = exports.getValue = exports.getSubdomainBaseUrl = exports.getLastDefined = exports.getLast = exports.fromEntries = exports.filterDefined = exports.entries = exports.deepFreeze = exports.createHasValue = exports.createGetValue = exports.bigIntComparator = exports.safeParseUnits = exports.safeParseNumber = exports.safeGetAddress = exports.restructure = exports.readContractRestructured = exports.optionalBoolean = exports.getPermitTypedData = exports.getPermit2TransferFromTypedData = exports.getPermit2PermitTypedData = exports.getAuthorizationTypedData = exports.decodeBytes32String = exports.VaultUtils = exports.SharesMath = exports.MathLib = exports.MarketUtils = exports.CapacityLimitReason = exports.AdaptiveCurveIrmLib = void 0;
4
- exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = void 0;
3
+ exports.validateRepayShares = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinBorrowSharePrice = exports.computeMaxRepaySharePrice = exports.addTransactionMetadata = exports.computeReallocations = exports.values = exports.transformValue = exports.Time = exports.retryPromiseLinearBackoff = exports.mergeEntries = exports.keys = exports.isNotUndefined = exports.isNotNull = exports.isDefined = exports.hasValue = exports.getValue = exports.getSubdomainBaseUrl = exports.getLastDefined = exports.getLast = exports.fromEntries = exports.filterDefined = exports.entries = exports.deepFreeze = exports.createHasValue = exports.createGetValue = exports.bigIntComparator = exports.safeParseUnits = exports.safeParseNumber = exports.safeGetAddress = exports.restructure = exports.readContractRestructured = exports.optionalBoolean = exports.getPermitTypedData = exports.getPermit2TransferFromTypedData = exports.getPermit2PermitTypedData = exports.getAuthorizationTypedData = exports.decodeBytes32String = exports.VaultUtils = exports.SharesMath = exports.MathLib = exports.MarketUtils = exports.CapacityLimitReason = exports.AdaptiveCurveIrmLib = void 0;
4
+ exports.validateUserAddress = exports.validateSlippageTolerance = void 0;
5
5
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  Object.defineProperty(exports, "AdaptiveCurveIrmLib", { enumerable: true, get: function () { return blue_sdk_1.AdaptiveCurveIrmLib; } });
7
7
  Object.defineProperty(exports, "CapacityLimitReason", { enumerable: true, get: function () { return blue_sdk_1.CapacityLimitReason; } });
@@ -58,7 +58,6 @@ Object.defineProperty(exports, "validatePositionHealth", { enumerable: true, get
58
58
  Object.defineProperty(exports, "validatePositionHealthAfterWithdraw", { enumerable: true, get: function () { return validate_js_1.validatePositionHealthAfterWithdraw; } });
59
59
  Object.defineProperty(exports, "validateReallocations", { enumerable: true, get: function () { return validate_js_1.validateReallocations; } });
60
60
  Object.defineProperty(exports, "validateRepayAmount", { enumerable: true, get: function () { return validate_js_1.validateRepayAmount; } });
61
- Object.defineProperty(exports, "validateRepayParams", { enumerable: true, get: function () { return validate_js_1.validateRepayParams; } });
62
61
  Object.defineProperty(exports, "validateRepayShares", { enumerable: true, get: function () { return validate_js_1.validateRepayShares; } });
63
62
  Object.defineProperty(exports, "validateSlippageTolerance", { enumerable: true, get: function () { return validate_js_1.validateSlippageTolerance; } });
64
63
  Object.defineProperty(exports, "validateUserAddress", { enumerable: true, get: function () { return validate_js_1.validateUserAddress; } });
@@ -0,0 +1,47 @@
1
+ import type { Address } from "viem";
2
+ import type { Action } from "../../bundler/index.js";
3
+ import type { PermitRequirementSignature } from "../../types/index.js";
4
+ /** Parameters for {@link buildAssetFundingActions}. */
5
+ export interface BuildAssetFundingActionsParams {
6
+ /** Chain the operation runs on — resolves adapter addresses and validates wNative. */
7
+ readonly chainId: number;
8
+ /** Asset wrapped and/or pulled into `GeneralAdapter1` (loan token, collateral token, …). */
9
+ readonly asset: Address;
10
+ /** ERC-20 amount of `asset` to pull from the payer (`0n` on a fully-native funding). */
11
+ readonly erc20Amount: bigint;
12
+ /** Native ETH to wrap into wNative before the pull (`0n` when not wrapping). */
13
+ readonly nativeAmount: bigint;
14
+ /** Optional pre-signed permit/permit2 approval for the ERC-20 pull. */
15
+ readonly requirementSignature?: PermitRequirementSignature;
16
+ }
17
+ /**
18
+ * Builds the shared asset-funding actions — native wrapping followed by the ERC-20 pull — that move
19
+ * `asset` into `GeneralAdapter1` before a bundled Morpho operation (`blueSupply`,
20
+ * `blueSupplyCollateral`, `blueSupplyCollateralBorrow`, `blueRepay`, `blueRepayWithdrawCollateral`).
21
+ *
22
+ * Encode-only and synchronous: returns a fresh `Action[]` (never mutates its inputs, mirroring
23
+ * `buildReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
24
+ * `asset` is the chain's wNative and emits `nativeTransfer → wrapNative`. When `erc20Amount > 0n`,
25
+ * pulls the ERC-20 via a signed permit/permit2 (`requirementSignature`) or a plain
26
+ * `erc20TransferFrom` — `getTokenRequirementActions` emits the latter itself when no signature is
27
+ * supplied. A fully-native funding emits no ERC-20 action; funding nothing returns `[]`.
28
+ *
29
+ * Single source of truth for the native-wrap + ERC-20-pull composition every bundled Blue funding
30
+ * path depends on — a fix here applies to all of them instead of risking a silent divergence
31
+ * between copies.
32
+ *
33
+ * @param params - See {@link BuildAssetFundingActionsParams}.
34
+ * @returns The `nativeTransfer`/`wrapNative`/pull actions, in bundle order (empty when nothing is
35
+ * funded).
36
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
37
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but `asset` is not the
38
+ * chain's wNative.
39
+ * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature` is
40
+ * provided and the signed asset differs from `asset`.
41
+ * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature` is
42
+ * provided and the signed amount differs from `erc20Amount`.
43
+ * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
44
+ * signature is missing its expiration.
45
+ * @internal
46
+ */
47
+ export declare const buildAssetFundingActions: ({ chainId, asset, erc20Amount, nativeAmount, requirementSignature, }: BuildAssetFundingActionsParams) => Action[];
@@ -0,0 +1,59 @@
1
+ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
+ import { validateNativeAsset } from "../../helpers/index.js";
3
+ import { getTokenRequirementActions } from "../signatures/getTokenRequirementActions.js";
4
+ /**
5
+ * Builds the shared asset-funding actions — native wrapping followed by the ERC-20 pull — that move
6
+ * `asset` into `GeneralAdapter1` before a bundled Morpho operation (`blueSupply`,
7
+ * `blueSupplyCollateral`, `blueSupplyCollateralBorrow`, `blueRepay`, `blueRepayWithdrawCollateral`).
8
+ *
9
+ * Encode-only and synchronous: returns a fresh `Action[]` (never mutates its inputs, mirroring
10
+ * `buildReallocationActions`) and reads no on-chain state. When `nativeAmount > 0n`, validates
11
+ * `asset` is the chain's wNative and emits `nativeTransfer → wrapNative`. When `erc20Amount > 0n`,
12
+ * pulls the ERC-20 via a signed permit/permit2 (`requirementSignature`) or a plain
13
+ * `erc20TransferFrom` — `getTokenRequirementActions` emits the latter itself when no signature is
14
+ * supplied. A fully-native funding emits no ERC-20 action; funding nothing returns `[]`.
15
+ *
16
+ * Single source of truth for the native-wrap + ERC-20-pull composition every bundled Blue funding
17
+ * path depends on — a fix here applies to all of them instead of risking a silent divergence
18
+ * between copies.
19
+ *
20
+ * @param params - See {@link BuildAssetFundingActionsParams}.
21
+ * @returns The `nativeTransfer`/`wrapNative`/pull actions, in bundle order (empty when nothing is
22
+ * funded).
23
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
24
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but `asset` is not the
25
+ * chain's wNative.
26
+ * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature` is
27
+ * provided and the signed asset differs from `asset`.
28
+ * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature` is
29
+ * provided and the signed amount differs from `erc20Amount`.
30
+ * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
31
+ * signature is missing its expiration.
32
+ * @internal
33
+ */
34
+ export const buildAssetFundingActions = ({ chainId, asset, erc20Amount, nativeAmount, requirementSignature, }) => {
35
+ const { bundler3: { generalAdapter1, bundler3 }, } = getChainAddresses(chainId);
36
+ const actions = [];
37
+ // Wrap native into wNative before pulling the ERC-20 remainder.
38
+ if (nativeAmount > 0n) {
39
+ validateNativeAsset(chainId, asset);
40
+ actions.push({
41
+ type: "nativeTransfer",
42
+ args: [bundler3, generalAdapter1, nativeAmount, false],
43
+ }, {
44
+ type: "wrapNative",
45
+ args: [nativeAmount, generalAdapter1, false],
46
+ });
47
+ }
48
+ // Pull the ERC-20 portion (0 on a fully native funding). getTokenRequirementActions emits a plain
49
+ // erc20TransferFrom itself when no permit/permit2 signature is supplied.
50
+ if (erc20Amount > 0n) {
51
+ actions.push(...getTokenRequirementActions({
52
+ asset,
53
+ amount: erc20Amount,
54
+ recipient: generalAdapter1,
55
+ requirementSignature,
56
+ }));
57
+ }
58
+ return actions;
59
+ };
@@ -1,23 +1,13 @@
1
1
  import { type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
- import type { BlueRepayAction, Metadata, PermitRequirementSignature, Transaction } from "../../types/index.js";
3
+ import type { BlueRepayAction, Metadata, PermitRequirementSignature, RepayActionAmountArgs, Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueRepay}. */
5
5
  export interface BlueRepayParams {
6
6
  market: {
7
7
  readonly chainId: number;
8
8
  readonly marketParams: MarketParams;
9
9
  };
10
- args: {
11
- /** Repay assets amount (0n when repaying by shares). */
12
- assets: bigint;
13
- /** Repay shares amount (0n when repaying by assets). */
14
- shares: bigint;
15
- /**
16
- * ERC-20 amount to pull into `GeneralAdapter1`. In assets mode, must equal `assets`
17
- * exactly (`TransferAmountNotEqualToAssetsError` fires otherwise). In shares mode, an
18
- * upper-bound estimate to absorb share-price drift; residual is skimmed back to `receiver`.
19
- */
20
- transferAmount: bigint;
10
+ args: RepayActionAmountArgs & {
21
11
  /** Address whose debt is being repaid. */
22
12
  onBehalf: Address;
23
13
  /** Receives residual loan tokens in shares mode. */
@@ -32,24 +22,28 @@ export interface BlueRepayParams {
32
22
  /**
33
23
  * Prepares a repay transaction for a Morpho Blue market.
34
24
  *
35
- * Routed through bundler3 via `GeneralAdapter1`. Supports two modes:
25
+ * Routed through bundler3 via `GeneralAdapter1`. All amount arithmetic is done upstream (see
26
+ * `MorphoBlue.repay`); this builder just assembles the bundle from the pre-resolved
27
+ * {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional native wrapping
28
+ * (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()` before the
29
+ * repay; the loan token must be the chain's wNative):
36
30
  *
37
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
38
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with
39
- * `transferAmount` set to an upper-bound asset estimate; residual loan tokens are skimmed back
40
- * to `receiver` after the call.
31
+ * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
32
+ * additive like `blueSupply`), pulling `amount` ERC-20 and wrapping `nativeAmount`. No residual.
33
+ * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
34
+ * ERC-20 (already net of native) and wrapping `nativeAmount`. Residual loan tokens are skimmed
35
+ * back to `receiver` after the call.
41
36
  *
42
- * Exactly one of `assets` / `shares` must be non-zero. Uses `maxSharePrice` to protect against
43
- * share price manipulation between transaction construction and execution.
37
+ * Uses `maxSharePrice` to protect against share price manipulation between construction and execution.
44
38
  *
45
39
  * @param params.market.chainId - The chain the market lives on.
46
40
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
47
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
48
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
49
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
50
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
51
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
52
- * tokens are skimmed back to `receiver`.
41
+ * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
42
+ * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
43
+ * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
44
+ * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
45
+ * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
46
+ * Requires the loan token to be the chain's wNative.
53
47
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
54
48
  * @param params.args.receiver - Address that receives residual loan tokens in shares mode.
55
49
  * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
@@ -57,36 +51,42 @@ export interface BlueRepayParams {
57
51
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
58
52
  * loan-token transfer.
59
53
  * @param params.metadata - Optional analytics metadata attached to the bundle.
60
- * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value`, `data`, and the
61
- * typed `action` discriminator the simulation layer consumes.
54
+ * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value` (= `nativeAmount`),
55
+ * `data`, and the typed `action` discriminator the simulation layer consumes.
62
56
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
63
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
64
- * both are zero.
65
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
66
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
67
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
57
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
58
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
59
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
60
+ * `transferAmount !== amount + nativeAmount`.
61
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
62
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
63
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
64
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
65
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
66
+ * the chain's wNative.
68
67
  * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
69
68
  * is provided and the signed asset differs from `marketParams.loanToken`.
70
69
  * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
71
- * is provided and the signed amount differs from `args.transferAmount`.
70
+ * is provided and the signed amount differs from the ERC-20 amount pulled.
72
71
  * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
73
72
  * signature is missing its expiration.
74
73
  * @example
75
74
  * ```ts
76
75
  * import { blueRepay } from "@morpho-org/morpho-sdk";
77
76
  *
77
+ * // Repay 0.5 loan-asset units, 0.2 of them funded by wrapping native ETH.
78
78
  * const tx = blueRepay({
79
- * market: { chainId: 1, marketParams },
79
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
80
80
  * args: {
81
- * assets: 500_000_000n,
82
- * shares: 0n,
83
- * transferAmount: 500_000_000n,
81
+ * amount: 300_000_000_000_000_000n, // ERC-20 part
82
+ * nativeAmount: 200_000_000_000_000_000n, // wrapped ETH part
83
+ * transferAmount: 500_000_000_000_000_000n, // total repaid = amount + nativeAmount
84
84
  * onBehalf: borrower,
85
85
  * receiver: borrower,
86
86
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
87
87
  * },
88
88
  * });
89
- * // tx satisfies Readonly<Transaction<BlueRepayAction>>
89
+ * // tx.value === 200_000_000_000_000_000n
90
90
  * ```
91
91
  */
92
- export declare const blueRepay: ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }: BlueRepayParams) => Readonly<Transaction<BlueRepayAction>>;
92
+ export declare const blueRepay: ({ market: { chainId, marketParams }, args, metadata, }: BlueRepayParams) => Readonly<Transaction<BlueRepayAction>>;
@@ -2,29 +2,34 @@ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
2
  import { deepFreeze } from "@morpho-org/morpho-ts";
3
3
  import { maxUint256 } from "viem";
4
4
  import { BundlerAction } from "../../bundler/index.js";
5
- import { addTransactionMetadata, validateRepayParams, } from "../../helpers/index.js";
6
- import { getTokenRequirementActions } from "../signatures/getTokenRequirementActions.js";
5
+ import { addTransactionMetadata } from "../../helpers/index.js";
6
+ import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
7
+ import { resolveRepayFunding } from "./resolveRepayFunding.js";
7
8
  /**
8
9
  * Prepares a repay transaction for a Morpho Blue market.
9
10
  *
10
- * Routed through bundler3 via `GeneralAdapter1`. Supports two modes:
11
+ * Routed through bundler3 via `GeneralAdapter1`. All amount arithmetic is done upstream (see
12
+ * `MorphoBlue.repay`); this builder just assembles the bundle from the pre-resolved
13
+ * {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional native wrapping
14
+ * (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()` before the
15
+ * repay; the loan token must be the chain's wNative):
11
16
  *
12
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
13
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with
14
- * `transferAmount` set to an upper-bound asset estimate; residual loan tokens are skimmed back
15
- * to `receiver` after the call.
17
+ * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
18
+ * additive like `blueSupply`), pulling `amount` ERC-20 and wrapping `nativeAmount`. No residual.
19
+ * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
20
+ * ERC-20 (already net of native) and wrapping `nativeAmount`. Residual loan tokens are skimmed
21
+ * back to `receiver` after the call.
16
22
  *
17
- * Exactly one of `assets` / `shares` must be non-zero. Uses `maxSharePrice` to protect against
18
- * share price manipulation between transaction construction and execution.
23
+ * Uses `maxSharePrice` to protect against share price manipulation between construction and execution.
19
24
  *
20
25
  * @param params.market.chainId - The chain the market lives on.
21
26
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
22
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
23
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
24
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
25
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
26
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
27
- * tokens are skimmed back to `receiver`.
27
+ * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
28
+ * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
29
+ * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
30
+ * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
31
+ * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
32
+ * Requires the loan token to be the chain's wNative.
28
33
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
29
34
  * @param params.args.receiver - Address that receives residual loan tokens in shares mode.
30
35
  * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
@@ -32,62 +37,71 @@ import { getTokenRequirementActions } from "../signatures/getTokenRequirementAct
32
37
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
33
38
  * loan-token transfer.
34
39
  * @param params.metadata - Optional analytics metadata attached to the bundle.
35
- * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value`, `data`, and the
36
- * typed `action` discriminator the simulation layer consumes.
40
+ * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value` (= `nativeAmount`),
41
+ * `data`, and the typed `action` discriminator the simulation layer consumes.
37
42
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
38
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
39
- * both are zero.
40
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
41
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
42
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
43
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
44
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
45
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
46
+ * `transferAmount !== amount + nativeAmount`.
47
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
48
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
49
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
50
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
51
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
52
+ * the chain's wNative.
43
53
  * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
44
54
  * is provided and the signed asset differs from `marketParams.loanToken`.
45
55
  * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
46
- * is provided and the signed amount differs from `args.transferAmount`.
56
+ * is provided and the signed amount differs from the ERC-20 amount pulled.
47
57
  * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
48
58
  * signature is missing its expiration.
49
59
  * @example
50
60
  * ```ts
51
61
  * import { blueRepay } from "@morpho-org/morpho-sdk";
52
62
  *
63
+ * // Repay 0.5 loan-asset units, 0.2 of them funded by wrapping native ETH.
53
64
  * const tx = blueRepay({
54
- * market: { chainId: 1, marketParams },
65
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
55
66
  * args: {
56
- * assets: 500_000_000n,
57
- * shares: 0n,
58
- * transferAmount: 500_000_000n,
67
+ * amount: 300_000_000_000_000_000n, // ERC-20 part
68
+ * nativeAmount: 200_000_000_000_000_000n, // wrapped ETH part
69
+ * transferAmount: 500_000_000_000_000_000n, // total repaid = amount + nativeAmount
59
70
  * onBehalf: borrower,
60
71
  * receiver: borrower,
61
72
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
62
73
  * },
63
74
  * });
64
- * // tx satisfies Readonly<Transaction<BlueRepayAction>>
75
+ * // tx.value === 200_000_000_000_000_000n
65
76
  * ```
66
77
  */
67
- export const blueRepay = ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }) => {
68
- validateRepayParams({
69
- assets,
70
- shares,
71
- transferAmount,
72
- maxSharePrice,
73
- marketId: marketParams.id,
74
- });
78
+ export const blueRepay = ({ market: { chainId, marketParams }, args, metadata, }) => {
79
+ const { amount = 0n, shares = 0n, nativeAmount = 0n, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, } = args;
80
+ const { isSharesMode, repayAssets, repayShares, erc20Amount } = resolveRepayFunding({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
75
81
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
76
- const actions = [];
77
- actions.push(...getTokenRequirementActions({
82
+ const actions = buildAssetFundingActions({
83
+ chainId,
78
84
  asset: marketParams.loanToken,
79
- amount: transferAmount,
80
- recipient: generalAdapter1,
85
+ erc20Amount,
86
+ nativeAmount,
81
87
  requirementSignature,
82
- }));
88
+ });
83
89
  actions.push({
84
90
  type: "morphoRepay",
85
- args: [marketParams, assets, shares, maxSharePrice, onBehalf, [], false],
91
+ args: [
92
+ marketParams,
93
+ repayAssets,
94
+ repayShares,
95
+ maxSharePrice,
96
+ onBehalf,
97
+ [],
98
+ false,
99
+ ],
86
100
  });
87
101
  // Skim residual loan tokens back to the payer when repaying by shares.
88
102
  // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
89
103
  // consumes only the exact amount needed, leaving a residual in the adapter.
90
- if (shares > 0n) {
104
+ if (isSharesMode) {
91
105
  actions.push({
92
106
  type: "erc20Transfer",
93
107
  args: [
@@ -99,7 +113,10 @@ export const blueRepay = ({ market: { chainId, marketParams }, args: { assets, s
99
113
  ],
100
114
  });
101
115
  }
102
- let tx = BundlerAction.encodeBundle(chainId, actions);
116
+ let tx = {
117
+ ...BundlerAction.encodeBundle(chainId, actions),
118
+ value: nativeAmount,
119
+ };
103
120
  if (metadata) {
104
121
  tx = addTransactionMetadata(tx, metadata);
105
122
  }
@@ -109,12 +126,14 @@ export const blueRepay = ({ market: { chainId, marketParams }, args: { assets, s
109
126
  type: "blueRepay",
110
127
  args: {
111
128
  market: marketParams.id,
112
- assets,
113
- shares,
114
- transferAmount,
129
+ assets: repayAssets,
130
+ shares: repayShares,
131
+ // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
132
+ transferAmount: erc20Amount + nativeAmount,
115
133
  onBehalf,
116
134
  receiver,
117
135
  maxSharePrice,
136
+ nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
118
137
  },
119
138
  },
120
139
  });
@@ -1,24 +1,13 @@
1
1
  import { type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
- import { type AuthorizationRequirementSignature, type BlueRepayWithdrawCollateralAction, type Metadata, type PermitRequirementSignature, type Transaction } from "../../types/index.js";
3
+ import { type AuthorizationRequirementSignature, type BlueRepayWithdrawCollateralAction, type Metadata, type PermitRequirementSignature, type RepayActionAmountArgs, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueRepayWithdrawCollateral}. */
5
5
  export interface BlueRepayWithdrawCollateralParams {
6
6
  market: {
7
7
  readonly chainId: number;
8
8
  readonly marketParams: MarketParams;
9
9
  };
10
- args: {
11
- /** Repay assets amount (0n when repaying by shares). */
12
- assets: bigint;
13
- /** Repay shares amount (0n when repaying by assets). */
14
- shares: bigint;
15
- /**
16
- * ERC-20 amount to pull into `GeneralAdapter1`. In assets mode, must equal `assets`
17
- * exactly (`TransferAmountNotEqualToAssetsError` fires otherwise). In shares mode, an
18
- * upper-bound estimate to absorb share-price drift; residual loan tokens are skimmed
19
- * back to `receiver`.
20
- */
21
- transferAmount: bigint;
10
+ args: RepayActionAmountArgs & {
22
11
  /** Amount of collateral to withdraw. */
23
12
  withdrawAmount: bigint;
24
13
  /** Address whose debt is being repaid. */
@@ -48,23 +37,29 @@ export interface BlueRepayWithdrawCollateralParams {
48
37
  * 3. `morphoWithdrawCollateral` — then withdraws collateral.
49
38
  *
50
39
  * If the order were reversed, Morpho would revert because the position would be insolvent at the
51
- * time of the withdraw. Supports two repay modes:
40
+ * time of the withdraw. All amount arithmetic is done upstream (see
41
+ * `MorphoBlue.repayWithdrawCollateral`); this builder just assembles the bundle from the
42
+ * pre-resolved {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional
43
+ * native wrapping (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()`
44
+ * before the repay; the loan token must be the chain's wNative):
52
45
  *
53
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
54
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with residual
55
- * loan tokens skimmed back to `receiver`.
46
+ * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
47
+ * additive like `blueSupply`), pulling `amount` ERC-20.
48
+ * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
49
+ * ERC-20 (already net of native); residual loan tokens are skimmed back to `receiver`.
56
50
  *
57
51
  * Prerequisites: ERC-20 approval for the loan token to `GeneralAdapter1` (for the repay) **and**
58
- * `GeneralAdapter1` must be authorized on Morpho (for the withdraw).
52
+ * `GeneralAdapter1` must be authorized on Morpho (for the withdraw). Passing an
53
+ * `authorizationSignature` prepends the authorization in-bundle instead.
59
54
  *
60
55
  * @param params.market.chainId - The chain the market lives on.
61
56
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
62
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
63
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
64
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
65
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
66
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
67
- * tokens are skimmed back to `receiver`.
57
+ * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
58
+ * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
59
+ * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
60
+ * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
61
+ * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
62
+ * Requires the loan token to be the chain's wNative.
68
63
  * @param params.args.withdrawAmount - Amount of collateral to withdraw after the repay leg
69
64
  * completes.
70
65
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
@@ -78,18 +73,23 @@ export interface BlueRepayWithdrawCollateralParams {
78
73
  * a `setAuthorizationWithSig` call is prepended to the bundle.
79
74
  * @param params.metadata - Optional analytics metadata attached to the bundle.
80
75
  * @returns A deep-frozen `Transaction<BlueRepayWithdrawCollateralAction>` with `to`,
81
- * `value`, `data`, and the typed `action` discriminator the simulation layer consumes.
76
+ * `value` (= `nativeAmount`), `data`, and the typed `action` discriminator the simulation layer consumes.
82
77
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
83
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
84
- * both are zero.
85
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
86
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
87
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
78
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
79
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
80
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
81
+ * `transferAmount !== amount + nativeAmount`.
82
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
83
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
84
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
88
85
  * @throws {NonPositiveWithdrawCollateralAmountError} when `withdrawAmount <= 0n`.
86
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
87
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
88
+ * the chain's wNative.
89
89
  * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
90
90
  * is provided and the signed asset differs from `marketParams.loanToken`.
91
91
  * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
92
- * is provided and the signed amount differs from `args.transferAmount`.
92
+ * is provided and the signed amount differs from the ERC-20 amount pulled.
93
93
  * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
94
94
  * signature is missing its expiration.
95
95
  * @example
@@ -97,18 +97,18 @@ export interface BlueRepayWithdrawCollateralParams {
97
97
  * import { blueRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
98
98
  *
99
99
  * const tx = blueRepayWithdrawCollateral({
100
- * market: { chainId: 1, marketParams },
100
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
101
101
  * args: {
102
- * assets: 500_000_000n,
103
- * shares: 0n,
104
- * transferAmount: 500_000_000n,
102
+ * shares: 500_000_000_000_000_000_000_000n,
103
+ * transferAmount: 310_000_000_000_000_000n, // ERC-20 pulled (net of native)
104
+ * nativeAmount: 200_000_000_000_000_000n, // 0.2 funded by wrapping native ETH
105
105
  * withdrawAmount: 1_000_000_000_000_000_000n,
106
106
  * onBehalf: borrower,
107
107
  * receiver: borrower,
108
108
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
109
109
  * },
110
110
  * });
111
- * // tx satisfies Readonly<Transaction<BlueRepayWithdrawCollateralAction>>
111
+ * // tx.value === 200_000_000_000_000_000n
112
112
  * ```
113
113
  */
114
- export declare const blueRepayWithdrawCollateral: ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, authorizationSignature, }, metadata, }: BlueRepayWithdrawCollateralParams) => Readonly<Transaction<BlueRepayWithdrawCollateralAction>>;
114
+ export declare const blueRepayWithdrawCollateral: ({ market: { chainId, marketParams }, args, metadata, }: BlueRepayWithdrawCollateralParams) => Readonly<Transaction<BlueRepayWithdrawCollateralAction>>;