@morpho-org/morpho-sdk 5.8.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 (167) hide show
  1. package/MIGRATION-v5-to-v6.md +201 -0
  2. package/README.md +62 -40
  3. package/lib/cjs/abis.d.ts +543 -0
  4. package/lib/cjs/abis.js +738 -0
  5. package/lib/cjs/actions/blue/borrow.d.ts +62 -58
  6. package/lib/cjs/actions/blue/borrow.js +48 -80
  7. package/lib/cjs/actions/blue/common.d.ts +99 -0
  8. package/lib/cjs/actions/blue/common.js +318 -0
  9. package/lib/cjs/actions/blue/refinance.d.ts +72 -107
  10. package/lib/cjs/actions/blue/refinance.js +97 -197
  11. package/lib/cjs/actions/blue/repay.d.ts +72 -68
  12. package/lib/cjs/actions/blue/repay.js +56 -118
  13. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  14. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +148 -137
  15. package/lib/cjs/actions/blue/supply.d.ts +62 -45
  16. package/lib/cjs/actions/blue/supply.js +94 -70
  17. package/lib/cjs/actions/blue/supplyCollateral.d.ts +63 -40
  18. package/lib/cjs/actions/blue/supplyCollateral.js +52 -69
  19. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +82 -86
  20. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +133 -119
  21. package/lib/cjs/actions/blue/withdraw.d.ts +68 -78
  22. package/lib/cjs/actions/blue/withdraw.js +101 -97
  23. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +56 -28
  24. package/lib/cjs/actions/blue/withdrawCollateral.js +45 -50
  25. package/lib/cjs/actions/index.d.ts +1 -1
  26. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  27. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +60 -19
  28. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  29. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +207 -0
  30. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  31. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +72 -0
  32. package/lib/cjs/actions/requirements/blue/index.d.ts +2 -0
  33. package/lib/cjs/actions/requirements/blue/index.js +2 -0
  34. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  35. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +30 -5
  36. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  37. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +7 -2
  38. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  39. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +33 -6
  40. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  41. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +123 -0
  42. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  43. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  44. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  45. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +5 -4
  46. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -4
  47. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  48. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +4 -0
  49. package/lib/cjs/blue/types.d.ts +3 -1
  50. package/lib/cjs/blue/utils.d.ts +3 -1
  51. package/lib/cjs/blue/utils.js +1 -0
  52. package/lib/cjs/bundler/actions.d.ts +6 -4
  53. package/lib/cjs/bundler/actions.js +6 -4
  54. package/lib/cjs/bundler/types.d.ts +10 -1
  55. package/lib/cjs/client/morphoViemExtension.d.ts +2 -1
  56. package/lib/cjs/client/morphoViemExtension.js +2 -1
  57. package/lib/cjs/entities/blue/blue.d.ts +817 -360
  58. package/lib/cjs/entities/blue/blue.js +455 -698
  59. package/lib/cjs/entities/index.d.ts +1 -0
  60. package/lib/cjs/entities/vaultV1/vaultV1.js +4 -12
  61. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +18 -3
  62. package/lib/cjs/entities/vaultV1ReallocationData.js +11 -1
  63. package/lib/cjs/entities/vaultV2/vaultV2.js +6 -18
  64. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +7 -10
  65. package/lib/cjs/helpers/computeVaultV1Reallocations.js +7 -10
  66. package/lib/cjs/helpers/validate.d.ts +16 -23
  67. package/lib/cjs/helpers/validate.js +32 -48
  68. package/lib/cjs/helpers/validateRequirementSpender.d.ts +2 -1
  69. package/lib/cjs/helpers/validateRequirementSpender.js +2 -0
  70. package/lib/cjs/types/action.d.ts +146 -162
  71. package/lib/cjs/types/action.js +29 -2
  72. package/lib/cjs/types/client.d.ts +9 -0
  73. package/lib/cjs/types/error.d.ts +173 -18
  74. package/lib/cjs/types/error.js +230 -25
  75. package/lib/cjs/types/sharedLiquidity.d.ts +20 -4
  76. package/lib/cjs/types.d.ts +3 -1
  77. package/lib/cjs/utils.d.ts +3 -1
  78. package/lib/cjs/utils.js +1 -0
  79. package/lib/esm/abis.d.ts +543 -0
  80. package/lib/esm/abis.js +737 -0
  81. package/lib/esm/actions/blue/borrow.d.ts +62 -58
  82. package/lib/esm/actions/blue/borrow.js +48 -80
  83. package/lib/esm/actions/blue/common.d.ts +99 -0
  84. package/lib/esm/actions/blue/common.js +306 -0
  85. package/lib/esm/actions/blue/refinance.d.ts +72 -107
  86. package/lib/esm/actions/blue/refinance.js +98 -198
  87. package/lib/esm/actions/blue/repay.d.ts +72 -68
  88. package/lib/esm/actions/blue/repay.js +56 -118
  89. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  90. package/lib/esm/actions/blue/repayWithdrawCollateral.js +149 -138
  91. package/lib/esm/actions/blue/supply.d.ts +62 -45
  92. package/lib/esm/actions/blue/supply.js +94 -70
  93. package/lib/esm/actions/blue/supplyCollateral.d.ts +63 -40
  94. package/lib/esm/actions/blue/supplyCollateral.js +52 -69
  95. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +82 -86
  96. package/lib/esm/actions/blue/supplyCollateralBorrow.js +134 -120
  97. package/lib/esm/actions/blue/withdraw.d.ts +68 -78
  98. package/lib/esm/actions/blue/withdraw.js +100 -96
  99. package/lib/esm/actions/blue/withdrawCollateral.d.ts +56 -28
  100. package/lib/esm/actions/blue/withdrawCollateral.js +45 -50
  101. package/lib/esm/actions/index.d.ts +1 -1
  102. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  103. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +63 -22
  104. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  105. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +203 -0
  106. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  107. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +68 -0
  108. package/lib/esm/actions/requirements/blue/index.d.ts +2 -0
  109. package/lib/esm/actions/requirements/blue/index.js +2 -0
  110. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  111. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +31 -6
  112. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  113. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +8 -3
  114. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  115. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +34 -7
  116. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  117. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +119 -0
  118. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  119. package/lib/esm/actions/requirements/encode/index.js +1 -0
  120. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  121. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +5 -4
  122. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -4
  123. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  124. package/lib/esm/actions/signatures/getTokenRequirementActions.js +5 -1
  125. package/lib/esm/blue/types.d.ts +3 -1
  126. package/lib/esm/blue/utils.d.ts +3 -1
  127. package/lib/esm/blue/utils.js +3 -1
  128. package/lib/esm/bundler/actions.d.ts +6 -4
  129. package/lib/esm/bundler/actions.js +6 -4
  130. package/lib/esm/bundler/types.d.ts +10 -1
  131. package/lib/esm/client/morphoViemExtension.d.ts +2 -1
  132. package/lib/esm/client/morphoViemExtension.js +2 -1
  133. package/lib/esm/entities/blue/blue.d.ts +817 -360
  134. package/lib/esm/entities/blue/blue.js +461 -704
  135. package/lib/esm/entities/index.d.ts +1 -0
  136. package/lib/esm/entities/vaultV1/vaultV1.js +4 -12
  137. package/lib/esm/entities/vaultV1ReallocationData.d.ts +18 -3
  138. package/lib/esm/entities/vaultV1ReallocationData.js +13 -2
  139. package/lib/esm/entities/vaultV2/vaultV2.js +7 -19
  140. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +7 -10
  141. package/lib/esm/helpers/computeVaultV1Reallocations.js +7 -10
  142. package/lib/esm/helpers/validate.d.ts +16 -23
  143. package/lib/esm/helpers/validate.js +32 -48
  144. package/lib/esm/helpers/validateRequirementSpender.d.ts +2 -1
  145. package/lib/esm/helpers/validateRequirementSpender.js +2 -0
  146. package/lib/esm/types/action.d.ts +146 -162
  147. package/lib/esm/types/action.js +28 -2
  148. package/lib/esm/types/client.d.ts +9 -0
  149. package/lib/esm/types/error.d.ts +173 -18
  150. package/lib/esm/types/error.js +216 -21
  151. package/lib/esm/types/sharedLiquidity.d.ts +20 -4
  152. package/lib/esm/types.d.ts +3 -1
  153. package/lib/esm/utils.d.ts +3 -1
  154. package/lib/esm/utils.js +3 -1
  155. package/package.json +7 -6
  156. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +0 -47
  157. package/lib/cjs/actions/blue/buildAssetFundingActions.js +0 -63
  158. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +0 -69
  159. package/lib/cjs/actions/blue/buildReallocationActions.js +0 -141
  160. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +0 -66
  161. package/lib/cjs/actions/blue/resolveRepayFunding.js +0 -85
  162. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +0 -47
  163. package/lib/esm/actions/blue/buildAssetFundingActions.js +0 -59
  164. package/lib/esm/actions/blue/buildReallocationActions.d.ts +0 -69
  165. package/lib/esm/actions/blue/buildReallocationActions.js +0 -135
  166. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +0 -66
  167. package/lib/esm/actions/blue/resolveRepayFunding.js +0 -81
@@ -1,226 +1,126 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.blueRefinance = void 0;
4
- const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
- const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
4
  const viem_1 = require("viem");
7
- const index_js_1 = require("../../bundler/index.js");
8
- const index_js_2 = require("../../helpers/index.js");
9
- const index_js_3 = require("../../types/index.js");
10
- const getBlueAuthorizationAction_js_1 = require("../signatures/getBlueAuthorizationAction.js");
11
- const buildReallocationActions_js_1 = require("./buildReallocationActions.js");
5
+ const abis_js_1 = require("../../abis.js");
6
+ const validate_js_1 = require("../../helpers/validate.js");
7
+ const index_js_1 = require("../../types/index.js");
8
+ const common_js_1 = require("./common.js");
12
9
  /**
13
- * Prepares an atomic refinance migrating a Morpho Blue position to another market on the same
14
- * chain that shares the same loan and collateral tokens.
10
+ * Encodes a direct BlueBundlesV1 full borrow-position migration transaction.
15
11
  *
16
- * Strategy: flash-collateral via the target's `onMorphoSupplyCollateral` callback. The collateral
17
- * is credited before the deferred `safeTransferFrom`, so inside the callback GA1 borrows on the
18
- * target, repays the source, then withdraws the source collateral to settle the transfer.
12
+ * BlueBundlesV1 reads and moves the user's complete live source debt and collateral. Source and
13
+ * destination must use identical tokens, and referral fees plus allocator penalties increase the
14
+ * destination debt. Partial and collateral-only migration are not supported.
19
15
  *
20
- * Bundle shape (callback contents depend on borrow mode):
21
- *
22
- * ```text
23
- * // optional targetReallocations run first:
24
- * reallocateTo(...) | reallocate(...) | allocateFromIdle(...),
25
- *
26
- * morphoSupplyCollateral(target, collateralAmount, user, [
27
- * // omitted in collat-only mode
28
- * morphoBorrow(target, borrowAssets, 0, minBorrowSharePrice, GA1),
29
- * morphoRepay(source, assets|0, 0|shares, maxRepaySharePrice, user, []),
30
- * // shares mode only: sweep overshoot before the withdraw so same-token markets aren't drained
31
- * morphoRepay(target, maxUint256, 0, maxUint256, user, [], skipRevert=true),
32
- * // shares mode only: fallback if the repay is skipped, skim residual loan tokens to the user
33
- * erc20Transfer(loanToken, user, maxUint256, GA1, skipRevert=false),
34
- * morphoWithdrawCollateral(source, collateralAmount, GA1),
35
- * ])
36
- * ```
37
- *
38
- * Borrow modes:
39
- *
40
- * - **Assets mode** (`borrowAssets > 0n`): exact-asset borrow and repay, no GA1 dust.
41
- * - **Shares mode** (`borrowShares > 0n`, `borrowAssets` is the overshoot): the trailing
42
- * `morphoRepay(target, maxUint256, …, skipRevert=true)` sweeps the residual into the target debt,
43
- * then an `erc20Transfer` skims any residual to the user if that repay is skipped.
44
- * - **Collat-only** (both zero/omitted): only collateral is migrated; borrow/repay legs omitted.
45
- *
46
- * Prerequisite: GA1 must be authorized on Blue — the entity's `getRequirements()` returns the
47
- * `setAuthorization` transaction when needed.
48
- *
49
- * @param params.source.chainId - The chain both markets live on.
50
- * @param params.source.marketParams - Source market params (the position being closed).
51
- * @param params.target.marketParams - Target market params; must share both tokens with the source.
52
- * @param params.args.user - Position owner on both markets.
53
- * @param params.args.collateralAmount - Amount of collateral to migrate.
54
- * @param params.args.borrowAssets - Loan assets to borrow on the target; exclusive with `borrowShares`. Defaults to `0n`.
55
- * @param params.args.borrowShares - Borrow shares to repay on the source; exclusive with `borrowAssets`. Defaults to `0n`.
56
- * @param params.args.minBorrowSharePrice - Minimum borrow share price (ray) on the target.
57
- * @param params.args.maxRepaySharePrice - Maximum repay share price (ray) on the source.
58
- * @param params.args.targetReallocations - Homogeneous Vault V1 or Vault V2 reallocations into the
59
- * target, run before the supply leg. V1 fees add to `tx.value`; V2 penalties are paid in the target loan token.
60
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
61
- * a `setAuthorizationWithSig` call is prepended to the bundle.
62
- * @param params.metadata - Optional analytics metadata appended to `tx.data`.
63
- * @returns A deep-frozen `Transaction<BlueRefinanceAction>`.
64
- * @remarks `borrowAssets` and `borrowShares` describe different markets (target borrow vs. source
65
- * repay); in shares mode the entity passes both. Caller-facing mutual exclusivity is enforced at the entity layer.
66
- * @throws {NonPositiveInputError} when `collateralAmount <= 0n`, a repay leg has a non-positive
67
- * `maxRepaySharePrice`, or any reallocation withdrawal amount is non-positive.
68
- * @throws {InputExceedsMaxError} when a V2 reallocation asset amount exceeds `uint128` or its penalty exceeds WAD.
69
- * @throws {InconsistentReallocationPenaltyError} when V2 entries for one vault use different penalties.
70
- * @throws {InvalidReallocationAddressError} when a V2 vault or adapter address is malformed.
71
- * @throws {InvalidReallocationSourceTypeError} when a V2 source is absent, incomplete, or has an unknown discriminator.
72
- * @throws {InvalidReallocationShapeError} when an entry matches both or neither V1/V2 shape.
73
- * @throws {MixedReallocationVersionsError} when one plan contains both V1 and V2 entries.
74
- * @throws {NegativeInputError} when `borrowAssets`, `borrowShares`, `minBorrowSharePrice`,
75
- * `maxRepaySharePrice`, a V1 fee, or a V2 penalty is negative.
76
- * @throws {RefinanceSameMarketError} when source and target market ids are equal.
77
- * @throws {RefinanceTokenMismatchError} when source and target do not share both tokens.
78
- * @throws {RefinanceSharesMissingBorrowAssetsError} when `borrowShares > 0n` but `borrowAssets` is omitted or non-positive.
79
- * @throws {EmptyReallocationWithdrawalsError} when any `reallocation.withdrawals` is empty.
80
- * @throws {ReallocationWithdrawalOnTargetMarketError} when a reallocation withdrawal references the target market.
81
- * @throws {UnsortedReallocationWithdrawalsError} when reallocation withdrawals are not strictly sorted by market id.
16
+ * @param params - Migration encoding parameters.
17
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
18
+ * @param params.market.sourceMarketParams - Source market scoped by the Blue entity.
19
+ * @param params.market.destinationMarketParams - Distinct compatible destination market.
20
+ * @param params.args.userAddress - Intended user used to bind an optional Morpho authorization and
21
+ * action metadata. This value is not encoded; the caller must send from the same account because
22
+ * BlueBundlesV1 always migrates `msg.sender`.
23
+ * @param params.args.maxLtv - Maximum destination LTV.
24
+ * @param params.args.reallocations - Vault V2 reallocations into the destination.
25
+ * @param params.args.deadline - Final call deadline in Unix seconds.
26
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
27
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
28
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
29
+ * @param params.metadata - Optional transaction metadata.
30
+ * @returns A deep-frozen `Readonly<Transaction<BlueRefinanceAction>>` whose
31
+ * `to` address is BlueBundlesV1 and whose `action` records the normalized migration inputs.
32
+ * @throws {RefinanceSameMarketError} when source and destination IDs match.
33
+ * @throws {RefinanceTokenMismatchError} when their loan or collateral tokens differ.
34
+ * @throws {NegativeInputError} when `maxLtv`, a referral fee, or a reallocation penalty is negative.
35
+ * @throws {NonPositiveInputError} when the deadline or a reallocation amount is not positive.
36
+ * @throws {InputExceedsMaxError} when a fee, reallocation amount, or penalty exceeds its ABI bound.
37
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
38
+ * @throws {InvalidReallocationAddressError} when a vault or adapter address is malformed.
39
+ * @throws {InvalidReallocationShapeError} when a reallocation entry is not a valid Vault V2 reallocation.
40
+ * @throws {InvalidReallocationSourceTypeError} when a reallocation source is malformed.
41
+ * @throws {InconsistentReallocationPenaltyError} when one vault uses different penalties.
42
+ * @throws {ReallocationWithdrawalOnTargetMarketError} when a source is the destination market.
43
+ * @throws {ReallocationLoanTokenMismatchError} when a source market uses another loan token.
44
+ * @throws {DepositOwnerMismatchError} when the signed authorization owner differs from `userAddress`.
45
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when authorization cannot be bound safely.
46
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
47
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
82
48
  * @example
83
49
  * ```ts
50
+ * import { markets } from "@morpho-org/morpho-test";
84
51
  * import { blueRefinance } from "@morpho-org/morpho-sdk";
52
+ * import { zeroAddress } from "viem";
53
+ * import { mainnet } from "viem/chains";
85
54
  *
55
+ * const sourceMarketParams = markets[mainnet.id].eth_wstEth_2;
56
+ * const destinationMarketParams = markets[mainnet.id].eth_wstEth;
86
57
  * const tx = blueRefinance({
87
- * source: { chainId: 1, marketParams: sourceParams },
88
- * target: { marketParams: targetParams },
58
+ * market: { chainId: mainnet.id, sourceMarketParams, destinationMarketParams },
89
59
  * args: {
90
- * user: borrower,
91
- * collateralAmount: 1_000_000_000_000_000_000n,
92
- * borrowShares: 500_000_000_000n,
93
- * borrowAssets: 501_000_000n, // overshoot computed by entity layer
94
- * minBorrowSharePrice: 0n,
95
- * maxRepaySharePrice: 1_500_000_000_000_000_000_000_000_000n,
60
+ * userAddress: zeroAddress,
61
+ * maxLtv: 850000000000000000n,
62
+ * deadline: 1_900_000_000n,
96
63
  * },
97
64
  * });
98
65
  * // tx satisfies Readonly<Transaction<BlueRefinanceAction>>
99
66
  * ```
100
67
  */
101
- const blueRefinance = ({ source: { chainId, marketParams: sourceParams }, target: { marketParams: targetParams }, args: { user, collateralAmount, borrowAssets = 0n, borrowShares = 0n, minBorrowSharePrice, maxRepaySharePrice, targetReallocations, authorizationSignature, }, metadata, }) => {
102
- if (collateralAmount <= 0n) {
103
- throw new index_js_3.NonPositiveInputError("collateralAmount", collateralAmount);
104
- }
105
- if (borrowAssets < 0n) {
106
- throw new index_js_3.NegativeInputError("borrowAssets", borrowAssets);
107
- }
108
- if (borrowShares < 0n) {
109
- throw new index_js_3.NegativeInputError("borrowShares", borrowShares);
110
- }
111
- if (minBorrowSharePrice < 0n) {
112
- throw new index_js_3.NegativeInputError("minBorrowSharePrice", minBorrowSharePrice);
113
- }
114
- if (maxRepaySharePrice < 0n) {
115
- throw new index_js_3.NegativeInputError("maxRepaySharePrice", maxRepaySharePrice);
116
- }
117
- if (sourceParams.id === targetParams.id) {
118
- throw new index_js_3.RefinanceSameMarketError(sourceParams.id);
119
- }
120
- if (!(0, viem_1.isAddressEqual)(sourceParams.collateralToken, targetParams.collateralToken) ||
121
- !(0, viem_1.isAddressEqual)(sourceParams.loanToken, targetParams.loanToken)) {
122
- throw new index_js_3.RefinanceTokenMismatchError(sourceParams.id, targetParams.id);
68
+ const blueRefinance = (params) => {
69
+ const { chainId, sourceMarketParams, destinationMarketParams } = params.market;
70
+ const { userAddress, maxLtv, authorizationSignature } = params.args;
71
+ if (sourceMarketParams.id === destinationMarketParams.id) {
72
+ throw new index_js_1.RefinanceSameMarketError(sourceMarketParams.id);
123
73
  }
124
- const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
125
- const sharesMode = borrowShares > 0n;
126
- const shouldMigrateBorrow = borrowAssets > 0n || sharesMode;
127
- // Shares mode borrows in assets; Morpho rejects a zero borrow, so require a positive overshoot.
128
- if (sharesMode && borrowAssets <= 0n) {
129
- throw new index_js_3.RefinanceSharesMissingBorrowAssetsError(sourceParams.id);
74
+ if (!(0, viem_1.isAddressEqual)(sourceMarketParams.loanToken, destinationMarketParams.loanToken) ||
75
+ !(0, viem_1.isAddressEqual)(sourceMarketParams.collateralToken, destinationMarketParams.collateralToken)) {
76
+ throw new index_js_1.RefinanceTokenMismatchError(sourceMarketParams.id, destinationMarketParams.id);
130
77
  }
131
- // A repay leg with maxRepaySharePrice = 0n always reverts; require a positive cap when debt is migrated.
132
- if (shouldMigrateBorrow && maxRepaySharePrice <= 0n) {
133
- throw new index_js_3.NonPositiveInputError("maxRepaySharePrice", maxRepaySharePrice);
134
- }
135
- const callback = [];
136
- if (shouldMigrateBorrow) {
137
- callback.push({
138
- type: "morphoBorrow",
139
- args: [
140
- targetParams,
141
- borrowAssets,
142
- 0n,
143
- minBorrowSharePrice,
144
- generalAdapter1,
145
- false,
146
- ],
147
- });
148
- callback.push(sharesMode
149
- ? {
150
- type: "morphoRepay",
151
- args: [
152
- sourceParams,
153
- 0n,
154
- borrowShares,
155
- maxRepaySharePrice,
156
- user,
157
- [],
158
- false,
159
- ],
160
- }
161
- : {
162
- type: "morphoRepay",
163
- args: [
164
- sourceParams,
165
- borrowAssets,
166
- 0n,
167
- maxRepaySharePrice,
168
- user,
169
- [],
170
- false,
171
- ],
172
- });
173
- }
174
- // Sweep the borrow overshoot back into target debt so GA1 ends drained. Must run before the
175
- // withdraw: in same-token markets maxUint256 would otherwise drain the just-withdrawn collateral.
176
- if (sharesMode) {
177
- callback.push({
178
- type: "morphoRepay",
179
- args: [targetParams, viem_1.maxUint256, 0n, viem_1.maxUint256, user, [], true],
180
- });
181
- // Fallback: if the repay above is skipped, skim any residual loan tokens to the user.
182
- callback.push({
183
- type: "erc20Transfer",
184
- args: [targetParams.loanToken, user, viem_1.maxUint256, generalAdapter1, false],
185
- });
186
- }
187
- callback.push({
188
- type: "morphoWithdrawCollateral",
189
- args: [sourceParams, collateralAmount, generalAdapter1, false],
190
- });
191
- const actions = [];
192
- if (authorizationSignature) {
193
- actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
194
- }
195
- const { actions: reallocationActions, fee: reallocationFee, penaltyAssets: reallocationPenaltyAssets, } = (0, buildReallocationActions_js_1.buildBlueReallocationActions)({
78
+ (0, validate_js_1.validateUint256Field)("maxLtv", maxLtv);
79
+ const common = {
196
80
  chainId,
197
- reallocations: targetReallocations,
198
- targetMarketParams: targetParams,
199
- });
200
- actions.push(...reallocationActions);
201
- actions.push({
202
- type: "morphoSupplyCollateral",
203
- args: [targetParams, collateralAmount, user, callback, false],
81
+ userAddress,
82
+ deadline: params.args.deadline,
83
+ referralFeePct: params.args.referralFeePct,
84
+ referralFeeRecipient: params.args.referralFeeRecipient,
85
+ metadata: params.metadata,
86
+ };
87
+ const { referralFeePct, referralFeeRecipient } = (0, common_js_1.normalizeBlueBundlesV1CommonParams)(common);
88
+ const signedAuthorization = (0, common_js_1.getBlueBundlesV1SignedAuthorization)({
89
+ chainId,
90
+ userAddress,
91
+ authorizationSignature,
204
92
  });
205
- let tx = index_js_1.BundlerAction.encodeBundle(chainId, actions);
206
- if (metadata) {
207
- tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
208
- }
209
- return (0, morpho_ts_1.deepFreeze)({
210
- ...tx,
93
+ const publicAllocations = (0, common_js_1.getBlueBundlesV1PublicAllocations)([...(params.args.reallocations ?? [])], destinationMarketParams);
94
+ const reallocationPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(publicAllocations);
95
+ return (0, common_js_1.finalizeBlueBundlesV1Transaction)({
96
+ common,
97
+ value: 0n,
98
+ data: (0, viem_1.encodeFunctionData)({
99
+ abi: abis_js_1.blueBundlesV1Abi,
100
+ functionName: "blueBundlesV1MigrateBorrowPosition",
101
+ args: [
102
+ sourceMarketParams,
103
+ destinationMarketParams,
104
+ maxLtv,
105
+ signedAuthorization,
106
+ publicAllocations,
107
+ referralFeePct,
108
+ referralFeeRecipient,
109
+ params.args.deadline,
110
+ ],
111
+ }),
211
112
  action: {
212
113
  type: "blueRefinance",
213
114
  args: {
214
- sourceMarket: sourceParams.id,
215
- targetMarket: targetParams.id,
216
- collateralAmount,
217
- borrowAssets,
218
- borrowShares,
219
- minBorrowSharePrice,
220
- maxRepaySharePrice,
221
- user,
222
- reallocationFee,
115
+ sourceMarket: sourceMarketParams.id,
116
+ destinationMarket: destinationMarketParams.id,
117
+ maxLtv,
118
+ onBehalf: userAddress,
119
+ reallocations: publicAllocations.length,
223
120
  reallocationPenaltyAssets,
121
+ referralFeePct,
122
+ referralFeeRecipient,
123
+ deadline: params.args.deadline,
224
124
  },
225
125
  },
226
126
  });
@@ -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>>;