@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.
@@ -4,6 +4,7 @@ exports.MorphoMarketV1 = void 0;
4
4
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
6
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
+ const viem_1 = require("viem");
7
8
  const index_js_1 = require("../../actions/index.js");
8
9
  const index_js_2 = require("../../helpers/index.js");
9
10
  const index_js_3 = require("../../types/index.js");
@@ -561,6 +562,163 @@ class MorphoMarketV1 {
561
562
  }),
562
563
  };
563
564
  }
565
+ refinance({ userAddress, positionData, target, collateralAmount, borrowAssets, borrowShares, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, targetReallocations, }) {
566
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
567
+ (0, index_js_2.validateSlippageTolerance)(slippageTolerance);
568
+ if (collateralAmount <= 0n) {
569
+ throw new index_js_3.ZeroCollateralAmountError(this.marketParams.id);
570
+ }
571
+ if (!positionData) {
572
+ throw new index_js_3.MissingAccrualPositionError(this.marketParams.id);
573
+ }
574
+ (0, index_js_2.validateAccrualPosition)({
575
+ positionData,
576
+ expectedMarketId: this.marketParams.id,
577
+ expectedUser: userAddress,
578
+ });
579
+ if (this.marketParams.id === target.marketParams.id) {
580
+ throw new index_js_3.RefinanceSameMarketError(this.marketParams.id);
581
+ }
582
+ if (!(0, viem_1.isAddressEqual)(this.marketParams.collateralToken, target.marketParams.collateralToken) ||
583
+ !(0, viem_1.isAddressEqual)(this.marketParams.loanToken, target.marketParams.loanToken)) {
584
+ throw new index_js_3.RefinanceTokenMismatchError(this.marketParams.id, target.marketParams.id);
585
+ }
586
+ (0, index_js_2.validateAccrualPosition)({
587
+ positionData: target.positionData,
588
+ expectedMarketId: target.marketParams.id,
589
+ expectedUser: userAddress,
590
+ });
591
+ const requestedAssets = borrowAssets ?? 0n;
592
+ const requestedShares = borrowShares ?? 0n;
593
+ // Reject negative debt up front; otherwise it slips past the `> 0n` mode checks and only fails at buildTx().
594
+ if (requestedAssets < 0n) {
595
+ throw new index_js_3.NonPositiveAssetAmountError(this.marketParams.loanToken);
596
+ }
597
+ if (requestedShares < 0n) {
598
+ throw new index_js_3.NegativeBorrowSharesError(this.marketParams.id);
599
+ }
600
+ if (requestedAssets > 0n && requestedShares > 0n) {
601
+ throw new index_js_3.BorrowAmountAndSharesExclusiveError(this.marketParams.id);
602
+ }
603
+ const sharesMode = requestedShares > 0n;
604
+ const shouldMigrateBorrow = requestedAssets > 0n || sharesMode;
605
+ if (collateralAmount > positionData.collateral) {
606
+ throw new index_js_3.RefinanceExceedsCollateralError({
607
+ market: this.marketParams.id,
608
+ requested: collateralAmount,
609
+ available: positionData.collateral,
610
+ });
611
+ }
612
+ if (requestedShares > positionData.borrowShares) {
613
+ throw new index_js_3.RefinanceExceedsBorrowSharesError({
614
+ market: this.marketParams.id,
615
+ requested: requestedShares,
616
+ available: positionData.borrowShares,
617
+ });
618
+ }
619
+ if (requestedAssets > positionData.borrowAssets) {
620
+ throw new index_js_3.RefinanceExceedsBorrowAssetsError({
621
+ market: this.marketParams.id,
622
+ requested: requestedAssets,
623
+ available: positionData.borrowAssets,
624
+ });
625
+ }
626
+ // Forward-accrue both markets to now (clamped to lastUpdate). Source gets a 2h buffer in
627
+ // shares mode (as in repay()) for repay headroom; target accrues without buffer to avoid
628
+ // tightening minBorrowSharePrice past on-chain reality.
629
+ const sourceAccrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), positionData.market.lastUpdate) +
630
+ (sharesMode ? morpho_ts_1.Time.s.from.h(2n) : 0n);
631
+ const targetAccrualTimestamp = blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), target.positionData.market.lastUpdate);
632
+ const accruedSource = positionData.market.accrueInterest(sourceAccrualTimestamp);
633
+ const accruedTarget = target.positionData.market.accrueInterest(targetAccrualTimestamp);
634
+ // Shares burned by the source repay: exact in shares mode, else mirror Morpho's toSharesDown.
635
+ const repaidShares = sharesMode
636
+ ? requestedShares
637
+ : accruedSource.toBorrowShares(requestedAssets, "Down");
638
+ // Post-state source health: any remaining debt must stay healthy (accrued market).
639
+ const remainingCollateral = positionData.collateral - collateralAmount;
640
+ const remainingShares = positionData.borrowShares - repaidShares;
641
+ if (remainingShares > 0n) {
642
+ const residualPosition = new blue_sdk_1.AccrualPosition({
643
+ user: positionData.user,
644
+ supplyShares: positionData.supplyShares,
645
+ borrowShares: remainingShares,
646
+ collateral: remainingCollateral,
647
+ }, accruedSource);
648
+ (0, index_js_2.validatePositionHealth)({
649
+ positionData: residualPosition,
650
+ additionalCollateral: 0n,
651
+ borrowAmount: 0n,
652
+ marketId: this.marketParams.id,
653
+ lltv: this.marketParams.lltv,
654
+ });
655
+ }
656
+ const projectedBorrowAssets = sharesMode
657
+ ? accruedSource.toBorrowAssets(requestedShares, "Up")
658
+ : requestedAssets;
659
+ // Shares-mode overshoot covers target drift + accrual on the borrow leg. Computed before the
660
+ // LLTV check so health validates the actual on-chain borrow, not the smaller projected value.
661
+ const borrowAssetsAdjusted = sharesMode
662
+ ? blue_sdk_1.MathLib.wMulUp(projectedBorrowAssets, blue_sdk_1.MathLib.WAD + slippageTolerance)
663
+ : projectedBorrowAssets;
664
+ // Post-state target health: aggregate must respect LLTV − buffer. Skipped for collat-only
665
+ // refinances, which can't degrade target health and would fail on missing-oracle markets.
666
+ if (shouldMigrateBorrow) {
667
+ const accruedTargetPosition = target.positionData.accrueInterest(targetAccrualTimestamp);
668
+ (0, index_js_2.validatePositionHealth)({
669
+ positionData: accruedTargetPosition,
670
+ additionalCollateral: collateralAmount,
671
+ borrowAmount: borrowAssetsAdjusted,
672
+ marketId: target.marketParams.id,
673
+ lltv: target.marketParams.lltv,
674
+ });
675
+ }
676
+ // Share-price bounds only when a debt leg exists (helpers throw on zero inputs); else 0n.
677
+ // Derived from borrowAssetsAdjusted (the encoded value) so rounding can't push the on-chain
678
+ // ratio below a guard computed from the smaller projected amount.
679
+ const minBorrowSharePrice = shouldMigrateBorrow
680
+ ? (0, index_js_2.computeMinBorrowSharePrice)({
681
+ borrowAmount: borrowAssetsAdjusted,
682
+ market: accruedTarget,
683
+ slippageTolerance,
684
+ })
685
+ : 0n;
686
+ const maxRepaySharePrice = shouldMigrateBorrow
687
+ ? (0, index_js_2.computeMaxRepaySharePrice)({
688
+ repayAssets: requestedAssets,
689
+ repayShares: requestedShares,
690
+ market: accruedSource,
691
+ slippageTolerance,
692
+ })
693
+ : 0n;
694
+ return {
695
+ getRequirements: async () => {
696
+ const authTx = await (0, index_js_1.getMorphoAuthorizationRequirement)({
697
+ viemClient: this.client.viemClient,
698
+ chainId: this.chainId,
699
+ userAddress,
700
+ });
701
+ return authTx ? [authTx] : [];
702
+ },
703
+ buildTx: () => (0, index_js_1.marketV1Refinance)({
704
+ source: {
705
+ chainId: this.chainId,
706
+ marketParams: this.marketParams,
707
+ },
708
+ target: { marketParams: target.marketParams },
709
+ args: {
710
+ user: userAddress,
711
+ collateralAmount,
712
+ borrowAssets: borrowAssetsAdjusted,
713
+ borrowShares: requestedShares,
714
+ minBorrowSharePrice,
715
+ maxRepaySharePrice,
716
+ targetReallocations,
717
+ },
718
+ metadata: this.client.options.metadata,
719
+ }),
720
+ };
721
+ }
564
722
  /**
565
723
  * Fetches all on-chain inputs needed to compute public allocator reallocations.
566
724
  *
@@ -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;
@@ -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
+ }
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.UnknownReallocationVaultError = exports.UnknownReallocationMarketError = exports.InsufficientSharedLiquidityError = exports.DisabledReallocationMarketError = exports.MissingPublicAllocatorConfigError = exports.RepaySharesExceedDebtError = exports.InvalidSignatureError = exports.RepayExceedsDebtError = exports.ShareDivideByZeroError = exports.WithdrawMakesPositionUnhealthyError = exports.WithdrawExceedsCollateralError = exports.NonPositiveWithdrawCollateralAmountError = exports.NonPositiveRepayMaxSharePriceError = exports.NonPositiveRepayAmountError = exports.MutuallyExclusiveRepayAmountsError = exports.TransferAmountNotEqualToAssetsError = exports.NonPositiveTransferAmountError = exports.UnsortedReallocationWithdrawalsError = exports.ReallocationWithdrawalOnTargetMarketError = exports.NonPositiveReallocationAmountError = exports.EmptyReallocationWithdrawalsError = exports.NegativeReallocationFeeError = exports.AccrualPositionUserMismatchError = exports.MarketIdMismatchError = exports.MissingMarketPriceError = exports.BorrowExceedsSafeLtvError = exports.NativeAmountOnNonWNativeCollateralError = exports.NativeAmountOnNonWNativeAssetError = exports.ZeroCollateralAmountError = exports.NonPositiveBorrowAmountError = exports.VaultAddressMismatchError = exports.ZeroDepositAmountError = exports.NegativeNativeAmountError = exports.ChainWNativeMissingError = exports.NativeAmountOnNonWNativeVaultError = exports.Permit2ExpirationMissingError = exports.DepositAssetMismatchError = exports.DepositAmountMismatchError = exports.EmptyDeallocationsError = exports.ExcessiveSlippageToleranceError = exports.MissingAccrualPositionError = exports.NegativeSlippageToleranceError = exports.ApprovalAmountLessThanSpendAmountError = exports.MissingClientPropertyError = exports.ChainIdMismatchError = exports.AddressMismatchError = exports.NonPositiveMaxSharePriceError = exports.NonPositiveSharesAmountError = exports.NonPositiveAssetAmountError = exports.BundlerErrors = void 0;
4
- exports.NegativeMinSharePriceError = exports.VaultAssetMismatchError = exports.ReallocationWithdrawExceedsMarketSupplyError = exports.WithdrawSharesExceedSupplyError = exports.WithdrawExceedsSupplyError = exports.MutuallyExclusiveWithdrawAmountsError = exports.NegativeWithdrawMinSharePriceError = exports.NonPositiveWithdrawAmountError = exports.ZeroSupplyAmountError = exports.NegativeSupplyMaxSharePriceError = exports.NegativeSupplyAmountError = exports.NonPositiveMinBorrowSharePriceError = exports.UnknownReallocationPositionError = exports.UnknownReallocationVaultMarketConfigError = void 0;
4
+ exports.RefinanceSharesMissingBorrowAssetsError = exports.RefinanceExceedsBorrowAssetsError = exports.RefinanceExceedsBorrowSharesError = exports.RefinanceExceedsCollateralError = exports.RefinanceTokenMismatchError = exports.RefinanceSameMarketError = exports.NegativeMaxRepaySharePriceError = exports.BorrowAmountAndSharesExclusiveError = exports.NegativeBorrowSharesError = exports.NegativeMinSharePriceError = exports.VaultAssetMismatchError = exports.ReallocationWithdrawExceedsMarketSupplyError = exports.WithdrawSharesExceedSupplyError = exports.WithdrawExceedsSupplyError = exports.MutuallyExclusiveWithdrawAmountsError = exports.NegativeWithdrawMinSharePriceError = exports.NonPositiveWithdrawAmountError = exports.ZeroSupplyAmountError = exports.NegativeSupplyMaxSharePriceError = exports.NegativeSupplyAmountError = exports.NonPositiveMinBorrowSharePriceError = exports.UnknownReallocationPositionError = exports.UnknownReallocationVaultMarketConfigError = void 0;
5
5
  const blue_sdk_1 = require("@morpho-org/blue-sdk");
6
6
  /**
7
7
  * Typed errors thrown while encoding supported Bundler3 actions.
@@ -536,3 +536,84 @@ class NegativeMinSharePriceError extends Error {
536
536
  }
537
537
  }
538
538
  exports.NegativeMinSharePriceError = NegativeMinSharePriceError;
539
+ /** Thrown when a refinance's `borrowShares` argument is negative. */
540
+ class NegativeBorrowSharesError extends Error {
541
+ constructor(market) {
542
+ super(`Borrow shares must be non-negative for market: ${market}`);
543
+ }
544
+ }
545
+ exports.NegativeBorrowSharesError = NegativeBorrowSharesError;
546
+ /** Thrown when a refinance specifies both `borrowAssets` and `borrowShares` as non-zero (modes are mutually exclusive). */
547
+ class BorrowAmountAndSharesExclusiveError extends Error {
548
+ constructor(market) {
549
+ super(`Exactly one of borrowAssets or borrowShares must be non-zero for market: ${market}. Both were provided.`);
550
+ }
551
+ }
552
+ exports.BorrowAmountAndSharesExclusiveError = BorrowAmountAndSharesExclusiveError;
553
+ /** Thrown when a refinance's `maxRepaySharePrice` slippage bound is negative. */
554
+ class NegativeMaxRepaySharePriceError extends Error {
555
+ constructor(market) {
556
+ super(`Max repay share price must be non-negative for market: ${market}`);
557
+ }
558
+ }
559
+ exports.NegativeMaxRepaySharePriceError = NegativeMaxRepaySharePriceError;
560
+ /** Thrown when a refinance has identical source and target market ids (a refinance to the same market is a costly no-op). */
561
+ class RefinanceSameMarketError extends Error {
562
+ constructor(market) {
563
+ super(`Refinance source and target market ${market} are identical. Refinance requires a different target market.`);
564
+ }
565
+ }
566
+ exports.RefinanceSameMarketError = RefinanceSameMarketError;
567
+ /** Thrown when a refinance's source and target markets do not share the same loan or collateral token. */
568
+ class RefinanceTokenMismatchError extends Error {
569
+ constructor(sourceMarket, targetMarket) {
570
+ super(`Refinance source market ${sourceMarket} and target market ${targetMarket} must share the same loanToken and collateralToken.`);
571
+ }
572
+ }
573
+ exports.RefinanceTokenMismatchError = RefinanceTokenMismatchError;
574
+ /** Thrown when a refinance's `collateralAmount` exceeds the source position's available collateral. */
575
+ class RefinanceExceedsCollateralError extends Error {
576
+ market;
577
+ requested;
578
+ available;
579
+ constructor(params) {
580
+ super(`Refinance collateral amount ${params.requested} exceeds available collateral ${params.available} for market: ${params.market}`);
581
+ this.market = params.market;
582
+ this.requested = params.requested;
583
+ this.available = params.available;
584
+ }
585
+ }
586
+ exports.RefinanceExceedsCollateralError = RefinanceExceedsCollateralError;
587
+ /** Thrown when a refinance's `borrowShares` exceeds the source position's outstanding borrow shares. */
588
+ class RefinanceExceedsBorrowSharesError extends Error {
589
+ market;
590
+ requested;
591
+ available;
592
+ constructor(params) {
593
+ super(`Refinance borrow shares ${params.requested} exceed outstanding borrow shares ${params.available} for market: ${params.market}`);
594
+ this.market = params.market;
595
+ this.requested = params.requested;
596
+ this.available = params.available;
597
+ }
598
+ }
599
+ exports.RefinanceExceedsBorrowSharesError = RefinanceExceedsBorrowSharesError;
600
+ /** Thrown when a refinance's `borrowAssets` exceeds the source position's outstanding debt assets. */
601
+ class RefinanceExceedsBorrowAssetsError extends Error {
602
+ market;
603
+ requested;
604
+ available;
605
+ constructor(params) {
606
+ super(`Refinance borrow assets ${params.requested} exceed outstanding debt assets ${params.available} for market: ${params.market}`);
607
+ this.market = params.market;
608
+ this.requested = params.requested;
609
+ this.available = params.available;
610
+ }
611
+ }
612
+ exports.RefinanceExceedsBorrowAssetsError = RefinanceExceedsBorrowAssetsError;
613
+ /** Thrown when a refinance in shares mode (`borrowShares > 0n`) omits the `borrowAssets` overshoot for the target borrow leg. */
614
+ class RefinanceSharesMissingBorrowAssetsError extends Error {
615
+ constructor(market) {
616
+ super(`Refinance shares mode requires a positive borrowAssets overshoot for the target borrow leg (market: ${market}).`);
617
+ }
618
+ }
619
+ exports.RefinanceSharesMissingBorrowAssetsError = RefinanceSharesMissingBorrowAssetsError;
@@ -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";
@@ -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";
@@ -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>>;