@morpho-org/morpho-sdk 4.2.0 → 5.1.1

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 (191) hide show
  1. package/README.md +16 -16
  2. package/lib/cjs/actions/blue/borrow.d.ts +12 -2
  3. package/lib/cjs/actions/blue/borrow.js +7 -1
  4. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +47 -0
  5. package/lib/cjs/actions/blue/buildAssetFundingActions.js +63 -0
  6. package/lib/cjs/actions/blue/refinance.d.ts +13 -3
  7. package/lib/cjs/actions/blue/refinance.js +8 -2
  8. package/lib/cjs/actions/blue/repay.d.ts +44 -43
  9. package/lib/cjs/actions/blue/repay.js +70 -59
  10. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +50 -41
  11. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +75 -54
  12. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +69 -0
  13. package/lib/cjs/actions/blue/resolveRepayFunding.js +82 -0
  14. package/lib/cjs/actions/blue/supply.d.ts +8 -8
  15. package/lib/cjs/actions/blue/supply.js +11 -35
  16. package/lib/cjs/actions/blue/supplyCollateral.d.ts +9 -9
  17. package/lib/cjs/actions/blue/supplyCollateral.js +12 -36
  18. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +19 -7
  19. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +17 -32
  20. package/lib/cjs/actions/blue/withdraw.d.ts +10 -2
  21. package/lib/cjs/actions/blue/withdraw.js +7 -1
  22. package/lib/cjs/actions/index.d.ts +1 -0
  23. package/lib/cjs/actions/index.js +1 -0
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +49 -0
  25. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +111 -0
  26. package/lib/cjs/actions/requirements/blue/index.d.ts +1 -0
  27. package/lib/cjs/actions/requirements/blue/index.js +17 -0
  28. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +55 -0
  29. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +89 -0
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +6 -5
  31. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +17 -5
  32. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +9 -7
  33. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +18 -4
  34. package/lib/cjs/actions/requirements/encode/{encodeErc20Permit2.d.ts → encodeErc20Permit2Approve.d.ts} +11 -13
  35. package/lib/cjs/actions/requirements/encode/{encodeErc20Permit2.js → encodeErc20Permit2Approve.js} +10 -14
  36. package/lib/cjs/actions/requirements/encode/index.d.ts +2 -1
  37. package/lib/cjs/actions/requirements/encode/index.js +2 -1
  38. package/lib/cjs/actions/requirements/{getRequirements.d.ts → generalAdapter/getGeneralAdapterRequirements.d.ts} +34 -20
  39. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +151 -0
  40. package/lib/{esm/actions/requirements/getRequirementsPermit.d.ts → cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts} +6 -14
  41. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +50 -0
  42. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.d.ts +57 -0
  43. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.js +74 -0
  44. package/lib/cjs/actions/requirements/generalAdapter/index.d.ts +3 -0
  45. package/lib/cjs/actions/requirements/generalAdapter/index.js +19 -0
  46. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +3 -2
  47. package/lib/cjs/actions/requirements/getRequirementsApproval.js +3 -2
  48. package/lib/cjs/actions/requirements/index.d.ts +2 -5
  49. package/lib/cjs/actions/requirements/index.js +2 -5
  50. package/lib/cjs/actions/signatures/getBlueAuthorizationAction.d.ts +29 -0
  51. package/lib/cjs/actions/signatures/getBlueAuthorizationAction.js +48 -0
  52. package/lib/{esm/actions/requirements/getRequirementsAction.d.ts → cjs/actions/signatures/getTokenRequirementActions.d.ts} +17 -17
  53. package/lib/cjs/actions/{requirements/getRequirementsAction.js → signatures/getTokenRequirementActions.js} +26 -13
  54. package/lib/cjs/actions/signatures/index.d.ts +2 -0
  55. package/lib/cjs/actions/signatures/index.js +18 -0
  56. package/lib/cjs/actions/vaultV1/deposit.d.ts +6 -8
  57. package/lib/cjs/actions/vaultV1/deposit.js +11 -21
  58. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +6 -6
  59. package/lib/cjs/actions/vaultV1/migrateToV2.js +12 -20
  60. package/lib/cjs/actions/vaultV2/deposit.d.ts +6 -8
  61. package/lib/cjs/actions/vaultV2/deposit.js +11 -21
  62. package/lib/cjs/addresses.d.ts +2 -2
  63. package/lib/cjs/addresses.js +2 -1
  64. package/lib/cjs/bundler/actions.d.ts +44 -4
  65. package/lib/cjs/bundler/actions.js +75 -2
  66. package/lib/cjs/bundler/types.d.ts +6 -0
  67. package/lib/cjs/constants.d.ts +2 -2
  68. package/lib/cjs/constants.js +3 -3
  69. package/lib/cjs/entities/blue/blue.d.ts +58 -33
  70. package/lib/cjs/entities/blue/blue.js +309 -189
  71. package/lib/cjs/entities/reallocationData.d.ts +0 -44
  72. package/lib/cjs/entities/reallocationData.js +3 -50
  73. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +9 -9
  74. package/lib/cjs/entities/vaultV1/vaultV1.js +44 -34
  75. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +6 -6
  76. package/lib/cjs/entities/vaultV2/vaultV2.js +21 -16
  77. package/lib/cjs/errors.d.ts +3 -2
  78. package/lib/cjs/errors.js +5 -2
  79. package/lib/cjs/helpers/index.d.ts +1 -1
  80. package/lib/cjs/helpers/index.js +1 -2
  81. package/lib/cjs/helpers/validate.d.ts +2 -20
  82. package/lib/cjs/helpers/validate.js +2 -39
  83. package/lib/cjs/types/action.d.ts +164 -12
  84. package/lib/cjs/types/action.js +79 -5
  85. package/lib/cjs/types/error.d.ts +97 -2
  86. package/lib/cjs/types/error.js +113 -7
  87. package/lib/cjs/types.d.ts +2 -1
  88. package/lib/cjs/utils.d.ts +2 -2
  89. package/lib/cjs/utils.js +2 -4
  90. package/lib/esm/actions/blue/borrow.d.ts +12 -2
  91. package/lib/esm/actions/blue/borrow.js +7 -1
  92. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +47 -0
  93. package/lib/esm/actions/blue/buildAssetFundingActions.js +59 -0
  94. package/lib/esm/actions/blue/refinance.d.ts +13 -3
  95. package/lib/esm/actions/blue/refinance.js +8 -2
  96. package/lib/esm/actions/blue/repay.d.ts +44 -43
  97. package/lib/esm/actions/blue/repay.js +71 -60
  98. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +50 -41
  99. package/lib/esm/actions/blue/repayWithdrawCollateral.js +76 -55
  100. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +69 -0
  101. package/lib/esm/actions/blue/resolveRepayFunding.js +78 -0
  102. package/lib/esm/actions/blue/supply.d.ts +8 -8
  103. package/lib/esm/actions/blue/supply.js +12 -36
  104. package/lib/esm/actions/blue/supplyCollateral.d.ts +9 -9
  105. package/lib/esm/actions/blue/supplyCollateral.js +13 -37
  106. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +19 -7
  107. package/lib/esm/actions/blue/supplyCollateralBorrow.js +18 -33
  108. package/lib/esm/actions/blue/withdraw.d.ts +10 -2
  109. package/lib/esm/actions/blue/withdraw.js +7 -1
  110. package/lib/esm/actions/index.d.ts +1 -0
  111. package/lib/esm/actions/index.js +1 -0
  112. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +49 -0
  113. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +107 -0
  114. package/lib/esm/actions/requirements/blue/index.d.ts +1 -0
  115. package/lib/esm/actions/requirements/blue/index.js +1 -0
  116. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +55 -0
  117. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +85 -0
  118. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +6 -5
  119. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +19 -7
  120. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +9 -7
  121. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +20 -6
  122. package/lib/esm/actions/requirements/encode/{encodeErc20Permit2.d.ts → encodeErc20Permit2Approve.d.ts} +11 -13
  123. package/lib/esm/actions/requirements/encode/{encodeErc20Permit2.js → encodeErc20Permit2Approve.js} +8 -12
  124. package/lib/esm/actions/requirements/encode/index.d.ts +2 -1
  125. package/lib/esm/actions/requirements/encode/index.js +2 -1
  126. package/lib/esm/actions/requirements/{getRequirements.d.ts → generalAdapter/getGeneralAdapterRequirements.d.ts} +34 -20
  127. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +147 -0
  128. package/lib/{cjs/actions/requirements/getRequirementsPermit.d.ts → esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts} +6 -14
  129. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +46 -0
  130. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.d.ts +57 -0
  131. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit2.js +70 -0
  132. package/lib/esm/actions/requirements/generalAdapter/index.d.ts +3 -0
  133. package/lib/esm/actions/requirements/generalAdapter/index.js +3 -0
  134. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +3 -2
  135. package/lib/esm/actions/requirements/getRequirementsApproval.js +3 -2
  136. package/lib/esm/actions/requirements/index.d.ts +2 -5
  137. package/lib/esm/actions/requirements/index.js +2 -5
  138. package/lib/esm/actions/signatures/getBlueAuthorizationAction.d.ts +29 -0
  139. package/lib/esm/actions/signatures/getBlueAuthorizationAction.js +44 -0
  140. package/lib/{cjs/actions/requirements/getRequirementsAction.d.ts → esm/actions/signatures/getTokenRequirementActions.d.ts} +17 -17
  141. package/lib/esm/actions/{requirements/getRequirementsAction.js → signatures/getTokenRequirementActions.js} +24 -11
  142. package/lib/esm/actions/signatures/index.d.ts +2 -0
  143. package/lib/esm/actions/signatures/index.js +2 -0
  144. package/lib/esm/actions/vaultV1/deposit.d.ts +6 -8
  145. package/lib/esm/actions/vaultV1/deposit.js +11 -21
  146. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +6 -6
  147. package/lib/esm/actions/vaultV1/migrateToV2.js +12 -20
  148. package/lib/esm/actions/vaultV2/deposit.d.ts +6 -8
  149. package/lib/esm/actions/vaultV2/deposit.js +11 -21
  150. package/lib/esm/addresses.d.ts +2 -2
  151. package/lib/esm/addresses.js +1 -1
  152. package/lib/esm/bundler/actions.d.ts +44 -4
  153. package/lib/esm/bundler/actions.js +77 -4
  154. package/lib/esm/bundler/types.d.ts +6 -0
  155. package/lib/esm/constants.d.ts +2 -2
  156. package/lib/esm/constants.js +2 -2
  157. package/lib/esm/entities/blue/blue.d.ts +58 -33
  158. package/lib/esm/entities/blue/blue.js +311 -191
  159. package/lib/esm/entities/reallocationData.d.ts +0 -44
  160. package/lib/esm/entities/reallocationData.js +2 -49
  161. package/lib/esm/entities/vaultV1/vaultV1.d.ts +9 -9
  162. package/lib/esm/entities/vaultV1/vaultV1.js +46 -36
  163. package/lib/esm/entities/vaultV2/vaultV2.d.ts +6 -6
  164. package/lib/esm/entities/vaultV2/vaultV2.js +23 -18
  165. package/lib/esm/errors.d.ts +3 -2
  166. package/lib/esm/errors.js +2 -1
  167. package/lib/esm/helpers/index.d.ts +1 -1
  168. package/lib/esm/helpers/index.js +1 -1
  169. package/lib/esm/helpers/validate.d.ts +2 -20
  170. package/lib/esm/helpers/validate.js +2 -38
  171. package/lib/esm/types/action.d.ts +164 -12
  172. package/lib/esm/types/action.js +75 -4
  173. package/lib/esm/types/error.d.ts +97 -2
  174. package/lib/esm/types/error.js +107 -5
  175. package/lib/esm/types.d.ts +2 -1
  176. package/lib/esm/utils.d.ts +2 -2
  177. package/lib/esm/utils.js +2 -2
  178. package/package.json +22 -21
  179. package/lib/cjs/actions/requirements/getMorphoAuthorizationRequirement.d.ts +0 -37
  180. package/lib/cjs/actions/requirements/getMorphoAuthorizationRequirement.js +0 -71
  181. package/lib/cjs/actions/requirements/getRequirements.js +0 -112
  182. package/lib/cjs/actions/requirements/getRequirementsPermit.js +0 -57
  183. package/lib/cjs/actions/requirements/getRequirementsPermit2.d.ts +0 -63
  184. package/lib/cjs/actions/requirements/getRequirementsPermit2.js +0 -85
  185. package/lib/esm/actions/requirements/getMorphoAuthorizationRequirement.d.ts +0 -37
  186. package/lib/esm/actions/requirements/getMorphoAuthorizationRequirement.js +0 -67
  187. package/lib/esm/actions/requirements/getRequirements.js +0 -108
  188. package/lib/esm/actions/requirements/getRequirementsPermit.js +0 -53
  189. package/lib/esm/actions/requirements/getRequirementsPermit2.d.ts +0 -63
  190. package/lib/esm/actions/requirements/getRequirementsPermit2.js +0 -81
  191. package/src/index.ts +0 -4
@@ -2,29 +2,34 @@ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
2
  import { deepFreeze } from "@morpho-org/morpho-ts";
3
3
  import { maxUint256 } from "viem";
4
4
  import { BundlerAction } from "../../bundler/index.js";
5
- import { addTransactionMetadata, validateRepayParams, } from "../../helpers/index.js";
6
- import { getRequirementsAction } from "../requirements/getRequirementsAction.js";
5
+ import { addTransactionMetadata } from "../../helpers/index.js";
6
+ import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
7
+ import { resolveRepayFunding } from "./resolveRepayFunding.js";
7
8
  /**
8
9
  * Prepares a repay transaction for a Morpho Blue market.
9
10
  *
10
- * Routed through bundler3 via `GeneralAdapter1`. Supports two modes:
11
+ * Routed through bundler3 via `GeneralAdapter1`. All amount arithmetic is done upstream (see
12
+ * `MorphoBlue.repay`); this builder just assembles the bundle from the pre-resolved
13
+ * {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional native wrapping
14
+ * (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()` before the
15
+ * repay; the loan token must be the chain's wNative):
11
16
  *
12
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
13
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with
14
- * `transferAmount` set to an upper-bound asset estimate; residual loan tokens are skimmed back
15
- * to `receiver` after the call.
17
+ * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
18
+ * additive like `blueSupply`), pulling `amount` ERC-20 and wrapping `nativeAmount`. No residual.
19
+ * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
20
+ * ERC-20 (already net of native) and wrapping `nativeAmount`. Residual loan tokens are skimmed
21
+ * back to `receiver` after the call.
16
22
  *
17
- * Exactly one of `assets` / `shares` must be non-zero. Uses `maxSharePrice` to protect against
18
- * share price manipulation between transaction construction and execution.
23
+ * Uses `maxSharePrice` to protect against share price manipulation between construction and execution.
19
24
  *
20
25
  * @param params.market.chainId - The chain the market lives on.
21
26
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
22
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
23
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
24
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
25
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
26
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
27
- * tokens are skimmed back to `receiver`.
27
+ * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
28
+ * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
29
+ * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
30
+ * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
31
+ * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
32
+ * Requires the loan token to be the chain's wNative.
28
33
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
29
34
  * @param params.args.receiver - Address that receives residual loan tokens in shares mode.
30
35
  * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
@@ -32,70 +37,71 @@ import { getRequirementsAction } from "../requirements/getRequirementsAction.js"
32
37
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
33
38
  * loan-token transfer.
34
39
  * @param params.metadata - Optional analytics metadata attached to the bundle.
35
- * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value`, `data`, and the
36
- * typed `action` discriminator the simulation layer consumes.
40
+ * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value` (= `nativeAmount`),
41
+ * `data`, and the typed `action` discriminator the simulation layer consumes.
37
42
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
38
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
39
- * both are zero.
40
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
41
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
42
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
43
- * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
43
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
44
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
45
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
46
+ * `transferAmount !== amount + nativeAmount`.
47
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
48
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
49
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
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`
44
54
  * is provided and the signed asset differs from `marketParams.loanToken`.
45
- * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
46
- * is provided and the signed amount differs from `args.transferAmount`.
47
- * @throws {Permit2ExpirationMissingError} from `getRequirementsAction` when a Permit2 requirement
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
48
58
  * signature is missing its expiration.
49
59
  * @example
50
60
  * ```ts
51
61
  * import { blueRepay } from "@morpho-org/morpho-sdk";
52
62
  *
63
+ * // Repay 0.5 loan-asset units, 0.2 of them funded by wrapping native ETH.
53
64
  * const tx = blueRepay({
54
- * market: { chainId: 1, marketParams },
65
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
55
66
  * args: {
56
- * assets: 500_000_000n,
57
- * shares: 0n,
58
- * transferAmount: 500_000_000n,
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
59
70
  * onBehalf: borrower,
60
71
  * receiver: borrower,
61
72
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
62
73
  * },
63
74
  * });
64
- * // tx satisfies Readonly<Transaction<BlueRepayAction>>
75
+ * // tx.value === 200_000_000_000_000_000n
65
76
  * ```
66
77
  */
67
- export const blueRepay = ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }) => {
68
- validateRepayParams({
69
- assets,
70
- shares,
71
- transferAmount,
72
- maxSharePrice,
73
- marketId: marketParams.id,
74
- });
78
+ export 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 } = resolveRepayFunding({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
75
81
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
76
- const actions = [];
77
- if (requirementSignature) {
78
- actions.push(...getRequirementsAction({
79
- asset: marketParams.loanToken,
80
- amount: transferAmount,
81
- recipient: generalAdapter1,
82
- requirementSignature,
83
- }));
84
- }
85
- else {
86
- actions.push({
87
- type: "erc20TransferFrom",
88
- args: [marketParams.loanToken, transferAmount, generalAdapter1, false],
89
- });
90
- }
82
+ const actions = buildAssetFundingActions({
83
+ chainId,
84
+ asset: marketParams.loanToken,
85
+ erc20Amount,
86
+ nativeAmount,
87
+ requirementSignature,
88
+ });
91
89
  actions.push({
92
90
  type: "morphoRepay",
93
- args: [marketParams, assets, shares, maxSharePrice, onBehalf, [], false],
91
+ args: [
92
+ marketParams,
93
+ repayAssets,
94
+ repayShares,
95
+ maxSharePrice,
96
+ onBehalf,
97
+ [],
98
+ false,
99
+ ],
94
100
  });
95
101
  // Skim residual loan tokens back to the payer when repaying by shares.
96
102
  // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
97
103
  // consumes only the exact amount needed, leaving a residual in the adapter.
98
- if (shares > 0n) {
104
+ if (isSharesMode) {
99
105
  actions.push({
100
106
  type: "erc20Transfer",
101
107
  args: [
@@ -107,7 +113,10 @@ export const blueRepay = ({ market: { chainId, marketParams }, args: { assets, s
107
113
  ],
108
114
  });
109
115
  }
110
- let tx = BundlerAction.encodeBundle(chainId, actions);
116
+ let tx = {
117
+ ...BundlerAction.encodeBundle(chainId, actions),
118
+ value: nativeAmount,
119
+ };
111
120
  if (metadata) {
112
121
  tx = addTransactionMetadata(tx, metadata);
113
122
  }
@@ -117,12 +126,14 @@ export const blueRepay = ({ market: { chainId, marketParams }, args: { assets, s
117
126
  type: "blueRepay",
118
127
  args: {
119
128
  market: marketParams.id,
120
- assets,
121
- shares,
122
- transferAmount,
129
+ assets: repayAssets,
130
+ shares: repayShares,
131
+ // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
132
+ transferAmount: erc20Amount + nativeAmount,
123
133
  onBehalf,
124
134
  receiver,
125
135
  maxSharePrice,
136
+ nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
126
137
  },
127
138
  },
128
139
  });
@@ -1,24 +1,13 @@
1
1
  import { type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { type Address } from "viem";
3
- import { type BlueRepayWithdrawCollateralAction, type Metadata, type RequirementSignature, type Transaction } from "../../types/index.js";
3
+ import { type AuthorizationRequirementSignature, type BlueRepayWithdrawCollateralAction, type Metadata, type PermitRequirementSignature, type RepayActionAmountArgs, type Transaction } from "../../types/index.js";
4
4
  /** Parameters for {@link blueRepayWithdrawCollateral}. */
5
5
  export interface BlueRepayWithdrawCollateralParams {
6
6
  market: {
7
7
  readonly chainId: number;
8
8
  readonly marketParams: MarketParams;
9
9
  };
10
- args: {
11
- /** Repay assets amount (0n when repaying by shares). */
12
- assets: bigint;
13
- /** Repay shares amount (0n when repaying by assets). */
14
- shares: bigint;
15
- /**
16
- * ERC-20 amount to pull into `GeneralAdapter1`. In assets mode, must equal `assets`
17
- * exactly (`TransferAmountNotEqualToAssetsError` fires otherwise). In shares mode, an
18
- * upper-bound estimate to absorb share-price drift; residual loan tokens are skimmed
19
- * back to `receiver`.
20
- */
21
- transferAmount: bigint;
10
+ args: RepayActionAmountArgs & {
22
11
  /** Amount of collateral to withdraw. */
23
12
  withdrawAmount: bigint;
24
13
  /** Address whose debt is being repaid. */
@@ -27,7 +16,14 @@ export interface BlueRepayWithdrawCollateralParams {
27
16
  receiver: Address;
28
17
  /** Maximum repay share price (in ray). Protects against share price manipulation. */
29
18
  maxSharePrice: bigint;
30
- requirementSignature?: RequirementSignature;
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;
31
27
  };
32
28
  metadata?: Metadata;
33
29
  }
@@ -41,23 +37,29 @@ export interface BlueRepayWithdrawCollateralParams {
41
37
  * 3. `morphoWithdrawCollateral` — then withdraws collateral.
42
38
  *
43
39
  * If the order were reversed, Morpho would revert because the position would be insolvent at the
44
- * time of the withdraw. Supports two repay modes:
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
45
  *
46
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
47
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with residual
48
- * loan tokens skimmed back to `receiver`.
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`.
49
50
  *
50
51
  * Prerequisites: ERC-20 approval for the loan token to `GeneralAdapter1` (for the repay) **and**
51
- * `GeneralAdapter1` must be authorized on Morpho (for the withdraw).
52
+ * `GeneralAdapter1` must be authorized on Morpho (for the withdraw). Passing an
53
+ * `authorizationSignature` prepends the authorization in-bundle instead.
52
54
  *
53
55
  * @param params.market.chainId - The chain the market lives on.
54
56
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
55
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
56
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
57
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
58
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
59
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
60
- * tokens are skimmed back to `receiver`.
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.
61
63
  * @param params.args.withdrawAmount - Amount of collateral to withdraw after the repay leg
62
64
  * completes.
63
65
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
@@ -67,39 +69,46 @@ export interface BlueRepayWithdrawCollateralParams {
67
69
  * protection.
68
70
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
69
71
  * loan-token transfer.
72
+ * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
73
+ * a `setAuthorizationWithSig` call is prepended to the bundle.
70
74
  * @param params.metadata - Optional analytics metadata attached to the bundle.
71
75
  * @returns A deep-frozen `Transaction<BlueRepayWithdrawCollateralAction>` with `to`,
72
- * `value`, `data`, and the typed `action` discriminator the simulation layer consumes.
76
+ * `value` (= `nativeAmount`), `data`, and the typed `action` discriminator the simulation layer consumes.
73
77
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
74
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
75
- * both are zero.
76
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
77
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
78
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
78
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
79
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
80
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
81
+ * `transferAmount !== amount + nativeAmount`.
82
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
83
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
84
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
79
85
  * @throws {NonPositiveWithdrawCollateralAmountError} when `withdrawAmount <= 0n`.
80
- * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
86
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
87
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
88
+ * the chain's wNative.
89
+ * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
81
90
  * is provided and the signed asset differs from `marketParams.loanToken`.
82
- * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
83
- * is provided and the signed amount differs from `args.transferAmount`.
84
- * @throws {Permit2ExpirationMissingError} from `getRequirementsAction` when a Permit2 requirement
91
+ * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
92
+ * is provided and the signed amount differs from the ERC-20 amount pulled.
93
+ * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
85
94
  * signature is missing its expiration.
86
95
  * @example
87
96
  * ```ts
88
97
  * import { blueRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
89
98
  *
90
99
  * const tx = blueRepayWithdrawCollateral({
91
- * market: { chainId: 1, marketParams },
100
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
92
101
  * args: {
93
- * assets: 500_000_000n,
94
- * shares: 0n,
95
- * transferAmount: 500_000_000n,
102
+ * shares: 500_000_000_000_000_000_000_000n,
103
+ * transferAmount: 310_000_000_000_000_000n, // ERC-20 pulled (net of native)
104
+ * nativeAmount: 200_000_000_000_000_000n, // 0.2 funded by wrapping native ETH
96
105
  * withdrawAmount: 1_000_000_000_000_000_000n,
97
106
  * onBehalf: borrower,
98
107
  * receiver: borrower,
99
108
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
100
109
  * },
101
110
  * });
102
- * // tx satisfies Readonly<Transaction<BlueRepayWithdrawCollateralAction>>
111
+ * // tx.value === 200_000_000_000_000_000n
103
112
  * ```
104
113
  */
105
- export declare const blueRepayWithdrawCollateral: ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }: BlueRepayWithdrawCollateralParams) => Readonly<Transaction<BlueRepayWithdrawCollateralAction>>;
114
+ export declare const blueRepayWithdrawCollateral: ({ market: { chainId, marketParams }, args, metadata, }: BlueRepayWithdrawCollateralParams) => Readonly<Transaction<BlueRepayWithdrawCollateralAction>>;
@@ -2,9 +2,11 @@ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
2
  import { deepFreeze } from "@morpho-org/morpho-ts";
3
3
  import { maxUint256 } from "viem";
4
4
  import { BundlerAction } from "../../bundler/index.js";
5
- import { addTransactionMetadata, validateRepayParams, } from "../../helpers/index.js";
5
+ import { addTransactionMetadata } from "../../helpers/index.js";
6
6
  import { NonPositiveWithdrawCollateralAmountError, } from "../../types/index.js";
7
- import { getRequirementsAction } from "../requirements/getRequirementsAction.js";
7
+ import { getBlueAuthorizationAction } from "../signatures/getBlueAuthorizationAction.js";
8
+ import { buildAssetFundingActions } from "./buildAssetFundingActions.js";
9
+ import { resolveRepayFunding } from "./resolveRepayFunding.js";
8
10
  /**
9
11
  * Prepares an atomic repay-and-withdraw-collateral transaction for a Morpho Blue market.
10
12
  *
@@ -15,23 +17,29 @@ import { getRequirementsAction } from "../requirements/getRequirementsAction.js"
15
17
  * 3. `morphoWithdrawCollateral` — then withdraws collateral.
16
18
  *
17
19
  * If the order were reversed, Morpho would revert because the position would be insolvent at the
18
- * time of the withdraw. Supports two repay modes:
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):
19
25
  *
20
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
21
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with residual
22
- * loan tokens skimmed back to `receiver`.
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`.
23
30
  *
24
31
  * Prerequisites: ERC-20 approval for the loan token to `GeneralAdapter1` (for the repay) **and**
25
- * `GeneralAdapter1` must be authorized on Morpho (for the withdraw).
32
+ * `GeneralAdapter1` must be authorized on Morpho (for the withdraw). Passing an
33
+ * `authorizationSignature` prepends the authorization in-bundle instead.
26
34
  *
27
35
  * @param params.market.chainId - The chain the market lives on.
28
36
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
29
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
30
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
31
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
32
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
33
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
34
- * tokens are skimmed back to `receiver`.
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.
35
43
  * @param params.args.withdrawAmount - Amount of collateral to withdraw after the repay leg
36
44
  * completes.
37
45
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
@@ -41,77 +49,85 @@ import { getRequirementsAction } from "../requirements/getRequirementsAction.js"
41
49
  * protection.
42
50
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
43
51
  * loan-token transfer.
52
+ * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
53
+ * a `setAuthorizationWithSig` call is prepended to the bundle.
44
54
  * @param params.metadata - Optional analytics metadata attached to the bundle.
45
55
  * @returns A deep-frozen `Transaction<BlueRepayWithdrawCollateralAction>` with `to`,
46
- * `value`, `data`, and the typed `action` discriminator the simulation layer consumes.
56
+ * `value` (= `nativeAmount`), `data`, and the typed `action` discriminator the simulation layer consumes.
47
57
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
48
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
49
- * both are zero.
50
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
51
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
52
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
58
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
59
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
60
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
61
+ * `transferAmount !== amount + nativeAmount`.
62
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
63
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
64
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
53
65
  * @throws {NonPositiveWithdrawCollateralAmountError} when `withdrawAmount <= 0n`.
54
- * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
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`
55
70
  * is provided and the signed asset differs from `marketParams.loanToken`.
56
- * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
57
- * is provided and the signed amount differs from `args.transferAmount`.
58
- * @throws {Permit2ExpirationMissingError} from `getRequirementsAction` when a Permit2 requirement
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
59
74
  * signature is missing its expiration.
60
75
  * @example
61
76
  * ```ts
62
77
  * import { blueRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
63
78
  *
64
79
  * const tx = blueRepayWithdrawCollateral({
65
- * market: { chainId: 1, marketParams },
80
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
66
81
  * args: {
67
- * assets: 500_000_000n,
68
- * shares: 0n,
69
- * transferAmount: 500_000_000n,
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
70
85
  * withdrawAmount: 1_000_000_000_000_000_000n,
71
86
  * onBehalf: borrower,
72
87
  * receiver: borrower,
73
88
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
74
89
  * },
75
90
  * });
76
- * // tx satisfies Readonly<Transaction<BlueRepayWithdrawCollateralAction>>
91
+ * // tx.value === 200_000_000_000_000_000n
77
92
  * ```
78
93
  */
79
- export const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }) => {
80
- validateRepayParams({
81
- assets,
82
- shares,
83
- transferAmount,
84
- maxSharePrice,
85
- marketId: marketParams.id,
86
- });
94
+ export 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 } = resolveRepayFunding({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
87
97
  if (withdrawAmount <= 0n) {
88
98
  throw new NonPositiveWithdrawCollateralAmountError(marketParams.id);
89
99
  }
90
100
  const { bundler3: { generalAdapter1 }, } = getChainAddresses(chainId);
91
101
  const actions = [];
92
- if (requirementSignature) {
93
- actions.push(...getRequirementsAction({
94
- asset: marketParams.loanToken,
95
- amount: transferAmount,
96
- recipient: generalAdapter1,
97
- requirementSignature,
98
- }));
99
- }
100
- else {
101
- actions.push({
102
- type: "erc20TransferFrom",
103
- args: [marketParams.loanToken, transferAmount, generalAdapter1, false],
104
- });
102
+ // Authorize GeneralAdapter1 in-bundle when a signed authorization is supplied.
103
+ if (authorizationSignature) {
104
+ actions.push(getBlueAuthorizationAction(chainId, authorizationSignature));
105
105
  }
106
+ // Fund the repay: wrap native (if any) then pull the ERC-20 remainder.
107
+ actions.push(...buildAssetFundingActions({
108
+ chainId,
109
+ asset: marketParams.loanToken,
110
+ erc20Amount,
111
+ nativeAmount,
112
+ requirementSignature,
113
+ }));
106
114
  // REPAY FIRST — reduces debt before withdrawing collateral
107
115
  actions.push({
108
116
  type: "morphoRepay",
109
- args: [marketParams, assets, shares, maxSharePrice, onBehalf, [], false],
117
+ args: [
118
+ marketParams,
119
+ repayAssets,
120
+ repayShares,
121
+ maxSharePrice,
122
+ onBehalf,
123
+ [],
124
+ false,
125
+ ],
110
126
  });
111
127
  // Skim residual loan tokens back to the payer when repaying by shares.
112
128
  // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
113
129
  // consumes only the exact amount needed, leaving a residual in the adapter.
114
- if (shares > 0n) {
130
+ if (isSharesMode) {
115
131
  actions.push({
116
132
  type: "erc20Transfer",
117
133
  args: [
@@ -127,7 +143,10 @@ export const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams },
127
143
  type: "morphoWithdrawCollateral",
128
144
  args: [marketParams, withdrawAmount, receiver, false],
129
145
  });
130
- let tx = BundlerAction.encodeBundle(chainId, actions);
146
+ let tx = {
147
+ ...BundlerAction.encodeBundle(chainId, actions),
148
+ value: nativeAmount,
149
+ };
131
150
  if (metadata) {
132
151
  tx = addTransactionMetadata(tx, metadata);
133
152
  }
@@ -137,13 +156,15 @@ export const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams },
137
156
  type: "blueRepayWithdrawCollateral",
138
157
  args: {
139
158
  market: marketParams.id,
140
- repayAssets: assets,
141
- repayShares: shares,
142
- transferAmount,
159
+ repayAssets,
160
+ repayShares,
161
+ // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
162
+ transferAmount: erc20Amount + nativeAmount,
143
163
  withdrawAmount,
144
164
  maxSharePrice,
145
165
  onBehalf,
146
166
  receiver,
167
+ nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
147
168
  },
148
169
  },
149
170
  });
@@ -0,0 +1,69 @@
1
+ import type { MarketId } from "@morpho-org/blue-sdk";
2
+ /**
3
+ * Pre-resolved repay amounts (plus `maxSharePrice`) validated by {@link resolveRepayFunding}.
4
+ *
5
+ * These are the fields the entity layer (`MorphoBlue.repay` / `repayWithdrawCollateral`) resolves
6
+ * from live market/position state before either repay builder assembles the bundle.
7
+ *
8
+ * @internal
9
+ */
10
+ export interface RepayFundingInput {
11
+ /** (assets mode) ERC-20 loan tokens pulled from the payer. */
12
+ readonly amount: bigint;
13
+ /** (shares mode) Borrow shares to repay. Discriminates the mode when `> 0n`. */
14
+ readonly shares: bigint;
15
+ /** Native ETH wrapped into wNative to help fund the repay. */
16
+ readonly nativeAmount: bigint;
17
+ /** Loan tokens routed into `GeneralAdapter1` (see `RepayActionAmountArgs`). */
18
+ readonly transferAmount: bigint;
19
+ /** Maximum acceptable repay share price (in ray). */
20
+ readonly maxSharePrice: bigint;
21
+ }
22
+ /**
23
+ * Derived repay funding values consumed by the repay builders.
24
+ *
25
+ * @internal
26
+ */
27
+ export interface RepayFunding {
28
+ /** `true` when repaying an exact share count (full close); `false` in assets mode. */
29
+ readonly isSharesMode: boolean;
30
+ /** Assets passed to `morphoRepay` (`transferAmount` in assets mode, `0n` in shares mode). */
31
+ readonly repayAssets: bigint;
32
+ /** Shares passed to `morphoRepay` (`shares` in shares mode, `0n` in assets mode). */
33
+ readonly repayShares: bigint;
34
+ /** ERC-20 loan tokens pulled into `GeneralAdapter1` (net of any wrapped native). */
35
+ readonly erc20Amount: bigint;
36
+ }
37
+ /**
38
+ * Resolves and validates the repay funding envelope shared by `blueRepay` and
39
+ * `blueRepayWithdrawCollateral`.
40
+ *
41
+ * Encode-only and synchronous — reads no on-chain state and does no amount arithmetic beyond
42
+ * deriving the bundle values from the pre-resolved args (the entity layer resolves the amounts
43
+ * upstream). Runs the shared mode/amount guards, discriminates assets vs shares mode on
44
+ * `shares > 0n`, then validates the funding so the assembled bundle neither strands over-pulled
45
+ * tokens nor under-funds the repay:
46
+ *
47
+ * - **assets mode** (`shares` `0n`): repays `transferAmount` (`= amount + nativeAmount`, additive
48
+ * like `blueSupply`); ERC-20 pulled = `amount`.
49
+ * - **shares mode** (`shares > 0n`): repays exact `shares`; ERC-20 pulled = `transferAmount` (already
50
+ * net of native).
51
+ *
52
+ * Single source of truth for the funding math both repay builders depend on — a correctness fix here
53
+ * applies to both paths instead of risking a silent divergence between two copies.
54
+ *
55
+ * @param input - The pre-resolved repay amounts plus the repay `maxSharePrice`.
56
+ * @param marketId - Market id used to tag the thrown errors.
57
+ * @returns `{ isSharesMode, repayAssets, repayShares, erc20Amount }` — the mode discriminator and the
58
+ * amounts the repay builders assemble the bundle from.
59
+ * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
60
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
61
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode and
62
+ * the repaid assets are `<= 0n`, or when in shares mode and `transferAmount` is negative or the total
63
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
64
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
65
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
66
+ * `transferAmount !== amount + nativeAmount`.
67
+ * @internal
68
+ */
69
+ export declare const resolveRepayFunding: ({ amount, shares, nativeAmount, transferAmount, maxSharePrice, }: RepayFundingInput, marketId: MarketId) => RepayFunding;