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