@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 +47 -0
- package/lib/cjs/actions/marketV1/index.d.ts +1 -0
- package/lib/cjs/actions/marketV1/index.js +1 -0
- package/lib/cjs/actions/marketV1/refinance.d.ts +117 -0
- package/lib/cjs/actions/marketV1/refinance.js +218 -0
- package/lib/cjs/entities/marketV1/marketV1.d.ts +58 -3
- package/lib/cjs/entities/marketV1/marketV1.js +158 -0
- package/lib/cjs/types/action.d.ts +13 -1
- package/lib/cjs/types/error.d.ts +57 -0
- package/lib/cjs/types/error.js +82 -1
- package/lib/esm/actions/marketV1/index.d.ts +1 -0
- package/lib/esm/actions/marketV1/index.js +1 -0
- package/lib/esm/actions/marketV1/refinance.d.ts +117 -0
- package/lib/esm/actions/marketV1/refinance.js +214 -0
- package/lib/esm/entities/marketV1/marketV1.d.ts +58 -3
- package/lib/esm/entities/marketV1/marketV1.js +161 -3
- package/lib/esm/types/action.d.ts +13 -1
- package/lib/esm/types/error.d.ts +57 -0
- package/lib/esm/types/error.js +72 -0
- package/package.json +3 -3
|
@@ -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
|
+
};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type
|
|
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 {
|
|
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
|
*
|
|
@@ -152,6 +152,18 @@ export interface MarketV1RepayWithdrawCollateralAction extends BaseAction<"marke
|
|
|
152
152
|
receiver: Address;
|
|
153
153
|
}> {
|
|
154
154
|
}
|
|
155
|
+
export interface MarketV1RefinanceAction extends BaseAction<"marketV1Refinance", {
|
|
156
|
+
readonly sourceMarket: Hex;
|
|
157
|
+
readonly targetMarket: Hex;
|
|
158
|
+
readonly collateralAmount: bigint;
|
|
159
|
+
readonly borrowAssets: bigint;
|
|
160
|
+
readonly borrowShares: bigint;
|
|
161
|
+
readonly minBorrowSharePrice: bigint;
|
|
162
|
+
readonly maxRepaySharePrice: bigint;
|
|
163
|
+
readonly user: Address;
|
|
164
|
+
readonly reallocationFee: bigint;
|
|
165
|
+
}> {
|
|
166
|
+
}
|
|
155
167
|
/**
|
|
156
168
|
* Enforces that exactly one of `assets` / `shares` is provided.
|
|
157
169
|
*
|
|
@@ -173,7 +185,7 @@ export interface MorphoAuthorizationAction extends BaseAction<"morphoAuthorizati
|
|
|
173
185
|
isAuthorized: boolean;
|
|
174
186
|
}> {
|
|
175
187
|
}
|
|
176
|
-
export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1MigrateToV2Action | MarketV1SupplyAction | MarketV1WithdrawAction | MarketV1SupplyCollateralAction | MarketV1BorrowAction | MarketV1SupplyCollateralBorrowAction | MarketV1RepayAction | MarketV1WithdrawCollateralAction | MarketV1RepayWithdrawCollateralAction | MorphoAuthorizationAction;
|
|
188
|
+
export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1MigrateToV2Action | MarketV1SupplyAction | MarketV1WithdrawAction | MarketV1SupplyCollateralAction | MarketV1BorrowAction | MarketV1SupplyCollateralBorrowAction | MarketV1RepayAction | MarketV1WithdrawCollateralAction | MarketV1RepayWithdrawCollateralAction | MarketV1RefinanceAction | MorphoAuthorizationAction;
|
|
177
189
|
export interface Transaction<TAction extends BaseAction = TransactionAction> {
|
|
178
190
|
readonly to: Address;
|
|
179
191
|
readonly value: bigint;
|
package/lib/esm/types/error.d.ts
CHANGED
|
@@ -375,3 +375,60 @@ export declare class VaultAssetMismatchError extends Error {
|
|
|
375
375
|
export declare class NegativeMinSharePriceError extends Error {
|
|
376
376
|
constructor(vault: Address);
|
|
377
377
|
}
|
|
378
|
+
/** Thrown when a refinance's `borrowShares` argument is negative. */
|
|
379
|
+
export declare class NegativeBorrowSharesError extends Error {
|
|
380
|
+
constructor(market: string);
|
|
381
|
+
}
|
|
382
|
+
/** Thrown when a refinance specifies both `borrowAssets` and `borrowShares` as non-zero (modes are mutually exclusive). */
|
|
383
|
+
export declare class BorrowAmountAndSharesExclusiveError extends Error {
|
|
384
|
+
constructor(market: string);
|
|
385
|
+
}
|
|
386
|
+
/** Thrown when a refinance's `maxRepaySharePrice` slippage bound is negative. */
|
|
387
|
+
export declare class NegativeMaxRepaySharePriceError extends Error {
|
|
388
|
+
constructor(market: string);
|
|
389
|
+
}
|
|
390
|
+
/** Thrown when a refinance has identical source and target market ids (a refinance to the same market is a costly no-op). */
|
|
391
|
+
export declare class RefinanceSameMarketError extends Error {
|
|
392
|
+
constructor(market: string);
|
|
393
|
+
}
|
|
394
|
+
/** Thrown when a refinance's source and target markets do not share the same loan or collateral token. */
|
|
395
|
+
export declare class RefinanceTokenMismatchError extends Error {
|
|
396
|
+
constructor(sourceMarket: string, targetMarket: string);
|
|
397
|
+
}
|
|
398
|
+
/** Thrown when a refinance's `collateralAmount` exceeds the source position's available collateral. */
|
|
399
|
+
export declare class RefinanceExceedsCollateralError extends Error {
|
|
400
|
+
readonly market: string;
|
|
401
|
+
readonly requested: bigint;
|
|
402
|
+
readonly available: bigint;
|
|
403
|
+
constructor(params: {
|
|
404
|
+
market: string;
|
|
405
|
+
requested: bigint;
|
|
406
|
+
available: bigint;
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
/** Thrown when a refinance's `borrowShares` exceeds the source position's outstanding borrow shares. */
|
|
410
|
+
export declare class RefinanceExceedsBorrowSharesError extends Error {
|
|
411
|
+
readonly market: string;
|
|
412
|
+
readonly requested: bigint;
|
|
413
|
+
readonly available: bigint;
|
|
414
|
+
constructor(params: {
|
|
415
|
+
market: string;
|
|
416
|
+
requested: bigint;
|
|
417
|
+
available: bigint;
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
/** Thrown when a refinance's `borrowAssets` exceeds the source position's outstanding debt assets. */
|
|
421
|
+
export declare class RefinanceExceedsBorrowAssetsError extends Error {
|
|
422
|
+
readonly market: string;
|
|
423
|
+
readonly requested: bigint;
|
|
424
|
+
readonly available: bigint;
|
|
425
|
+
constructor(params: {
|
|
426
|
+
market: string;
|
|
427
|
+
requested: bigint;
|
|
428
|
+
available: bigint;
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
/** Thrown when a refinance in shares mode (`borrowShares > 0n`) omits the `borrowAssets` overshoot for the target borrow leg. */
|
|
432
|
+
export declare class RefinanceSharesMissingBorrowAssetsError extends Error {
|
|
433
|
+
constructor(market: string);
|
|
434
|
+
}
|
package/lib/esm/types/error.js
CHANGED
|
@@ -470,3 +470,75 @@ export class NegativeMinSharePriceError extends Error {
|
|
|
470
470
|
super(`Min share price must be non-negative for vault: ${vault}`);
|
|
471
471
|
}
|
|
472
472
|
}
|
|
473
|
+
/** Thrown when a refinance's `borrowShares` argument is negative. */
|
|
474
|
+
export class NegativeBorrowSharesError extends Error {
|
|
475
|
+
constructor(market) {
|
|
476
|
+
super(`Borrow shares must be non-negative for market: ${market}`);
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
/** Thrown when a refinance specifies both `borrowAssets` and `borrowShares` as non-zero (modes are mutually exclusive). */
|
|
480
|
+
export class BorrowAmountAndSharesExclusiveError extends Error {
|
|
481
|
+
constructor(market) {
|
|
482
|
+
super(`Exactly one of borrowAssets or borrowShares must be non-zero for market: ${market}. Both were provided.`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
/** Thrown when a refinance's `maxRepaySharePrice` slippage bound is negative. */
|
|
486
|
+
export class NegativeMaxRepaySharePriceError extends Error {
|
|
487
|
+
constructor(market) {
|
|
488
|
+
super(`Max repay share price must be non-negative for market: ${market}`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
/** Thrown when a refinance has identical source and target market ids (a refinance to the same market is a costly no-op). */
|
|
492
|
+
export class RefinanceSameMarketError extends Error {
|
|
493
|
+
constructor(market) {
|
|
494
|
+
super(`Refinance source and target market ${market} are identical. Refinance requires a different target market.`);
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
/** Thrown when a refinance's source and target markets do not share the same loan or collateral token. */
|
|
498
|
+
export class RefinanceTokenMismatchError extends Error {
|
|
499
|
+
constructor(sourceMarket, targetMarket) {
|
|
500
|
+
super(`Refinance source market ${sourceMarket} and target market ${targetMarket} must share the same loanToken and collateralToken.`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
/** Thrown when a refinance's `collateralAmount` exceeds the source position's available collateral. */
|
|
504
|
+
export class RefinanceExceedsCollateralError extends Error {
|
|
505
|
+
market;
|
|
506
|
+
requested;
|
|
507
|
+
available;
|
|
508
|
+
constructor(params) {
|
|
509
|
+
super(`Refinance collateral amount ${params.requested} exceeds available collateral ${params.available} for market: ${params.market}`);
|
|
510
|
+
this.market = params.market;
|
|
511
|
+
this.requested = params.requested;
|
|
512
|
+
this.available = params.available;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
/** Thrown when a refinance's `borrowShares` exceeds the source position's outstanding borrow shares. */
|
|
516
|
+
export class RefinanceExceedsBorrowSharesError extends Error {
|
|
517
|
+
market;
|
|
518
|
+
requested;
|
|
519
|
+
available;
|
|
520
|
+
constructor(params) {
|
|
521
|
+
super(`Refinance borrow shares ${params.requested} exceed outstanding borrow shares ${params.available} for market: ${params.market}`);
|
|
522
|
+
this.market = params.market;
|
|
523
|
+
this.requested = params.requested;
|
|
524
|
+
this.available = params.available;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
/** Thrown when a refinance's `borrowAssets` exceeds the source position's outstanding debt assets. */
|
|
528
|
+
export class RefinanceExceedsBorrowAssetsError extends Error {
|
|
529
|
+
market;
|
|
530
|
+
requested;
|
|
531
|
+
available;
|
|
532
|
+
constructor(params) {
|
|
533
|
+
super(`Refinance borrow assets ${params.requested} exceed outstanding debt assets ${params.available} for market: ${params.market}`);
|
|
534
|
+
this.market = params.market;
|
|
535
|
+
this.requested = params.requested;
|
|
536
|
+
this.available = params.available;
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
/** Thrown when a refinance in shares mode (`borrowShares > 0n`) omits the `borrowAssets` overshoot for the target borrow leg. */
|
|
540
|
+
export class RefinanceSharesMissingBorrowAssetsError extends Error {
|
|
541
|
+
constructor(market) {
|
|
542
|
+
super(`Refinance shares mode requires a positive borrowAssets overshoot for the target borrow leg (market: ${market}).`);
|
|
543
|
+
}
|
|
544
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@morpho-org/morpho-sdk",
|
|
3
3
|
"description": "Abstraction layer for Morpho's complexity.",
|
|
4
|
-
"version": "3.
|
|
4
|
+
"version": "3.2.0",
|
|
5
5
|
"author": "Morpho Association <contact@morpho.org>",
|
|
6
6
|
"contributors": [
|
|
7
7
|
"Foulks-Plb <https://x.com/FoulkPlb>"
|
|
@@ -138,8 +138,8 @@
|
|
|
138
138
|
"dependencies": {
|
|
139
139
|
"zod": "^4.4.3",
|
|
140
140
|
"@morpho-org/blue-sdk": "^6.1.0",
|
|
141
|
-
"@morpho-org/
|
|
142
|
-
"@morpho-org/
|
|
141
|
+
"@morpho-org/morpho-ts": "^2.6.0",
|
|
142
|
+
"@morpho-org/blue-sdk-viem": "^5.1.0"
|
|
143
143
|
},
|
|
144
144
|
"peerDependencies": {
|
|
145
145
|
"viem": "^2.0.0"
|