@morpho-org/morpho-sdk 3.1.1 → 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
@@ -39,6 +39,7 @@ pnpm add @morpho-org/morpho-sdk
39
39
  | | `withdraw` | Bundler (general adapter) | `morphoWithdraw` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
40
40
  | | `withdrawCollateral` | Direct Morpho call | No bundler overhead. Validates position health after withdrawal. |
41
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. |
42
43
 
43
44
  ### The `getRequirements` flow
44
45
 
@@ -88,6 +89,7 @@ const tx = buildTx(permitSignature);
88
89
  | | `borrow` | Bundler (general adapter) | `morphoBorrow` with `minSharePrice` slippage protection. Requires GA1 auth. Supports reallocations. |
89
90
  | | `supplyCollateralBorrow` | Bundler (general adapter) | Atomic supply + borrow. LLTV buffer prevents instant liquidation. Supports reallocations. |
90
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. |
91
93
 
92
94
  ### VaultV2
93
95
 
@@ -418,6 +420,49 @@ const tx = buildTx(requirementSignature);
418
420
 
419
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.
420
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
+
421
466
  #### Borrow with Shared Liquidity (Reallocations)
422
467
 
423
468
  When a market lacks sufficient liquidity, you can reallocate liquidity from other markets managed by MetaMorpho Vaults via the **PublicAllocator** contract:
@@ -510,12 +555,14 @@ graph LR
510
555
  MM1 --> M1B[marketV1Borrow]
511
556
  MM1 --> M1SCB[marketV1SupplyCollateralBorrow]
512
557
  MM1 --> M1W[marketV1Withdraw]
558
+ MM1 --> M1RF[marketV1Refinance]
513
559
 
514
560
  M1S -->|nativeWrap? + erc20TransferFrom + morphoSupply| B3[Bundler3]
515
561
  M1SC -->|erc20TransferFrom + morphoSupplyCollateral| B3
516
562
  M1B -->|reallocateTo? + morphoBorrow| B3
517
563
  M1SCB -->|transfer + supplyCollateral + reallocateTo? + borrow| B3
518
564
  M1W -->|reallocateTo? + morphoWithdraw| B3
565
+ M1RF -->|reallocateTo? + supplyCollateral callback: borrow + repay + withdrawCollateral| B3
519
566
 
520
567
  B3 -.->|reallocateTo| PA[PublicAllocator]
521
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;
@@ -1,7 +1,7 @@
1
- import { type AccrualPosition, type Market, type MarketParams } from "@morpho-org/blue-sdk";
2
- import type { Address } from "viem";
1
+ import { AccrualPosition, type Market, type MarketParams } from "@morpho-org/blue-sdk";
2
+ import { type Address } from "viem";
3
3
  import type { FetchParameters } from "../../types/data.js";
4
- import { type AssetsOrSharesArgs, type DepositAmountArgs, type ERC20ApprovalAction, type MarketV1BorrowAction, type MarketV1RepayAction, type MarketV1RepayWithdrawCollateralAction, type MarketV1SupplyAction, type MarketV1SupplyCollateralAction, type MarketV1SupplyCollateralBorrowAction, type MarketV1WithdrawAction, type MarketV1WithdrawCollateralAction, type MorphoAuthorizationAction, type MorphoClientType, type ReallocationComputeOptions, type RepayAmountArgs, type Requirement, type RequirementSignature, type Transaction, type VaultReallocation } from "../../types/index.js";
4
+ import { type AssetsOrSharesArgs, type DepositAmountArgs, type ERC20ApprovalAction, type MarketV1BorrowAction, type MarketV1RefinanceAction, type MarketV1RepayAction, type MarketV1RepayWithdrawCollateralAction, type MarketV1SupplyAction, type MarketV1SupplyCollateralAction, type MarketV1SupplyCollateralBorrowAction, type MarketV1WithdrawAction, type MarketV1WithdrawCollateralAction, type MorphoAuthorizationAction, type MorphoClientType, type ReallocationComputeOptions, type RepayAmountArgs, type Requirement, type RequirementSignature, type Transaction, type VaultReallocation } from "../../types/index.js";
5
5
  import { ReallocationData } from "../reallocationData.js";
6
6
  export interface MarketV1Actions {
7
7
  /**
@@ -227,6 +227,45 @@ export interface MarketV1Actions {
227
227
  useSimplePermit?: boolean;
228
228
  }) => Promise<(Readonly<Transaction<ERC20ApprovalAction>> | Readonly<Transaction<MorphoAuthorizationAction>> | Requirement)[]>;
229
229
  };
230
+ /**
231
+ * Prepares an atomic refinance migrating this market's position to another Morpho Blue market
232
+ * that shares the same loan and collateral tokens. See {@link marketV1Refinance} for the bundle.
233
+ *
234
+ * Validates ownership, token/id match, that amounts do not exceed the source position, and that
235
+ * both the residual source and the aggregate target position stay within LLTV − buffer. Both
236
+ * markets are forward-accrued to `now`; in shares mode the target borrow is overshot by
237
+ * `slippageTolerance` and the callback sweeps the residual.
238
+ *
239
+ * `getRequirements` returns `morpho.setAuthorization(generalAdapter1, true)` when GA1 is not yet
240
+ * authorized (a single global authorization covers both markets).
241
+ *
242
+ * @param params.userAddress - Position owner on both markets.
243
+ * @param params.positionData - Pre-fetched source-market accrual position.
244
+ * @param params.target.marketParams - Target market params.
245
+ * @param params.target.positionData - Pre-fetched target-market accrual position (zero-position if none).
246
+ * @param params.collateralAmount - Amount of collateral to migrate from source to target.
247
+ * @param params.borrowAssets - Loan assets to repay on source; exclusive with `borrowShares`.
248
+ * @param params.borrowShares - Borrow shares to repay on source; exclusive with `borrowAssets`.
249
+ * @param params.slippageTolerance - WAD slippage tolerance. Defaults to `DEFAULT_SLIPPAGE_TOLERANCE`.
250
+ * @param params.targetReallocations - PublicAllocator reallocations into the target market.
251
+ * @returns Object with `buildTx` and `getRequirements`.
252
+ */
253
+ refinance: (params: {
254
+ userAddress: Address;
255
+ positionData: AccrualPosition;
256
+ target: {
257
+ marketParams: MarketParams;
258
+ positionData: AccrualPosition;
259
+ };
260
+ collateralAmount: bigint;
261
+ borrowAssets?: bigint;
262
+ borrowShares?: bigint;
263
+ slippageTolerance?: bigint;
264
+ targetReallocations?: readonly VaultReallocation[];
265
+ }) => {
266
+ buildTx: () => Readonly<Transaction<MarketV1RefinanceAction>>;
267
+ getRequirements: () => Promise<Readonly<Transaction<MorphoAuthorizationAction>>[]>;
268
+ };
230
269
  /**
231
270
  * Fetches all on-chain data needed to construct a {@link ReallocationData}
232
271
  * for computing vault reallocations via the public allocator.
@@ -379,6 +418,22 @@ export declare class MorphoMarketV1 implements MarketV1Actions {
379
418
  }) => Promise<(Requirement | Readonly<Transaction<ERC20ApprovalAction>> | Readonly<Transaction<MorphoAuthorizationAction>>)[]>;
380
419
  buildTx: (requirementSignature?: RequirementSignature) => Readonly<Transaction<MarketV1SupplyCollateralBorrowAction>>;
381
420
  };
421
+ refinance({ userAddress, positionData, target, collateralAmount, borrowAssets, borrowShares, slippageTolerance, targetReallocations, }: {
422
+ userAddress: Address;
423
+ positionData: AccrualPosition;
424
+ target: {
425
+ marketParams: MarketParams;
426
+ positionData: AccrualPosition;
427
+ };
428
+ collateralAmount: bigint;
429
+ borrowAssets?: bigint;
430
+ borrowShares?: bigint;
431
+ slippageTolerance?: bigint;
432
+ targetReallocations?: readonly VaultReallocation[];
433
+ }): {
434
+ getRequirements: () => Promise<Readonly<Transaction<MorphoAuthorizationAction>>[]>;
435
+ buildTx: () => Readonly<Transaction<MarketV1RefinanceAction>>;
436
+ };
382
437
  /**
383
438
  * Fetches all on-chain inputs needed to compute public allocator reallocations.
384
439
  *