@morpho-org/morpho-sdk 5.9.0 → 6.0.0-next.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.
Files changed (141) hide show
  1. package/MIGRATION-v5-to-v6.md +201 -0
  2. package/README.md +58 -40
  3. package/lib/cjs/actions/blue/borrow.d.ts +62 -61
  4. package/lib/cjs/actions/blue/borrow.js +48 -80
  5. package/lib/cjs/actions/blue/common.d.ts +99 -0
  6. package/lib/cjs/actions/blue/common.js +318 -0
  7. package/lib/cjs/actions/blue/refinance.d.ts +72 -112
  8. package/lib/cjs/actions/blue/refinance.js +97 -199
  9. package/lib/cjs/actions/blue/repay.d.ts +72 -68
  10. package/lib/cjs/actions/blue/repay.js +56 -118
  11. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  12. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +148 -137
  13. package/lib/cjs/actions/blue/supply.d.ts +62 -45
  14. package/lib/cjs/actions/blue/supply.js +94 -70
  15. package/lib/cjs/actions/blue/supplyCollateral.d.ts +63 -40
  16. package/lib/cjs/actions/blue/supplyCollateral.js +52 -69
  17. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  18. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +133 -120
  19. package/lib/cjs/actions/blue/withdraw.d.ts +68 -79
  20. package/lib/cjs/actions/blue/withdraw.js +101 -97
  21. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +56 -28
  22. package/lib/cjs/actions/blue/withdrawCollateral.js +45 -50
  23. package/lib/cjs/actions/index.d.ts +1 -1
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  25. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +60 -19
  26. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  27. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +207 -0
  28. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  29. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +72 -0
  30. package/lib/cjs/actions/requirements/blue/index.d.ts +2 -0
  31. package/lib/cjs/actions/requirements/blue/index.js +2 -0
  32. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  33. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +30 -5
  34. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  35. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +7 -2
  36. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  37. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +33 -6
  38. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  39. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +123 -0
  40. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  41. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  42. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  43. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +5 -4
  44. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -4
  45. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  46. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +4 -0
  47. package/lib/cjs/bundler/actions.d.ts +4 -4
  48. package/lib/cjs/bundler/actions.js +4 -4
  49. package/lib/cjs/client/morphoViemExtension.d.ts +2 -1
  50. package/lib/cjs/client/morphoViemExtension.js +2 -1
  51. package/lib/cjs/entities/blue/blue.d.ts +806 -374
  52. package/lib/cjs/entities/blue/blue.js +447 -696
  53. package/lib/cjs/entities/index.d.ts +1 -0
  54. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +3 -9
  55. package/lib/cjs/helpers/computeVaultV1Reallocations.js +3 -9
  56. package/lib/cjs/helpers/validate.d.ts +14 -23
  57. package/lib/cjs/helpers/validate.js +30 -48
  58. package/lib/cjs/helpers/validateRequirementSpender.d.ts +2 -1
  59. package/lib/cjs/helpers/validateRequirementSpender.js +2 -0
  60. package/lib/cjs/types/action.d.ts +146 -162
  61. package/lib/cjs/types/action.js +29 -2
  62. package/lib/cjs/types/client.d.ts +9 -0
  63. package/lib/cjs/types/error.d.ts +141 -14
  64. package/lib/cjs/types/error.js +198 -21
  65. package/lib/cjs/types/sharedLiquidity.d.ts +0 -7
  66. package/lib/esm/actions/blue/borrow.d.ts +62 -61
  67. package/lib/esm/actions/blue/borrow.js +48 -80
  68. package/lib/esm/actions/blue/common.d.ts +99 -0
  69. package/lib/esm/actions/blue/common.js +306 -0
  70. package/lib/esm/actions/blue/refinance.d.ts +72 -112
  71. package/lib/esm/actions/blue/refinance.js +98 -200
  72. package/lib/esm/actions/blue/repay.d.ts +72 -68
  73. package/lib/esm/actions/blue/repay.js +56 -118
  74. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  75. package/lib/esm/actions/blue/repayWithdrawCollateral.js +149 -138
  76. package/lib/esm/actions/blue/supply.d.ts +62 -45
  77. package/lib/esm/actions/blue/supply.js +94 -70
  78. package/lib/esm/actions/blue/supplyCollateral.d.ts +63 -40
  79. package/lib/esm/actions/blue/supplyCollateral.js +52 -69
  80. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  81. package/lib/esm/actions/blue/supplyCollateralBorrow.js +134 -121
  82. package/lib/esm/actions/blue/withdraw.d.ts +68 -79
  83. package/lib/esm/actions/blue/withdraw.js +100 -96
  84. package/lib/esm/actions/blue/withdrawCollateral.d.ts +56 -28
  85. package/lib/esm/actions/blue/withdrawCollateral.js +45 -50
  86. package/lib/esm/actions/index.d.ts +1 -1
  87. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  88. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +63 -22
  89. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  90. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +203 -0
  91. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  92. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +68 -0
  93. package/lib/esm/actions/requirements/blue/index.d.ts +2 -0
  94. package/lib/esm/actions/requirements/blue/index.js +2 -0
  95. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  96. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +31 -6
  97. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  98. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +8 -3
  99. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  100. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +34 -7
  101. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  102. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +119 -0
  103. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  104. package/lib/esm/actions/requirements/encode/index.js +1 -0
  105. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  106. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +5 -4
  107. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -4
  108. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  109. package/lib/esm/actions/signatures/getTokenRequirementActions.js +5 -1
  110. package/lib/esm/bundler/actions.d.ts +4 -4
  111. package/lib/esm/bundler/actions.js +4 -4
  112. package/lib/esm/client/morphoViemExtension.d.ts +2 -1
  113. package/lib/esm/client/morphoViemExtension.js +2 -1
  114. package/lib/esm/entities/blue/blue.d.ts +806 -374
  115. package/lib/esm/entities/blue/blue.js +453 -702
  116. package/lib/esm/entities/index.d.ts +1 -0
  117. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +3 -9
  118. package/lib/esm/helpers/computeVaultV1Reallocations.js +3 -9
  119. package/lib/esm/helpers/validate.d.ts +14 -23
  120. package/lib/esm/helpers/validate.js +30 -48
  121. package/lib/esm/helpers/validateRequirementSpender.d.ts +2 -1
  122. package/lib/esm/helpers/validateRequirementSpender.js +2 -0
  123. package/lib/esm/types/action.d.ts +146 -162
  124. package/lib/esm/types/action.js +28 -2
  125. package/lib/esm/types/client.d.ts +9 -0
  126. package/lib/esm/types/error.d.ts +141 -14
  127. package/lib/esm/types/error.js +184 -17
  128. package/lib/esm/types/sharedLiquidity.d.ts +0 -7
  129. package/package.json +4 -3
  130. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +0 -47
  131. package/lib/cjs/actions/blue/buildAssetFundingActions.js +0 -63
  132. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +0 -69
  133. package/lib/cjs/actions/blue/buildReallocationActions.js +0 -141
  134. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +0 -66
  135. package/lib/cjs/actions/blue/resolveRepayFunding.js +0 -85
  136. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +0 -47
  137. package/lib/esm/actions/blue/buildAssetFundingActions.js +0 -59
  138. package/lib/esm/actions/blue/buildReallocationActions.d.ts +0 -69
  139. package/lib/esm/actions/blue/buildReallocationActions.js +0 -135
  140. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +0 -66
  141. package/lib/esm/actions/blue/resolveRepayFunding.js +0 -81
@@ -1,225 +1,123 @@
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 { NegativeInputError, NonPositiveInputError, RefinanceSameMarketError, RefinanceSharesMissingBorrowAssetsError, RefinanceTokenMismatchError, } from "../../types/index.js";
7
- import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
8
- import { buildBlueReallocationActions } from "./buildReallocationActions.js";
1
+ import { encodeFunctionData, isAddressEqual } from "viem";
2
+ import { blueBundlesV1Abi } from "../../abis.js";
3
+ import { validateUint256Field } from "../../helpers/validate.js";
4
+ import { RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
5
+ import { finalizeBlueBundlesV1Transaction, getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1SignedAuthorization, normalizeBlueBundlesV1CommonParams, } from "./common.js";
9
6
  /**
10
- * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
11
- * chain that shares the same loan and collateral tokens.
7
+ * Encodes a direct BlueBundlesV1 full borrow-position migration transaction.
12
8
  *
13
- * Strategy: flash-collateral via the target's `onMorphoSupplyCollateral` callback. The collateral
14
- * is credited before the deferred `safeTransferFrom`, so inside the callback GA1 borrows on the
15
- * target, repays the source, then withdraws the source collateral to settle the transfer.
9
+ * BlueBundlesV1 reads and moves the user's complete live source debt and collateral. Source and
10
+ * destination must use identical tokens, and referral fees plus allocator penalties increase the
11
+ * destination debt. Partial and collateral-only migration are not supported.
16
12
  *
17
- * Bundle shape (callback contents depend on borrow mode):
18
- *
19
- * ```text
20
- * // optional targetReallocations run first:
21
- * reallocateTo(...) | reallocate(...) | allocateFromIdle(...),
22
- *
23
- * morphoSupplyCollateral(target, collateralAmount, user, [
24
- * // omitted in collat-only mode
25
- * morphoBorrow(target, borrowAssets, 0, minBorrowSharePrice, GA1),
26
- * morphoRepay(source, assets|0, 0|shares, maxRepaySharePrice, user, []),
27
- * // shares mode only: sweep overshoot before the withdraw so same-token markets aren't drained
28
- * morphoRepay(target, maxUint256, 0, maxUint256, user, [], skipRevert=true),
29
- * // shares mode only: fallback if the repay is skipped, skim residual loan tokens to the user
30
- * erc20Transfer(loanToken, user, maxUint256, GA1, skipRevert=false),
31
- * morphoWithdrawCollateral(source, collateralAmount, GA1),
32
- * ])
33
- * ```
34
- *
35
- * Borrow modes:
36
- *
37
- * - **Assets mode** (`borrowAssets > 0n`): exact-asset borrow and repay, no GA1 dust.
38
- * - **Shares mode** (`borrowShares > 0n`, `borrowAssets` is the overshoot): the trailing
39
- * `morphoRepay(target, maxUint256, …, skipRevert=true)` sweeps the residual into the target debt,
40
- * then an `erc20Transfer` skims any residual to the user if that repay is skipped.
41
- * - **Collat-only** (both zero/omitted): only collateral is migrated; borrow/repay legs omitted.
42
- *
43
- * Prerequisite: GA1 must be authorized on Blue — the entity's `getRequirements()` returns the
44
- * `setAuthorization` transaction when needed.
45
- *
46
- * @param params.source.chainId - The chain both markets live on.
47
- * @param params.source.marketParams - Source market params (the position being closed).
48
- * @param params.target.marketParams - Target market params; must share both tokens with the source.
49
- * @param params.args.user - Position owner on both markets.
50
- * @param params.args.collateralAmount - Amount of collateral to migrate.
51
- * @param params.args.borrowAssets - Loan assets to borrow on the target; exclusive with `borrowShares`. Defaults to `0n`.
52
- * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
53
- * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
54
- * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
55
- * @param params.args.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the
56
- * target, run before the supply leg. Vault V1 inputs are deprecated for high-level Blue writes;
57
- * use Vault V2 for new integrations. V1 fees add to `tx.value`; V2 penalties are paid in the
58
- * target loan token.
59
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
60
- * a `setAuthorizationWithSig` call is prepended to the bundle.
61
- * @param params.metadata - Optional analytics metadata appended to `tx.data`.
62
- * @returns A deep-frozen `Transaction<BlueRefinanceAction>`.
63
- * @remarks `borrowAssets` and `borrowShares` describe different markets (target borrow vs. source
64
- * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
65
- * @throws {NonPositiveInputError} when `collateralAmount <= 0n`, a repay leg has a non-positive
66
- * `maxRepaySharePrice`, or any reallocation withdrawal amount is non-positive.
67
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
68
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
69
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
70
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
71
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
72
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
73
- * @throws {NegativeInputError} when `borrowAssets`, `borrowShares`, `minBorrowSharePrice`,
74
- * `maxRepaySharePrice`, a V1 fee, or a V2 penalty is negative.
75
- * @throws {RefinanceSameMarketError} when source and target market ids are equal.
76
- * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
77
- * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
78
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
79
- * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references the target market.
80
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly sorted by market id.
13
+ * @param params - Migration encoding parameters.
14
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
15
+ * @param params.market.sourceMarketParams - Source market scoped by the Blue entity.
16
+ * @param params.market.destinationMarketParams - Distinct compatible destination market.
17
+ * @param params.args.userAddress - Intended user used to bind an optional Morpho authorization and
18
+ * action metadata. This value is not encoded; the caller must send from the same account because
19
+ * BlueBundlesV1 always migrates `msg.sender`.
20
+ * @param params.args.maxLtv - Maximum destination LTV.
21
+ * @param params.args.reallocations - Vault V2 reallocations into the destination.
22
+ * @param params.args.deadline - Final call deadline in Unix seconds.
23
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
24
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
25
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
26
+ * @param params.metadata - Optional transaction metadata.
27
+ * @returns A deep-frozen `Readonly<Transaction<BlueRefinanceAction>>` whose
28
+ * `to` address is BlueBundlesV1 and whose `action` records the normalized migration inputs.
29
+ * @throws {RefinanceSameMarketError} when source and destination IDs match.
30
+ * @throws {RefinanceTokenMismatchError} when their loan or collateral tokens differ.
31
+ * @throws {NegativeInputError} when `maxLtv`, a referral fee, or a reallocation penalty is negative.
32
+ * @throws {NonPositiveInputError} when the deadline or a reallocation amount is not positive.
33
+ * @throws {InputExceedsMaxError} when a fee, reallocation amount, or penalty exceeds its ABI bound.
34
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
35
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is malformed.
36
+ * @throws {InvalidReallocationShapeError} when a reallocation entry is not a valid Vault V2 reallocation.
37
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
38
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
39
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a source is the destination market.
40
+ * @throws {ReallocationLoanTokenMismatchError} when a source market uses another loan token.
41
+ * @throws {DepositOwnerMismatchError} when the signed authorization owner differs from `userAddress`.
42
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when authorization cannot be bound safely.
43
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
44
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
81
45
  * @example
82
46
  * ```ts
47
+ * import { markets } from "@morpho-org/morpho-test";
83
48
  * import { blueRefinance } from "@morpho-org/morpho-sdk";
49
+ * import { zeroAddress } from "viem";
50
+ * import { mainnet } from "viem/chains";
84
51
  *
52
+ * const sourceMarketParams = markets[mainnet.id].eth_wstEth_2;
53
+ * const destinationMarketParams = markets[mainnet.id].eth_wstEth;
85
54
  * const tx = blueRefinance({
86
- * source: { chainId: 1, marketParams: sourceParams },
87
- * target: { marketParams: targetParams },
55
+ * market: { chainId: mainnet.id, sourceMarketParams, destinationMarketParams },
88
56
  * args: {
89
- * user: borrower,
90
- * collateralAmount: 1_000_000_000_000_000_000n,
91
- * borrowShares: 500_000_000_000n,
92
- * borrowAssets: 501_000_000n, // overshoot computed by entity layer
93
- * minBorrowSharePrice: 0n,
94
- * maxRepaySharePrice: 1_500_000_000_000_000_000_000_000_000n,
57
+ * userAddress: zeroAddress,
58
+ * maxLtv: 850000000000000000n,
59
+ * deadline: 1_900_000_000n,
95
60
  * },
96
61
  * });
97
62
  * // tx satisfies Readonly<Transaction<BlueRefinanceAction>>
98
63
  * ```
99
64
  */
100
- export const blueRefinance = ({ source: { chainId, marketParams: sourceParams }, target: { marketParams: targetParams }, args: { user, collateralAmount, borrowAssets = 0n, borrowShares = 0n, minBorrowSharePrice, maxRepaySharePrice, targetReallocations, authorizationSignature, }, metadata, }) => {
101
- if (collateralAmount <= 0n) {
102
- throw new NonPositiveInputError("collateralAmount", collateralAmount);
103
- }
104
- if (borrowAssets < 0n) {
105
- throw new NegativeInputError("borrowAssets", borrowAssets);
106
- }
107
- if (borrowShares < 0n) {
108
- throw new NegativeInputError("borrowShares", borrowShares);
109
- }
110
- if (minBorrowSharePrice < 0n) {
111
- throw new NegativeInputError("minBorrowSharePrice", minBorrowSharePrice);
112
- }
113
- if (maxRepaySharePrice < 0n) {
114
- throw new NegativeInputError("maxRepaySharePrice", maxRepaySharePrice);
115
- }
116
- if (sourceParams.id === targetParams.id) {
117
- throw new RefinanceSameMarketError(sourceParams.id);
118
- }
119
- if (!isAddressEqual(sourceParams.collateralToken, targetParams.collateralToken) ||
120
- !isAddressEqual(sourceParams.loanToken, targetParams.loanToken)) {
121
- throw new RefinanceTokenMismatchError(sourceParams.id, targetParams.id);
65
+ export const blueRefinance = (params) => {
66
+ const { chainId, sourceMarketParams, destinationMarketParams } = params.market;
67
+ const { userAddress, maxLtv, authorizationSignature } = params.args;
68
+ if (sourceMarketParams.id === destinationMarketParams.id) {
69
+ throw new RefinanceSameMarketError(sourceMarketParams.id);
122
70
  }
123
- const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
124
- const sharesMode = borrowShares > 0n;
125
- const shouldMigrateBorrow = borrowAssets > 0n || sharesMode;
126
- // Shares mode borrows in assets; Morpho rejects a zero borrow, so require a positive overshoot.
127
- if (sharesMode && borrowAssets <= 0n) {
128
- throw new RefinanceSharesMissingBorrowAssetsError(sourceParams.id);
71
+ if (!isAddressEqual(sourceMarketParams.loanToken, destinationMarketParams.loanToken) ||
72
+ !isAddressEqual(sourceMarketParams.collateralToken, destinationMarketParams.collateralToken)) {
73
+ throw new RefinanceTokenMismatchError(sourceMarketParams.id, destinationMarketParams.id);
129
74
  }
130
- // A repay leg with maxRepaySharePrice = 0n always reverts; require a positive cap when debt is migrated.
131
- if (shouldMigrateBorrow && maxRepaySharePrice <= 0n) {
132
- throw new NonPositiveInputError("maxRepaySharePrice", maxRepaySharePrice);
133
- }
134
- const callback = [];
135
- if (shouldMigrateBorrow) {
136
- callback.push({
137
- type: "morphoBorrow",
138
- args: [
139
- targetParams,
140
- borrowAssets,
141
- 0n,
142
- minBorrowSharePrice,
143
- generalAdapter1,
144
- false,
145
- ],
146
- });
147
- callback.push(sharesMode
148
- ? {
149
- type: "morphoRepay",
150
- args: [
151
- sourceParams,
152
- 0n,
153
- borrowShares,
154
- maxRepaySharePrice,
155
- user,
156
- [],
157
- false,
158
- ],
159
- }
160
- : {
161
- type: "morphoRepay",
162
- args: [
163
- sourceParams,
164
- borrowAssets,
165
- 0n,
166
- maxRepaySharePrice,
167
- user,
168
- [],
169
- false,
170
- ],
171
- });
172
- }
173
- // Sweep the borrow overshoot back into target debt so GA1 ends drained. Must run before the
174
- // withdraw: in same-token markets maxUint256 would otherwise drain the just-withdrawn collateral.
175
- if (sharesMode) {
176
- callback.push({
177
- type: "morphoRepay",
178
- args: [targetParams, maxUint256, 0n, maxUint256, user, [], true],
179
- });
180
- // Fallback: if the repay above is skipped, skim any residual loan tokens to the user.
181
- callback.push({
182
- type: "erc20Transfer",
183
- args: [targetParams.loanToken, user, maxUint256, generalAdapter1, false],
184
- });
185
- }
186
- callback.push({
187
- type: "morphoWithdrawCollateral",
188
- args: [sourceParams, collateralAmount, generalAdapter1, false],
189
- });
190
- const actions = [];
191
- if (authorizationSignature) {
192
- actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
193
- }
194
- const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = buildBlueReallocationActions({
75
+ validateUint256Field("maxLtv", maxLtv);
76
+ const common = {
195
77
  chainId,
196
- reallocations: targetReallocations,
197
- targetMarketParams: targetParams,
198
- });
199
- actions.push(...reallocationActions);
200
- actions.push({
201
- type: "morphoSupplyCollateral",
202
- args: [targetParams, collateralAmount, user, callback, false],
78
+ userAddress,
79
+ deadline: params.args.deadline,
80
+ referralFeePct: params.args.referralFeePct,
81
+ referralFeeRecipient: params.args.referralFeeRecipient,
82
+ metadata: params.metadata,
83
+ };
84
+ const { referralFeePct, referralFeeRecipient } = normalizeBlueBundlesV1CommonParams(common);
85
+ const signedAuthorization = getBlueBundlesV1SignedAuthorization({
86
+ chainId,
87
+ userAddress,
88
+ authorizationSignature,
203
89
  });
204
- let tx = BundlerAction.encodeBundle(chainId, actions);
205
- if (metadata) {
206
- tx = addTransactionMetadata(tx, metadata);
207
- }
208
- return deepFreeze({
209
- ...tx,
90
+ const publicAllocations = getBlueBundlesV1PublicAllocations([...(params.args.reallocations ?? [])], destinationMarketParams);
91
+ const reallocationPenaltyAssets = getBlueBundlesV1PenaltyAssets(publicAllocations);
92
+ return finalizeBlueBundlesV1Transaction({
93
+ common,
94
+ value: 0n,
95
+ data: encodeFunctionData({
96
+ abi: blueBundlesV1Abi,
97
+ functionName: "blueBundlesV1MigrateBorrowPosition",
98
+ args: [
99
+ sourceMarketParams,
100
+ destinationMarketParams,
101
+ maxLtv,
102
+ signedAuthorization,
103
+ publicAllocations,
104
+ referralFeePct,
105
+ referralFeeRecipient,
106
+ params.args.deadline,
107
+ ],
108
+ }),
210
109
  action: {
211
110
  type: "blueRefinance",
212
111
  args: {
213
- sourceMarket: sourceParams.id,
214
- targetMarket: targetParams.id,
215
- collateralAmount,
216
- borrowAssets,
217
- borrowShares,
218
- minBorrowSharePrice,
219
- maxRepaySharePrice,
220
- user,
221
- reallocationFee,
112
+ sourceMarket: sourceMarketParams.id,
113
+ destinationMarket: destinationMarketParams.id,
114
+ maxLtv,
115
+ onBehalf: userAddress,
116
+ reallocations: publicAllocations.length,
222
117
  reallocationPenaltyAssets,
118
+ referralFeePct,
119
+ referralFeeRecipient,
120
+ deadline: params.args.deadline,
223
121
  },
224
122
  },
225
123
  });
@@ -1,89 +1,93 @@
1
- import { type MarketParams } from "@morpho-org/blue-sdk";
1
+ import type { MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
- import type { BlueRepayAction, Metadata, PermitRequirementSignature, RepayActionAmountArgs, Transaction } from "../../types/index.js";
3
+ import type { BlueBundlesV1TokenRequirementSignature, BlueRepayAction, Metadata, Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueRepay}. */
5
5
  export interface BlueRepayParams {
6
- market: {
6
+ /** Chain and scoped Morpho Blue market. */
7
+ readonly market: {
7
8
  readonly chainId: number;
8
9
  readonly marketParams: MarketParams;
9
10
  };
10
- args: RepayActionAmountArgs & {
11
- /** Address whose debt is being repaid. */
12
- onBehalf: Address;
13
- /** Receives residual loan tokens in shares mode. */
14
- receiver: Address;
15
- /** Maximum repay share price (in ray). Protects against share price manipulation. */
16
- maxSharePrice: bigint;
17
- /** Optional pre-signed permit/permit2 approval for the loan-token transfer. */
18
- requirementSignature?: PermitRequirementSignature;
11
+ /** Direct BlueBundlesV1 repay arguments. */
12
+ readonly args: {
13
+ /** User whose debt is repaid. */
14
+ readonly userAddress: Address;
15
+ /** Exact assets repaid, exclusive with `repayShares`. */
16
+ readonly repayAssets: bigint;
17
+ /** Exact shares repaid; use `maxUint256` for a saturated full repay. */
18
+ readonly repayShares: bigint;
19
+ /** Maximum gross loan-token funding, including referral fees. */
20
+ readonly maxRepayAssets: bigint;
21
+ /** Full native repay funding; must equal `maxRepayAssets`. */
22
+ readonly nativeAmount?: bigint;
23
+ /** Final call deadline in Unix seconds. */
24
+ readonly deadline: bigint;
25
+ /** Optional WAD-scaled referral fee, strictly below 100%. */
26
+ readonly referralFeePct?: bigint;
27
+ /** Recipient required when `referralFeePct` is positive. */
28
+ readonly referralFeeRecipient?: Address;
29
+ /** Optional loan-token ERC-2612 or Permit2 SignatureTransfer result. */
30
+ readonly requirementSignature?: BlueBundlesV1TokenRequirementSignature;
19
31
  };
20
- metadata?: Metadata;
32
+ /** Optional transaction metadata suffix. */
33
+ readonly metadata?: Metadata;
21
34
  }
22
35
  /**
23
- * Prepares a repay transaction for a Morpho Blue market.
36
+ * Encodes a pure repayment through BlueBundlesV1.
24
37
  *
25
- * Routed through bundler3 via `GeneralAdapter1`. All amount arithmetic is done upstream (see
26
- * `MorphoBlue.repay`); this builder just assembles the bundle from the pre-resolved
27
- * {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional native wrapping
28
- * (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()` before the
29
- * repay; the loan token must be the chain's wNative):
38
+ * Delegates to {@link blueRepayWithdrawCollateral} with a zero collateral-withdrawal leg and an
39
+ * unrestricted LTV cap. BlueBundlesV1 refunds unused `maxRepayAssets` funding.
30
40
  *
31
- * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
32
- * additive like `blueSupply`), pulling `amount` ERC-20 and wrapping `nativeAmount`. No residual.
33
- * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
34
- * ERC-20 (already net of native) and wrapping `nativeAmount`. Residual loan tokens are skimmed
35
- * back to `receiver` after the call.
36
- *
37
- * Uses `maxSharePrice` to protect against share price manipulation between construction and execution.
38
- *
39
- * @param params.market.chainId - The chain the market lives on.
40
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
41
- * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
42
- * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
43
- * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
44
- * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
45
- * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
46
- * Requires the loan token to be the chain's wNative.
47
- * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
48
- * @param params.args.receiver - Address that receives residual loan tokens in shares mode.
49
- * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
50
- * protection.
51
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
52
- * loan-token transfer.
53
- * @param params.metadata - Optional analytics metadata attached to the bundle.
54
- * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value` (= `nativeAmount`),
55
- * `data`, and the typed `action` discriminator the simulation layer consumes.
56
- * @throws {NonPositiveInputError} when `maxSharePrice <= 0n` or the total funding is zero.
57
- * @throws {NegativeInputError} when `amount`, `shares`, `nativeAmount`, or `transferAmount` is negative.
58
- * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
59
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
60
- * `transferAmount !== amount + nativeAmount`.
61
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
62
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
63
- * the chain's wNative.
64
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
65
- * is provided and the signed asset differs from `marketParams.loanToken`.
66
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
67
- * is provided and the signed amount differs from the ERC-20 amount pulled.
68
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
69
- * signature is missing its expiration.
41
+ * @param params - Repay encoding parameters.
42
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
43
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
44
+ * @param params.args.userAddress - User whose debt is repaid.
45
+ * @param params.args.repayAssets - Exact assets repaid, exclusive with shares.
46
+ * @param params.args.repayShares - Exact shares or `maxUint256` for full repay.
47
+ * @param params.args.maxRepayAssets - Gross repayment and fee funding cap.
48
+ * @param params.args.nativeAmount - Exclusive native repay funding.
49
+ * @param params.args.deadline - Final call deadline in Unix seconds.
50
+ * @param params.args.referralFeePct - Optional WAD-scaled referral fee.
51
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
52
+ * @param params.args.requirementSignature - Optional loan-token signature.
53
+ * @param params.metadata - Optional transaction metadata.
54
+ * @returns A deep-frozen `Readonly<Transaction<BlueRepayAction>>` whose calldata invokes the
55
+ * combined BlueBundlesV1 entrypoint with a zero collateral-withdrawal leg.
56
+ * @throws {NegativeInputError} when an amount or fee is negative.
57
+ * @throws {MutuallyExclusiveRepayAmountsError} when assets and shares are both nonzero.
58
+ * @throws {NonPositiveInputError} when repayment, funding, or deadline is not positive.
59
+ * @throws {MaxRepayAssetsBelowRepayAssetsError} when funding cannot cover repayment and fees.
60
+ * @throws {NativeFundingAmountMismatchError} when native funding is partial or mixed.
61
+ * @throws {ChainWNativeMissingError} when native funding is requested without a registered wNative.
62
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets another loan token.
63
+ * @throws {UnexpectedRequirementSignatureError} when native funding also supplies a token signature.
64
+ * @throws {DepositOwnerMismatchError} when the signed owner differs from `userAddress`.
65
+ * @throws {DepositAssetMismatchError} when the signed asset differs from the loan token.
66
+ * @throws {DepositAmountMismatchError} when the signed amount differs from `maxRepayAssets`.
67
+ * @throws {DepositSpenderMismatchError} when the signed spender is not BlueBundlesV1.
68
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when a signature cannot be encoded safely.
69
+ * @throws {InputExceedsMaxError} when the referral fee is at least WAD.
70
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
71
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
72
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
70
73
  * @example
71
74
  * ```ts
75
+ * import { markets } from "@morpho-org/morpho-test";
72
76
  * import { blueRepay } from "@morpho-org/morpho-sdk";
77
+ * import { zeroAddress } from "viem";
78
+ * import { mainnet } from "viem/chains";
73
79
  *
74
- * // Repay 0.5 loan-asset units, 0.2 of them funded by wrapping native ETH.
75
80
  * const tx = blueRepay({
76
- * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
81
+ * market: { chainId: mainnet.id, marketParams: markets[mainnet.id].usdc_wbtc },
77
82
  * args: {
78
- * amount: 300_000_000_000_000_000n, // ERC-20 part
79
- * nativeAmount: 200_000_000_000_000_000n, // wrapped ETH part
80
- * transferAmount: 500_000_000_000_000_000n, // total repaid = amount + nativeAmount
81
- * onBehalf: borrower,
82
- * receiver: borrower,
83
- * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
83
+ * userAddress: zeroAddress,
84
+ * repayAssets: 1_000_000n,
85
+ * repayShares: 0n,
86
+ * maxRepayAssets: 1_000_000n,
87
+ * deadline: 1_900_000_000n,
84
88
  * },
85
89
  * });
86
- * // tx.value === 200_000_000_000_000_000n
90
+ * // tx satisfies Readonly<Transaction<BlueRepayAction>>
87
91
  * ```
88
92
  */
89
- export declare const blueRepay: ({ market: { chainId, marketParams }, args, metadata, }: BlueRepayParams) => Readonly<Transaction<BlueRepayAction>>;
93
+ export declare const blueRepay: (params: BlueRepayParams) => Readonly<Transaction<BlueRepayAction>>;