@morpho-org/morpho-sdk 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,12 +31,15 @@ pnpm add @morpho-org/morpho-sdk
31
31
  | **VaultV1** | `deposit` | Bundler (general adapter) | Same ERC-4626 inflation attack prevention as V2. Supports native token wrapping. |
32
32
  | | `withdraw` | Direct vault call | No attack surface |
33
33
  | | `redeem` | Direct vault call | No attack surface |
34
- | **MarketV1** | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
34
+ | **MarketV1** | `supply` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupply` with `maxSharePrice` (inflation guard). Supports native wrapping when `loanToken === wNative`. |
35
+ | | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
35
36
  | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
36
37
  | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
37
38
  | | `repay` | Bundler (general adapter) | `erc20TransferFrom` + `morphoRepay` with `maxSharePrice` protection. Supports partial or full. |
39
+ | | `withdraw` | Bundler (general adapter) | `morphoWithdraw` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
38
40
  | | `withdrawCollateral` | Direct Morpho call | No bundler overhead. Validates position health after withdrawal. |
39
41
  | | `repayWithdrawCollateral` | Bundler (general adapter) | Atomic repay + withdraw. Bundle order matters: repay first, then withdraw. |
42
+ | | `refinance` | Bundler (general adapter) | Atomic position migration to another market with the same loan + collateral tokens. Flash-collateral via the target's `onMorphoSupplyCollateral` callback: borrow target → repay source → withdraw source collateral. Requires GA1 auth. Supports target reallocations. |
40
43
 
41
44
  ### The `getRequirements` flow
42
45
 
@@ -81,9 +84,12 @@ const tx = buildTx(permitSignature);
81
84
  | | `withdraw` | Direct vault call | No attack surface |
82
85
  | | `redeem` | Direct vault call | No attack surface |
83
86
  | | `migrateToV2` | Bundler (general adapter) | Atomic V1 → V2 migration: redeem V1 shares + deposit into V2 in one tx. Slippage-protected. |
84
- | **MarketV1** | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
87
+ | **MarketV1** | `supply` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupply` with `maxSharePrice` (inflation guard). Supports native wrapping when `loanToken === wNative`. |
88
+ | | `supplyCollateral` | Bundler (general adapter) | `erc20TransferFrom` + `morphoSupplyCollateral`. Supports native wrapping. |
85
89
  | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
86
90
  | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
91
+ | | `withdraw` | Bundler (general adapter) | `morphoWithdraw` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
92
+ | | `refinance` | Bundler (general adapter) | Atomic position migration to another market sharing the same loan + collateral tokens. Requires GA1 auth. Supports reallocations. |
87
93
 
88
94
  ### VaultV2
89
95
 
@@ -252,6 +258,37 @@ const market = client.morpho.marketV1(
252
258
  );
253
259
  ```
254
260
 
261
+ #### Supply (loan asset)
262
+
263
+ Supply the loan asset to earn yield on the market.
264
+
265
+ ```typescript
266
+ const marketData = await market.getMarketData();
267
+
268
+ const { buildTx, getRequirements } = market.supply({
269
+ amount: 1000000000n,
270
+ userAddress: "0xUser...",
271
+ marketData,
272
+ });
273
+
274
+ const requirements = await getRequirements();
275
+ const tx = buildTx(requirementSignature);
276
+ ```
277
+
278
+ ##### Supply with native token wrapping
279
+
280
+ If the market's `loanToken` is the chain's wNative, you can supply native token that will be wrapped automatically:
281
+
282
+ ```typescript
283
+ const { buildTx, getRequirements } = market.supply({
284
+ nativeAmount: 1000000000000000000n,
285
+ userAddress: "0xUser...",
286
+ marketData,
287
+ });
288
+ ```
289
+
290
+ The bundle routes through `GeneralAdapter1` with `maxSharePrice` slippage protection (anti-inflation guard).
291
+
255
292
  #### Supply Collateral
256
293
 
257
294
  ```typescript
@@ -322,6 +359,33 @@ const tx = buildTx(requirementSignature);
322
359
 
323
360
  Repay does **not** require Morpho authorization (it only requires a loan token approval for `GeneralAdapter1`).
324
361
 
362
+ #### Withdraw (loan asset)
363
+
364
+ Two modes — `assets` (exact amount) or `shares` (full close, immune to interest accrual between quote and inclusion). Routed through bundler3 with `minSharePrice` slippage protection; the withdrawn assets are sent directly to `receiver` (defaults to `userAddress`). Optional `reallocations` top up market liquidity via the **PublicAllocator** when the on-market liquidity is insufficient (same mechanism as `borrow`).
365
+
366
+ ```typescript
367
+ const positionData = await market.getPositionData("0xUser...");
368
+
369
+ // Withdraw an exact amount of loan asset
370
+ const { buildTx, getRequirements } = market.withdraw({
371
+ assets: 500000000n,
372
+ userAddress: "0xUser...",
373
+ positionData,
374
+ });
375
+
376
+ // Or close the full supply position by shares
377
+ const { buildTx, getRequirements } = market.withdraw({
378
+ shares: positionData.supplyShares,
379
+ userAddress: "0xUser...",
380
+ positionData,
381
+ });
382
+
383
+ const requirements = await getRequirements();
384
+ const tx = buildTx();
385
+ ```
386
+
387
+ Loan-asset withdraw requires Morpho authorization for `GeneralAdapter1` (returned by `getRequirements` when missing). It does **not** require a token approval.
388
+
325
389
  #### Withdraw Collateral
326
390
 
327
391
  ```typescript
@@ -356,6 +420,49 @@ const tx = buildTx(requirementSignature);
356
420
 
357
421
  Atomically bundles repay → withdraw collateral via bundler3. Bundle order is critical: repay runs first to reduce debt, then withdraw. Requires both a loan token approval (for repay) and a Morpho authorization (for withdraw). The SDK validates combined position health by simulating the repay before checking withdrawal safety.
358
422
 
423
+ #### Refinance
424
+
425
+ Atomically migrate a position from this market to another Morpho Blue market that shares the **same loan and collateral tokens** on the same chain — no flash loan, no upfront capital. The bundle flash-collateralizes the target via its `onMorphoSupplyCollateral` callback: inside the callback `GeneralAdapter1` borrows on the target, repays the source debt, then withdraws the source collateral to settle the deferred transfer.
426
+
427
+ ```typescript
428
+ const source = client.morpho.marketV1(sourceMarketParams, 1);
429
+ const target = client.morpho.marketV1(targetMarketParams, 1);
430
+
431
+ const positionData = await source.getPositionData("0xUser...");
432
+ const targetPositionData = await target.getPositionData("0xUser...");
433
+
434
+ // Refinance by assets — exact-asset borrow and repay, no GA1 dust
435
+ const { buildTx, getRequirements } = source.refinance({
436
+ userAddress: "0xUser...",
437
+ positionData,
438
+ target: { marketParams: targetMarketParams, positionData: targetPositionData },
439
+ collateralAmount: 1000000000000000000n,
440
+ borrowAssets: 500000000000000000n,
441
+ });
442
+
443
+ // Or migrate the full debt by shares (immune to interest accrual between quote and inclusion)
444
+ const { buildTx, getRequirements } = source.refinance({
445
+ userAddress: "0xUser...",
446
+ positionData,
447
+ target: { marketParams: targetMarketParams, positionData: targetPositionData },
448
+ collateralAmount: 1000000000000000000n,
449
+ borrowShares: positionData.borrowShares,
450
+ });
451
+
452
+ // Collateral-only migration — omit both borrow fields
453
+ const { buildTx, getRequirements } = source.refinance({
454
+ userAddress: "0xUser...",
455
+ positionData,
456
+ target: { marketParams: targetMarketParams, positionData: targetPositionData },
457
+ collateralAmount: 1000000000000000000n,
458
+ });
459
+
460
+ const requirements = await getRequirements();
461
+ const tx = buildTx();
462
+ ```
463
+
464
+ The SDK validates ownership, token/id match, and that amounts do not exceed the source position. Health is checked against `LLTV − buffer` where it can degrade: the residual source position is validated whenever debt remains after the repay, and the aggregate target position is validated whenever a borrow leg is migrated. Collateral-only migrations (both borrow fields omitted) skip the target health check — they can't degrade target health and would otherwise fail on missing-oracle target markets. Both markets are forward-accrued to `now`; in shares mode the target borrow overshoots by `slippageTolerance` and the callback sweeps the residual back into the target debt (or skims it to the user). `getRequirements` returns the `setAuthorization(generalAdapter1, true)` transaction when GA1 is not yet authorized — a single global authorization covers both markets. Optional `targetReallocations` top up target-market liquidity via the **PublicAllocator** (same mechanism as `borrow`); their fees add to `tx.value`.
465
+
359
466
  #### Borrow with Shared Liquidity (Reallocations)
360
467
 
361
468
  When a market lacks sufficient liquidity, you can reallocate liquidity from other markets managed by MetaMorpho Vaults via the **PublicAllocator** contract:
@@ -443,13 +550,19 @@ graph LR
443
550
 
444
551
  subgraph MarketV1 Flow
445
552
  MM1[MorphoMarketV1]
553
+ MM1 --> M1S[marketV1Supply]
446
554
  MM1 --> M1SC[marketV1SupplyCollateral]
447
555
  MM1 --> M1B[marketV1Borrow]
448
556
  MM1 --> M1SCB[marketV1SupplyCollateralBorrow]
557
+ MM1 --> M1W[marketV1Withdraw]
558
+ MM1 --> M1RF[marketV1Refinance]
449
559
 
450
- M1SC -->|erc20TransferFrom + morphoSupplyCollateral| B3[Bundler3]
560
+ M1S -->|nativeWrap? + erc20TransferFrom + morphoSupply| B3[Bundler3]
561
+ M1SC -->|erc20TransferFrom + morphoSupplyCollateral| B3
451
562
  M1B -->|reallocateTo? + morphoBorrow| B3
452
563
  M1SCB -->|transfer + supplyCollateral + reallocateTo? + borrow| B3
564
+ M1W -->|reallocateTo? + morphoWithdraw| B3
565
+ M1RF -->|reallocateTo? + supplyCollateral callback: borrow + repay + withdrawCollateral| B3
453
566
 
454
567
  B3 -.->|reallocateTo| PA[PublicAllocator]
455
568
  end
@@ -1,4 +1,5 @@
1
1
  export * from "./borrow.js";
2
+ export * from "./refinance.js";
2
3
  export * from "./repay.js";
3
4
  export * from "./repayWithdrawCollateral.js";
4
5
  export * from "./supply.js";
@@ -15,6 +15,7 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./borrow.js"), exports);
18
+ __exportStar(require("./refinance.js"), exports);
18
19
  __exportStar(require("./repay.js"), exports);
19
20
  __exportStar(require("./repayWithdrawCollateral.js"), exports);
20
21
  __exportStar(require("./supply.js"), exports);
@@ -0,0 +1,117 @@
1
+ import { type MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address } from "viem";
3
+ import { type MarketV1RefinanceAction, type Metadata, type Transaction, type VaultReallocation } from "../../types/index.js";
4
+ /** Parameters for {@link marketV1Refinance}. */
5
+ export interface MarketV1RefinanceParams {
6
+ source: {
7
+ readonly chainId: number;
8
+ readonly marketParams: MarketParams;
9
+ };
10
+ target: {
11
+ readonly marketParams: MarketParams;
12
+ };
13
+ args: {
14
+ user: Address;
15
+ collateralAmount: bigint;
16
+ /**
17
+ * Loan assets to borrow on the target. Assets mode: the exact borrow (exclusive with
18
+ * `borrowShares`). Shares mode: the positive overshoot covering accrual + slippage; omitting it
19
+ * throws {@link RefinanceSharesMissingBorrowAssetsError}.
20
+ */
21
+ borrowAssets?: bigint;
22
+ /** Source borrow shares to repay (immune to mid-tx accrual); exclusive with `borrowAssets`. */
23
+ borrowShares?: bigint;
24
+ /** Minimum borrow share price on the target market (in ray). */
25
+ minBorrowSharePrice: bigint;
26
+ /** Maximum repay share price on the source market (in ray); must be > 0 when a repay leg exists. */
27
+ maxRepaySharePrice: bigint;
28
+ /** PublicAllocator reallocations into the target market, run before the bundle. Fees add to `tx.value`. */
29
+ targetReallocations?: readonly VaultReallocation[];
30
+ };
31
+ metadata?: Metadata;
32
+ }
33
+ /**
34
+ * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
35
+ * chain that shares the same loan and collateral tokens.
36
+ *
37
+ * Strategy: flash-collateral via the target's `onMorphoSupplyCollateral` callback. The collateral
38
+ * is credited before the deferred `safeTransferFrom`, so inside the callback GA1 borrows on the
39
+ * target, repays the source, then withdraws the source collateral to settle the transfer.
40
+ *
41
+ * Bundle shape (callback contents depend on borrow mode):
42
+ *
43
+ * ```text
44
+ * // optional: one reallocateTo per targetReallocations entry, run first
45
+ * reallocateTo(vault_i, fee_i, withdrawals_i, target, false),
46
+ *
47
+ * morphoSupplyCollateral(target, collateralAmount, user, [
48
+ * // omitted in collat-only mode
49
+ * morphoBorrow(target, borrowAssets, 0, minBorrowSharePrice, GA1),
50
+ * morphoRepay(source, assets|0, 0|shares, maxRepaySharePrice, user, []),
51
+ * // shares mode only: sweep overshoot before the withdraw so same-token markets aren't drained
52
+ * morphoRepay(target, maxUint256, 0, maxUint256, user, [], skipRevert=true),
53
+ * // shares mode only: fallback if the repay is skipped, skim residual loan tokens to the user
54
+ * erc20Transfer(loanToken, user, maxUint256, GA1, skipRevert=false),
55
+ * morphoWithdrawCollateral(source, collateralAmount, GA1),
56
+ * ])
57
+ * ```
58
+ *
59
+ * Borrow modes:
60
+ *
61
+ * - **Assets mode** (`borrowAssets > 0n`): exact-asset borrow and repay, no GA1 dust.
62
+ * - **Shares mode** (`borrowShares > 0n`, `borrowAssets` is the overshoot): the trailing
63
+ * `morphoRepay(target, maxUint256, …, skipRevert=true)` sweeps the residual into the target debt,
64
+ * then an `erc20Transfer` skims any residual to the user if that repay is skipped.
65
+ * - **Collat-only** (both zero/omitted): only collateral is migrated; borrow/repay legs omitted.
66
+ *
67
+ * Prerequisite: GA1 must be authorized on Morpho — the entity's `getRequirements()` returns the
68
+ * `setAuthorization` transaction when needed.
69
+ *
70
+ * @param params.source.chainId - The chain both markets live on.
71
+ * @param params.source.marketParams - Source market params (the position being closed).
72
+ * @param params.target.marketParams - Target market params; must share both tokens with the source.
73
+ * @param params.args.user - Position owner on both markets.
74
+ * @param params.args.collateralAmount - Amount of collateral to migrate.
75
+ * @param params.args.borrowAssets - Loan assets to borrow on the target; exclusive with `borrowShares`. Defaults to `0n`.
76
+ * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
77
+ * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
78
+ * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
79
+ * @param params.args.targetReallocations - PublicAllocator reallocations into the target, run before the supply leg.
80
+ * @param params.metadata - Optional analytics metadata appended to `tx.data`.
81
+ * @returns A deep-frozen `Transaction<MarketV1RefinanceAction>`.
82
+ * @remarks `borrowAssets` and `borrowShares` describe different markets (target borrow vs. source
83
+ * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
84
+ * @throws {ZeroCollateralAmountError} when `collateralAmount <= 0n`.
85
+ * @throws {NonPositiveAssetAmountError} when `borrowAssets < 0n`.
86
+ * @throws {NegativeBorrowSharesError} when `borrowShares < 0n`.
87
+ * @throws {NonPositiveMinBorrowSharePriceError} when `minBorrowSharePrice < 0n`.
88
+ * @throws {NegativeMaxRepaySharePriceError} when `maxRepaySharePrice < 0n`.
89
+ * @throws {RefinanceSameMarketError} when source and target market ids are equal.
90
+ * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
91
+ * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
92
+ * @throws {NonPositiveRepayMaxSharePriceError} when a repay leg is encoded and `maxRepaySharePrice <= 0n`.
93
+ * @throws {NegativeReallocationFeeError} when any `reallocation.fee < 0n`.
94
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
95
+ * @throws {NonPositiveReallocationAmountError} when any `reallocation.withdrawals[i].amount <= 0n`.
96
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references the target market.
97
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly sorted by market id.
98
+ * @example
99
+ * ```ts
100
+ * import { marketV1Refinance } from "@morpho-org/morpho-sdk";
101
+ *
102
+ * const tx = marketV1Refinance({
103
+ * source: { chainId: 1, marketParams: sourceParams },
104
+ * target: { marketParams: targetParams },
105
+ * args: {
106
+ * user: borrower,
107
+ * collateralAmount: 1_000_000_000_000_000_000n,
108
+ * borrowShares: 500_000_000_000n,
109
+ * borrowAssets: 501_000_000n, // overshoot computed by entity layer
110
+ * minBorrowSharePrice: 0n,
111
+ * maxRepaySharePrice: 1_500_000_000_000_000_000_000_000_000n,
112
+ * },
113
+ * });
114
+ * // tx satisfies Readonly<Transaction<MarketV1RefinanceAction>>
115
+ * ```
116
+ */
117
+ export declare const marketV1Refinance: ({ source: { chainId, marketParams: sourceParams }, target: { marketParams: targetParams }, args: { user, collateralAmount, borrowAssets, borrowShares, minBorrowSharePrice, maxRepaySharePrice, targetReallocations, }, metadata, }: MarketV1RefinanceParams) => Readonly<Transaction<MarketV1RefinanceAction>>;
@@ -0,0 +1,218 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.marketV1Refinance = void 0;
4
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
+ const viem_1 = require("viem");
7
+ const index_js_1 = require("../../bundler/index.js");
8
+ const index_js_2 = require("../../helpers/index.js");
9
+ const index_js_3 = require("../../types/index.js");
10
+ const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
11
+ /**
12
+ * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
13
+ * chain that shares the same loan and collateral tokens.
14
+ *
15
+ * Strategy: flash-collateral via the target's `onMorphoSupplyCollateral` callback. The collateral
16
+ * is credited before the deferred `safeTransferFrom`, so inside the callback GA1 borrows on the
17
+ * target, repays the source, then withdraws the source collateral to settle the transfer.
18
+ *
19
+ * Bundle shape (callback contents depend on borrow mode):
20
+ *
21
+ * ```text
22
+ * // optional: one reallocateTo per targetReallocations entry, run first
23
+ * reallocateTo(vault_i, fee_i, withdrawals_i, target, false),
24
+ *
25
+ * morphoSupplyCollateral(target, collateralAmount, user, [
26
+ * // omitted in collat-only mode
27
+ * morphoBorrow(target, borrowAssets, 0, minBorrowSharePrice, GA1),
28
+ * morphoRepay(source, assets|0, 0|shares, maxRepaySharePrice, user, []),
29
+ * // shares mode only: sweep overshoot before the withdraw so same-token markets aren't drained
30
+ * morphoRepay(target, maxUint256, 0, maxUint256, user, [], skipRevert=true),
31
+ * // shares mode only: fallback if the repay is skipped, skim residual loan tokens to the user
32
+ * erc20Transfer(loanToken, user, maxUint256, GA1, skipRevert=false),
33
+ * morphoWithdrawCollateral(source, collateralAmount, GA1),
34
+ * ])
35
+ * ```
36
+ *
37
+ * Borrow modes:
38
+ *
39
+ * - **Assets mode** (`borrowAssets > 0n`): exact-asset borrow and repay, no GA1 dust.
40
+ * - **Shares mode** (`borrowShares > 0n`, `borrowAssets` is the overshoot): the trailing
41
+ * `morphoRepay(target, maxUint256, …, skipRevert=true)` sweeps the residual into the target debt,
42
+ * then an `erc20Transfer` skims any residual to the user if that repay is skipped.
43
+ * - **Collat-only** (both zero/omitted): only collateral is migrated; borrow/repay legs omitted.
44
+ *
45
+ * Prerequisite: GA1 must be authorized on Morpho — the entity's `getRequirements()` returns the
46
+ * `setAuthorization` transaction when needed.
47
+ *
48
+ * @param params.source.chainId - The chain both markets live on.
49
+ * @param params.source.marketParams - Source market params (the position being closed).
50
+ * @param params.target.marketParams - Target market params; must share both tokens with the source.
51
+ * @param params.args.user - Position owner on both markets.
52
+ * @param params.args.collateralAmount - Amount of collateral to migrate.
53
+ * @param params.args.borrowAssets - Loan assets to borrow on the target; exclusive with `borrowShares`. Defaults to `0n`.
54
+ * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
55
+ * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
56
+ * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
57
+ * @param params.args.targetReallocations - PublicAllocator reallocations into the target, run before the supply leg.
58
+ * @param params.metadata - Optional analytics metadata appended to `tx.data`.
59
+ * @returns A deep-frozen `Transaction<MarketV1RefinanceAction>`.
60
+ * @remarks `borrowAssets` and `borrowShares` describe different markets (target borrow vs. source
61
+ * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
62
+ * @throws {ZeroCollateralAmountError} when `collateralAmount <= 0n`.
63
+ * @throws {NonPositiveAssetAmountError} when `borrowAssets < 0n`.
64
+ * @throws {NegativeBorrowSharesError} when `borrowShares < 0n`.
65
+ * @throws {NonPositiveMinBorrowSharePriceError} when `minBorrowSharePrice < 0n`.
66
+ * @throws {NegativeMaxRepaySharePriceError} when `maxRepaySharePrice < 0n`.
67
+ * @throws {RefinanceSameMarketError} when source and target market ids are equal.
68
+ * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
69
+ * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
70
+ * @throws {NonPositiveRepayMaxSharePriceError} when a repay leg is encoded and `maxRepaySharePrice <= 0n`.
71
+ * @throws {NegativeReallocationFeeError} when any `reallocation.fee < 0n`.
72
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
73
+ * @throws {NonPositiveReallocationAmountError} when any `reallocation.withdrawals[i].amount <= 0n`.
74
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references the target market.
75
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly sorted by market id.
76
+ * @example
77
+ * ```ts
78
+ * import { marketV1Refinance } from "@morpho-org/morpho-sdk";
79
+ *
80
+ * const tx = marketV1Refinance({
81
+ * source: { chainId: 1, marketParams: sourceParams },
82
+ * target: { marketParams: targetParams },
83
+ * args: {
84
+ * user: borrower,
85
+ * collateralAmount: 1_000_000_000_000_000_000n,
86
+ * borrowShares: 500_000_000_000n,
87
+ * borrowAssets: 501_000_000n, // overshoot computed by entity layer
88
+ * minBorrowSharePrice: 0n,
89
+ * maxRepaySharePrice: 1_500_000_000_000_000_000_000_000_000n,
90
+ * },
91
+ * });
92
+ * // tx satisfies Readonly<Transaction<MarketV1RefinanceAction>>
93
+ * ```
94
+ */
95
+ const marketV1Refinance = ({ source: { chainId, marketParams: sourceParams }, target: { marketParams: targetParams }, args: { user, collateralAmount, borrowAssets = 0n, borrowShares = 0n, minBorrowSharePrice, maxRepaySharePrice, targetReallocations, }, metadata, }) => {
96
+ if (collateralAmount <= 0n) {
97
+ throw new index_js_3.ZeroCollateralAmountError(sourceParams.id);
98
+ }
99
+ if (borrowAssets < 0n) {
100
+ throw new index_js_3.NonPositiveAssetAmountError(sourceParams.loanToken);
101
+ }
102
+ if (borrowShares < 0n) {
103
+ throw new index_js_3.NegativeBorrowSharesError(sourceParams.id);
104
+ }
105
+ if (minBorrowSharePrice < 0n) {
106
+ throw new index_js_3.NonPositiveMinBorrowSharePriceError(targetParams.id);
107
+ }
108
+ if (maxRepaySharePrice < 0n) {
109
+ throw new index_js_3.NegativeMaxRepaySharePriceError(sourceParams.id);
110
+ }
111
+ if (sourceParams.id === targetParams.id) {
112
+ throw new index_js_3.RefinanceSameMarketError(sourceParams.id);
113
+ }
114
+ if (!(0, viem_1.isAddressEqual)(sourceParams.collateralToken, targetParams.collateralToken) ||
115
+ !(0, viem_1.isAddressEqual)(sourceParams.loanToken, targetParams.loanToken)) {
116
+ throw new index_js_3.RefinanceTokenMismatchError(sourceParams.id, targetParams.id);
117
+ }
118
+ const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
119
+ const sharesMode = borrowShares > 0n;
120
+ const shouldMigrateBorrow = borrowAssets > 0n || sharesMode;
121
+ // Shares mode borrows in assets; Morpho rejects a zero borrow, so require a positive overshoot.
122
+ if (sharesMode && borrowAssets <= 0n) {
123
+ throw new index_js_3.RefinanceSharesMissingBorrowAssetsError(sourceParams.id);
124
+ }
125
+ // A repay leg with maxRepaySharePrice = 0n always reverts; require a positive cap when debt is migrated.
126
+ if (shouldMigrateBorrow && maxRepaySharePrice <= 0n) {
127
+ throw new index_js_3.NonPositiveRepayMaxSharePriceError(sourceParams.id);
128
+ }
129
+ const callback = [];
130
+ if (shouldMigrateBorrow) {
131
+ callback.push({
132
+ type: "morphoBorrow",
133
+ args: [
134
+ targetParams,
135
+ borrowAssets,
136
+ 0n,
137
+ minBorrowSharePrice,
138
+ generalAdapter1,
139
+ false,
140
+ ],
141
+ });
142
+ callback.push(sharesMode
143
+ ? {
144
+ type: "morphoRepay",
145
+ args: [
146
+ sourceParams,
147
+ 0n,
148
+ borrowShares,
149
+ maxRepaySharePrice,
150
+ user,
151
+ [],
152
+ false,
153
+ ],
154
+ }
155
+ : {
156
+ type: "morphoRepay",
157
+ args: [
158
+ sourceParams,
159
+ borrowAssets,
160
+ 0n,
161
+ maxRepaySharePrice,
162
+ user,
163
+ [],
164
+ false,
165
+ ],
166
+ });
167
+ }
168
+ // Sweep the borrow overshoot back into target debt so GA1 ends drained. Must run before the
169
+ // withdraw: in same-token markets maxUint256 would otherwise drain the just-withdrawn collateral.
170
+ if (sharesMode) {
171
+ callback.push({
172
+ type: "morphoRepay",
173
+ args: [targetParams, viem_1.maxUint256, 0n, viem_1.maxUint256, user, [], true],
174
+ });
175
+ // Fallback: if the repay above is skipped, skim any residual loan tokens to the user.
176
+ callback.push({
177
+ type: "erc20Transfer",
178
+ args: [targetParams.loanToken, user, viem_1.maxUint256, generalAdapter1, false],
179
+ });
180
+ }
181
+ callback.push({
182
+ type: "morphoWithdrawCollateral",
183
+ args: [sourceParams, collateralAmount, generalAdapter1, false],
184
+ });
185
+ const actions = [];
186
+ let reallocationFee = 0n;
187
+ if (targetReallocations && targetReallocations.length > 0) {
188
+ const result = (0, buildReallocationActions_js_1.buildReallocationActions)(targetReallocations, targetParams);
189
+ actions.push(...result.actions);
190
+ reallocationFee = result.fee;
191
+ }
192
+ actions.push({
193
+ type: "morphoSupplyCollateral",
194
+ args: [targetParams, collateralAmount, user, callback, false],
195
+ });
196
+ let tx = index_js_1.BundlerAction.encodeBundle(chainId, actions);
197
+ if (metadata) {
198
+ tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
199
+ }
200
+ return (0, morpho_ts_1.deepFreeze)({
201
+ ...tx,
202
+ action: {
203
+ type: "marketV1Refinance",
204
+ args: {
205
+ sourceMarket: sourceParams.id,
206
+ targetMarket: targetParams.id,
207
+ collateralAmount,
208
+ borrowAssets,
209
+ borrowShares,
210
+ minBorrowSharePrice,
211
+ maxRepaySharePrice,
212
+ user,
213
+ reallocationFee,
214
+ },
215
+ },
216
+ });
217
+ };
218
+ exports.marketV1Refinance = marketV1Refinance;
@@ -421,7 +421,7 @@ export declare namespace BundlerAction {
421
421
  * @param market - Morpho Blue market parameters.
422
422
  * @param assets - Borrow asset amount.
423
423
  * @param shares - Borrow share amount.
424
- * @param slippageAmount - Slippage guard amount.
424
+ * @param minSharePrice - Minimum amount of borrowed assets per borrow share minted, scaled by 1e27.
425
425
  * @param receiver - Recipient of borrowed assets.
426
426
  * @param skipRevert - Whether Bundler3 should tolerate a revert.
427
427
  * @returns Encoded Bundler3 calls.
@@ -453,7 +453,7 @@ export declare namespace BundlerAction {
453
453
  * );
454
454
  * ```
455
455
  */
456
- function morphoBorrow(chainId: number, market: InputMarketParams, assets: bigint, shares: bigint, slippageAmount: bigint, receiver: Address, skipRevert?: boolean): BundlerCall[];
456
+ function morphoBorrow(chainId: number, market: InputMarketParams, assets: bigint, shares: bigint, minSharePrice: bigint, receiver: Address, skipRevert?: boolean): BundlerCall[];
457
457
  /**
458
458
  * Encodes a GeneralAdapter1 Morpho Blue repay call.
459
459
  *
@@ -461,7 +461,7 @@ export declare namespace BundlerAction {
461
461
  * @param market - Morpho Blue market parameters.
462
462
  * @param assets - Repay asset amount.
463
463
  * @param shares - Repay share amount.
464
- * @param slippageAmount - Slippage guard amount.
464
+ * @param maxSharePrice - Maximum amount of repaid assets per borrow share redeemed, scaled by 1e27.
465
465
  * @param onBehalf - Account whose borrow is repaid.
466
466
  * @param callbackCalls - Calls executed in Morpho's callback.
467
467
  * @param skipRevert - Whether Bundler3 should tolerate a revert.
@@ -495,7 +495,7 @@ export declare namespace BundlerAction {
495
495
  * );
496
496
  * ```
497
497
  */
498
- function morphoRepay(chainId: number, market: InputMarketParams, assets: bigint, shares: bigint, slippageAmount: bigint, onBehalf: Address, callbackCalls: BundlerCall[], skipRevert?: boolean): BundlerCall[];
498
+ function morphoRepay(chainId: number, market: InputMarketParams, assets: bigint, shares: bigint, maxSharePrice: bigint, onBehalf: Address, callbackCalls: BundlerCall[], skipRevert?: boolean): BundlerCall[];
499
499
  /**
500
500
  * Encodes a GeneralAdapter1 Morpho Blue withdraw call.
501
501
  *
@@ -176,8 +176,8 @@ var BundlerAction;
176
176
  return BundlerAction.morphoWithdraw(chainId, ...args);
177
177
  }
178
178
  case "morphoRepay": {
179
- const [market, assets, shares, slippageAmount, onBehalf, onMorphoRepay, skipRevert,] = args;
180
- return BundlerAction.morphoRepay(chainId, market, assets, shares, slippageAmount, onBehalf, onMorphoRepay.flatMap(BundlerAction.encode.bind(null, chainId)), skipRevert);
179
+ const [market, assets, shares, maxSharePrice, onBehalf, onMorphoRepay, skipRevert,] = args;
180
+ return BundlerAction.morphoRepay(chainId, market, assets, shares, maxSharePrice, onBehalf, onMorphoRepay.flatMap(BundlerAction.encode.bind(null, chainId)), skipRevert);
181
181
  }
182
182
  case "morphoWithdrawCollateral": {
183
183
  return BundlerAction.morphoWithdrawCollateral(chainId, ...args);
@@ -766,7 +766,7 @@ var BundlerAction;
766
766
  * @param market - Morpho Blue market parameters.
767
767
  * @param assets - Borrow asset amount.
768
768
  * @param shares - Borrow share amount.
769
- * @param slippageAmount - Slippage guard amount.
769
+ * @param minSharePrice - Minimum amount of borrowed assets per borrow share minted, scaled by 1e27.
770
770
  * @param receiver - Recipient of borrowed assets.
771
771
  * @param skipRevert - Whether Bundler3 should tolerate a revert.
772
772
  * @returns Encoded Bundler3 calls.
@@ -799,7 +799,7 @@ var BundlerAction;
799
799
  * ```
800
800
  */
801
801
  // biome-ignore lint/complexity/useMaxParams: TODO refactor to ≤2 params
802
- function morphoBorrow(chainId, market, assets, shares, slippageAmount, receiver, skipRevert = false) {
802
+ function morphoBorrow(chainId, market, assets, shares, minSharePrice, receiver, skipRevert = false) {
803
803
  const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
804
804
  return [
805
805
  {
@@ -807,7 +807,7 @@ var BundlerAction;
807
807
  data: (0, viem_1.encodeFunctionData)({
808
808
  abi: abis_js_1.generalAdapter1Abi,
809
809
  functionName: "morphoBorrow",
810
- args: [market, assets, shares, slippageAmount, receiver],
810
+ args: [market, assets, shares, minSharePrice, receiver],
811
811
  }),
812
812
  value: 0n,
813
813
  skipRevert,
@@ -823,7 +823,7 @@ var BundlerAction;
823
823
  * @param market - Morpho Blue market parameters.
824
824
  * @param assets - Repay asset amount.
825
825
  * @param shares - Repay share amount.
826
- * @param slippageAmount - Slippage guard amount.
826
+ * @param maxSharePrice - Maximum amount of repaid assets per borrow share redeemed, scaled by 1e27.
827
827
  * @param onBehalf - Account whose borrow is repaid.
828
828
  * @param callbackCalls - Calls executed in Morpho's callback.
829
829
  * @param skipRevert - Whether Bundler3 should tolerate a revert.
@@ -858,7 +858,7 @@ var BundlerAction;
858
858
  * ```
859
859
  */
860
860
  // biome-ignore lint/complexity/useMaxParams: TODO refactor to ≤2 params
861
- function morphoRepay(chainId, market, assets, shares, slippageAmount, onBehalf, callbackCalls, skipRevert = false) {
861
+ function morphoRepay(chainId, market, assets, shares, maxSharePrice, onBehalf, callbackCalls, skipRevert = false) {
862
862
  const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
863
863
  const { callbackHash, reenterData } = encodeCallbackCalls(callbackCalls);
864
864
  return [
@@ -867,7 +867,7 @@ var BundlerAction;
867
867
  data: (0, viem_1.encodeFunctionData)({
868
868
  abi: abis_js_1.generalAdapter1Abi,
869
869
  functionName: "morphoRepay",
870
- args: [market, assets, shares, slippageAmount, onBehalf, reenterData],
870
+ args: [market, assets, shares, maxSharePrice, onBehalf, reenterData],
871
871
  }),
872
872
  value: 0n,
873
873
  skipRevert,
@@ -131,21 +131,21 @@ export interface ActionArgs {
131
131
  onMorphoSupply: Action[],
132
132
  skipRevert?: boolean
133
133
  ];
134
- /** Morpho Blue borrow call for `market`, `assets` or `shares`, `slippageAmount`, and `receiver`; `skipRevert` controls Bundler3 revert handling. */
134
+ /** Morpho Blue borrow call for `market`, `assets` or `shares`, `minSharePrice`, and `receiver`; `skipRevert` controls Bundler3 revert handling. */
135
135
  readonly morphoBorrow: [
136
136
  market: InputMarketParams,
137
137
  assets: bigint,
138
138
  shares: bigint,
139
- slippageAmount: bigint,
139
+ minSharePrice: bigint,
140
140
  receiver: Address,
141
141
  skipRevert?: boolean
142
142
  ];
143
- /** Morpho Blue repay call for `market`, `assets` or `shares`, `slippageAmount`, `onBehalf`, and callback actions; `skipRevert` controls Bundler3 revert handling. */
143
+ /** Morpho Blue repay call for `market`, `assets` or `shares`, `maxSharePrice`, `onBehalf`, and callback actions; `skipRevert` controls Bundler3 revert handling. */
144
144
  readonly morphoRepay: [
145
145
  market: InputMarketParams,
146
146
  assets: bigint,
147
147
  shares: bigint,
148
- slippageAmount: bigint,
148
+ maxSharePrice: bigint,
149
149
  onBehalf: Address,
150
150
  onMorphoRepay: Action[],
151
151
  skipRevert?: boolean