@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.
@@ -0,0 +1,214 @@
1
+ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
+ import { deepFreeze } from "@morpho-org/morpho-ts";
3
+ import { isAddressEqual, maxUint256 } from "viem";
4
+ import { BundlerAction } from "../../bundler/index.js";
5
+ import { addTransactionMetadata } from "../../helpers/index.js";
6
+ import { NegativeBorrowSharesError, NegativeMaxRepaySharePriceError, NonPositiveAssetAmountError, NonPositiveMinBorrowSharePriceError, NonPositiveRepayMaxSharePriceError, RefinanceSameMarketError, RefinanceSharesMissingBorrowAssetsError, RefinanceTokenMismatchError, ZeroCollateralAmountError, } from "../../types/index.js";
7
+ import { buildReallocationActions } from "./buildReallocationActions.js";
8
+ /**
9
+ * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
10
+ * chain that shares the same loan and collateral tokens.
11
+ *
12
+ * Strategy: flash-collateral via the target's `onMorphoSupplyCollateral` callback. The collateral
13
+ * is credited before the deferred `safeTransferFrom`, so inside the callback GA1 borrows on the
14
+ * target, repays the source, then withdraws the source collateral to settle the transfer.
15
+ *
16
+ * Bundle shape (callback contents depend on borrow mode):
17
+ *
18
+ * ```text
19
+ * // optional: one reallocateTo per targetReallocations entry, run first
20
+ * reallocateTo(vault_i, fee_i, withdrawals_i, target, false),
21
+ *
22
+ * morphoSupplyCollateral(target, collateralAmount, user, [
23
+ * // omitted in collat-only mode
24
+ * morphoBorrow(target, borrowAssets, 0, minBorrowSharePrice, GA1),
25
+ * morphoRepay(source, assets|0, 0|shares, maxRepaySharePrice, user, []),
26
+ * // shares mode only: sweep overshoot before the withdraw so same-token markets aren't drained
27
+ * morphoRepay(target, maxUint256, 0, maxUint256, user, [], skipRevert=true),
28
+ * // shares mode only: fallback if the repay is skipped, skim residual loan tokens to the user
29
+ * erc20Transfer(loanToken, user, maxUint256, GA1, skipRevert=false),
30
+ * morphoWithdrawCollateral(source, collateralAmount, GA1),
31
+ * ])
32
+ * ```
33
+ *
34
+ * Borrow modes:
35
+ *
36
+ * - **Assets mode** (`borrowAssets > 0n`): exact-asset borrow and repay, no GA1 dust.
37
+ * - **Shares mode** (`borrowShares > 0n`, `borrowAssets` is the overshoot): the trailing
38
+ * `morphoRepay(target, maxUint256, …, skipRevert=true)` sweeps the residual into the target debt,
39
+ * then an `erc20Transfer` skims any residual to the user if that repay is skipped.
40
+ * - **Collat-only** (both zero/omitted): only collateral is migrated; borrow/repay legs omitted.
41
+ *
42
+ * Prerequisite: GA1 must be authorized on Morpho — the entity's `getRequirements()` returns the
43
+ * `setAuthorization` transaction when needed.
44
+ *
45
+ * @param params.source.chainId - The chain both markets live on.
46
+ * @param params.source.marketParams - Source market params (the position being closed).
47
+ * @param params.target.marketParams - Target market params; must share both tokens with the source.
48
+ * @param params.args.user - Position owner on both markets.
49
+ * @param params.args.collateralAmount - Amount of collateral to migrate.
50
+ * @param params.args.borrowAssets - Loan assets to borrow on the target; exclusive with `borrowShares`. Defaults to `0n`.
51
+ * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
52
+ * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
53
+ * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
54
+ * @param params.args.targetReallocations - PublicAllocator reallocations into the target, run before the supply leg.
55
+ * @param params.metadata - Optional analytics metadata appended to `tx.data`.
56
+ * @returns A deep-frozen `Transaction<MarketV1RefinanceAction>`.
57
+ * @remarks `borrowAssets` and `borrowShares` describe different markets (target borrow vs. source
58
+ * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
59
+ * @throws {ZeroCollateralAmountError} when `collateralAmount <= 0n`.
60
+ * @throws {NonPositiveAssetAmountError} when `borrowAssets < 0n`.
61
+ * @throws {NegativeBorrowSharesError} when `borrowShares < 0n`.
62
+ * @throws {NonPositiveMinBorrowSharePriceError} when `minBorrowSharePrice < 0n`.
63
+ * @throws {NegativeMaxRepaySharePriceError} when `maxRepaySharePrice < 0n`.
64
+ * @throws {RefinanceSameMarketError} when source and target market ids are equal.
65
+ * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
66
+ * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
67
+ * @throws {NonPositiveRepayMaxSharePriceError} when a repay leg is encoded and `maxRepaySharePrice <= 0n`.
68
+ * @throws {NegativeReallocationFeeError} when any `reallocation.fee < 0n`.
69
+ * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
70
+ * @throws {NonPositiveReallocationAmountError} when any `reallocation.withdrawals[i].amount <= 0n`.
71
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references the target market.
72
+ * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly sorted by market id.
73
+ * @example
74
+ * ```ts
75
+ * import { marketV1Refinance } from "@morpho-org/morpho-sdk";
76
+ *
77
+ * const tx = marketV1Refinance({
78
+ * source: { chainId: 1, marketParams: sourceParams },
79
+ * target: { marketParams: targetParams },
80
+ * args: {
81
+ * user: borrower,
82
+ * collateralAmount: 1_000_000_000_000_000_000n,
83
+ * borrowShares: 500_000_000_000n,
84
+ * borrowAssets: 501_000_000n, // overshoot computed by entity layer
85
+ * minBorrowSharePrice: 0n,
86
+ * maxRepaySharePrice: 1_500_000_000_000_000_000_000_000_000n,
87
+ * },
88
+ * });
89
+ * // tx satisfies Readonly<Transaction<MarketV1RefinanceAction>>
90
+ * ```
91
+ */
92
+ export const marketV1Refinance = ({ source: { chainId, marketParams: sourceParams }, target: { marketParams: targetParams }, args: { user, collateralAmount, borrowAssets = 0n, borrowShares = 0n, minBorrowSharePrice, maxRepaySharePrice, targetReallocations, }, metadata, }) => {
93
+ if (collateralAmount <= 0n) {
94
+ throw new ZeroCollateralAmountError(sourceParams.id);
95
+ }
96
+ if (borrowAssets < 0n) {
97
+ throw new NonPositiveAssetAmountError(sourceParams.loanToken);
98
+ }
99
+ if (borrowShares < 0n) {
100
+ throw new NegativeBorrowSharesError(sourceParams.id);
101
+ }
102
+ if (minBorrowSharePrice < 0n) {
103
+ throw new NonPositiveMinBorrowSharePriceError(targetParams.id);
104
+ }
105
+ if (maxRepaySharePrice < 0n) {
106
+ throw new NegativeMaxRepaySharePriceError(sourceParams.id);
107
+ }
108
+ if (sourceParams.id === targetParams.id) {
109
+ throw new RefinanceSameMarketError(sourceParams.id);
110
+ }
111
+ if (!isAddressEqual(sourceParams.collateralToken, targetParams.collateralToken) ||
112
+ !isAddressEqual(sourceParams.loanToken, targetParams.loanToken)) {
113
+ throw new RefinanceTokenMismatchError(sourceParams.id, targetParams.id);
114
+ }
115
+ const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
116
+ const sharesMode = borrowShares > 0n;
117
+ const shouldMigrateBorrow = borrowAssets > 0n || sharesMode;
118
+ // Shares mode borrows in assets; Morpho rejects a zero borrow, so require a positive overshoot.
119
+ if (sharesMode && borrowAssets <= 0n) {
120
+ throw new RefinanceSharesMissingBorrowAssetsError(sourceParams.id);
121
+ }
122
+ // A repay leg with maxRepaySharePrice = 0n always reverts; require a positive cap when debt is migrated.
123
+ if (shouldMigrateBorrow && maxRepaySharePrice <= 0n) {
124
+ throw new NonPositiveRepayMaxSharePriceError(sourceParams.id);
125
+ }
126
+ const callback = [];
127
+ if (shouldMigrateBorrow) {
128
+ callback.push({
129
+ type: "morphoBorrow",
130
+ args: [
131
+ targetParams,
132
+ borrowAssets,
133
+ 0n,
134
+ minBorrowSharePrice,
135
+ generalAdapter1,
136
+ false,
137
+ ],
138
+ });
139
+ callback.push(sharesMode
140
+ ? {
141
+ type: "morphoRepay",
142
+ args: [
143
+ sourceParams,
144
+ 0n,
145
+ borrowShares,
146
+ maxRepaySharePrice,
147
+ user,
148
+ [],
149
+ false,
150
+ ],
151
+ }
152
+ : {
153
+ type: "morphoRepay",
154
+ args: [
155
+ sourceParams,
156
+ borrowAssets,
157
+ 0n,
158
+ maxRepaySharePrice,
159
+ user,
160
+ [],
161
+ false,
162
+ ],
163
+ });
164
+ }
165
+ // Sweep the borrow overshoot back into target debt so GA1 ends drained. Must run before the
166
+ // withdraw: in same-token markets maxUint256 would otherwise drain the just-withdrawn collateral.
167
+ if (sharesMode) {
168
+ callback.push({
169
+ type: "morphoRepay",
170
+ args: [targetParams, maxUint256, 0n, maxUint256, user, [], true],
171
+ });
172
+ // Fallback: if the repay above is skipped, skim any residual loan tokens to the user.
173
+ callback.push({
174
+ type: "erc20Transfer",
175
+ args: [targetParams.loanToken, user, maxUint256, generalAdapter1, false],
176
+ });
177
+ }
178
+ callback.push({
179
+ type: "morphoWithdrawCollateral",
180
+ args: [sourceParams, collateralAmount, generalAdapter1, false],
181
+ });
182
+ const actions = [];
183
+ let reallocationFee = 0n;
184
+ if (targetReallocations && targetReallocations.length > 0) {
185
+ const result = buildReallocationActions(targetReallocations, targetParams);
186
+ actions.push(...result.actions);
187
+ reallocationFee = result.fee;
188
+ }
189
+ actions.push({
190
+ type: "morphoSupplyCollateral",
191
+ args: [targetParams, collateralAmount, user, callback, false],
192
+ });
193
+ let tx = BundlerAction.encodeBundle(chainId, actions);
194
+ if (metadata) {
195
+ tx = addTransactionMetadata(tx, metadata);
196
+ }
197
+ return deepFreeze({
198
+ ...tx,
199
+ action: {
200
+ type: "marketV1Refinance",
201
+ args: {
202
+ sourceMarket: sourceParams.id,
203
+ targetMarket: targetParams.id,
204
+ collateralAmount,
205
+ borrowAssets,
206
+ borrowShares,
207
+ minBorrowSharePrice,
208
+ maxRepaySharePrice,
209
+ user,
210
+ reallocationFee,
211
+ },
212
+ },
213
+ });
214
+ };
@@ -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
  *
@@ -173,8 +173,8 @@ export var BundlerAction;
173
173
  return BundlerAction.morphoWithdraw(chainId, ...args);
174
174
  }
175
175
  case "morphoRepay": {
176
- const [market, assets, shares, slippageAmount, onBehalf, onMorphoRepay, skipRevert,] = args;
177
- return BundlerAction.morphoRepay(chainId, market, assets, shares, slippageAmount, onBehalf, onMorphoRepay.flatMap(BundlerAction.encode.bind(null, chainId)), skipRevert);
176
+ const [market, assets, shares, maxSharePrice, onBehalf, onMorphoRepay, skipRevert,] = args;
177
+ return BundlerAction.morphoRepay(chainId, market, assets, shares, maxSharePrice, onBehalf, onMorphoRepay.flatMap(BundlerAction.encode.bind(null, chainId)), skipRevert);
178
178
  }
179
179
  case "morphoWithdrawCollateral": {
180
180
  return BundlerAction.morphoWithdrawCollateral(chainId, ...args);
@@ -763,7 +763,7 @@ export var BundlerAction;
763
763
  * @param market - Morpho Blue market parameters.
764
764
  * @param assets - Borrow asset amount.
765
765
  * @param shares - Borrow share amount.
766
- * @param slippageAmount - Slippage guard amount.
766
+ * @param minSharePrice - Minimum amount of borrowed assets per borrow share minted, scaled by 1e27.
767
767
  * @param receiver - Recipient of borrowed assets.
768
768
  * @param skipRevert - Whether Bundler3 should tolerate a revert.
769
769
  * @returns Encoded Bundler3 calls.
@@ -796,7 +796,7 @@ export var BundlerAction;
796
796
  * ```
797
797
  */
798
798
  // biome-ignore lint/complexity/useMaxParams: TODO refactor to ≤2 params
799
- function morphoBorrow(chainId, market, assets, shares, slippageAmount, receiver, skipRevert = false) {
799
+ function morphoBorrow(chainId, market, assets, shares, minSharePrice, receiver, skipRevert = false) {
800
800
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
801
801
  return [
802
802
  {
@@ -804,7 +804,7 @@ export var BundlerAction;
804
804
  data: encodeFunctionData({
805
805
  abi: generalAdapter1Abi,
806
806
  functionName: "morphoBorrow",
807
- args: [market, assets, shares, slippageAmount, receiver],
807
+ args: [market, assets, shares, minSharePrice, receiver],
808
808
  }),
809
809
  value: 0n,
810
810
  skipRevert,
@@ -820,7 +820,7 @@ export var BundlerAction;
820
820
  * @param market - Morpho Blue market parameters.
821
821
  * @param assets - Repay asset amount.
822
822
  * @param shares - Repay share amount.
823
- * @param slippageAmount - Slippage guard amount.
823
+ * @param maxSharePrice - Maximum amount of repaid assets per borrow share redeemed, scaled by 1e27.
824
824
  * @param onBehalf - Account whose borrow is repaid.
825
825
  * @param callbackCalls - Calls executed in Morpho's callback.
826
826
  * @param skipRevert - Whether Bundler3 should tolerate a revert.
@@ -855,7 +855,7 @@ export var BundlerAction;
855
855
  * ```
856
856
  */
857
857
  // biome-ignore lint/complexity/useMaxParams: TODO refactor to ≤2 params
858
- function morphoRepay(chainId, market, assets, shares, slippageAmount, onBehalf, callbackCalls, skipRevert = false) {
858
+ function morphoRepay(chainId, market, assets, shares, maxSharePrice, onBehalf, callbackCalls, skipRevert = false) {
859
859
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
860
860
  const { callbackHash, reenterData } = encodeCallbackCalls(callbackCalls);
861
861
  return [
@@ -864,7 +864,7 @@ export var BundlerAction;
864
864
  data: encodeFunctionData({
865
865
  abi: generalAdapter1Abi,
866
866
  functionName: "morphoRepay",
867
- args: [market, assets, shares, slippageAmount, onBehalf, reenterData],
867
+ args: [market, assets, shares, maxSharePrice, onBehalf, reenterData],
868
868
  }),
869
869
  value: 0n,
870
870
  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
@@ -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
  *
@@ -1,9 +1,10 @@
1
- import { DEFAULT_SLIPPAGE_TOLERANCE, MathLib, } from "@morpho-org/blue-sdk";
1
+ import { AccrualPosition, DEFAULT_SLIPPAGE_TOLERANCE, MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualPosition, fetchMarket, fetchPosition, fetchVault, fetchVaultMarketConfig, } from "@morpho-org/blue-sdk-viem";
3
3
  import { Time } from "@morpho-org/morpho-ts";
4
- import { getMorphoAuthorizationRequirement, getRequirements, marketV1Borrow, marketV1Repay, marketV1RepayWithdrawCollateral, marketV1Supply, marketV1SupplyCollateral, marketV1SupplyCollateralBorrow, marketV1Withdraw, marketV1WithdrawCollateral, } from "../../actions/index.js";
4
+ import { isAddressEqual } from "viem";
5
+ import { getMorphoAuthorizationRequirement, getRequirements, marketV1Borrow, marketV1Refinance, marketV1Repay, marketV1RepayWithdrawCollateral, marketV1Supply, marketV1SupplyCollateral, marketV1SupplyCollateralBorrow, marketV1Withdraw, marketV1WithdrawCollateral, } from "../../actions/index.js";
5
6
  import { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, computeReallocations, validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
6
- import { MarketIdMismatchError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeNativeAmountError, NegativeSupplyAmountError, NonPositiveAssetAmountError, NonPositiveBorrowAmountError, NonPositiveRepayAmountError, NonPositiveWithdrawAmountError, NonPositiveWithdrawCollateralAmountError, WithdrawExceedsCollateralError, ZeroCollateralAmountError, ZeroSupplyAmountError, } from "../../types/index.js";
7
+ import { BorrowAmountAndSharesExclusiveError, MarketIdMismatchError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeBorrowSharesError, NegativeNativeAmountError, NegativeSupplyAmountError, NonPositiveAssetAmountError, NonPositiveBorrowAmountError, NonPositiveRepayAmountError, NonPositiveWithdrawAmountError, NonPositiveWithdrawCollateralAmountError, RefinanceExceedsBorrowAssetsError, RefinanceExceedsBorrowSharesError, RefinanceExceedsCollateralError, RefinanceSameMarketError, RefinanceTokenMismatchError, WithdrawExceedsCollateralError, ZeroCollateralAmountError, ZeroSupplyAmountError, } from "../../types/index.js";
7
8
  import { ReallocationData } from "../reallocationData.js";
8
9
  export class MorphoMarketV1 {
9
10
  client;
@@ -558,6 +559,163 @@ export class MorphoMarketV1 {
558
559
  }),
559
560
  };
560
561
  }
562
+ refinance({ userAddress, positionData, target, collateralAmount, borrowAssets, borrowShares, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, targetReallocations, }) {
563
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
564
+ validateSlippageTolerance(slippageTolerance);
565
+ if (collateralAmount <= 0n) {
566
+ throw new ZeroCollateralAmountError(this.marketParams.id);
567
+ }
568
+ if (!positionData) {
569
+ throw new MissingAccrualPositionError(this.marketParams.id);
570
+ }
571
+ validateAccrualPosition({
572
+ positionData,
573
+ expectedMarketId: this.marketParams.id,
574
+ expectedUser: userAddress,
575
+ });
576
+ if (this.marketParams.id === target.marketParams.id) {
577
+ throw new RefinanceSameMarketError(this.marketParams.id);
578
+ }
579
+ if (!isAddressEqual(this.marketParams.collateralToken, target.marketParams.collateralToken) ||
580
+ !isAddressEqual(this.marketParams.loanToken, target.marketParams.loanToken)) {
581
+ throw new RefinanceTokenMismatchError(this.marketParams.id, target.marketParams.id);
582
+ }
583
+ validateAccrualPosition({
584
+ positionData: target.positionData,
585
+ expectedMarketId: target.marketParams.id,
586
+ expectedUser: userAddress,
587
+ });
588
+ const requestedAssets = borrowAssets ?? 0n;
589
+ const requestedShares = borrowShares ?? 0n;
590
+ // Reject negative debt up front; otherwise it slips past the `> 0n` mode checks and only fails at buildTx().
591
+ if (requestedAssets < 0n) {
592
+ throw new NonPositiveAssetAmountError(this.marketParams.loanToken);
593
+ }
594
+ if (requestedShares < 0n) {
595
+ throw new NegativeBorrowSharesError(this.marketParams.id);
596
+ }
597
+ if (requestedAssets > 0n && requestedShares > 0n) {
598
+ throw new BorrowAmountAndSharesExclusiveError(this.marketParams.id);
599
+ }
600
+ const sharesMode = requestedShares > 0n;
601
+ const shouldMigrateBorrow = requestedAssets > 0n || sharesMode;
602
+ if (collateralAmount > positionData.collateral) {
603
+ throw new RefinanceExceedsCollateralError({
604
+ market: this.marketParams.id,
605
+ requested: collateralAmount,
606
+ available: positionData.collateral,
607
+ });
608
+ }
609
+ if (requestedShares > positionData.borrowShares) {
610
+ throw new RefinanceExceedsBorrowSharesError({
611
+ market: this.marketParams.id,
612
+ requested: requestedShares,
613
+ available: positionData.borrowShares,
614
+ });
615
+ }
616
+ if (requestedAssets > positionData.borrowAssets) {
617
+ throw new RefinanceExceedsBorrowAssetsError({
618
+ market: this.marketParams.id,
619
+ requested: requestedAssets,
620
+ available: positionData.borrowAssets,
621
+ });
622
+ }
623
+ // Forward-accrue both markets to now (clamped to lastUpdate). Source gets a 2h buffer in
624
+ // shares mode (as in repay()) for repay headroom; target accrues without buffer to avoid
625
+ // tightening minBorrowSharePrice past on-chain reality.
626
+ const sourceAccrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
627
+ (sharesMode ? Time.s.from.h(2n) : 0n);
628
+ const targetAccrualTimestamp = MathLib.max(Time.timestamp(), target.positionData.market.lastUpdate);
629
+ const accruedSource = positionData.market.accrueInterest(sourceAccrualTimestamp);
630
+ const accruedTarget = target.positionData.market.accrueInterest(targetAccrualTimestamp);
631
+ // Shares burned by the source repay: exact in shares mode, else mirror Morpho's toSharesDown.
632
+ const repaidShares = sharesMode
633
+ ? requestedShares
634
+ : accruedSource.toBorrowShares(requestedAssets, "Down");
635
+ // Post-state source health: any remaining debt must stay healthy (accrued market).
636
+ const remainingCollateral = positionData.collateral - collateralAmount;
637
+ const remainingShares = positionData.borrowShares - repaidShares;
638
+ if (remainingShares > 0n) {
639
+ const residualPosition = new AccrualPosition({
640
+ user: positionData.user,
641
+ supplyShares: positionData.supplyShares,
642
+ borrowShares: remainingShares,
643
+ collateral: remainingCollateral,
644
+ }, accruedSource);
645
+ validatePositionHealth({
646
+ positionData: residualPosition,
647
+ additionalCollateral: 0n,
648
+ borrowAmount: 0n,
649
+ marketId: this.marketParams.id,
650
+ lltv: this.marketParams.lltv,
651
+ });
652
+ }
653
+ const projectedBorrowAssets = sharesMode
654
+ ? accruedSource.toBorrowAssets(requestedShares, "Up")
655
+ : requestedAssets;
656
+ // Shares-mode overshoot covers target drift + accrual on the borrow leg. Computed before the
657
+ // LLTV check so health validates the actual on-chain borrow, not the smaller projected value.
658
+ const borrowAssetsAdjusted = sharesMode
659
+ ? MathLib.wMulUp(projectedBorrowAssets, MathLib.WAD + slippageTolerance)
660
+ : projectedBorrowAssets;
661
+ // Post-state target health: aggregate must respect LLTV − buffer. Skipped for collat-only
662
+ // refinances, which can't degrade target health and would fail on missing-oracle markets.
663
+ if (shouldMigrateBorrow) {
664
+ const accruedTargetPosition = target.positionData.accrueInterest(targetAccrualTimestamp);
665
+ validatePositionHealth({
666
+ positionData: accruedTargetPosition,
667
+ additionalCollateral: collateralAmount,
668
+ borrowAmount: borrowAssetsAdjusted,
669
+ marketId: target.marketParams.id,
670
+ lltv: target.marketParams.lltv,
671
+ });
672
+ }
673
+ // Share-price bounds only when a debt leg exists (helpers throw on zero inputs); else 0n.
674
+ // Derived from borrowAssetsAdjusted (the encoded value) so rounding can't push the on-chain
675
+ // ratio below a guard computed from the smaller projected amount.
676
+ const minBorrowSharePrice = shouldMigrateBorrow
677
+ ? computeMinBorrowSharePrice({
678
+ borrowAmount: borrowAssetsAdjusted,
679
+ market: accruedTarget,
680
+ slippageTolerance,
681
+ })
682
+ : 0n;
683
+ const maxRepaySharePrice = shouldMigrateBorrow
684
+ ? computeMaxRepaySharePrice({
685
+ repayAssets: requestedAssets,
686
+ repayShares: requestedShares,
687
+ market: accruedSource,
688
+ slippageTolerance,
689
+ })
690
+ : 0n;
691
+ return {
692
+ getRequirements: async () => {
693
+ const authTx = await getMorphoAuthorizationRequirement({
694
+ viemClient: this.client.viemClient,
695
+ chainId: this.chainId,
696
+ userAddress,
697
+ });
698
+ return authTx ? [authTx] : [];
699
+ },
700
+ buildTx: () => marketV1Refinance({
701
+ source: {
702
+ chainId: this.chainId,
703
+ marketParams: this.marketParams,
704
+ },
705
+ target: { marketParams: target.marketParams },
706
+ args: {
707
+ user: userAddress,
708
+ collateralAmount,
709
+ borrowAssets: borrowAssetsAdjusted,
710
+ borrowShares: requestedShares,
711
+ minBorrowSharePrice,
712
+ maxRepaySharePrice,
713
+ targetReallocations,
714
+ },
715
+ metadata: this.client.options.metadata,
716
+ }),
717
+ };
718
+ }
561
719
  /**
562
720
  * Fetches all on-chain inputs needed to compute public allocator reallocations.
563
721
  *
@@ -282,6 +282,7 @@ export class ReallocationData {
282
282
  if (count <= 1)
283
283
  continue;
284
284
  const vaultPublicAllocatorConfig = data.getVault(vault).publicAllocatorConfig;
285
+ /* v8 ignore next: repeated withdrawals require a configured public allocator earlier in the flow. */
285
286
  if (vaultPublicAllocatorConfig == null)
286
287
  throw new MissingPublicAllocatorConfigError(vault);
287
288
  vaultPublicAllocatorConfig.accruedFee -=
@@ -354,7 +355,9 @@ export class ReallocationData {
354
355
  applyPublicReallocation({ vault, supplyMarketId, withdrawal, timestamp, }) {
355
356
  const data = this.forkAliasedState();
356
357
  data.vaults[vault] = cloneVault(this.getVault(vault));
358
+ /* v8 ignore next: forkAliasedState keeps vault position buckets initialized for known vaults. */
357
359
  data.positions[vault] = { ...(this.positions[vault] ?? {}) };
360
+ /* v8 ignore next: forkAliasedState keeps vault market config buckets initialized for known vaults. */
358
361
  data.vaultMarketConfigs[vault] = {
359
362
  ...(this.vaultMarketConfigs[vault] ?? {}),
360
363
  };
@@ -35,6 +35,7 @@ const capVaultWithdrawals = (withdrawals, assets) => {
35
35
  let remainingAssets = assets;
36
36
  for (const withdrawal of withdrawals) {
37
37
  const cappedAssets = MathLib.min(withdrawal.assets, remainingAssets);
38
+ /* v8 ignore next: grouped withdrawals and positive reallocation cap keep this defensive guard unreachable. */
38
39
  if (cappedAssets <= 0n)
39
40
  continue;
40
41
  const existing = cappedWithdrawals.find((item) => item.id === withdrawal.id);
@@ -185,6 +186,7 @@ export const computeReallocations = ({ reallocationData: data, marketId, operati
185
186
  let remainingRequiredAssets = requiredAssets;
186
187
  for (const group of groupWithdrawalsByVault(withdrawals)) {
187
188
  const reallocatedAssets = MathLib.min(group.totalAssets, remainingRequiredAssets);
189
+ /* v8 ignore next: groups with non-positive assets are filtered before this point. */
188
190
  if (reallocatedAssets <= 0n)
189
191
  continue;
190
192
  reallocations.push({