@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
@@ -6,28 +6,33 @@ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../bundler/index.js");
8
8
  const index_js_2 = require("../../helpers/index.js");
9
- const getRequirementsAction_js_1 = require("../requirements/getRequirementsAction.js");
9
+ const buildAssetFundingActions_js_1 = require("./buildAssetFundingActions.js");
10
+ const resolveRepayFunding_js_1 = require("./resolveRepayFunding.js");
10
11
  /**
11
12
  * Prepares a repay transaction for a Morpho Blue market.
12
13
  *
13
- * Routed through bundler3 via `GeneralAdapter1`. Supports two modes:
14
+ * Routed through bundler3 via `GeneralAdapter1`. All amount arithmetic is done upstream (see
15
+ * `MorphoBlue.repay`); this builder just assembles the bundle from the pre-resolved
16
+ * {@link RepayActionAmountArgs}. The mode is discriminated on `shares`, plus optional native wrapping
17
+ * (when `nativeAmount > 0`, native ETH is wrapped via `GeneralAdapter1.wrapNative()` before the
18
+ * repay; the loan token must be the chain's wNative):
14
19
  *
15
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
16
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with
17
- * `transferAmount` set to an upper-bound asset estimate; residual loan tokens are skimmed back
18
- * to `receiver` after the call.
20
+ * - **assets mode** (`shares` unset/`0n`): repays `transferAmount` assets (`= amount + nativeAmount`,
21
+ * additive like `blueSupply`), pulling `amount` ERC-20 and wrapping `nativeAmount`. No residual.
22
+ * - **shares mode** (`shares > 0n`): repays exact shares (full repay), pulling `transferAmount`
23
+ * ERC-20 (already net of native) and wrapping `nativeAmount`. Residual loan tokens are skimmed
24
+ * back to `receiver` after the call.
19
25
  *
20
- * Exactly one of `assets` / `shares` must be non-zero. Uses `maxSharePrice` to protect against
21
- * share price manipulation between transaction construction and execution.
26
+ * Uses `maxSharePrice` to protect against share price manipulation between construction and execution.
22
27
  *
23
28
  * @param params.market.chainId - The chain the market lives on.
24
29
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
25
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
26
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
27
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
28
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
29
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
30
- * tokens are skimmed back to `receiver`.
30
+ * @param params.args.amount - (assets mode) ERC-20 loan tokens pulled from the payer. Defaults to `0n`.
31
+ * @param params.args.shares - (shares mode) Repay amount in borrow shares. Discriminates the mode.
32
+ * @param params.args.transferAmount - Loan tokens routed into `GeneralAdapter1`: assets mode = the
33
+ * total repaid (`amount + nativeAmount`); shares mode = the ERC-20 pulled (net of native).
34
+ * @param params.args.nativeAmount - Optional native token to wrap into wNative to fund the repay.
35
+ * Requires the loan token to be the chain's wNative.
31
36
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
32
37
  * @param params.args.receiver - Address that receives residual loan tokens in shares mode.
33
38
  * @param params.args.maxSharePrice - Maximum acceptable repay share price (in ray). Slippage
@@ -35,70 +40,71 @@ const getRequirementsAction_js_1 = require("../requirements/getRequirementsActio
35
40
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
36
41
  * loan-token transfer.
37
42
  * @param params.metadata - Optional analytics metadata attached to the bundle.
38
- * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value`, `data`, and the
39
- * typed `action` discriminator the simulation layer consumes.
43
+ * @returns A deep-frozen `Transaction<BlueRepayAction>` with `to`, `value` (= `nativeAmount`),
44
+ * `data`, and the typed `action` discriminator the simulation layer consumes.
40
45
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
41
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
42
- * both are zero.
43
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
44
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
45
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
46
- * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
46
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
47
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
48
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
49
+ * `transferAmount !== amount + nativeAmount`.
50
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
51
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
52
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
53
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
54
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
55
+ * the chain's wNative.
56
+ * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
47
57
  * is provided and the signed asset differs from `marketParams.loanToken`.
48
- * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
49
- * is provided and the signed amount differs from `args.transferAmount`.
50
- * @throws {Permit2ExpirationMissingError} from `getRequirementsAction` when a Permit2 requirement
58
+ * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
59
+ * is provided and the signed amount differs from the ERC-20 amount pulled.
60
+ * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
51
61
  * signature is missing its expiration.
52
62
  * @example
53
63
  * ```ts
54
64
  * import { blueRepay } from "@morpho-org/morpho-sdk";
55
65
  *
66
+ * // Repay 0.5 loan-asset units, 0.2 of them funded by wrapping native ETH.
56
67
  * const tx = blueRepay({
57
- * market: { chainId: 1, marketParams },
68
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
58
69
  * args: {
59
- * assets: 500_000_000n,
60
- * shares: 0n,
61
- * transferAmount: 500_000_000n,
70
+ * amount: 300_000_000_000_000_000n, // ERC-20 part
71
+ * nativeAmount: 200_000_000_000_000_000n, // wrapped ETH part
72
+ * transferAmount: 500_000_000_000_000_000n, // total repaid = amount + nativeAmount
62
73
  * onBehalf: borrower,
63
74
  * receiver: borrower,
64
75
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
65
76
  * },
66
77
  * });
67
- * // tx satisfies Readonly<Transaction<BlueRepayAction>>
78
+ * // tx.value === 200_000_000_000_000_000n
68
79
  * ```
69
80
  */
70
- const blueRepay = ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }) => {
71
- (0, index_js_2.validateRepayParams)({
72
- assets,
73
- shares,
74
- transferAmount,
75
- maxSharePrice,
76
- marketId: marketParams.id,
77
- });
81
+ const blueRepay = ({ market: { chainId, marketParams }, args, metadata, }) => {
82
+ const { amount = 0n, shares = 0n, nativeAmount = 0n, transferAmount, onBehalf, receiver, maxSharePrice, requirementSignature, } = args;
83
+ const { isSharesMode, repayAssets, repayShares, erc20Amount } = (0, resolveRepayFunding_js_1.resolveRepayFunding)({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
78
84
  const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
79
- const actions = [];
80
- if (requirementSignature) {
81
- actions.push(...(0, getRequirementsAction_js_1.getRequirementsAction)({
82
- asset: marketParams.loanToken,
83
- amount: transferAmount,
84
- recipient: generalAdapter1,
85
- requirementSignature,
86
- }));
87
- }
88
- else {
89
- actions.push({
90
- type: "erc20TransferFrom",
91
- args: [marketParams.loanToken, transferAmount, generalAdapter1, false],
92
- });
93
- }
85
+ const actions = (0, buildAssetFundingActions_js_1.buildAssetFundingActions)({
86
+ chainId,
87
+ asset: marketParams.loanToken,
88
+ erc20Amount,
89
+ nativeAmount,
90
+ requirementSignature,
91
+ });
94
92
  actions.push({
95
93
  type: "morphoRepay",
96
- args: [marketParams, assets, shares, maxSharePrice, onBehalf, [], false],
94
+ args: [
95
+ marketParams,
96
+ repayAssets,
97
+ repayShares,
98
+ maxSharePrice,
99
+ onBehalf,
100
+ [],
101
+ false,
102
+ ],
97
103
  });
98
104
  // Skim residual loan tokens back to the payer when repaying by shares.
99
105
  // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
100
106
  // consumes only the exact amount needed, leaving a residual in the adapter.
101
- if (shares > 0n) {
107
+ if (isSharesMode) {
102
108
  actions.push({
103
109
  type: "erc20Transfer",
104
110
  args: [
@@ -110,7 +116,10 @@ const blueRepay = ({ market: { chainId, marketParams }, args: { assets, shares,
110
116
  ],
111
117
  });
112
118
  }
113
- let tx = index_js_1.BundlerAction.encodeBundle(chainId, actions);
119
+ let tx = {
120
+ ...index_js_1.BundlerAction.encodeBundle(chainId, actions),
121
+ value: nativeAmount,
122
+ };
114
123
  if (metadata) {
115
124
  tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
116
125
  }
@@ -120,12 +129,14 @@ const blueRepay = ({ market: { chainId, marketParams }, args: { assets, shares,
120
129
  type: "blueRepay",
121
130
  args: {
122
131
  market: marketParams.id,
123
- assets,
124
- shares,
125
- transferAmount,
132
+ assets: repayAssets,
133
+ shares: repayShares,
134
+ // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
135
+ transferAmount: erc20Amount + nativeAmount,
126
136
  onBehalf,
127
137
  receiver,
128
138
  maxSharePrice,
139
+ nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
129
140
  },
130
141
  },
131
142
  });
@@ -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>>;
@@ -7,7 +7,9 @@ const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../bundler/index.js");
8
8
  const index_js_2 = require("../../helpers/index.js");
9
9
  const index_js_3 = require("../../types/index.js");
10
- const getRequirementsAction_js_1 = require("../requirements/getRequirementsAction.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");
11
13
  /**
12
14
  * Prepares an atomic repay-and-withdraw-collateral transaction for a Morpho Blue market.
13
15
  *
@@ -18,23 +20,29 @@ const getRequirementsAction_js_1 = require("../requirements/getRequirementsActio
18
20
  * 3. `morphoWithdrawCollateral` — then withdraws collateral.
19
21
  *
20
22
  * If the order were reversed, Morpho would revert because the position would be insolvent at the
21
- * time of the withdraw. Supports two repay modes:
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):
22
28
  *
23
- * - **By assets** (`assets > 0, shares = 0`): repays an exact asset amount.
24
- * - **By shares** (`assets = 0, shares > 0`): repays exact shares (full repay), with residual
25
- * loan tokens skimmed back to `receiver`.
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`.
26
33
  *
27
34
  * Prerequisites: ERC-20 approval for the loan token to `GeneralAdapter1` (for the repay) **and**
28
- * `GeneralAdapter1` must be authorized on Morpho (for the withdraw).
35
+ * `GeneralAdapter1` must be authorized on Morpho (for the withdraw). Passing an
36
+ * `authorizationSignature` prepends the authorization in-bundle instead.
29
37
  *
30
38
  * @param params.market.chainId - The chain the market lives on.
31
39
  * @param params.market.marketParams - Market params (loanToken, collateralToken, oracle, irm, lltv).
32
- * @param params.args.assets - Repay amount in loan-token assets. Set to `0n` when repaying by shares.
33
- * @param params.args.shares - Repay amount in borrow shares. Set to `0n` when repaying by assets.
34
- * @param params.args.transferAmount - ERC-20 amount to pull into `GeneralAdapter1`. In assets
35
- * mode, must equal `assets` exactly (`TransferAmountNotEqualToAssetsError` fires otherwise).
36
- * In shares mode, this is an upper-bound estimate to absorb share-price drift; residual loan
37
- * tokens are skimmed back to `receiver`.
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.
38
46
  * @param params.args.withdrawAmount - Amount of collateral to withdraw after the repay leg
39
47
  * completes.
40
48
  * @param params.args.onBehalf - Address whose Morpho debt is being repaid.
@@ -44,77 +52,85 @@ const getRequirementsAction_js_1 = require("../requirements/getRequirementsActio
44
52
  * protection.
45
53
  * @param params.args.requirementSignature - Optional pre-signed permit/permit2 approval for the
46
54
  * loan-token transfer.
55
+ * @param params.args.authorizationSignature - Optional signed Morpho authorization; when present,
56
+ * a `setAuthorizationWithSig` call is prepended to the bundle.
47
57
  * @param params.metadata - Optional analytics metadata attached to the bundle.
48
58
  * @returns A deep-frozen `Transaction<BlueRepayWithdrawCollateralAction>` with `to`,
49
- * `value`, `data`, and the typed `action` discriminator the simulation layer consumes.
59
+ * `value` (= `nativeAmount`), `data`, and the typed `action` discriminator the simulation layer consumes.
50
60
  * @throws {NonPositiveRepayMaxSharePriceError} when `maxSharePrice <= 0n`.
51
- * @throws {NonPositiveRepayAmountError} when either `assets` or `shares` is negative, or when
52
- * both are zero.
53
- * @throws {MutuallyExclusiveRepayAmountsError} when both `assets` and `shares` are non-zero.
54
- * @throws {NonPositiveTransferAmountError} when `transferAmount <= 0n`.
55
- * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and `transferAmount !== assets`.
61
+ * @throws {NegativeNativeAmountError} when `nativeAmount < 0n`.
62
+ * @throws {MutuallyExclusiveRepayAmountsError} when both `amount` and `shares` are `> 0n`.
63
+ * @throws {TransferAmountNotEqualToAssetsError} when in assets mode and
64
+ * `transferAmount !== amount + nativeAmount`.
65
+ * @throws {NonPositiveRepayAmountError} when `amount` or `shares` is negative, when in assets mode
66
+ * and `transferAmount <= 0n`, or when in shares mode and `transferAmount` is negative or the total
67
+ * funding (`transferAmount + nativeAmount`) is `<= 0n`.
56
68
  * @throws {NonPositiveWithdrawCollateralAmountError} when `withdrawAmount <= 0n`.
57
- * @throws {DepositAssetMismatchError} from `getRequirementsAction` when `requirementSignature`
69
+ * @throws {ChainWNativeMissingError} when `nativeAmount > 0n` but the chain has no configured wNative.
70
+ * @throws {NativeAmountOnNonWNativeAssetError} when `nativeAmount > 0n` but the loan token is not
71
+ * the chain's wNative.
72
+ * @throws {DepositAssetMismatchError} from `getTokenRequirementActions` when `requirementSignature`
58
73
  * is provided and the signed asset differs from `marketParams.loanToken`.
59
- * @throws {DepositAmountMismatchError} from `getRequirementsAction` when `requirementSignature`
60
- * is provided and the signed amount differs from `args.transferAmount`.
61
- * @throws {Permit2ExpirationMissingError} from `getRequirementsAction` when a Permit2 requirement
74
+ * @throws {DepositAmountMismatchError} from `getTokenRequirementActions` when `requirementSignature`
75
+ * is provided and the signed amount differs from the ERC-20 amount pulled.
76
+ * @throws {Permit2ExpirationMissingError} from `getTokenRequirementActions` when a Permit2 requirement
62
77
  * signature is missing its expiration.
63
78
  * @example
64
79
  * ```ts
65
80
  * import { blueRepayWithdrawCollateral } from "@morpho-org/morpho-sdk";
66
81
  *
67
82
  * const tx = blueRepayWithdrawCollateral({
68
- * market: { chainId: 1, marketParams },
83
+ * market: { chainId: 1, marketParams }, // marketParams.loanToken === wNative
69
84
  * args: {
70
- * assets: 500_000_000n,
71
- * shares: 0n,
72
- * transferAmount: 500_000_000n,
85
+ * shares: 500_000_000_000_000_000_000_000n,
86
+ * transferAmount: 310_000_000_000_000_000n, // ERC-20 pulled (net of native)
87
+ * nativeAmount: 200_000_000_000_000_000n, // 0.2 funded by wrapping native ETH
73
88
  * withdrawAmount: 1_000_000_000_000_000_000n,
74
89
  * onBehalf: borrower,
75
90
  * receiver: borrower,
76
91
  * maxSharePrice: 1_010_000_000_000_000_000_000_000_000n, // RAY-scaled, 1.01x
77
92
  * },
78
93
  * });
79
- * // tx satisfies Readonly<Transaction<BlueRepayWithdrawCollateralAction>>
94
+ * // tx.value === 200_000_000_000_000_000n
80
95
  * ```
81
96
  */
82
- const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args: { assets, shares, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, }, metadata, }) => {
83
- (0, index_js_2.validateRepayParams)({
84
- assets,
85
- shares,
86
- transferAmount,
87
- maxSharePrice,
88
- marketId: marketParams.id,
89
- });
97
+ const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args, metadata, }) => {
98
+ const { amount = 0n, shares = 0n, nativeAmount = 0n, transferAmount, withdrawAmount, onBehalf, receiver, maxSharePrice, requirementSignature, authorizationSignature, } = args;
99
+ const { isSharesMode, repayAssets, repayShares, erc20Amount } = (0, resolveRepayFunding_js_1.resolveRepayFunding)({ amount, shares, nativeAmount, transferAmount, maxSharePrice }, marketParams.id);
90
100
  if (withdrawAmount <= 0n) {
91
101
  throw new index_js_3.NonPositiveWithdrawCollateralAmountError(marketParams.id);
92
102
  }
93
103
  const { bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(chainId);
94
104
  const actions = [];
95
- if (requirementSignature) {
96
- actions.push(...(0, getRequirementsAction_js_1.getRequirementsAction)({
97
- asset: marketParams.loanToken,
98
- amount: transferAmount,
99
- recipient: generalAdapter1,
100
- requirementSignature,
101
- }));
102
- }
103
- else {
104
- actions.push({
105
- type: "erc20TransferFrom",
106
- args: [marketParams.loanToken, transferAmount, generalAdapter1, false],
107
- });
105
+ // Authorize GeneralAdapter1 in-bundle when a signed authorization is supplied.
106
+ if (authorizationSignature) {
107
+ actions.push((0, getBlueAuthorizationAction_js_1.getBlueAuthorizationAction)(chainId, authorizationSignature));
108
108
  }
109
+ // Fund the repay: wrap native (if any) then pull the ERC-20 remainder.
110
+ actions.push(...(0, buildAssetFundingActions_js_1.buildAssetFundingActions)({
111
+ chainId,
112
+ asset: marketParams.loanToken,
113
+ erc20Amount,
114
+ nativeAmount,
115
+ requirementSignature,
116
+ }));
109
117
  // REPAY FIRST — reduces debt before withdrawing collateral
110
118
  actions.push({
111
119
  type: "morphoRepay",
112
- args: [marketParams, assets, shares, maxSharePrice, onBehalf, [], false],
120
+ args: [
121
+ marketParams,
122
+ repayAssets,
123
+ repayShares,
124
+ maxSharePrice,
125
+ onBehalf,
126
+ [],
127
+ false,
128
+ ],
113
129
  });
114
130
  // Skim residual loan tokens back to the payer when repaying by shares.
115
131
  // In shares mode, transferAmount is an upper-bound estimate; morphoRepay
116
132
  // consumes only the exact amount needed, leaving a residual in the adapter.
117
- if (shares > 0n) {
133
+ if (isSharesMode) {
118
134
  actions.push({
119
135
  type: "erc20Transfer",
120
136
  args: [
@@ -130,7 +146,10 @@ const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args:
130
146
  type: "morphoWithdrawCollateral",
131
147
  args: [marketParams, withdrawAmount, receiver, false],
132
148
  });
133
- let tx = index_js_1.BundlerAction.encodeBundle(chainId, actions);
149
+ let tx = {
150
+ ...index_js_1.BundlerAction.encodeBundle(chainId, actions),
151
+ value: nativeAmount,
152
+ };
134
153
  if (metadata) {
135
154
  tx = (0, index_js_2.addTransactionMetadata)(tx, metadata);
136
155
  }
@@ -140,13 +159,15 @@ const blueRepayWithdrawCollateral = ({ market: { chainId, marketParams }, args:
140
159
  type: "blueRepayWithdrawCollateral",
141
160
  args: {
142
161
  market: marketParams.id,
143
- repayAssets: assets,
144
- repayShares: shares,
145
- transferAmount,
162
+ repayAssets,
163
+ repayShares,
164
+ // Total loan tokens routed to the adapter: ERC-20 pulled + native wrapped.
165
+ transferAmount: erc20Amount + nativeAmount,
146
166
  withdrawAmount,
147
167
  maxSharePrice,
148
168
  onBehalf,
149
169
  receiver,
170
+ nativeAmount: nativeAmount > 0n ? nativeAmount : undefined,
150
171
  },
151
172
  },
152
173
  });
@@ -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;