@morpho-org/morpho-sdk 5.0.0 → 5.1.2

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 +20 -19
  51. package/src/index.ts +0 -4
@@ -2,10 +2,11 @@ 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";
5
+ import { addTransactionMetadata } from "../../helpers/index.js";
6
6
  import { NonPositiveWithdrawCollateralAmountError, } from "../../types/index.js";
7
7
  import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
8
- import { getTokenRequirementActions } from "../signatures/getTokenRequirementActions.js";
8
+ import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
9
+ import { resolveRepayFunding } from "./resolveRepayFunding.js";
9
10
  /**
10
11
  * Prepares an atomic repay-and-withdraw-collateral transaction for a Morpho Blue market.
11
12
  *
@@ -16,23 +17,29 @@ import { getTokenRequirementActions } from "../signatures/getTokenRequirementAct
16
17
  * 3. `morphoWithdrawCollateral` — then withdraws collateral.
17
18
  *
18
19
  * If the order were reversed, Morpho would revert because the position would be insolvent at the
19
- * time of the withdraw. Supports two repay modes:
20
+ * time of the withdraw. All amount arithmetic is done upstream (see
21
+ * `MorphoBlue.repayWithdrawCollateral`); this builder just assembles the bundle from the
22
+ * pre-resolved {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional
23
+ * native wrapping (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()`
24
+ * before the repay; the loan token must be the chain's wNative):
20
25
  *
21
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
22
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with residual
23
- * loan tokens skimmed back to `receiver`.
26
+ * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
27
+ * additive like `blueSupply`), pulling `amount` ERC-20.
28
+ * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
29
+ * ERC-20 (already net of native); residual loan tokens are skimmed back to `receiver`.
24
30
  *
25
31
  * Prerequisites: ERC-20 approval for the loan token to `GeneralAdapter1` (for the repay) **and**
26
- * `GeneralAdapter1` must be authorized on Morpho (for the withdraw).
32
+ * `GeneralAdapter1` must be authorized on Morpho (for the withdraw). Passing an
33
+ * `authorizationSignature` prepends the authorization in-bundle instead.
27
34
  *
28
35
  * @param params.market.chainId - The chain the market lives on.
29
36
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
30
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
31
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
32
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
33
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
34
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
35
- * tokens are skimmed back to `receiver`.
37
+ * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
38
+ * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
39
+ * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
40
+ * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
41
+ * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
42
+ * Requires the loan token to be the chain's wNative.
36
43
  * @param params.args.withdrawAmount - Amount of collateral to withdraw after the repay leg
37
44
  * completes.
38
45
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
@@ -46,18 +53,23 @@ import { getTokenRequirementActions } from "../signatures/getTokenRequirementAct
46
53
  * a `setAuthorizationWithSig` call is prepended to the bundle.
47
54
  * @param params.metadata - Optional analytics metadata attached to the bundle.
48
55
  * @returns A deep-frozen `Transaction<BlueRepayWithdrawCollateralAction>` with `to`,
49
- * `value`, `data`, and the typed `action` discriminator the simulation layer consumes.
56
+ * `value` (= `nativeAmount`), `data`, and the typed `action` discriminator the simulation layer consumes.
50
57
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
51
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
52
- * both are zero.
53
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
54
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
55
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
58
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
59
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
60
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
61
+ * `transferAmount !== amount + nativeAmount`.
62
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
63
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
64
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
56
65
  * @throws {NonPositiveWithdrawCollateralAmountError} when `withdrawAmount <= 0n`.
66
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
67
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
68
+ * the chain's wNative.
57
69
  * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
58
70
  * is provided and the signed asset differs from `marketParams.loanToken`.
59
71
  * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
60
- * is provided and the signed amount differs from `args.transferAmount`.
72
+ * is provided and the signed amount differs from the ERC-20 amount pulled.
61
73
  * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
62
74
  * signature is missing its expiration.
63
75
  * @example
@@ -65,51 +77,57 @@ import { getTokenRequirementActions } from "../signatures/getTokenRequirementAct
65
77
  * import { blueRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
66
78
  *
67
79
  * const tx = blueRepayWithdrawCollateral({
68
- * market: { chainId: 1, marketParams },
80
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
69
81
  * args: {
70
- * assets: 500_000_000n,
71
- * shares: 0n,
72
- * transferAmount: 500_000_000n,
82
+ * shares: 500_000_000_000_000_000_000_000n,
83
+ * transferAmount: 310_000_000_000_000_000n, // ERC-20 pulled (net of native)
84
+ * nativeAmount: 200_000_000_000_000_000n, // 0.2 funded by wrapping native ETH
73
85
  * withdrawAmount: 1_000_000_000_000_000_000n,
74
86
  * onBehalf: borrower,
75
87
  * receiver: borrower,
76
88
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
77
89
  * },
78
90
  * });
79
- * // tx satisfies Readonly<Transaction<BlueRepayWithdrawCollateralAction>>
91
+ * // tx.value === 200_000_000_000_000_000n
80
92
  * ```
81
93
  */
82
- export const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, authorizationSignature, }, metadata, }) => {
83
- validateRepayParams({
84
- assets,
85
- shares,
86
- transferAmount,
87
- maxSharePrice,
88
- marketId: marketParams.id,
89
- });
94
+ export const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args, metadata, }) => {
95
+ const { amount = 0n, shares = 0n, nativeAmount = 0n, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, authorizationSignature, } = args;
96
+ const { isSharesMode, repayAssets, repayShares, erc20Amount } = resolveRepayFunding({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
90
97
  if (withdrawAmount <= 0n) {
91
98
  throw new NonPositiveWithdrawCollateralAmountError(marketParams.id);
92
99
  }
93
100
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
94
101
  const actions = [];
102
+ // Authorize GeneralAdapter1 in-bundle when a signed authorization is supplied.
95
103
  if (authorizationSignature) {
96
104
  actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
97
105
  }
98
- actions.push(...getTokenRequirementActions({
106
+ // Fund the repay: wrap native (if any) then pull the ERC-20 remainder.
107
+ actions.push(...buildAssetFundingActions({
108
+ chainId,
99
109
  asset: marketParams.loanToken,
100
- amount: transferAmount,
101
- recipient: generalAdapter1,
110
+ erc20Amount,
111
+ nativeAmount,
102
112
  requirementSignature,
103
113
  }));
104
114
  // REPAY FIRST — reduces debt before withdrawing collateral
105
115
  actions.push({
106
116
  type: "morphoRepay",
107
- args: [marketParams, assets, shares, maxSharePrice, onBehalf, [], false],
117
+ args: [
118
+ marketParams,
119
+ repayAssets,
120
+ repayShares,
121
+ maxSharePrice,
122
+ onBehalf,
123
+ [],
124
+ false,
125
+ ],
108
126
  });
109
127
  // Skim residual loan tokens back to the payer when repaying by shares.
110
128
  // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
111
129
  // consumes only the exact amount needed, leaving a residual in the adapter.
112
- if (shares > 0n) {
130
+ if (isSharesMode) {
113
131
  actions.push({
114
132
  type: "erc20Transfer",
115
133
  args: [
@@ -125,7 +143,10 @@ export const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams },
125
143
  type: "morphoWithdrawCollateral",
126
144
  args: [marketParams, withdrawAmount, receiver, false],
127
145
  });
128
- let tx = BundlerAction.encodeBundle(chainId, actions);
146
+ let tx = {
147
+ ...BundlerAction.encodeBundle(chainId, actions),
148
+ value: nativeAmount,
149
+ };
129
150
  if (metadata) {
130
151
  tx = addTransactionMetadata(tx, metadata);
131
152
  }
@@ -135,13 +156,15 @@ export const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams },
135
156
  type: "blueRepayWithdrawCollateral",
136
157
  args: {
137
158
  market: marketParams.id,
138
- repayAssets: assets,
139
- repayShares: shares,
140
- transferAmount,
159
+ repayAssets,
160
+ repayShares,
161
+ // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
162
+ transferAmount: erc20Amount + nativeAmount,
141
163
  withdrawAmount,
142
164
  maxSharePrice,
143
165
  onBehalf,
144
166
  receiver,
167
+ nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
145
168
  },
146
169
  },
147
170
  });
@@ -0,0 +1,69 @@
1
+ import type { MarketId } from "@morpho-org/blue-sdk";
2
+ /**
3
+ * Pre-resolved repay amounts (plus `maxSharePrice`) validated by {@link resolveRepayFunding}.
4
+ *
5
+ * These are the fields the entity layer (`MorphoBlue.repay` / `repayWithdrawCollateral`) resolves
6
+ * from live market/position state before either repay builder assembles the bundle.
7
+ *
8
+ * @internal
9
+ */
10
+ export interface RepayFundingInput {
11
+ /** (assets mode) ERC-20 loan tokens pulled from the payer. */
12
+ readonly amount: bigint;
13
+ /** (shares mode) Borrow shares to repay. Discriminates the mode when `> 0n`. */
14
+ readonly shares: bigint;
15
+ /** Native ETH wrapped into wNative to help fund the repay. */
16
+ readonly nativeAmount: bigint;
17
+ /** Loan tokens routed into `GeneralAdapter1` (see `RepayActionAmountArgs`). */
18
+ readonly transferAmount: bigint;
19
+ /** Maximum acceptable repay share price (in ray). */
20
+ readonly maxSharePrice: bigint;
21
+ }
22
+ /**
23
+ * Derived repay funding values consumed by the repay builders.
24
+ *
25
+ * @internal
26
+ */
27
+ export interface RepayFunding {
28
+ /** `true` when repaying an exact share count (full close); `false` in assets mode. */
29
+ readonly isSharesMode: boolean;
30
+ /** Assets passed to `morphoRepay` (`transferAmount` in assets mode, `0n` in shares mode). */
31
+ readonly repayAssets: bigint;
32
+ /** Shares passed to `morphoRepay` (`shares` in shares mode, `0n` in assets mode). */
33
+ readonly repayShares: bigint;
34
+ /** ERC-20 loan tokens pulled into `GeneralAdapter1` (net of any wrapped native). */
35
+ readonly erc20Amount: bigint;
36
+ }
37
+ /**
38
+ * Resolves and validates the repay funding envelope shared by `blueRepay` and
39
+ * `blueRepayWithdrawCollateral`.
40
+ *
41
+ * Encode-only and synchronous — reads no on-chain state and does no amount arithmetic beyond
42
+ * deriving the bundle values from the pre-resolved args (the entity layer resolves the amounts
43
+ * upstream). Runs the shared mode/amount guards, discriminates assets vs shares mode on
44
+ * `shares > 0n`, then validates the funding so the assembled bundle neither strands over-pulled
45
+ * tokens nor under-funds the repay:
46
+ *
47
+ * - **assets mode** (`shares` `0n`): repays `transferAmount` (`= amount + nativeAmount`, additive
48
+ * like `blueSupply`); ERC-20 pulled = `amount`.
49
+ * - **shares mode** (`shares > 0n`): repays exact `shares`; ERC-20 pulled = `transferAmount` (already
50
+ * net of native).
51
+ *
52
+ * Single source of truth for the funding math both repay builders depend on — a correctness fix here
53
+ * applies to both paths instead of risking a silent divergence between two copies.
54
+ *
55
+ * @param input - The pre-resolved repay amounts plus the repay `maxSharePrice`.
56
+ * @param marketId - Market id used to tag the thrown errors.
57
+ * @returns `{ isSharesMode, repayAssets, repayShares, erc20Amount }` — the mode discriminator and the
58
+ * amounts the repay builders assemble the bundle from.
59
+ * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
60
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
61
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode and
62
+ * the repaid assets are `<= 0n`, or when in shares mode and `transferAmount` is negative or the total
63
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
64
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
65
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
66
+ * `transferAmount !== amount + nativeAmount`.
67
+ * @internal
68
+ */
69
+ export declare const resolveRepayFunding: ({ amount, shares, nativeAmount, transferAmount, maxSharePrice, }: RepayFundingInput, marketId: MarketId) => RepayFunding;
@@ -0,0 +1,78 @@
1
+ import { MutuallyExclusiveRepayAmountsError, NegativeNativeAmountError, NonPositiveRepayAmountError, NonPositiveRepayMaxSharePriceError, TransferAmountNotEqualToAssetsError, } from "../../types/index.js";
2
+ /**
3
+ * Resolves and validates the repay funding envelope shared by `blueRepay` and
4
+ * `blueRepayWithdrawCollateral`.
5
+ *
6
+ * Encode-only and synchronous — reads no on-chain state and does no amount arithmetic beyond
7
+ * deriving the bundle values from the pre-resolved args (the entity layer resolves the amounts
8
+ * upstream). Runs the shared mode/amount guards, discriminates assets vs shares mode on
9
+ * `shares > 0n`, then validates the funding so the assembled bundle neither strands over-pulled
10
+ * tokens nor under-funds the repay:
11
+ *
12
+ * - **assets mode** (`shares` `0n`): repays `transferAmount` (`= amount + nativeAmount`, additive
13
+ * like `blueSupply`); ERC-20 pulled = `amount`.
14
+ * - **shares mode** (`shares > 0n`): repays exact `shares`; ERC-20 pulled = `transferAmount` (already
15
+ * net of native).
16
+ *
17
+ * Single source of truth for the funding math both repay builders depend on — a correctness fix here
18
+ * applies to both paths instead of risking a silent divergence between two copies.
19
+ *
20
+ * @param input - The pre-resolved repay amounts plus the repay `maxSharePrice`.
21
+ * @param marketId - Market id used to tag the thrown errors.
22
+ * @returns `{ isSharesMode, repayAssets, repayShares, erc20Amount }` — the mode discriminator and the
23
+ * amounts the repay builders assemble the bundle from.
24
+ * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
25
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
26
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode and
27
+ * the repaid assets are `<= 0n`, or when in shares mode and `transferAmount` is negative or the total
28
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
29
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
30
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
31
+ * `transferAmount !== amount + nativeAmount`.
32
+ * @internal
33
+ */
34
+ export const resolveRepayFunding = ({ amount, shares, nativeAmount, transferAmount, maxSharePrice, }, marketId) => {
35
+ if (maxSharePrice <= 0n) {
36
+ throw new NonPositiveRepayMaxSharePriceError(marketId);
37
+ }
38
+ if (nativeAmount < 0n) {
39
+ throw new NegativeNativeAmountError(nativeAmount);
40
+ }
41
+ if (amount < 0n || shares < 0n) {
42
+ throw new NonPositiveRepayAmountError(marketId);
43
+ }
44
+ if (amount > 0n && shares > 0n) {
45
+ throw new MutuallyExclusiveRepayAmountsError(marketId);
46
+ }
47
+ // Shares mode repays an exact share count and pulls `transferAmount` ERC-20
48
+ // (already net of native), skimming the residual. Assets mode repays
49
+ // `transferAmount` (= amount + native, additive) and pulls `amount`.
50
+ const isSharesMode = shares > 0n;
51
+ const repayAssets = isSharesMode ? 0n : transferAmount;
52
+ const repayShares = shares;
53
+ const erc20Amount = isSharesMode ? transferAmount : amount;
54
+ // Validate the pre-resolved funding. Assets mode is additive like `blueSupply`:
55
+ // the ERC-20 pulled (`amount`) plus the wrapped `nativeAmount` must equal the
56
+ // assets repaid, and the total must be positive — so the adapter neither strands
57
+ // over-pulled tokens nor under-funds the repay. Shares mode pulls `transferAmount`
58
+ // ERC-20 (0 on a fully-native repay) and wraps `nativeAmount`; the bundle must
59
+ // fund the repay with a non-negative transfer and a positive total.
60
+ if (isSharesMode) {
61
+ if (transferAmount < 0n || transferAmount + nativeAmount <= 0n) {
62
+ throw new NonPositiveRepayAmountError(marketId);
63
+ }
64
+ }
65
+ else {
66
+ if (transferAmount !== amount + nativeAmount) {
67
+ throw new TransferAmountNotEqualToAssetsError({
68
+ transferAmount,
69
+ assets: amount + nativeAmount,
70
+ market: marketId,
71
+ });
72
+ }
73
+ if (repayAssets <= 0n) {
74
+ throw new NonPositiveRepayAmountError(marketId);
75
+ }
76
+ }
77
+ return { isSharesMode, repayAssets, repayShares, erc20Amount };
78
+ };
@@ -1,4 +1,4 @@
1
- import { type MarketParams } from "@morpho-org/blue-sdk";
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address } from "viem";
3
3
  import { type BlueSupplyAction, type DepositAmountArgs, type Metadata, type PermitRequirementSignature, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueSupply}. */
@@ -1,9 +1,8 @@
1
- import { getChainAddresses } from "@morpho-org/blue-sdk";
2
1
  import { deepFreeze } from "@morpho-org/morpho-ts";
3
2
  import { BundlerAction } from "../../bundler/index.js";
4
- import { addTransactionMetadata, validateNativeAsset, } from "../../helpers/index.js";
3
+ import { addTransactionMetadata } from "../../helpers/index.js";
5
4
  import { NegativeNativeAmountError, NegativeSupplyAmountError, NegativeSupplyMaxSharePriceError, ZeroSupplyAmountError, } from "../../types/index.js";
6
- import { getTokenRequirementActions } from "../signatures/getTokenRequirementActions.js";
5
+ import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
7
6
  /**
8
7
  * Prepares a loan-asset supply transaction for a Morpho Blue market.
9
8
  *
@@ -67,26 +66,13 @@ export const blueSupply = ({ market: { chainId, marketParams }, args: { amount =
67
66
  if (totalAssets === 0n) {
68
67
  throw new ZeroSupplyAmountError(marketParams.id);
69
68
  }
70
- const { bundler3: { generalAdapter1, bundler3 }, } = getChainAddresses(chainId);
71
- const actions = [];
72
- if (nativeAmount !== undefined && nativeAmount > 0n) {
73
- validateNativeAsset(chainId, marketParams.loanToken);
74
- actions.push({
75
- type: "nativeTransfer",
76
- args: [bundler3, generalAdapter1, nativeAmount, false],
77
- }, {
78
- type: "wrapNative",
79
- args: [nativeAmount, generalAdapter1, false],
80
- });
81
- }
82
- if (amount > 0n) {
83
- actions.push(...getTokenRequirementActions({
84
- asset: marketParams.loanToken,
85
- amount,
86
- recipient: generalAdapter1,
87
- requirementSignature,
88
- }));
89
- }
69
+ const actions = buildAssetFundingActions({
70
+ chainId,
71
+ asset: marketParams.loanToken,
72
+ erc20Amount: amount,
73
+ nativeAmount: nativeAmount ?? 0n,
74
+ requirementSignature,
75
+ });
90
76
  actions.push({
91
77
  type: "morphoSupply",
92
78
  args: [marketParams, totalAssets, 0n, maxSharePrice, onBehalf, [], false],
@@ -1,4 +1,4 @@
1
- import { type MarketParams } from "@morpho-org/blue-sdk";
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address } from "viem";
3
3
  import { type BlueSupplyCollateralAction, type DepositAmountArgs, type Metadata, type PermitRequirementSignature, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueSupplyCollateral}. */
@@ -1,9 +1,8 @@
1
- import { getChainAddresses } from "@morpho-org/blue-sdk";
2
1
  import { deepFreeze } from "@morpho-org/morpho-ts";
3
2
  import { BundlerAction } from "../../bundler/index.js";
4
- import { addTransactionMetadata, validateNativeAsset, } from "../../helpers/index.js";
3
+ import { addTransactionMetadata } from "../../helpers/index.js";
5
4
  import { NegativeNativeAmountError, NonPositiveAssetAmountError, ZeroCollateralAmountError, } from "../../types/index.js";
6
- import { getTokenRequirementActions } from "../signatures/getTokenRequirementActions.js";
5
+ import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
7
6
  /**
8
7
  * Prepares a supply-collateral transaction for a Morpho Blue market.
9
8
  *
@@ -58,26 +57,13 @@ export const blueSupplyCollateral = ({ market: { chainId, marketParams }, args:
58
57
  if (totalCollateral === 0n) {
59
58
  throw new ZeroCollateralAmountError(marketParams.id);
60
59
  }
61
- const { bundler3: { generalAdapter1, bundler3 }, } = getChainAddresses(chainId);
62
- const actions = [];
63
- if (nativeAmount !== undefined && nativeAmount > 0n) {
64
- validateNativeAsset(chainId, marketParams.collateralToken);
65
- actions.push({
66
- type: "nativeTransfer",
67
- args: [bundler3, generalAdapter1, nativeAmount, false],
68
- }, {
69
- type: "wrapNative",
70
- args: [nativeAmount, generalAdapter1, false],
71
- });
72
- }
73
- if (amount > 0n) {
74
- actions.push(...getTokenRequirementActions({
75
- asset: marketParams.collateralToken,
76
- amount,
77
- recipient: generalAdapter1,
78
- requirementSignature,
79
- }));
80
- }
60
+ const actions = buildAssetFundingActions({
61
+ chainId,
62
+ asset: marketParams.collateralToken,
63
+ erc20Amount: amount,
64
+ nativeAmount: nativeAmount ?? 0n,
65
+ requirementSignature,
66
+ });
81
67
  actions.push({
82
68
  type: "morphoSupplyCollateral",
83
69
  args: [marketParams, totalCollateral, onBehalf, [], false],
@@ -1,4 +1,4 @@
1
- import { type MarketParams } from "@morpho-org/blue-sdk";
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import type { Address } from "viem";
3
3
  import { type AuthorizationRequirementSignature, type BlueSupplyCollateralBorrowAction, type DepositAmountArgs, type Metadata, type PermitRequirementSignature, type Transaction, type VaultReallocation } from "../../types/index.js";
4
4
  /** Parameters for {@link blueSupplyCollateralBorrow}. */
@@ -1,10 +1,9 @@
1
- import { getChainAddresses } from "@morpho-org/blue-sdk";
2
1
  import { deepFreeze } from "@morpho-org/morpho-ts";
3
2
  import { BundlerAction } from "../../bundler/index.js";
4
- import { addTransactionMetadata, validateNativeAsset, } from "../../helpers/index.js";
3
+ import { addTransactionMetadata } from "../../helpers/index.js";
5
4
  import { NegativeNativeAmountError, NonPositiveAssetAmountError, NonPositiveBorrowAmountError, NonPositiveMinBorrowSharePriceError, ZeroCollateralAmountError, } from "../../types/index.js";
6
5
  import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
7
- import { getTokenRequirementActions } from "../signatures/getTokenRequirementActions.js";
6
+ import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
8
7
  import { buildReallocationActions } from "./buildReallocationActions.js";
9
8
  /**
10
9
  * Prepares an atomic supply-collateral-and-borrow transaction for a Morpho Blue market.
@@ -96,29 +95,17 @@ export const blueSupplyCollateralBorrow = ({ market: { chainId, marketParams },
96
95
  if (totalCollateral === 0n) {
97
96
  throw new ZeroCollateralAmountError(marketParams.id);
98
97
  }
99
- const { bundler3: { generalAdapter1, bundler3 }, } = getChainAddresses(chainId);
100
98
  const actions = [];
101
99
  if (authorizationSignature) {
102
100
  actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
103
101
  }
104
- if (nativeAmount !== undefined && nativeAmount > 0n) {
105
- validateNativeAsset(chainId, marketParams.collateralToken);
106
- actions.push({
107
- type: "nativeTransfer",
108
- args: [bundler3, generalAdapter1, nativeAmount, false],
109
- }, {
110
- type: "wrapNative",
111
- args: [nativeAmount, generalAdapter1, false],
112
- });
113
- }
114
- if (amount > 0n) {
115
- actions.push(...getTokenRequirementActions({
116
- asset: marketParams.collateralToken,
117
- amount,
118
- recipient: generalAdapter1,
119
- requirementSignature,
120
- }));
121
- }
102
+ actions.push(...buildAssetFundingActions({
103
+ chainId,
104
+ asset: marketParams.collateralToken,
105
+ erc20Amount: amount,
106
+ nativeAmount: nativeAmount ?? 0n,
107
+ requirementSignature,
108
+ }));
122
109
  actions.push({
123
110
  type: "morphoSupplyCollateral",
124
111
  args: [marketParams, totalCollateral, onBehalf, [], false],