@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,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>>;
@@ -1,141 +1,79 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.blueRepay = void 0;
4
- const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
4
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
5
  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 buildAssetFundingActions_js_1 = require("./buildAssetFundingActions.js");
10
- const resolveRepayFunding_js_1 = require("./resolveRepayFunding.js");
6
+ const repayWithdrawCollateral_js_1 = require("./repayWithdrawCollateral.js");
11
7
  /**
12
- * Prepares a repay transaction for a Morpho Blue market.
8
+ * Encodes a pure repayment through BlueBundlesV1.
13
9
  *
14
- * Routed through bundler3 via `GeneralAdapter1`. All amount arithmetic is done upstream (see
15
- * `MorphoBlue.repay`); this builder just assembles the bundle from the pre-resolved
16
- * {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional native wrapping
17
- * (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()` before the
18
- * repay; the loan token must be the chain's wNative):
10
+ * Delegates to {@link blueRepayWithdrawCollateral} with a zero collateral-withdrawal leg and an
11
+ * unrestricted LTV cap. BlueBundlesV1 refunds unused `maxRepayAssets` funding.
19
12
  *
20
- * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
21
- * additive like `blueSupply`), pulling `amount` ERC-20 and wrapping `nativeAmount`. No residual.
22
- * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
23
- * ERC-20 (already net of native) and wrapping `nativeAmount`. Residual loan tokens are skimmed
24
- * back to `receiver` after the call.
25
- *
26
- * Uses `maxSharePrice` to protect against share price manipulation between construction and execution.
27
- *
28
- * @param params.market.chainId - The chain the market lives on.
29
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
30
- * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
31
- * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
32
- * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
33
- * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
34
- * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
35
- * Requires the loan token to be the chain's wNative.
36
- * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
37
- * @param params.args.receiver - Address that receives residual loan tokens in shares mode.
38
- * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
39
- * protection.
40
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
41
- * loan-token transfer.
42
- * @param params.metadata - Optional analytics metadata attached to the bundle.
43
- * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value` (= `nativeAmount`),
44
- * `data`, and the typed `action` discriminator the simulation layer consumes.
45
- * @throws {NonPositiveInputError} when `maxSharePrice <= 0n` or the total funding is zero.
46
- * @throws {NegativeInputError} when `amount`, `shares`, `nativeAmount`, or `transferAmount` is negative.
47
- * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
48
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
49
- * `transferAmount !== amount + nativeAmount`.
50
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
51
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
52
- * the chain's wNative.
53
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
54
- * is provided and the signed asset differs from `marketParams.loanToken`.
55
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
56
- * is provided and the signed amount differs from the ERC-20 amount pulled.
57
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
58
- * signature is missing its expiration.
13
+ * @param params - Repay encoding parameters.
14
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
15
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
16
+ * @param params.args.userAddress - User whose debt is repaid.
17
+ * @param params.args.repayAssets - Exact assets repaid, exclusive with shares.
18
+ * @param params.args.repayShares - Exact shares or `maxUint256` for full repay.
19
+ * @param params.args.maxRepayAssets - Gross repayment and fee funding cap.
20
+ * @param params.args.nativeAmount - Exclusive native repay funding.
21
+ * @param params.args.deadline - Final call deadline in Unix seconds.
22
+ * @param params.args.referralFeePct - Optional WAD-scaled referral fee.
23
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
24
+ * @param params.args.requirementSignature - Optional loan-token signature.
25
+ * @param params.metadata - Optional transaction metadata.
26
+ * @returns A deep-frozen `Readonly<Transaction<BlueRepayAction>>` whose calldata invokes the
27
+ * combined BlueBundlesV1 entrypoint with a zero collateral-withdrawal leg.
28
+ * @throws {NegativeInputError} when an amount or fee is negative.
29
+ * @throws {MutuallyExclusiveRepayAmountsError} when assets and shares are both nonzero.
30
+ * @throws {NonPositiveInputError} when repayment, funding, or deadline is not positive.
31
+ * @throws {MaxRepayAssetsBelowRepayAssetsError} when funding cannot cover repayment and fees.
32
+ * @throws {NativeFundingAmountMismatchError} when native funding is partial or mixed.
33
+ * @throws {ChainWNativeMissingError} when native funding is requested without a registered wNative.
34
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets another loan token.
35
+ * @throws {UnexpectedRequirementSignatureError} when native funding also supplies a token signature.
36
+ * @throws {DepositOwnerMismatchError} when the signed owner differs from `userAddress`.
37
+ * @throws {DepositAssetMismatchError} when the signed asset differs from the loan token.
38
+ * @throws {DepositAmountMismatchError} when the signed amount differs from `maxRepayAssets`.
39
+ * @throws {DepositSpenderMismatchError} when the signed spender is not BlueBundlesV1.
40
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when a signature cannot be encoded safely.
41
+ * @throws {InputExceedsMaxError} when the referral fee is at least WAD.
42
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
43
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
44
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
59
45
  * @example
60
46
  * ```ts
47
+ * import { markets } from "@morpho-org/morpho-test";
61
48
  * import { blueRepay } from "@morpho-org/morpho-sdk";
49
+ * import { zeroAddress } from "viem";
50
+ * import { mainnet } from "viem/chains";
62
51
  *
63
- * // Repay 0.5 loan-asset units, 0.2 of them funded by wrapping native ETH.
64
52
  * const tx = blueRepay({
65
- * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
53
+ * market: { chainId: mainnet.id, marketParams: markets[mainnet.id].usdc_wbtc },
66
54
  * args: {
67
- * amount: 300_000_000_000_000_000n, // ERC-20 part
68
- * nativeAmount: 200_000_000_000_000_000n, // wrapped ETH part
69
- * transferAmount: 500_000_000_000_000_000n, // total repaid = amount + nativeAmount
70
- * onBehalf: borrower,
71
- * receiver: borrower,
72
- * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
55
+ * userAddress: zeroAddress,
56
+ * repayAssets: 1_000_000n,
57
+ * repayShares: 0n,
58
+ * maxRepayAssets: 1_000_000n,
59
+ * deadline: 1_900_000_000n,
73
60
  * },
74
61
  * });
75
- * // tx.value === 200_000_000_000_000_000n
62
+ * // tx satisfies Readonly<Transaction<BlueRepayAction>>
76
63
  * ```
77
64
  */
78
- const blueRepay = ({ market: { chainId, marketParams }, args, metadata, }) => {
79
- const { amount = 0n, shares = 0n, nativeAmount = 0n, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, } = args;
80
- const { isSharesMode, repayAssets, repayShares, erc20Amount } = (0, resolveRepayFunding_js_1.resolveRepayFunding)({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
81
- const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
82
- const actions = (0, buildAssetFundingActions_js_1.buildAssetFundingActions)({
83
- chainId,
84
- asset: marketParams.loanToken,
85
- erc20Amount,
86
- nativeAmount,
87
- requirementSignature,
88
- });
89
- actions.push({
90
- type: "morphoRepay",
91
- args: [
92
- marketParams,
93
- repayAssets,
94
- repayShares,
95
- maxSharePrice,
96
- onBehalf,
97
- [],
98
- false,
99
- ],
65
+ const blueRepay = (params) => {
66
+ const transaction = (0, repayWithdrawCollateral_js_1.blueRepayWithdrawCollateral)({
67
+ ...params,
68
+ args: {
69
+ ...params.args,
70
+ collateralAssets: 0n,
71
+ maxLtv: viem_1.maxUint256,
72
+ },
100
73
  });
101
- // Skim residual loan tokens back to the payer when repaying by shares.
102
- // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
103
- // consumes only the exact amount needed, leaving a residual in the adapter.
104
- if (isSharesMode) {
105
- actions.push({
106
- type: "erc20Transfer",
107
- args: [
108
- marketParams.loanToken,
109
- receiver,
110
- viem_1.maxUint256,
111
- generalAdapter1,
112
- false,
113
- ],
114
- });
115
- }
116
- let tx = {
117
- ...index_js_1.BundlerAction.encodeBundle(chainId, actions),
118
- value: nativeAmount,
119
- };
120
- if (metadata) {
121
- tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
122
- }
123
74
  return (0, morpho_ts_1.deepFreeze)({
124
- ...tx,
125
- action: {
126
- type: "blueRepay",
127
- args: {
128
- market: marketParams.id,
129
- assets: repayAssets,
130
- shares: repayShares,
131
- // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
132
- transferAmount: erc20Amount + nativeAmount,
133
- onBehalf,
134
- receiver,
135
- maxSharePrice,
136
- nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
137
- },
138
- },
75
+ ...transaction,
76
+ action: { ...transaction.action, type: "blueRepay" },
139
77
  });
140
78
  };
141
79
  exports.blueRepay = blueRepay;
@@ -1,111 +1,106 @@
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 AuthorizationRequirementSignature, type BlueRepayWithdrawCollateralAction, type Metadata, type PermitRequirementSignature, type RepayActionAmountArgs, type Transaction } from "../../types/index.js";
3
+ import { type AuthorizationRequirementSignature, type BlueBundlesV1TokenRequirementSignature, type BlueRepayWithdrawCollateralAction, type Metadata, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueRepayWithdrawCollateral}. */
5
5
  export interface BlueRepayWithdrawCollateralParams {
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
- /** Amount of collateral to withdraw. */
12
- withdrawAmount: bigint;
13
- /** Address whose debt is being repaid. */
14
- onBehalf: Address;
15
- /** Receives withdrawn collateral and residual loan tokens in shares mode. */
16
- receiver: Address;
17
- /** Maximum repay share price (in ray). Protects against share price manipulation. */
18
- maxSharePrice: bigint;
19
- /** Optional pre-signed permit/permit2 approval for the loan-token transfer. */
20
- requirementSignature?: PermitRequirementSignature;
21
- /**
22
- * Optional signed Morpho authorization. When provided, a `setAuthorizationWithSig` call is
23
- * prepended to the bundle so GeneralAdapter1 is authorized in-bundle instead of via a
24
- * standalone `setAuthorization` transaction.
25
- */
26
- authorizationSignature?: AuthorizationRequirementSignature;
11
+ /** Direct BlueBundlesV1 combined-operation arguments. */
12
+ readonly args: {
13
+ /** User whose debt and collateral position is changed. */
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
+ /** Collateral assets withdrawn; zero selects a pure repay. */
22
+ readonly collateralAssets: bigint;
23
+ /** Maximum post-operation LTV enforced by BlueBundlesV1. */
24
+ readonly maxLtv: bigint;
25
+ /** Full native repay funding; must equal `maxRepayAssets`. */
26
+ readonly nativeAmount?: bigint;
27
+ /** Final call deadline in Unix seconds. */
28
+ readonly deadline: bigint;
29
+ /** Optional WAD-scaled referral fee, strictly below 100%. */
30
+ readonly referralFeePct?: bigint;
31
+ /** Recipient required when `referralFeePct` is positive. */
32
+ readonly referralFeeRecipient?: Address;
33
+ /** Optional loan-token ERC-2612 or Permit2 SignatureTransfer result. */
34
+ readonly requirementSignature?: BlueBundlesV1TokenRequirementSignature;
35
+ /** Optional Morpho authorization signature for BlueBundlesV1. */
36
+ readonly authorizationSignature?: AuthorizationRequirementSignature;
27
37
  };
28
- metadata?: Metadata;
38
+ /** Optional transaction metadata suffix. */
39
+ readonly metadata?: Metadata;
29
40
  }
30
41
  /**
31
- * Prepares an atomic repay-and-withdraw-collateral transaction for a Morpho Blue market.
42
+ * Encodes a direct BlueBundlesV1 repay and/or collateral-withdrawal transaction.
32
43
  *
33
- * Routed through bundler3. The bundle order is critical:
44
+ * `maxRepayAssets` funds the live repayment plus fee and BlueBundlesV1 refunds the unused amount.
45
+ * A saturated `repayShares = maxUint256` closes the live remaining debt. This route has no
46
+ * Bundler3 share-price bound or `slippageTolerance` input.
34
47
  *
35
- * 1. ERC-20 transfer of the loan token to `GeneralAdapter1`.
36
- * 2. `morphoRepay` — reduces debt **first**.
37
- * 3. `morphoWithdrawCollateral` — then withdraws collateral.
38
- *
39
- * If the order were reversed, Morpho would revert because the position would be insolvent at the
40
- * time of the withdraw. All amount arithmetic is done upstream (see
41
- * `MorphoBlue.repayWithdrawCollateral`); this builder just assembles the bundle from the
42
- * pre-resolved {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional
43
- * native wrapping (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()`
44
- * before the repay; the loan token must be the chain's wNative):
45
- *
46
- * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
47
- * additive like `blueSupply`), pulling `amount` ERC-20.
48
- * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
49
- * ERC-20 (already net of native); residual loan tokens are skimmed back to `receiver`.
50
- *
51
- * Prerequisites: ERC-20 approval for the loan token to `GeneralAdapter1` (for the repay) **and**
52
- * `GeneralAdapter1` must be authorized on Morpho (for the withdraw). Passing an
53
- * `authorizationSignature` prepends the authorization in-bundle instead.
54
- *
55
- * @param params.market.chainId - The chain the market lives on.
56
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
57
- * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
58
- * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
59
- * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
60
- * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
61
- * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
62
- * Requires the loan token to be the chain's wNative.
63
- * @param params.args.withdrawAmount - Amount of collateral to withdraw after the repay leg
64
- * completes.
65
- * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
66
- * @param params.args.receiver - Address that receives the withdrawn collateral and any residual
67
- * loan tokens in shares mode.
68
- * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
69
- * protection.
70
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
71
- * loan-token transfer.
72
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
73
- * a `setAuthorizationWithSig` call is prepended to the bundle.
74
- * @param params.metadata - Optional analytics metadata attached to the bundle.
75
- * @returns A deep-frozen `Transaction<BlueRepayWithdrawCollateralAction>` with `to`,
76
- * `value` (= `nativeAmount`), `data`, and the typed `action` discriminator the simulation layer consumes.
77
- * @throws {NonPositiveInputError} when `maxSharePrice <= 0n`, the total funding is zero, or
78
- * `withdrawAmount <= 0n`.
79
- * @throws {NegativeInputError} when `amount`, `shares`, `nativeAmount`, or `transferAmount` is negative.
80
- * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
81
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
82
- * `transferAmount !== amount + nativeAmount`.
83
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
84
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
85
- * the chain's wNative.
86
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
87
- * is provided and the signed asset differs from `marketParams.loanToken`.
88
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
89
- * is provided and the signed amount differs from the ERC-20 amount pulled.
90
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
91
- * signature is missing its expiration.
48
+ * @param params - Combined-operation encoding parameters.
49
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
50
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
51
+ * @param params.args.userAddress - User whose position is changed.
52
+ * @param params.args.repayAssets - Exact assets repaid, exclusive with shares.
53
+ * @param params.args.repayShares - Exact shares or `maxUint256` for full repay.
54
+ * @param params.args.maxRepayAssets - Gross repayment and fee funding cap.
55
+ * @param params.args.collateralAssets - Collateral withdrawn, or zero.
56
+ * @param params.args.maxLtv - Maximum post-operation LTV.
57
+ * @param params.args.nativeAmount - Exclusive native repay funding.
58
+ * @param params.args.deadline - Final call deadline in Unix seconds.
59
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
60
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
61
+ * @param params.args.requirementSignature - Optional loan-token signature.
62
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
63
+ * @param params.metadata - Optional transaction metadata.
64
+ * @returns A deep-frozen `Readonly<Transaction<BlueRepayWithdrawCollateralAction>>`
65
+ * whose `to` address is BlueBundlesV1 and whose `action` records the normalized inputs.
66
+ * @throws {NegativeInputError} when an amount, `maxLtv`, native value, or fee is negative.
67
+ * @throws {MutuallyExclusiveRepayAmountsError} when assets and shares are both nonzero.
68
+ * @throws {NonPositiveInputError} when both operation legs are zero, repay funding is absent, or the deadline is invalid.
69
+ * @throws {MaxRepayAssetsBelowRepayAssetsError} when exact-asset funding cannot cover the repayment and referral fee.
70
+ * @throws {InputExceedsMaxError} when the referral fee is at least WAD.
71
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
72
+ * @throws {NativeFundingAmountMismatchError} when native funding is partial or mixed.
73
+ * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
74
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets another token.
75
+ * @throws {UnexpectedRequirementSignatureError} when a signature is supplied for an inactive leg.
76
+ * @throws {DepositOwnerMismatchError} when a signed owner differs from `userAddress`.
77
+ * @throws {DepositAssetMismatchError} when the signed asset differs from the loan token.
78
+ * @throws {DepositAmountMismatchError} when the signed amount differs from `maxRepayAssets`.
79
+ * @throws {DepositSpenderMismatchError} when the signed spender is not BlueBundlesV1.
80
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when a signature cannot be bound safely.
81
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
82
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
92
83
  * @example
93
84
  * ```ts
85
+ * import { markets } from "@morpho-org/morpho-test";
94
86
  * import { blueRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
87
+ * import { maxUint256, zeroAddress } from "viem";
88
+ * import { mainnet } from "viem/chains";
95
89
  *
90
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
96
91
  * const tx = blueRepayWithdrawCollateral({
97
- * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
92
+ * market: { chainId: mainnet.id, marketParams },
98
93
  * args: {
99
- * shares: 500_000_000_000_000_000_000_000n,
100
- * transferAmount: 310_000_000_000_000_000n, // ERC-20 pulled (net of native)
101
- * nativeAmount: 200_000_000_000_000_000n, // 0.2 funded by wrapping native ETH
102
- * withdrawAmount: 1_000_000_000_000_000_000n,
103
- * onBehalf: borrower,
104
- * receiver: borrower,
105
- * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
94
+ * userAddress: zeroAddress,
95
+ * repayAssets: 1_000_000n,
96
+ * repayShares: 0n,
97
+ * maxRepayAssets: 1_000_000n,
98
+ * collateralAssets: 0n,
99
+ * maxLtv: maxUint256,
100
+ * deadline: 1_900_000_000n,
106
101
  * },
107
102
  * });
108
- * // tx.value === 200_000_000_000_000_000n
103
+ * // tx satisfies Readonly<Transaction<BlueRepayWithdrawCollateralAction>>
109
104
  * ```
110
105
  */
111
- export declare const blueRepayWithdrawCollateral: ({ market: { chainId, marketParams }, args, metadata, }: BlueRepayWithdrawCollateralParams) => Readonly<Transaction<BlueRepayWithdrawCollateralAction>>;
106
+ export declare const blueRepayWithdrawCollateral: (params: BlueRepayWithdrawCollateralParams) => Readonly<Transaction<BlueRepayWithdrawCollateralAction>>;