@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,170 +1,181 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.blueRepayWithdrawCollateral = 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 buildAssetFundingActions_js_1 = require("./buildAssetFundingActions.js");
12
- const resolveRepayFunding_js_1 = require("./resolveRepayFunding.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");
13
9
  /**
14
- * Prepares an atomic repay-and-withdraw-collateral transaction for a Morpho Blue market.
10
+ * Encodes a direct BlueBundlesV1 repay and/or collateral-withdrawal transaction.
15
11
  *
16
- * Routed through bundler3. The bundle order is critical:
12
+ * `maxRepayAssets` funds the live repayment plus fee and BlueBundlesV1 refunds the unused amount.
13
+ * A saturated `repayShares = maxUint256` closes the live remaining debt. This route has no
14
+ * Bundler3 share-price bound or `slippageTolerance` input.
17
15
  *
18
- * 1. ERC-20 transfer of the loan token to `GeneralAdapter1`.
19
- * 2. `morphoRepay` — reduces debt **first**.
20
- * 3. `morphoWithdrawCollateral` — then withdraws collateral.
21
- *
22
- * If the order were reversed, Morpho would revert because the position would be insolvent at the
23
- * time of the withdraw. All amount arithmetic is done upstream (see
24
- * `MorphoBlue.repayWithdrawCollateral`); this builder just assembles the bundle from the
25
- * pre-resolved {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional
26
- * native wrapping (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()`
27
- * before the repay; the loan token must be the chain's wNative):
28
- *
29
- * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
30
- * additive like `blueSupply`), pulling `amount` ERC-20.
31
- * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
32
- * ERC-20 (already net of native); residual loan tokens are skimmed back to `receiver`.
33
- *
34
- * Prerequisites: ERC-20 approval for the loan token to `GeneralAdapter1` (for the repay) **and**
35
- * `GeneralAdapter1` must be authorized on Morpho (for the withdraw). Passing an
36
- * `authorizationSignature` prepends the authorization in-bundle instead.
37
- *
38
- * @param params.market.chainId - The chain the market lives on.
39
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
40
- * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
41
- * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
42
- * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
43
- * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
44
- * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
45
- * Requires the loan token to be the chain's wNative.
46
- * @param params.args.withdrawAmount - Amount of collateral to withdraw after the repay leg
47
- * completes.
48
- * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
49
- * @param params.args.receiver - Address that receives the withdrawn collateral and any residual
50
- * loan tokens in shares mode.
51
- * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
52
- * protection.
53
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
54
- * loan-token transfer.
55
- * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
56
- * a `setAuthorizationWithSig` call is prepended to the bundle.
57
- * @param params.metadata - Optional analytics metadata attached to the bundle.
58
- * @returns A deep-frozen `Transaction<BlueRepayWithdrawCollateralAction>` with `to`,
59
- * `value` (= `nativeAmount`), `data`, and the typed `action` discriminator the simulation layer consumes.
60
- * @throws {NonPositiveInputError} when `maxSharePrice <= 0n`, the total funding is zero, or
61
- * `withdrawAmount <= 0n`.
62
- * @throws {NegativeInputError} when `amount`, `shares`, `nativeAmount`, or `transferAmount` is negative.
63
- * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
64
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
65
- * `transferAmount !== amount + nativeAmount`.
66
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
67
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
68
- * the chain's wNative.
69
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
70
- * is provided and the signed asset differs from `marketParams.loanToken`.
71
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
72
- * is provided and the signed amount differs from the ERC-20 amount pulled.
73
- * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
74
- * signature is missing its expiration.
16
+ * @param params - Combined-operation encoding parameters.
17
+ * @param params.market.chainId - Chain containing BlueBundlesV1.
18
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
19
+ * @param params.args.userAddress - User whose position is changed.
20
+ * @param params.args.repayAssets - Exact assets repaid, exclusive with shares.
21
+ * @param params.args.repayShares - Exact shares or `maxUint256` for full repay.
22
+ * @param params.args.maxRepayAssets - Gross repayment and fee funding cap.
23
+ * @param params.args.collateralAssets - Collateral withdrawn, or zero.
24
+ * @param params.args.maxLtv - Maximum post-operation LTV.
25
+ * @param params.args.nativeAmount - Exclusive native repay funding.
26
+ * @param params.args.deadline - Final call deadline in Unix seconds.
27
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
28
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
29
+ * @param params.args.requirementSignature - Optional loan-token signature.
30
+ * @param params.args.authorizationSignature - Optional Blue authorization signature.
31
+ * @param params.metadata - Optional transaction metadata.
32
+ * @returns A deep-frozen `Readonly<Transaction<BlueRepayWithdrawCollateralAction>>`
33
+ * whose `to` address is BlueBundlesV1 and whose `action` records the normalized inputs.
34
+ * @throws {NegativeInputError} when an amount, `maxLtv`, native value, or fee is negative.
35
+ * @throws {MutuallyExclusiveRepayAmountsError} when assets and shares are both nonzero.
36
+ * @throws {NonPositiveInputError} when both operation legs are zero, repay funding is absent, or the deadline is invalid.
37
+ * @throws {MaxRepayAssetsBelowRepayAssetsError} when exact-asset funding cannot cover the repayment and referral fee.
38
+ * @throws {InputExceedsMaxError} when the referral fee is at least WAD.
39
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
40
+ * @throws {NativeFundingAmountMismatchError} when native funding is partial or mixed.
41
+ * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
42
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets another token.
43
+ * @throws {UnexpectedRequirementSignatureError} when a signature is supplied for an inactive leg.
44
+ * @throws {DepositOwnerMismatchError} when a signed owner differs from `userAddress`.
45
+ * @throws {DepositAssetMismatchError} when the signed asset differs from the loan token.
46
+ * @throws {DepositAmountMismatchError} when the signed amount differs from `maxRepayAssets`.
47
+ * @throws {DepositSpenderMismatchError} when the signed spender is not BlueBundlesV1.
48
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when a signature cannot be bound safely.
49
+ * @throws {UnsupportedChainIdError} when the chain is absent from the registry.
50
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
75
51
  * @example
76
52
  * ```ts
53
+ * import { markets } from "@morpho-org/morpho-test";
77
54
  * import { blueRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
55
+ * import { maxUint256, zeroAddress } from "viem";
56
+ * import { mainnet } from "viem/chains";
78
57
  *
58
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
79
59
  * const tx = blueRepayWithdrawCollateral({
80
- * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
60
+ * market: { chainId: mainnet.id, marketParams },
81
61
  * args: {
82
- * shares: 500_000_000_000_000_000_000_000n,
83
- * transferAmount: 310_000_000_000_000_000n, // ERC-20 pulled (net of native)
84
- * nativeAmount: 200_000_000_000_000_000n, // 0.2 funded by wrapping native ETH
85
- * withdrawAmount: 1_000_000_000_000_000_000n,
86
- * onBehalf: borrower,
87
- * receiver: borrower,
88
- * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
62
+ * userAddress: zeroAddress,
63
+ * repayAssets: 1_000_000n,
64
+ * repayShares: 0n,
65
+ * maxRepayAssets: 1_000_000n,
66
+ * collateralAssets: 0n,
67
+ * maxLtv: maxUint256,
68
+ * deadline: 1_900_000_000n,
89
69
  * },
90
70
  * });
91
- * // tx.value === 200_000_000_000_000_000n
71
+ * // tx satisfies Readonly<Transaction<BlueRepayWithdrawCollateralAction>>
92
72
  * ```
93
73
  */
94
- const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args, metadata, }) => {
95
- const { amount = 0n, shares = 0n, nativeAmount = 0n, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, authorizationSignature, } = args;
96
- const { isSharesMode, repayAssets, repayShares, erc20Amount } = (0, resolveRepayFunding_js_1.resolveRepayFunding)({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
97
- if (withdrawAmount <= 0n) {
98
- throw new index_js_3.NonPositiveInputError("withdrawAmount", withdrawAmount);
74
+ const blueRepayWithdrawCollateral = (params) => {
75
+ const { chainId, marketParams } = params.market;
76
+ const { userAddress, repayAssets, repayShares, maxRepayAssets, collateralAssets, maxLtv, requirementSignature, authorizationSignature, } = params.args;
77
+ for (const [field, value] of [
78
+ ["repayAssets", repayAssets],
79
+ ["repayShares", repayShares],
80
+ ["maxRepayAssets", maxRepayAssets],
81
+ ["collateralAssets", collateralAssets],
82
+ ["maxLtv", maxLtv],
83
+ ]) {
84
+ (0, validate_js_1.validateUint256Field)(field, value);
85
+ }
86
+ if (repayAssets > 0n && repayShares > 0n) {
87
+ throw new index_js_1.MutuallyExclusiveRepayAmountsError(marketParams.id);
88
+ }
89
+ const hasRepay = repayAssets > 0n || repayShares > 0n;
90
+ if (!hasRepay && collateralAssets === 0n) {
91
+ throw new index_js_1.NonPositiveInputError("repayAssets, repayShares, or collateralAssets", 0n);
92
+ }
93
+ if (hasRepay && maxRepayAssets === 0n) {
94
+ throw new index_js_1.NonPositiveInputError("maxRepayAssets", maxRepayAssets);
99
95
  }
100
- const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
101
- const actions = [];
102
- // Authorize GeneralAdapter1 in-bundle when a signed authorization is supplied.
103
- if (authorizationSignature) {
104
- actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
96
+ if (!hasRepay && maxRepayAssets > 0n) {
97
+ // Withdrawal-only has no repay leg to fund: reject stray funding that would encode a phantom
98
+ // repay. Native funding is transitively rejected — `validateBlueBundlesV1NativeFunding`
99
+ // requires `nativeAmount === maxRepayAssets` (= 0).
100
+ throw new index_js_1.InputExceedsMaxError({
101
+ field: "maxRepayAssets",
102
+ value: maxRepayAssets,
103
+ max: 0n,
104
+ });
105
+ }
106
+ if (!hasRepay && requirementSignature != null) {
107
+ throw new index_js_1.UnexpectedRequirementSignatureError(requirementSignature.action.type);
108
+ }
109
+ if (collateralAssets === 0n && authorizationSignature != null) {
110
+ throw new index_js_1.UnexpectedRequirementSignatureError("authorization");
111
+ }
112
+ const common = {
113
+ chainId,
114
+ userAddress,
115
+ deadline: params.args.deadline,
116
+ referralFeePct: params.args.referralFeePct,
117
+ referralFeeRecipient: params.args.referralFeeRecipient,
118
+ metadata: params.metadata,
119
+ };
120
+ const { referralFeePct, referralFeeRecipient } = (0, common_js_1.normalizeBlueBundlesV1CommonParams)(common);
121
+ const minimumRepayAssets = repayAssets +
122
+ (0, common_js_1.getBlueBundlesV1ReferralFeeAssets)(repayAssets, referralFeePct);
123
+ if (minimumRepayAssets > maxRepayAssets) {
124
+ throw new index_js_1.MaxRepayAssetsBelowRepayAssetsError(maxRepayAssets, minimumRepayAssets);
105
125
  }
106
- // Fund the repay: wrap native (if any) then pull the ERC-20 remainder.
107
- actions.push(...(0, buildAssetFundingActions_js_1.buildAssetFundingActions)({
126
+ const value = (0, common_js_1.validateBlueBundlesV1NativeFunding)({
108
127
  chainId,
109
- asset: marketParams.loanToken,
110
- erc20Amount,
111
- nativeAmount,
128
+ token: marketParams.loanToken,
129
+ fundedAmount: maxRepayAssets,
130
+ nativeAmount: params.args.nativeAmount,
112
131
  requirementSignature,
113
- }));
114
- // REPAY FIRST — reduces debt before withdrawing collateral
115
- actions.push({
116
- type: "morphoRepay",
117
- args: [
118
- marketParams,
119
- repayAssets,
120
- repayShares,
121
- maxSharePrice,
122
- onBehalf,
123
- [],
124
- false,
125
- ],
126
132
  });
127
- // Skim residual loan tokens back to the payer when repaying by shares.
128
- // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
129
- // consumes only the exact amount needed, leaving a residual in the adapter.
130
- if (isSharesMode) {
131
- actions.push({
132
- type: "erc20Transfer",
133
+ const loanTokenPermit = (0, common_js_1.getBlueBundlesV1TokenPermit)({
134
+ chainId,
135
+ userAddress,
136
+ token: marketParams.loanToken,
137
+ amount: maxRepayAssets,
138
+ requirementSignature,
139
+ });
140
+ const signedAuthorization = (0, common_js_1.getBlueBundlesV1SignedAuthorization)({
141
+ chainId,
142
+ userAddress,
143
+ authorizationSignature,
144
+ });
145
+ return (0, common_js_1.finalizeBlueBundlesV1Transaction)({
146
+ common,
147
+ value,
148
+ data: (0, viem_1.encodeFunctionData)({
149
+ abi: abis_js_1.blueBundlesV1Abi,
150
+ functionName: "blueBundlesV1RepayAndWithdrawCollateral",
133
151
  args: [
134
- marketParams.loanToken,
135
- receiver,
136
- viem_1.maxUint256,
137
- generalAdapter1,
138
- false,
152
+ marketParams,
153
+ repayAssets,
154
+ repayShares,
155
+ maxRepayAssets,
156
+ collateralAssets,
157
+ maxLtv,
158
+ loanTokenPermit,
159
+ signedAuthorization,
160
+ referralFeePct,
161
+ referralFeeRecipient,
162
+ params.args.deadline,
139
163
  ],
140
- });
141
- }
142
- actions.push({
143
- type: "morphoWithdrawCollateral",
144
- args: [marketParams, withdrawAmount, receiver, false],
145
- });
146
- let tx = {
147
- ...index_js_1.BundlerAction.encodeBundle(chainId, actions),
148
- value: nativeAmount,
149
- };
150
- if (metadata) {
151
- tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
152
- }
153
- return (0, morpho_ts_1.deepFreeze)({
154
- ...tx,
164
+ }),
155
165
  action: {
156
166
  type: "blueRepayWithdrawCollateral",
157
167
  args: {
158
168
  market: marketParams.id,
159
169
  repayAssets,
160
170
  repayShares,
161
- // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
162
- transferAmount: erc20Amount + nativeAmount,
163
- withdrawAmount,
164
- maxSharePrice,
165
- onBehalf,
166
- receiver,
167
- nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
171
+ maxRepayAssets,
172
+ collateralAssets,
173
+ maxLtv,
174
+ onBehalf: userAddress,
175
+ nativeAmount: value > 0n ? value : undefined,
176
+ referralFeePct,
177
+ referralFeeRecipient,
178
+ deadline: params.args.deadline,
168
179
  },
169
180
  },
170
181
  });
@@ -1,67 +1,84 @@
1
1
  import type { MarketParams } from "@morpho-org/blue-sdk";
2
- import type { Address } from "viem";
3
- import { type BlueSupplyAction, type DepositAmountArgs, type Metadata, type PermitRequirementSignature, type Transaction } from "../../types/index.js";
2
+ import { type Address } from "viem";
3
+ import type { BlueBundlesV1TokenRequirementSignature, BlueSupplyAction, Metadata, Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueSupply}. */
5
5
  export interface BlueSupplyParams {
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: DepositAmountArgs & {
11
- /** Address whose Morpho supply position is credited. */
12
- onBehalf: Address;
13
- /** Maximum supply share price (in ray). Slippage protection against inflation attacks. */
14
- maxSharePrice: bigint;
15
- /** Optional pre-signed permit/permit2 approval for the loan-token transfer. */
16
- requirementSignature?: PermitRequirementSignature;
11
+ /** Direct BlueBundlesV1 supply arguments. */
12
+ readonly args: {
13
+ /** User funding and receiving the supply position. */
14
+ readonly userAddress: Address;
15
+ /** Gross loan-token assets funded before any referral fee. */
16
+ readonly assets: bigint;
17
+ /** Full native funding amount; must equal `assets` and requires a wNative loan token. */
18
+ readonly nativeAmount?: bigint;
19
+ /** Final call deadline in Unix seconds. */
20
+ readonly deadline: bigint;
21
+ /** Optional WAD-scaled referral fee, strictly below 100%. */
22
+ readonly referralFeePct?: bigint;
23
+ /** Recipient required when `referralFeePct` is positive. */
24
+ readonly referralFeeRecipient?: Address;
25
+ /** Optional ERC-2612 or Permit2 SignatureTransfer requirement result. */
26
+ readonly requirementSignature?: BlueBundlesV1TokenRequirementSignature;
17
27
  };
18
- metadata?: Metadata;
28
+ /** Optional transaction metadata suffix. */
29
+ readonly metadata?: Metadata;
19
30
  }
20
31
  /**
21
- * Prepares a loan-asset supply transaction for a Morpho Blue market.
32
+ * Encodes a direct BlueBundlesV1 loan-asset supply transaction.
22
33
  *
23
- * Routed through bundler3 via `GeneralAdapter1`. When `nativeAmount > 0`, native ETH is wrapped
24
- * via `GeneralAdapter1.wrapNative()` before the supply; the loan token must be the chain's
25
- * wNative for that path. Uses `maxSharePrice` to protect against share-price inflation between
26
- * transaction construction and execution.
34
+ * `assets` is the gross funded amount; BlueBundlesV1 deducts the referral fee before supplying.
35
+ * This route has no Bundler3 share-price bound or `slippageTolerance` input.
27
36
  *
28
- * Zero loss: all supplied assets reach Morpho. No dust left in bundler or adapter.
29
- *
30
- * @param params.market.chainId - The chain the market lives on.
31
- * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
32
- * @param params.args.amount - Amount of ERC-20 loan asset to supply. At least one of `amount` or
33
- * `nativeAmount` must be positive. Defaults to `0n`.
34
- * @param params.args.onBehalf - Address whose Morpho supply position is credited.
35
- * @param params.args.maxSharePrice - Maximum acceptable supply share price (in ray). Slippage
36
- * protection.
37
- * @param params.args.nativeAmount - Optional amount of native token to wrap into wNative for the
38
- * supply. Requires the loan token to be the chain's wNative.
39
- * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval.
40
- * @param params.metadata - Optional analytics metadata attached to the bundle.
41
- * @returns A deep-frozen `Transaction<BlueSupplyAction>` with `to`, `value`, `data`, and the
42
- * typed `action` discriminator the simulation layer consumes.
43
- * @throws {NegativeInputError} when `amount`, `nativeAmount`, or `maxSharePrice` is negative.
44
- * @throws {NonPositiveInputError} when both `amount` and `nativeAmount` resolve to zero.
45
- * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
46
- * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
47
- * the chain's wNative.
48
- * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
49
- * is provided and the signed asset differs from `marketParams.loanToken`.
50
- * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
51
- * is provided and the signed amount differs from `args.amount`.
37
+ * @param params - Supply encoding parameters.
38
+ * @param params.market.chainId - Chain containing the BlueBundlesV1 deployment.
39
+ * @param params.market.marketParams - Scoped Morpho Blue market parameters.
40
+ * @param params.args.userAddress - User funding and receiving the position.
41
+ * @param params.args.assets - Gross loan-token funding amount.
42
+ * @param params.args.nativeAmount - Exclusive native funding; must equal `assets`.
43
+ * @param params.args.deadline - Final call deadline in Unix seconds.
44
+ * @param params.args.referralFeePct - Optional WAD-scaled fee below 100%.
45
+ * @param params.args.referralFeeRecipient - Recipient required for a positive fee.
46
+ * @param params.args.requirementSignature - Optional ERC-2612 or Permit2 SignatureTransfer result.
47
+ * @param params.metadata - Optional transaction metadata.
48
+ * @returns A deep-frozen `Readonly<Transaction<BlueSupplyAction>>` whose `to` address is
49
+ * BlueBundlesV1 and whose `action` records the normalized supply inputs.
50
+ * @throws {NonPositiveInputError} when `assets` or `deadline` is not positive.
51
+ * @throws {NegativeInputError} when `nativeAmount` or `referralFeePct` is negative.
52
+ * @throws {InputExceedsMaxError} when `assets` exceeds `uint256` or `referralFeePct` is at least WAD.
53
+ * @throws {MissingReferralFeeRecipientError} when a positive fee has no recipient.
54
+ * @throws {NativeFundingAmountMismatchError} when native funding does not equal `assets`.
55
+ * @throws {ChainWNativeMissingError} when native funding is requested on a chain without wNative.
56
+ * @throws {NativeAmountOnNonWNativeAssetError} when native funding targets another token.
57
+ * @throws {UnexpectedRequirementSignatureError} when native funding also supplies a token signature.
58
+ * @throws {DepositOwnerMismatchError} when the signed owner differs from `userAddress`.
59
+ * @throws {DepositAssetMismatchError} when the signed asset differs from the loan token.
60
+ * @throws {DepositAmountMismatchError} when the signed amount differs from `assets`.
61
+ * @throws {DepositSpenderMismatchError} when the signed spender is not BlueBundlesV1.
62
+ * @throws {BlueBundlesV1RequirementSignatureMismatchError} when the signature kind or encoding is invalid.
63
+ * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
64
+ * @throws {UnknownAddressError} when BlueBundlesV1 is not registered.
52
65
  * @example
53
66
  * ```ts
67
+ * import { markets } from "@morpho-org/morpho-test";
54
68
  * import { blueSupply } from "@morpho-org/morpho-sdk";
69
+ * import { zeroAddress } from "viem";
70
+ * import { mainnet } from "viem/chains";
55
71
  *
72
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
56
73
  * const tx = blueSupply({
57
- * market: { chainId: 1, marketParams },
74
+ * market: { chainId: mainnet.id, marketParams },
58
75
  * args: {
59
- * amount: 1_000_000_000n,
60
- * onBehalf: supplier,
61
- * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
76
+ * userAddress: zeroAddress,
77
+ * assets: 1_000_000n,
78
+ * deadline: 1_900_000_000n,
62
79
  * },
63
80
  * });
64
81
  * // tx satisfies Readonly<Transaction<BlueSupplyAction>>
65
82
  * ```
66
83
  */
67
- export declare const blueSupply: ({ market: { chainId, marketParams }, args: { amount, onBehalf, maxSharePrice, requirementSignature, nativeAmount, }, metadata, }: BlueSupplyParams) => Readonly<Transaction<BlueSupplyAction>>;
84
+ export declare const blueSupply: (params: BlueSupplyParams) => Readonly<Transaction<BlueSupplyAction>>;