@morpho-org/morpho-sdk 5.9.0 → 6.0.0-next.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 (243) hide show
  1. package/MIGRATION-v5-to-v6.md +404 -0
  2. package/README.md +127 -69
  3. package/lib/cjs/abis.d.ts +210 -0
  4. package/lib/cjs/abis.js +142 -2
  5. package/lib/cjs/actions/blue/borrow.d.ts +62 -61
  6. package/lib/cjs/actions/blue/borrow.js +48 -80
  7. package/lib/cjs/actions/blue/common.d.ts +86 -0
  8. package/lib/cjs/actions/blue/common.js +205 -0
  9. package/lib/cjs/actions/blue/refinance.d.ts +72 -112
  10. package/lib/cjs/actions/blue/refinance.js +97 -199
  11. package/lib/cjs/actions/blue/repay.d.ts +72 -68
  12. package/lib/cjs/actions/blue/repay.js +56 -118
  13. package/lib/cjs/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  14. package/lib/cjs/actions/blue/repayWithdrawCollateral.js +148 -137
  15. package/lib/cjs/actions/blue/supply.d.ts +62 -45
  16. package/lib/cjs/actions/blue/supply.js +94 -70
  17. package/lib/cjs/actions/blue/supplyCollateral.d.ts +63 -40
  18. package/lib/cjs/actions/blue/supplyCollateral.js +52 -69
  19. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  20. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +133 -120
  21. package/lib/cjs/actions/blue/withdraw.d.ts +68 -79
  22. package/lib/cjs/actions/blue/withdraw.js +101 -97
  23. package/lib/cjs/actions/blue/withdrawCollateral.d.ts +56 -28
  24. package/lib/cjs/actions/blue/withdrawCollateral.js +45 -50
  25. package/lib/cjs/actions/bundles/common.d.ts +200 -0
  26. package/lib/cjs/actions/bundles/common.js +469 -0
  27. package/lib/cjs/actions/bundles/index.d.ts +3 -0
  28. package/lib/cjs/actions/bundles/index.js +23 -0
  29. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +76 -0
  30. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +125 -0
  31. package/lib/cjs/actions/index.d.ts +2 -1
  32. package/lib/cjs/actions/index.js +1 -0
  33. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  34. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  35. package/lib/cjs/actions/midnight/takeBorrow.d.ts +2 -2
  36. package/lib/cjs/actions/midnight/takeBorrow.js +2 -2
  37. package/lib/cjs/actions/midnight/takeLend.d.ts +2 -2
  38. package/lib/cjs/actions/midnight/takeLend.js +2 -2
  39. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  40. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +60 -19
  41. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  42. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +72 -0
  43. package/lib/cjs/actions/requirements/blue/index.d.ts +1 -0
  44. package/lib/cjs/actions/requirements/blue/index.js +1 -0
  45. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  46. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +30 -5
  47. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  48. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +8 -2
  49. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  50. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +39 -6
  51. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +61 -0
  52. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +123 -0
  53. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -4
  54. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +6 -5
  55. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  56. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  57. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  58. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +6 -4
  59. package/lib/cjs/actions/requirements/getRequirementsApproval.js +6 -4
  60. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  61. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +4 -0
  62. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +22 -30
  63. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +18 -66
  64. package/lib/cjs/actions/vaultV1/deposit.d.ts +73 -57
  65. package/lib/cjs/actions/vaultV1/deposit.js +110 -109
  66. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +43 -66
  67. package/lib/cjs/actions/vaultV1/migrateToV2.js +91 -104
  68. package/lib/cjs/actions/vaultV1/redeem.d.ts +30 -23
  69. package/lib/cjs/actions/vaultV1/redeem.js +56 -33
  70. package/lib/cjs/actions/vaultV1/withdraw.d.ts +58 -24
  71. package/lib/cjs/actions/vaultV1/withdraw.js +86 -34
  72. package/lib/cjs/actions/vaultV2/deposit.d.ts +74 -57
  73. package/lib/cjs/actions/vaultV2/deposit.js +111 -109
  74. package/lib/cjs/actions/vaultV2/redeem.d.ts +30 -24
  75. package/lib/cjs/actions/vaultV2/redeem.js +56 -34
  76. package/lib/cjs/actions/vaultV2/withdraw.d.ts +58 -25
  77. package/lib/cjs/actions/vaultV2/withdraw.js +86 -35
  78. package/lib/cjs/bundler/actions.d.ts +4 -4
  79. package/lib/cjs/bundler/actions.js +4 -4
  80. package/lib/cjs/client/morphoViemExtension.d.ts +2 -1
  81. package/lib/cjs/client/morphoViemExtension.js +2 -1
  82. package/lib/cjs/entities/blue/blue.d.ts +806 -374
  83. package/lib/cjs/entities/blue/blue.js +449 -696
  84. package/lib/cjs/entities/index.d.ts +2 -0
  85. package/lib/cjs/entities/index.js +15 -0
  86. package/lib/cjs/entities/midnight/midnight.d.ts +2 -2
  87. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +87 -0
  88. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +203 -0
  89. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +28 -0
  90. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +74 -0
  91. package/lib/cjs/entities/requirements/index.d.ts +1 -0
  92. package/lib/cjs/entities/requirements/index.js +17 -0
  93. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +348 -98
  94. package/lib/cjs/entities/vaultV1/vaultV1.js +322 -120
  95. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +221 -68
  96. package/lib/cjs/entities/vaultV2/vaultV2.js +219 -77
  97. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +3 -9
  98. package/lib/cjs/helpers/computeVaultV1Reallocations.js +3 -9
  99. package/lib/cjs/helpers/index.d.ts +2 -1
  100. package/lib/cjs/helpers/index.js +5 -1
  101. package/lib/cjs/helpers/referralFee.d.ts +21 -0
  102. package/lib/cjs/helpers/referralFee.js +35 -0
  103. package/lib/cjs/helpers/slippage.d.ts +90 -1
  104. package/lib/cjs/helpers/slippage.js +123 -0
  105. package/lib/cjs/helpers/validate.d.ts +16 -23
  106. package/lib/cjs/helpers/validate.js +41 -48
  107. package/lib/cjs/helpers/validateRequirementSpender.d.ts +2 -1
  108. package/lib/cjs/helpers/validateRequirementSpender.js +3 -0
  109. package/lib/cjs/index.d.ts +1 -0
  110. package/lib/cjs/index.js +1 -0
  111. package/lib/cjs/types/action.d.ts +303 -210
  112. package/lib/cjs/types/action.js +29 -2
  113. package/lib/cjs/types/client.d.ts +9 -0
  114. package/lib/cjs/types/error.d.ts +193 -18
  115. package/lib/cjs/types/error.js +267 -24
  116. package/lib/cjs/types/sharedLiquidity.d.ts +0 -7
  117. package/lib/esm/abis.d.ts +210 -0
  118. package/lib/esm/abis.js +140 -0
  119. package/lib/esm/actions/blue/borrow.d.ts +62 -61
  120. package/lib/esm/actions/blue/borrow.js +48 -80
  121. package/lib/esm/actions/blue/common.d.ts +86 -0
  122. package/lib/esm/actions/blue/common.js +193 -0
  123. package/lib/esm/actions/blue/refinance.d.ts +72 -112
  124. package/lib/esm/actions/blue/refinance.js +98 -200
  125. package/lib/esm/actions/blue/repay.d.ts +72 -68
  126. package/lib/esm/actions/blue/repay.js +56 -118
  127. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  128. package/lib/esm/actions/blue/repayWithdrawCollateral.js +149 -138
  129. package/lib/esm/actions/blue/supply.d.ts +62 -45
  130. package/lib/esm/actions/blue/supply.js +94 -70
  131. package/lib/esm/actions/blue/supplyCollateral.d.ts +63 -40
  132. package/lib/esm/actions/blue/supplyCollateral.js +52 -69
  133. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +82 -90
  134. package/lib/esm/actions/blue/supplyCollateralBorrow.js +134 -121
  135. package/lib/esm/actions/blue/withdraw.d.ts +68 -79
  136. package/lib/esm/actions/blue/withdraw.js +100 -96
  137. package/lib/esm/actions/blue/withdrawCollateral.d.ts +56 -28
  138. package/lib/esm/actions/blue/withdrawCollateral.js +45 -50
  139. package/lib/esm/actions/bundles/common.d.ts +200 -0
  140. package/lib/esm/actions/bundles/common.js +457 -0
  141. package/lib/esm/actions/bundles/index.d.ts +3 -0
  142. package/lib/esm/actions/bundles/index.js +2 -0
  143. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +76 -0
  144. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +121 -0
  145. package/lib/esm/actions/index.d.ts +2 -1
  146. package/lib/esm/actions/index.js +1 -0
  147. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +2 -2
  148. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +2 -2
  149. package/lib/esm/actions/midnight/takeBorrow.d.ts +2 -2
  150. package/lib/esm/actions/midnight/takeBorrow.js +2 -2
  151. package/lib/esm/actions/midnight/takeLend.d.ts +2 -2
  152. package/lib/esm/actions/midnight/takeLend.js +2 -2
  153. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  154. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +63 -22
  155. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  156. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +68 -0
  157. package/lib/esm/actions/requirements/blue/index.d.ts +1 -0
  158. package/lib/esm/actions/requirements/blue/index.js +1 -0
  159. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  160. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +31 -6
  161. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  162. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +9 -3
  163. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  164. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +40 -7
  165. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +61 -0
  166. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +119 -0
  167. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +4 -4
  168. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -5
  169. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  170. package/lib/esm/actions/requirements/encode/index.js +1 -0
  171. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  172. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +6 -4
  173. package/lib/esm/actions/requirements/getRequirementsApproval.js +6 -4
  174. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  175. package/lib/esm/actions/signatures/getTokenRequirementActions.js +5 -1
  176. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +22 -30
  177. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +19 -67
  178. package/lib/esm/actions/vaultV1/deposit.d.ts +73 -57
  179. package/lib/esm/actions/vaultV1/deposit.js +112 -111
  180. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +43 -66
  181. package/lib/esm/actions/vaultV1/migrateToV2.js +93 -106
  182. package/lib/esm/actions/vaultV1/redeem.d.ts +30 -23
  183. package/lib/esm/actions/vaultV1/redeem.js +56 -33
  184. package/lib/esm/actions/vaultV1/withdraw.d.ts +58 -24
  185. package/lib/esm/actions/vaultV1/withdraw.js +86 -34
  186. package/lib/esm/actions/vaultV2/deposit.d.ts +74 -57
  187. package/lib/esm/actions/vaultV2/deposit.js +113 -111
  188. package/lib/esm/actions/vaultV2/redeem.d.ts +30 -24
  189. package/lib/esm/actions/vaultV2/redeem.js +56 -34
  190. package/lib/esm/actions/vaultV2/withdraw.d.ts +58 -25
  191. package/lib/esm/actions/vaultV2/withdraw.js +86 -35
  192. package/lib/esm/bundler/actions.d.ts +4 -4
  193. package/lib/esm/bundler/actions.js +4 -4
  194. package/lib/esm/client/morphoViemExtension.d.ts +2 -1
  195. package/lib/esm/client/morphoViemExtension.js +2 -1
  196. package/lib/esm/entities/blue/blue.d.ts +806 -374
  197. package/lib/esm/entities/blue/blue.js +455 -702
  198. package/lib/esm/entities/index.d.ts +2 -0
  199. package/lib/esm/entities/index.js +1 -0
  200. package/lib/esm/entities/midnight/midnight.d.ts +2 -2
  201. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +87 -0
  202. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +199 -0
  203. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +28 -0
  204. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +70 -0
  205. package/lib/esm/entities/requirements/index.d.ts +1 -0
  206. package/lib/esm/entities/requirements/index.js +1 -0
  207. package/lib/esm/entities/vaultV1/vaultV1.d.ts +348 -98
  208. package/lib/esm/entities/vaultV1/vaultV1.js +326 -124
  209. package/lib/esm/entities/vaultV2/vaultV2.d.ts +221 -68
  210. package/lib/esm/entities/vaultV2/vaultV2.js +222 -80
  211. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +3 -9
  212. package/lib/esm/helpers/computeVaultV1Reallocations.js +3 -9
  213. package/lib/esm/helpers/index.d.ts +2 -1
  214. package/lib/esm/helpers/index.js +2 -1
  215. package/lib/esm/helpers/referralFee.d.ts +21 -0
  216. package/lib/esm/helpers/referralFee.js +31 -0
  217. package/lib/esm/helpers/slippage.d.ts +90 -1
  218. package/lib/esm/helpers/slippage.js +122 -2
  219. package/lib/esm/helpers/validate.d.ts +16 -23
  220. package/lib/esm/helpers/validate.js +40 -48
  221. package/lib/esm/helpers/validateRequirementSpender.d.ts +2 -1
  222. package/lib/esm/helpers/validateRequirementSpender.js +3 -0
  223. package/lib/esm/index.d.ts +1 -0
  224. package/lib/esm/index.js +1 -0
  225. package/lib/esm/types/action.d.ts +303 -210
  226. package/lib/esm/types/action.js +28 -2
  227. package/lib/esm/types/client.d.ts +9 -0
  228. package/lib/esm/types/error.d.ts +193 -18
  229. package/lib/esm/types/error.js +252 -21
  230. package/lib/esm/types/sharedLiquidity.d.ts +0 -7
  231. package/package.json +6 -5
  232. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +0 -47
  233. package/lib/cjs/actions/blue/buildAssetFundingActions.js +0 -63
  234. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +0 -69
  235. package/lib/cjs/actions/blue/buildReallocationActions.js +0 -141
  236. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +0 -66
  237. package/lib/cjs/actions/blue/resolveRepayFunding.js +0 -85
  238. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +0 -47
  239. package/lib/esm/actions/blue/buildAssetFundingActions.js +0 -59
  240. package/lib/esm/actions/blue/buildReallocationActions.d.ts +0 -69
  241. package/lib/esm/actions/blue/buildReallocationActions.js +0 -135
  242. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +0 -66
  243. package/lib/esm/actions/blue/resolveRepayFunding.js +0 -81
@@ -1,11 +1,12 @@
1
- import { AccrualPosition, DEFAULT_SLIPPAGE_TOLERANCE, MathLib, VaultV2BluePublicAllocatorConfigUtils, } from "@morpho-org/blue-sdk";
1
+ import { MathLib, } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualPosition, fetchAccrualVaultV2, fetchMarket, fetchPosition, fetchVault, fetchVaultMarketConfig, fetchVaultV2BluePublicAllocatorData, } from "@morpho-org/blue-sdk-viem";
3
- import { Time } from "@morpho-org/morpho-ts";
4
- import { isAddressEqual } from "viem";
5
- import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, getGeneralAdapterRequirements, } from "../../actions/index.js";
6
- import { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, computeVaultV1Reallocations, validateAccrualPosition, validateChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
7
- import { validateAndNormalizeReallocations } from "../../helpers/validate.js";
8
- import { BorrowAmountAndSharesExclusiveError, MarketIdMismatchError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, RefinanceExceedsBorrowAssetsError, RefinanceExceedsBorrowSharesError, RefinanceExceedsCollateralError, RefinanceSameMarketError, RefinanceTokenMismatchError, selectRequirementSignatures, WithdrawExceedsCollateralError, } from "../../types/index.js";
3
+ import { getChainAddress, Time } from "@morpho-org/morpho-ts";
4
+ import { getAddress, isAddressEqual, maxUint256 } from "viem";
5
+ import { getBlueBundlesV1PenaltyAssets, getBlueBundlesV1PublicAllocations, getBlueBundlesV1ReferralFeeAssets, normalizeBlueBundlesV1CommonParams, selectBlueBundlesV1RequirementSignatures, validateBlueBundlesV1NativeFunding, } from "../../actions/blue/common.js";
6
+ import { blueBorrow, blueRefinance, blueRepay, blueRepayWithdrawCollateral, blueSupply, blueSupplyCollateral, blueSupplyCollateralBorrow, blueWithdraw, blueWithdrawCollateral, getBlueAuthorizationRequirement, } from "../../actions/index.js";
7
+ import { computeVaultV1Reallocations, DEFAULT_LLTV_BUFFER, MAX_TOKEN_APPROVALS, validateAccrualPosition, validateChainId, validatePositionHealth, validatePositionHealthAfterWithdraw, validateRepayAmount, validateRepayShares, validateWithdrawAmount, validateWithdrawShares, } from "../../helpers/index.js";
8
+ import { ExpiredDeadlineError, InputExceedsMaxError, MaxRepayAssetsBelowRepayAssetsError, MissingAccrualPositionError, MutuallyExclusiveRepayAmountsError, MutuallyExclusiveWithdrawAmountsError, NegativeInputError, NonPositiveInputError, ReallocationsRequireBorrowError, RefinanceSameMarketError, RefinanceTokenMismatchError, } from "../../types/index.js";
9
+ import { getBundlesTokenRequirements } from "../requirements/index.js";
9
10
  import { VaultV1ReallocationData } from "../vaultV1ReallocationData.js";
10
11
  import { VaultV2BlueReallocationData } from "../vaultV2BlueReallocationData.js";
11
12
  export class MorphoBlue {
@@ -18,22 +19,61 @@ export class MorphoBlue {
18
19
  this.marketParams = marketParams;
19
20
  this.chainId = chainId;
20
21
  }
21
- getReallocationPenaltyRequirements(userAddress, reallocationPlan) {
22
- if (reallocationPlan.type === "vaultV1")
23
- return [];
24
- const { reallocations } = reallocationPlan;
25
- const amount = reallocations.reduce((total, reallocation) => total +
26
- VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n);
27
- // Separate-token penalty funding uses a classic GeneralAdapter1 allowance so a collateral
28
- // permit and a loan-token penalty can coexist in one bundle. The shared-token path aggregates
29
- // both amounts into the collateral requirement instead.
30
- return getGeneralAdapterRequirements(this.client.viemClient, {
31
- address: this.marketParams.loanToken,
22
+ validateDeadline(deadline) {
23
+ const timestamp = Time.timestamp();
24
+ if (deadline <= timestamp) {
25
+ throw new ExpiredDeadlineError(deadline, timestamp);
26
+ }
27
+ }
28
+ validateWriteCommon(params) {
29
+ validateChainId(this.client.viemClient.chain?.id, this.chainId);
30
+ this.validateDeadline(params.deadline);
31
+ // Resolve at handle creation so unsupported deployments fail before any RPC prerequisite work.
32
+ getChainAddress(this.chainId, "bundles.blueBundlesV1");
33
+ // Validate the referral inputs eagerly; the normalized result is intentionally discarded here
34
+ // because the pure action re-normalizes it at encode time.
35
+ normalizeBlueBundlesV1CommonParams({
32
36
  chainId: this.chainId,
33
- supportSignature: false,
34
- args: { amount, from: userAddress },
37
+ userAddress: params.userAddress,
38
+ deadline: params.deadline,
39
+ referralFeePct: params.referralFeePct,
40
+ referralFeeRecipient: params.referralFeeRecipient,
35
41
  });
36
42
  }
43
+ getMaxLtv(marketParams = this.marketParams) {
44
+ return MathLib.zeroFloorSub(marketParams.lltv, DEFAULT_LLTV_BUFFER);
45
+ }
46
+ getBlueBundlesV1QuoteTimestamp(lastUpdate) {
47
+ return MathLib.max(Time.timestamp(), lastUpdate) + Time.s.from.h(2n);
48
+ }
49
+ async getTokenRequirements(params) {
50
+ this.validateDeadline(params.deadline);
51
+ return getBundlesTokenRequirements(this.client.viemClient, {
52
+ token: params.token,
53
+ spender: getChainAddress(this.chainId, "bundles.blueBundlesV1"),
54
+ amount: params.amount,
55
+ owner: params.userAddress,
56
+ chainId: this.chainId,
57
+ deadline: params.deadline,
58
+ supportSignature: this.client.options.supportSignature,
59
+ supportDeployless: this.client.options.supportDeployless,
60
+ useSimplePermit: params.useSimplePermit,
61
+ permit2Nonce: params.permit2Nonce,
62
+ approvalAmount: params.approvalAmount,
63
+ });
64
+ }
65
+ async getAuthorizationRequirements(params) {
66
+ this.validateDeadline(params.deadline);
67
+ const requirement = await getBlueAuthorizationRequirement({
68
+ viemClient: this.client.viemClient,
69
+ chainId: this.chainId,
70
+ userAddress: params.userAddress,
71
+ supportSignature: this.client.options.supportSignature,
72
+ authorized: getChainAddress(this.chainId, "bundles.blueBundlesV1"),
73
+ deadline: params.deadline,
74
+ });
75
+ return requirement == null ? [] : [requirement];
76
+ }
37
77
  async getMarketData(parameters) {
38
78
  validateChainId(this.client.viemClient.chain?.id, this.chainId);
39
79
  return fetchMarket(this.marketParams.id, this.client.viemClient, {
@@ -50,91 +90,70 @@ export class MorphoBlue {
50
90
  chainId: this.chainId,
51
91
  });
52
92
  }
53
- supply({ amount = 0n, userAddress, nativeAmount, marketData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, }) {
54
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
55
- if (amount < 0n) {
56
- throw new NegativeInputError("amount", amount);
57
- }
58
- if (nativeAmount !== undefined && nativeAmount < 0n) {
59
- throw new NegativeInputError("nativeAmount", nativeAmount);
60
- }
61
- const totalAssets = amount + (nativeAmount ?? 0n);
62
- if (totalAssets === 0n) {
63
- throw new NonPositiveInputError("totalAssets", totalAssets);
64
- }
65
- if (marketData.id !== this.marketParams.id) {
66
- throw new MarketIdMismatchError(marketData.id, this.marketParams.id);
67
- }
68
- validateSlippageTolerance(slippageTolerance);
69
- if (nativeAmount !== undefined && nativeAmount > 0n) {
70
- validateNativeAsset(this.chainId, this.marketParams.loanToken);
71
- }
72
- // Forward-accrue (2h) before deriving `maxSharePrice`: on-chain `morphoSupply` accrues `lastUpdate → execution`, raising the supply share price, so an un-accrued bound reverts on quiet markets.
73
- const accrualTimestamp = MathLib.max(Time.timestamp(), marketData.lastUpdate) + Time.s.from.h(2n);
74
- const marketForSupply = marketData.accrueInterest(accrualTimestamp);
75
- const maxSharePrice = computeMaxSupplySharePrice({
76
- supplyAssets: totalAssets,
77
- market: marketForSupply,
78
- slippageTolerance,
93
+ /** {@inheritDoc BlueActions.supply} */
94
+ supply(params) {
95
+ const { userAddress, assets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
96
+ this.validateWriteCommon(params);
97
+ if (assets <= 0n)
98
+ throw new NonPositiveInputError("assets", assets);
99
+ const nativeValue = validateBlueBundlesV1NativeFunding({
100
+ chainId: this.chainId,
101
+ token: this.marketParams.loanToken,
102
+ fundedAmount: assets,
103
+ nativeAmount,
79
104
  });
80
105
  return {
81
- getRequirements: (params) => getGeneralAdapterRequirements(this.client.viemClient, {
82
- address: this.marketParams.loanToken,
83
- chainId: this.chainId,
84
- supportSignature: this.client.options.supportSignature,
85
- supportDeployless: this.client.options.supportDeployless,
86
- useSimplePermit: params?.useSimplePermit,
87
- args: { amount, from: userAddress },
88
- }),
106
+ getRequirements: (requirementsParams) => {
107
+ this.validateDeadline(deadline);
108
+ if (nativeValue > 0n)
109
+ return Promise.resolve([]);
110
+ return this.getTokenRequirements({
111
+ token: this.marketParams.loanToken,
112
+ amount: assets,
113
+ userAddress,
114
+ deadline,
115
+ useSimplePermit: requirementsParams?.useSimplePermit,
116
+ permit2Nonce: requirementsParams?.permit2Nonce,
117
+ approvalAmount: requirementsParams?.approvalAmount,
118
+ });
119
+ },
89
120
  buildTx: (signatures) => {
90
- const { permit } = selectRequirementSignatures(signatures, {
91
- permit: true,
121
+ const { token } = selectBlueBundlesV1RequirementSignatures(signatures, {
122
+ token: nativeValue === 0n,
92
123
  });
93
124
  return blueSupply({
94
125
  market: { chainId: this.chainId, marketParams: this.marketParams },
95
126
  args: {
96
- amount,
97
- nativeAmount,
98
- onBehalf: userAddress,
99
- maxSharePrice,
100
- requirementSignature: permit,
127
+ userAddress,
128
+ assets,
129
+ nativeAmount: nativeValue > 0n ? nativeValue : undefined,
130
+ deadline,
131
+ referralFeePct,
132
+ referralFeeRecipient,
133
+ requirementSignature: token,
101
134
  },
102
135
  metadata: this.client.options.metadata,
103
136
  });
104
137
  },
105
138
  };
106
139
  }
140
+ /** {@inheritDoc BlueActions.withdraw} */
107
141
  withdraw(params) {
108
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
109
- const { userAddress, receiver = userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, } = params;
110
- const reallocationPlan = validateAndNormalizeReallocations({
111
- reallocations,
112
- targetMarketId: this.marketParams.id,
113
- chainId: this.chainId,
114
- });
115
- const reallocationList = reallocationPlan.reallocations;
116
- // Mode normalization: a missing or undefined `assets`/`shares` key collapses to `0n`
117
- // so the mutual-exclusion and positivity checks below are pure value comparisons.
142
+ const { userAddress, positionData, deadline, referralFeePct, referralFeeRecipient, } = params;
143
+ this.validateWriteCommon(params);
118
144
  const assets = ("assets" in params ? params.assets : undefined) ?? 0n;
119
145
  const shares = ("shares" in params ? params.shares : undefined) ?? 0n;
120
- // Mode conflict comes first: detect "both values present" (either non-zero)
121
- // before positivity, so `{ assets: -1n, shares: 5n }` reports the actual
122
- // mode conflict instead of being misclassified as a positivity error.
123
- // Mirrors action layer.
124
- if (assets !== 0n && shares !== 0n) {
125
- throw new MutuallyExclusiveWithdrawAmountsError(this.marketParams.id);
126
- }
127
- if (assets < 0n) {
146
+ if (assets < 0n)
128
147
  throw new NegativeInputError("assets", assets);
129
- }
130
- if (shares < 0n) {
148
+ if (shares < 0n)
131
149
  throw new NegativeInputError("shares", shares);
150
+ if (assets > 0n && shares > 0n) {
151
+ throw new MutuallyExclusiveWithdrawAmountsError(this.marketParams.id);
132
152
  }
133
153
  if (assets === 0n && shares === 0n) {
134
154
  throw new NonPositiveInputError("assets or shares", 0n);
135
155
  }
136
- validateSlippageTolerance(slippageTolerance);
137
- if (!positionData) {
156
+ if (positionData == null) {
138
157
  throw new MissingAccrualPositionError(this.marketParams.id);
139
158
  }
140
159
  validateAccrualPosition({
@@ -156,37 +175,34 @@ export class MorphoBlue {
156
175
  marketId: this.marketParams.id,
157
176
  });
158
177
  }
159
- const minSharePrice = computeMinWithdrawSharePrice({
160
- withdrawAssets: assets,
161
- withdrawShares: shares,
162
- market: positionData.market,
163
- slippageTolerance,
164
- });
178
+ const reallocations = [...(params.reallocations ?? [])];
179
+ // Validate the exact PublicAllocations mapping before requirement reads.
180
+ const publicAllocations = getBlueBundlesV1PublicAllocations(reallocations, this.marketParams);
181
+ const reallocationPenaltyAssets = getBlueBundlesV1PenaltyAssets(publicAllocations);
182
+ const expectedWithdrawAssets = assets > 0n ? assets : positionData.market.toSupplyAssets(shares, "Down");
183
+ if (reallocationPenaltyAssets > expectedWithdrawAssets) {
184
+ throw new InputExceedsMaxError({
185
+ field: "reallocationPenaltyAssets",
186
+ value: reallocationPenaltyAssets,
187
+ max: expectedWithdrawAssets,
188
+ });
189
+ }
165
190
  return {
166
- getRequirements: async () => {
167
- const [penaltyRequirements, authTx] = await Promise.all([
168
- this.getReallocationPenaltyRequirements(userAddress, reallocationPlan),
169
- getBlueAuthorizationRequirement({
170
- viemClient: this.client.viemClient,
171
- chainId: this.chainId,
172
- userAddress,
173
- supportSignature: this.client.options.supportSignature,
174
- }),
175
- ]);
176
- return [...penaltyRequirements, ...(authTx ? [authTx] : [])];
177
- },
191
+ getRequirements: () => this.getAuthorizationRequirements({ userAddress, deadline }),
178
192
  buildTx: (signatures) => {
179
- const { authorization } = selectRequirementSignatures(signatures, {
193
+ const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, {
180
194
  authorization: true,
181
195
  });
182
196
  return blueWithdraw({
183
197
  market: { chainId: this.chainId, marketParams: this.marketParams },
184
198
  args: {
185
- assets,
186
- shares,
187
- receiver,
188
- minSharePrice,
189
- reallocations: reallocationList,
199
+ userAddress,
200
+ withdrawAssets: assets,
201
+ withdrawShares: shares,
202
+ reallocations,
203
+ deadline,
204
+ referralFeePct,
205
+ referralFeeRecipient,
190
206
  authorizationSignature: authorization,
191
207
  },
192
208
  metadata: this.client.options.metadata,
@@ -194,109 +210,68 @@ export class MorphoBlue {
194
210
  },
195
211
  };
196
212
  }
197
- supplyCollateral({ amount = 0n, userAddress, nativeAmount, }) {
198
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
199
- if (amount < 0n) {
200
- throw new NegativeInputError("amount", amount);
201
- }
202
- if (nativeAmount !== undefined && nativeAmount < 0n) {
203
- throw new NegativeInputError("nativeAmount", nativeAmount);
204
- }
205
- const totalCollateral = amount + (nativeAmount ?? 0n);
206
- if (totalCollateral === 0n) {
207
- throw new NonPositiveInputError("totalCollateral", totalCollateral);
208
- }
209
- if (nativeAmount !== undefined && nativeAmount > 0n) {
210
- validateNativeAsset(this.chainId, this.marketParams.collateralToken);
211
- }
213
+ /** {@inheritDoc BlueActions.supplyCollateral} */
214
+ supplyCollateral(params) {
215
+ const { userAddress, collateralAssets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
216
+ const combinedAction = this.supplyCollateralBorrow({
217
+ userAddress,
218
+ collateralAssets,
219
+ borrowAssets: 0n,
220
+ nativeAmount,
221
+ deadline,
222
+ referralFeePct,
223
+ referralFeeRecipient,
224
+ });
212
225
  return {
213
- getRequirements: (params) => getGeneralAdapterRequirements(this.client.viemClient, {
214
- address: this.marketParams.collateralToken,
215
- chainId: this.chainId,
216
- supportSignature: this.client.options.supportSignature,
217
- supportDeployless: this.client.options.supportDeployless,
218
- useSimplePermit: params?.useSimplePermit,
219
- args: { amount, from: userAddress },
220
- }),
226
+ getRequirements: combinedAction.getRequirements,
221
227
  buildTx: (signatures) => {
222
- const { permit } = selectRequirementSignatures(signatures, {
223
- permit: true,
228
+ const { token } = selectBlueBundlesV1RequirementSignatures(signatures, {
229
+ token: (nativeAmount ?? 0n) === 0n,
224
230
  });
225
231
  return blueSupplyCollateral({
226
- market: {
227
- chainId: this.chainId,
228
- marketParams: this.marketParams,
229
- },
232
+ market: { chainId: this.chainId, marketParams: this.marketParams },
230
233
  args: {
231
- amount,
234
+ userAddress,
235
+ collateralAssets,
232
236
  nativeAmount,
233
- onBehalf: userAddress,
234
- requirementSignature: permit,
237
+ deadline,
238
+ referralFeePct,
239
+ referralFeeRecipient,
240
+ requirementSignature: token,
235
241
  },
236
242
  metadata: this.client.options.metadata,
237
243
  });
238
244
  },
239
245
  };
240
246
  }
241
- borrow({ amount, userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
242
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
243
- const reallocationPlan = validateAndNormalizeReallocations({
244
- reallocations,
245
- targetMarketId: this.marketParams.id,
246
- chainId: this.chainId,
247
- });
248
- const reallocationList = reallocationPlan.reallocations;
249
- if (amount <= 0n) {
250
- throw new NonPositiveInputError("amount", amount);
251
- }
252
- validateSlippageTolerance(slippageTolerance);
253
- if (!positionData) {
254
- throw new MissingAccrualPositionError(this.marketParams.id);
255
- }
256
- validateAccrualPosition({
247
+ /** {@inheritDoc BlueActions.borrow} */
248
+ borrow(params) {
249
+ const { userAddress, borrowAssets, positionData, reallocations, deadline, referralFeePct, referralFeeRecipient, } = params;
250
+ const normalizedReallocations = [...(reallocations ?? [])];
251
+ const combinedAction = this.supplyCollateralBorrow({
252
+ userAddress,
253
+ collateralAssets: 0n,
254
+ borrowAssets,
257
255
  positionData,
258
- expectedMarketId: this.marketParams.id,
259
- expectedUser: userAddress,
260
- });
261
- validatePositionHealth({
262
- positionData,
263
- additionalCollateral: 0n,
264
- borrowAmount: amount,
265
- marketId: this.marketParams.id,
266
- lltv: this.marketParams.lltv,
267
- });
268
- const minSharePrice = computeMinBorrowSharePrice({
269
- borrowAmount: amount,
270
- market: positionData.market,
271
- slippageTolerance,
256
+ reallocations: normalizedReallocations,
257
+ deadline,
258
+ referralFeePct,
259
+ referralFeeRecipient,
272
260
  });
273
261
  return {
274
- getRequirements: async () => {
275
- const [penaltyRequirements, authTx] = await Promise.all([
276
- this.getReallocationPenaltyRequirements(userAddress, reallocationPlan),
277
- getBlueAuthorizationRequirement({
278
- viemClient: this.client.viemClient,
279
- chainId: this.chainId,
280
- userAddress,
281
- supportSignature: this.client.options.supportSignature,
282
- }),
283
- ]);
284
- return [...penaltyRequirements, ...(authTx ? [authTx] : [])];
285
- },
262
+ getRequirements: () => combinedAction.getRequirements(),
286
263
  buildTx: (signatures) => {
287
- const { authorization } = selectRequirementSignatures(signatures, {
288
- authorization: true,
289
- });
264
+ const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, { authorization: true });
290
265
  return blueBorrow({
291
- market: {
292
- chainId: this.chainId,
293
- marketParams: this.marketParams,
294
- },
266
+ market: { chainId: this.chainId, marketParams: this.marketParams },
295
267
  args: {
296
- amount,
297
- receiver: userAddress,
298
- minSharePrice,
299
- reallocations: reallocationList,
268
+ userAddress,
269
+ borrowAssets,
270
+ maxLtv: this.getMaxLtv(),
271
+ reallocations: normalizedReallocations,
272
+ deadline,
273
+ referralFeePct,
274
+ referralFeeRecipient,
300
275
  authorizationSignature: authorization,
301
276
  },
302
277
  metadata: this.client.options.metadata,
@@ -304,209 +279,98 @@ export class MorphoBlue {
304
279
  },
305
280
  };
306
281
  }
282
+ /** {@inheritDoc BlueActions.repay} */
307
283
  repay(params) {
308
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
309
- const { userAddress, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, } = params;
310
- const nativeAmount = params.nativeAmount ?? 0n;
311
- if (nativeAmount < 0n) {
312
- throw new NegativeInputError("nativeAmount", nativeAmount);
313
- }
314
- const amount = ("amount" in params ? params.amount : undefined) ?? 0n;
315
- const shares = ("shares" in params ? params.shares : undefined) ?? 0n;
316
- if (amount < 0n) {
317
- throw new NegativeInputError("amount", amount);
318
- }
319
- if (shares < 0n) {
320
- throw new NegativeInputError("shares", shares);
321
- }
322
- if (amount > 0n && shares > 0n) {
323
- throw new MutuallyExclusiveRepayAmountsError(this.marketParams.id);
324
- }
325
- if ("shares" in params) {
326
- if (shares === 0n) {
327
- throw new NonPositiveInputError("shares", shares);
328
- }
329
- }
330
- else {
331
- if (amount + nativeAmount <= 0n) {
332
- throw new NonPositiveInputError("amount + nativeAmount", amount + nativeAmount);
333
- }
334
- }
335
- validateSlippageTolerance(slippageTolerance);
336
- if (!positionData) {
337
- throw new MissingAccrualPositionError(this.marketParams.id);
338
- }
339
- validateAccrualPosition({
340
- positionData,
341
- expectedMarketId: this.marketParams.id,
342
- expectedUser: userAddress,
343
- });
344
- if (nativeAmount > 0n) {
345
- validateNativeAsset(this.chainId, this.marketParams.loanToken);
346
- }
347
- let repayAssets;
348
- let repayShares;
349
- let erc20Amount;
350
- // Forward-accrue (2h) before deriving `maxSharePrice` (both modes): on-chain `morphoRepay` accrues `lastUpdate → execution`, so an un-accrued bound reverts on quiet markets.
351
- const accrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
352
- Time.s.from.h(2n);
353
- const marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
354
- if ("shares" in params) {
355
- validateRepayShares({
356
- positionData,
357
- repayShares: shares,
358
- marketId: this.marketParams.id,
359
- });
360
- repayAssets = 0n;
361
- repayShares = shares;
362
- const borrowAssets = marketForRepay.toBorrowAssets(shares, "Up");
363
- // Native funds the transfer first; the ERC-20 pulled is the remainder.
364
- // When native covers the full (2h-forward-accrued, rounded-up) borrow
365
- // assets, nothing is pulled as ERC-20 — the bundle wraps the native and
366
- // skims any residual wNative back to the receiver. So a fully-native
367
- // shares repay pulls no ERC-20 and emits no loan-token approval requirement.
368
- erc20Amount = MathLib.zeroFloorSub(borrowAssets, nativeAmount);
369
- }
370
- else {
371
- // Assets mode is additive, like supply: repaid = amount + nativeAmount.
372
- repayAssets = amount + nativeAmount;
373
- validateRepayAmount({
374
- positionData,
375
- repayAssets,
376
- marketId: this.marketParams.id,
377
- });
378
- repayShares = 0n;
379
- erc20Amount = amount;
380
- }
381
- const maxSharePrice = computeMaxRepaySharePrice({
382
- repayAssets,
383
- repayShares,
384
- market: marketForRepay,
385
- slippageTolerance,
284
+ const combinedAction = this.repayWithdrawCollateral({
285
+ ...params,
286
+ collateralAssets: 0n,
386
287
  });
387
288
  return {
388
- getRequirements: (reqParams) => {
389
- // Fully native repay pulls no ERC-20, so it needs no approval/permit.
390
- if (erc20Amount === 0n)
391
- return Promise.resolve([]);
392
- return getGeneralAdapterRequirements(this.client.viemClient, {
393
- address: this.marketParams.loanToken,
394
- chainId: this.chainId,
395
- supportSignature: this.client.options.supportSignature,
396
- supportDeployless: this.client.options.supportDeployless,
397
- useSimplePermit: reqParams?.useSimplePermit,
398
- args: { amount: erc20Amount, from: userAddress },
399
- });
400
- },
289
+ getRequirements: combinedAction.getRequirements,
401
290
  buildTx: (signatures) => {
402
- const { permit } = selectRequirementSignatures(signatures, {
403
- permit: true,
291
+ const combinedTransaction = combinedAction.buildTx(signatures);
292
+ const { token } = selectBlueBundlesV1RequirementSignatures(signatures, {
293
+ token: combinedTransaction.value === 0n,
404
294
  });
295
+ const { repayAssets, repayShares, maxRepayAssets, nativeAmount, referralFeePct, referralFeeRecipient, deadline, } = combinedTransaction.action.args;
405
296
  return blueRepay({
406
- market: {
407
- chainId: this.chainId,
408
- marketParams: this.marketParams,
297
+ market: { chainId: this.chainId, marketParams: this.marketParams },
298
+ args: {
299
+ userAddress: params.userAddress,
300
+ repayAssets,
301
+ repayShares,
302
+ maxRepayAssets,
303
+ nativeAmount,
304
+ deadline,
305
+ referralFeePct,
306
+ referralFeeRecipient,
307
+ requirementSignature: token,
409
308
  },
410
- // Shares mode: repay `shares`, ERC-20 to pull = `erc20Amount`.
411
- // Assets mode: repay `repayAssets` (= amount + native), pull `erc20Amount`.
412
- args: repayShares > 0n
413
- ? {
414
- shares: repayShares,
415
- transferAmount: erc20Amount,
416
- nativeAmount,
417
- onBehalf: userAddress,
418
- receiver: userAddress,
419
- maxSharePrice,
420
- requirementSignature: permit,
421
- }
422
- : {
423
- amount: erc20Amount,
424
- transferAmount: repayAssets,
425
- nativeAmount,
426
- onBehalf: userAddress,
427
- receiver: userAddress,
428
- maxSharePrice,
429
- requirementSignature: permit,
430
- },
431
309
  metadata: this.client.options.metadata,
432
310
  });
433
311
  },
434
312
  };
435
313
  }
436
- withdrawCollateral({ userAddress, amount, positionData, }) {
437
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
438
- if (amount <= 0n) {
439
- throw new NonPositiveInputError("amount", amount);
440
- }
441
- if (!positionData) {
442
- throw new MissingAccrualPositionError(this.marketParams.id);
443
- }
444
- validateAccrualPosition({
314
+ /** {@inheritDoc BlueActions.withdrawCollateral} */
315
+ withdrawCollateral(params) {
316
+ const { userAddress, positionData, collateralAssets, deadline, referralFeePct, referralFeeRecipient, } = params;
317
+ const combinedAction = this.repayWithdrawCollateral({
318
+ userAddress,
445
319
  positionData,
446
- expectedMarketId: this.marketParams.id,
447
- expectedUser: userAddress,
448
- });
449
- if (amount > positionData.collateral) {
450
- throw new WithdrawExceedsCollateralError({
451
- withdrawAmount: amount,
452
- available: positionData.collateral,
453
- market: positionData.marketId,
454
- });
455
- }
456
- validatePositionHealthAfterWithdraw({
457
- positionData,
458
- withdrawAmount: amount,
459
- lltv: this.marketParams.lltv,
460
- marketId: this.marketParams.id,
320
+ repayAssets: 0n,
321
+ collateralAssets,
322
+ deadline,
323
+ referralFeePct,
324
+ referralFeeRecipient,
461
325
  });
462
326
  return {
463
- buildTx: () => blueWithdrawCollateral({
464
- market: {
465
- chainId: this.chainId,
466
- marketParams: this.marketParams,
467
- },
468
- args: {
469
- amount,
470
- onBehalf: userAddress,
471
- receiver: userAddress,
472
- },
473
- metadata: this.client.options.metadata,
474
- }),
327
+ getRequirements: () => combinedAction.getRequirements(),
328
+ buildTx: (signatures) => {
329
+ const combinedTransaction = combinedAction.buildTx(signatures);
330
+ const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, { authorization: true });
331
+ const combinedArgs = combinedTransaction.action.args;
332
+ return blueWithdrawCollateral({
333
+ market: { chainId: this.chainId, marketParams: this.marketParams },
334
+ args: {
335
+ userAddress,
336
+ collateralAssets: combinedArgs.collateralAssets,
337
+ maxLtv: combinedArgs.maxLtv,
338
+ deadline: combinedArgs.deadline,
339
+ referralFeePct: combinedArgs.referralFeePct,
340
+ referralFeeRecipient: combinedArgs.referralFeeRecipient,
341
+ authorizationSignature: authorization,
342
+ },
343
+ metadata: this.client.options.metadata,
344
+ });
345
+ },
475
346
  };
476
347
  }
348
+ /** {@inheritDoc BlueActions.repayWithdrawCollateral} */
477
349
  repayWithdrawCollateral(params) {
478
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
479
- const { userAddress, withdrawAmount, positionData, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, } = params;
480
- const nativeAmount = params.nativeAmount ?? 0n;
481
- if (nativeAmount < 0n) {
482
- throw new NegativeInputError("nativeAmount", nativeAmount);
483
- }
484
- const amount = ("amount" in params ? params.amount : undefined) ?? 0n;
485
- const shares = ("shares" in params ? params.shares : undefined) ?? 0n;
486
- if (amount < 0n) {
487
- throw new NegativeInputError("amount", amount);
488
- }
489
- if (shares < 0n) {
490
- throw new NegativeInputError("shares", shares);
491
- }
492
- if (amount > 0n && shares > 0n) {
350
+ const { userAddress, positionData, collateralAssets, nativeAmount, deadline, referralFeeRecipient, } = params;
351
+ this.validateWriteCommon(params);
352
+ // `validateWriteCommon` returns void, so default an omitted `referralFeePct` to `0n`
353
+ // here, matching the pure action's normalization.
354
+ const referralFeePct = params.referralFeePct ?? 0n;
355
+ const repayAssets = params.repayAssets ?? 0n;
356
+ const repayShares = params.repayShares ?? 0n;
357
+ if (repayAssets < 0n) {
358
+ throw new NegativeInputError("repayAssets", repayAssets);
359
+ }
360
+ if (repayShares < 0n) {
361
+ throw new NegativeInputError("repayShares", repayShares);
362
+ }
363
+ if (collateralAssets < 0n) {
364
+ throw new NegativeInputError("collateralAssets", collateralAssets);
365
+ }
366
+ if (repayAssets > 0n && repayShares > 0n) {
493
367
  throw new MutuallyExclusiveRepayAmountsError(this.marketParams.id);
494
368
  }
495
- if ("shares" in params) {
496
- if (shares === 0n) {
497
- throw new NonPositiveInputError("shares", shares);
498
- }
369
+ const hasRepay = repayAssets > 0n || repayShares > 0n;
370
+ if (!hasRepay && collateralAssets === 0n) {
371
+ throw new NonPositiveInputError("repayAssets, repayShares, or collateralAssets", 0n);
499
372
  }
500
- else {
501
- if (amount + nativeAmount <= 0n) {
502
- throw new NonPositiveInputError("amount + nativeAmount", amount + nativeAmount);
503
- }
504
- }
505
- if (withdrawAmount <= 0n) {
506
- throw new NonPositiveInputError("withdrawAmount", withdrawAmount);
507
- }
508
- validateSlippageTolerance(slippageTolerance);
509
- if (!positionData) {
373
+ if (positionData == null) {
510
374
  throw new MissingAccrualPositionError(this.marketParams.id);
511
375
  }
512
376
  validateAccrualPosition({
@@ -514,250 +378,222 @@ export class MorphoBlue {
514
378
  expectedMarketId: this.marketParams.id,
515
379
  expectedUser: userAddress,
516
380
  });
517
- if (nativeAmount > 0n) {
518
- validateNativeAsset(this.chainId, this.marketParams.loanToken);
519
- }
520
- let repayAssets;
521
- let repayShares;
522
- let erc20Amount;
523
- // Forward-accrue (2h) for `maxSharePrice` (both modes) and the post-repay health check: on-chain `morphoRepay` accrues `lastUpdate → execution`, so an un-accrued bound reverts on quiet markets.
524
- const accrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
525
- Time.s.from.h(2n);
526
- const marketForRepay = positionData.market.accrueInterest(accrualTimestamp);
527
- if ("shares" in params) {
528
- validateRepayShares({
381
+ const saturatedRepay = repayShares === maxUint256;
382
+ const simulatedRepayShares = saturatedRepay
383
+ ? positionData.borrowShares
384
+ : repayShares;
385
+ if (repayAssets > 0n) {
386
+ validateRepayAmount({
529
387
  positionData,
530
- repayShares: shares,
388
+ repayAssets,
531
389
  marketId: this.marketParams.id,
532
390
  });
533
- repayAssets = 0n;
534
- repayShares = shares;
535
- const borrowAssets = marketForRepay.toBorrowAssets(shares, "Up");
536
- // Native funds the transfer first; the ERC-20 pulled is the remainder.
537
- // When native covers the full (2h-forward-accrued, rounded-up) borrow
538
- // assets, nothing is pulled as ERC-20 — the bundle wraps the native and
539
- // skims any residual wNative back to the receiver. So a fully-native
540
- // shares repay pulls no ERC-20 and emits no loan-token approval requirement.
541
- erc20Amount = MathLib.zeroFloorSub(borrowAssets, nativeAmount);
542
391
  }
543
- else {
544
- // Assets mode is additive, like supply: repaid = amount + nativeAmount.
545
- repayAssets = amount + nativeAmount;
546
- validateRepayAmount({
392
+ else if (repayShares > 0n && !saturatedRepay) {
393
+ validateRepayShares({
547
394
  positionData,
548
- repayAssets,
395
+ repayShares,
549
396
  marketId: this.marketParams.id,
550
397
  });
551
- repayShares = 0n;
552
- erc20Amount = amount;
553
398
  }
554
- if (withdrawAmount > positionData.collateral) {
555
- throw new WithdrawExceedsCollateralError({
556
- withdrawAmount,
557
- available: positionData.collateral,
558
- market: positionData.marketId,
399
+ const quoteHorizon = this.getBlueBundlesV1QuoteTimestamp(positionData.market.lastUpdate);
400
+ if (repayShares > 0n && deadline > quoteHorizon) {
401
+ throw new InputExceedsMaxError({
402
+ field: "deadline",
403
+ value: deadline,
404
+ max: quoteHorizon,
559
405
  });
560
406
  }
561
- const { position: positionAfterRepay } = positionData.repay(repayAssets, repayShares, accrualTimestamp);
562
- validatePositionHealthAfterWithdraw({
563
- positionData: positionAfterRepay,
564
- withdrawAmount,
565
- lltv: this.marketParams.lltv,
566
- marketId: this.marketParams.id,
567
- });
568
- const maxSharePrice = computeMaxRepaySharePrice({
569
- repayAssets,
570
- repayShares,
571
- market: marketForRepay,
572
- slippageTolerance,
407
+ const accrualTimestamp = repayShares > 0n ? deadline : quoteHorizon;
408
+ const accruedPosition = positionData.accrueInterest(accrualTimestamp);
409
+ const expectedRepayAssets = repayAssets > 0n
410
+ ? repayAssets
411
+ : hasRepay
412
+ ? accruedPosition.market.toBorrowAssets(simulatedRepayShares, "Up")
413
+ : 0n;
414
+ const referralFeeAssets = getBlueBundlesV1ReferralFeeAssets(expectedRepayAssets, referralFeePct);
415
+ const maxRepayAssets = expectedRepayAssets + referralFeeAssets;
416
+ const nativeValue = validateBlueBundlesV1NativeFunding({
417
+ chainId: this.chainId,
418
+ token: this.marketParams.loanToken,
419
+ fundedAmount: maxRepayAssets,
420
+ nativeAmount,
573
421
  });
422
+ if (collateralAssets > 0n) {
423
+ const postRepayPosition = hasRepay
424
+ ? accruedPosition.repay(repayAssets, simulatedRepayShares).position
425
+ : accruedPosition;
426
+ validatePositionHealthAfterWithdraw({
427
+ positionData: postRepayPosition,
428
+ withdrawAmount: collateralAssets,
429
+ lltv: this.marketParams.lltv,
430
+ marketId: this.marketParams.id,
431
+ });
432
+ }
574
433
  return {
575
- getRequirements: async (reqParams) => {
576
- const [erc20Requirements, authTx] = await Promise.all([
577
- // Fully native repay pulls no ERC-20, so it needs no approval/permit.
578
- erc20Amount === 0n
579
- ? Promise.resolve([])
580
- : getGeneralAdapterRequirements(this.client.viemClient, {
581
- address: this.marketParams.loanToken,
582
- chainId: this.chainId,
583
- supportSignature: this.client.options.supportSignature,
584
- supportDeployless: this.client.options.supportDeployless,
585
- useSimplePermit: reqParams?.useSimplePermit,
586
- args: { amount: erc20Amount, from: userAddress },
587
- }),
588
- getBlueAuthorizationRequirement({
589
- viemClient: this.client.viemClient,
590
- chainId: this.chainId,
591
- userAddress,
592
- supportSignature: this.client.options.supportSignature,
593
- }),
434
+ getRequirements: async (requirementsParams) => {
435
+ this.validateDeadline(deadline);
436
+ const [tokenRequirements, authorizationRequirements] = await Promise.all([
437
+ hasRepay && nativeValue === 0n
438
+ ? this.getTokenRequirements({
439
+ token: this.marketParams.loanToken,
440
+ amount: maxRepayAssets,
441
+ // A caller-requested reusable approval wins; a full repay otherwise defaults to
442
+ // the token's reusable cap. Checksum the key so a differently-cased loan token
443
+ // (common from subgraphs/APIs) resolves that cap instead of falling back to
444
+ // maxUint256, which UNI/ONDO/COMP/FLUID reject.
445
+ approvalAmount: requirementsParams?.approvalAmount ??
446
+ (saturatedRepay
447
+ ? (MAX_TOKEN_APPROVALS[this.chainId]?.[getAddress(this.marketParams.loanToken)] ?? maxUint256)
448
+ : undefined),
449
+ userAddress,
450
+ deadline,
451
+ useSimplePermit: requirementsParams?.useSimplePermit,
452
+ permit2Nonce: requirementsParams?.permit2Nonce,
453
+ })
454
+ : Promise.resolve([]),
455
+ collateralAssets > 0n
456
+ ? this.getAuthorizationRequirements({ userAddress, deadline })
457
+ : Promise.resolve([]),
594
458
  ]);
595
- return [...erc20Requirements, ...(authTx ? [authTx] : [])];
459
+ return [...tokenRequirements, ...authorizationRequirements];
596
460
  },
597
461
  buildTx: (signatures) => {
598
- const { permit, authorization } = selectRequirementSignatures(signatures, { permit: true, authorization: true });
462
+ const { token, authorization } = selectBlueBundlesV1RequirementSignatures(signatures, {
463
+ token: hasRepay && nativeValue === 0n,
464
+ authorization: collateralAssets > 0n,
465
+ });
466
+ const selectedMaxRepayAssets = repayShares > 0n && token != null
467
+ ? token.args.amount
468
+ : maxRepayAssets;
469
+ if (selectedMaxRepayAssets < maxRepayAssets) {
470
+ throw new MaxRepayAssetsBelowRepayAssetsError(selectedMaxRepayAssets, maxRepayAssets);
471
+ }
599
472
  return blueRepayWithdrawCollateral({
600
- market: {
601
- chainId: this.chainId,
602
- marketParams: this.marketParams,
473
+ market: { chainId: this.chainId, marketParams: this.marketParams },
474
+ args: {
475
+ userAddress,
476
+ repayAssets,
477
+ repayShares,
478
+ maxRepayAssets: selectedMaxRepayAssets,
479
+ collateralAssets,
480
+ maxLtv: collateralAssets > 0n ? this.getMaxLtv() : maxUint256,
481
+ nativeAmount: nativeValue > 0n ? nativeValue : undefined,
482
+ deadline,
483
+ referralFeePct,
484
+ referralFeeRecipient,
485
+ requirementSignature: token,
486
+ authorizationSignature: authorization,
603
487
  },
604
- // Shares mode: repay `shares`, ERC-20 to pull = `erc20Amount`.
605
- // Assets mode: repay `repayAssets` (= amount + native), pull `erc20Amount`.
606
- args: repayShares > 0n
607
- ? {
608
- shares: repayShares,
609
- transferAmount: erc20Amount,
610
- nativeAmount,
611
- withdrawAmount,
612
- onBehalf: userAddress,
613
- receiver: userAddress,
614
- maxSharePrice,
615
- requirementSignature: permit,
616
- authorizationSignature: authorization,
617
- }
618
- : {
619
- amount: erc20Amount,
620
- transferAmount: repayAssets,
621
- nativeAmount,
622
- withdrawAmount,
623
- onBehalf: userAddress,
624
- receiver: userAddress,
625
- maxSharePrice,
626
- requirementSignature: permit,
627
- authorizationSignature: authorization,
628
- },
629
488
  metadata: this.client.options.metadata,
630
489
  });
631
490
  },
632
491
  };
633
492
  }
634
- supplyCollateralBorrow({ amount = 0n, userAddress, positionData, borrowAmount, nativeAmount, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, reallocations, }) {
635
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
636
- const reallocationPlan = validateAndNormalizeReallocations({
637
- reallocations,
638
- targetMarketId: this.marketParams.id,
639
- chainId: this.chainId,
640
- });
641
- const reallocationList = reallocationPlan.reallocations;
642
- if (amount < 0n) {
643
- throw new NegativeInputError("amount", amount);
644
- }
645
- if (nativeAmount !== undefined && nativeAmount < 0n) {
646
- throw new NegativeInputError("nativeAmount", nativeAmount);
647
- }
648
- if (borrowAmount <= 0n) {
649
- throw new NonPositiveInputError("borrowAmount", borrowAmount);
650
- }
651
- const totalCollateral = amount + (nativeAmount ?? 0n);
652
- if (totalCollateral === 0n) {
653
- throw new NonPositiveInputError("totalCollateral", totalCollateral);
654
- }
655
- validateSlippageTolerance(slippageTolerance);
656
- if (!positionData) {
657
- throw new MissingAccrualPositionError(this.marketParams.id);
493
+ /** {@inheritDoc BlueActions.supplyCollateralBorrow} */
494
+ supplyCollateralBorrow(params) {
495
+ const { userAddress, collateralAssets, borrowAssets, positionData, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
496
+ this.validateWriteCommon(params);
497
+ if (collateralAssets < 0n) {
498
+ throw new NegativeInputError("collateralAssets", collateralAssets);
499
+ }
500
+ if (borrowAssets < 0n) {
501
+ throw new NegativeInputError("borrowAssets", borrowAssets);
502
+ }
503
+ if (collateralAssets === 0n && borrowAssets === 0n) {
504
+ throw new NonPositiveInputError("collateralAssets or borrowAssets", 0n);
505
+ }
506
+ const reallocations = [...(params.reallocations ?? [])];
507
+ if (borrowAssets === 0n && reallocations.length > 0) {
508
+ throw new ReallocationsRequireBorrowError();
509
+ }
510
+ // Validate the exact PublicAllocations mapping before requirement reads.
511
+ const publicAllocations = getBlueBundlesV1PublicAllocations(reallocations, this.marketParams);
512
+ const reallocationPenaltyAssets = getBlueBundlesV1PenaltyAssets(publicAllocations);
513
+ if (reallocationPenaltyAssets > borrowAssets) {
514
+ throw new InputExceedsMaxError({
515
+ field: "reallocationPenaltyAssets",
516
+ value: reallocationPenaltyAssets,
517
+ max: borrowAssets,
518
+ });
658
519
  }
659
- validateAccrualPosition({
660
- positionData,
661
- expectedMarketId: this.marketParams.id,
662
- expectedUser: userAddress,
663
- });
664
- if (nativeAmount !== undefined && nativeAmount > 0n) {
665
- validateNativeAsset(this.chainId, this.marketParams.collateralToken);
520
+ if (borrowAssets > 0n) {
521
+ if (positionData == null) {
522
+ throw new MissingAccrualPositionError(this.marketParams.id);
523
+ }
524
+ validateAccrualPosition({
525
+ positionData,
526
+ expectedMarketId: this.marketParams.id,
527
+ expectedUser: userAddress,
528
+ });
529
+ validatePositionHealth({
530
+ positionData: positionData.accrueInterest(this.getBlueBundlesV1QuoteTimestamp(positionData.market.lastUpdate)),
531
+ additionalCollateral: collateralAssets,
532
+ borrowAmount: borrowAssets,
533
+ marketId: this.marketParams.id,
534
+ lltv: this.marketParams.lltv,
535
+ });
666
536
  }
667
- validatePositionHealth({
668
- positionData,
669
- additionalCollateral: totalCollateral,
670
- borrowAmount,
671
- marketId: this.marketParams.id,
672
- lltv: this.marketParams.lltv,
673
- });
674
- const minSharePrice = computeMinBorrowSharePrice({
675
- borrowAmount,
676
- market: positionData.market,
677
- slippageTolerance,
537
+ const nativeValue = validateBlueBundlesV1NativeFunding({
538
+ chainId: this.chainId,
539
+ token: this.marketParams.collateralToken,
540
+ fundedAmount: collateralAssets,
541
+ nativeAmount,
678
542
  });
679
543
  return {
680
- getRequirements: async (params) => {
681
- const penaltyAssets = reallocationPlan.type === "vaultV2Blue"
682
- ? reallocationPlan.reallocations.reduce((total, reallocation) => total +
683
- VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets), 0n)
684
- : 0n;
685
- const usesSharedFundingToken = isAddressEqual(this.marketParams.collateralToken, this.marketParams.loanToken);
686
- const [erc20Requirements, penaltyRequirements, authTx] = await Promise.all([
687
- getGeneralAdapterRequirements(this.client.viemClient, {
688
- address: this.marketParams.collateralToken,
689
- chainId: this.chainId,
690
- supportSignature: this.client.options.supportSignature,
691
- supportDeployless: this.client.options.supportDeployless,
692
- useSimplePermit: params?.useSimplePermit,
693
- args: {
694
- amount: amount + (usesSharedFundingToken ? penaltyAssets : 0n),
695
- from: userAddress,
696
- },
697
- }),
698
- usesSharedFundingToken
699
- ? []
700
- : this.getReallocationPenaltyRequirements(userAddress, reallocationPlan),
701
- getBlueAuthorizationRequirement({
702
- viemClient: this.client.viemClient,
703
- chainId: this.chainId,
704
- userAddress,
705
- supportSignature: this.client.options.supportSignature,
706
- }),
544
+ getRequirements: async (requirementsParams) => {
545
+ this.validateDeadline(deadline);
546
+ const [tokenRequirements, authorizationRequirements] = await Promise.all([
547
+ collateralAssets > 0n && nativeValue === 0n
548
+ ? this.getTokenRequirements({
549
+ token: this.marketParams.collateralToken,
550
+ amount: collateralAssets,
551
+ approvalAmount: requirementsParams?.approvalAmount,
552
+ userAddress,
553
+ deadline,
554
+ useSimplePermit: requirementsParams?.useSimplePermit,
555
+ permit2Nonce: requirementsParams?.permit2Nonce,
556
+ })
557
+ : Promise.resolve([]),
558
+ borrowAssets > 0n
559
+ ? this.getAuthorizationRequirements({ userAddress, deadline })
560
+ : Promise.resolve([]),
707
561
  ]);
708
- return [
709
- ...erc20Requirements,
710
- ...penaltyRequirements,
711
- ...(authTx ? [authTx] : []),
712
- ];
562
+ return [...tokenRequirements, ...authorizationRequirements];
713
563
  },
714
564
  buildTx: (signatures) => {
715
- const { permit, authorization } = selectRequirementSignatures(signatures, { permit: true, authorization: true });
565
+ const { token, authorization } = selectBlueBundlesV1RequirementSignatures(signatures, {
566
+ token: collateralAssets > 0n && nativeValue === 0n,
567
+ authorization: borrowAssets > 0n,
568
+ });
716
569
  return blueSupplyCollateralBorrow({
717
- market: {
718
- chainId: this.chainId,
719
- marketParams: this.marketParams,
720
- },
570
+ market: { chainId: this.chainId, marketParams: this.marketParams },
721
571
  args: {
722
- amount,
723
- nativeAmount,
724
- borrowAmount,
725
- onBehalf: userAddress,
726
- receiver: userAddress,
727
- minSharePrice,
728
- requirementSignature: permit,
572
+ userAddress,
573
+ collateralAssets,
574
+ borrowAssets,
575
+ maxLtv: borrowAssets > 0n ? this.getMaxLtv() : maxUint256,
576
+ nativeAmount: nativeValue > 0n ? nativeValue : undefined,
577
+ reallocations,
578
+ deadline,
579
+ referralFeePct,
580
+ referralFeeRecipient,
581
+ requirementSignature: token,
729
582
  authorizationSignature: authorization,
730
- reallocations: reallocationList,
731
583
  },
732
584
  metadata: this.client.options.metadata,
733
585
  });
734
586
  },
735
587
  };
736
588
  }
737
- refinance({ userAddress, positionData, target, collateralAmount, borrowAssets, borrowShares, slippageTolerance = DEFAULT_SLIPPAGE_TOLERANCE, targetReallocations, }) {
738
- validateChainId(this.client.viemClient.chain?.id, this.chainId);
739
- validateSlippageTolerance(slippageTolerance);
740
- const targetReallocationPlan = validateAndNormalizeReallocations({
741
- reallocations: targetReallocations,
742
- targetMarketId: target.marketParams.id,
743
- chainId: this.chainId,
744
- });
745
- const targetReallocationList = targetReallocationPlan.reallocations;
746
- if (collateralAmount <= 0n) {
747
- throw new NonPositiveInputError("collateralAmount", collateralAmount);
748
- }
749
- const requestedAssets = borrowAssets ?? 0n;
750
- const requestedShares = borrowShares ?? 0n;
751
- if (requestedAssets < 0n) {
752
- throw new NegativeInputError("borrowAssets", requestedAssets);
753
- }
754
- if (requestedShares < 0n) {
755
- throw new NegativeInputError("borrowShares", requestedShares);
756
- }
757
- if (requestedAssets > 0n && requestedShares > 0n) {
758
- throw new BorrowAmountAndSharesExclusiveError(this.marketParams.id);
759
- }
760
- if (!positionData) {
589
+ /** {@inheritDoc BlueActions.refinance} */
590
+ refinance(params) {
591
+ const { userAddress, positionData, destination, deadline, referralFeeRecipient, } = params;
592
+ this.validateWriteCommon(params);
593
+ // `validateWriteCommon` returns void, so default an omitted `referralFeePct` to `0n`
594
+ // here, matching the pure action's normalization.
595
+ const referralFeePct = params.referralFeePct ?? 0n;
596
+ if (positionData == null) {
761
597
  throw new MissingAccrualPositionError(this.marketParams.id);
762
598
  }
763
599
  validateAccrualPosition({
@@ -765,140 +601,57 @@ export class MorphoBlue {
765
601
  expectedMarketId: this.marketParams.id,
766
602
  expectedUser: userAddress,
767
603
  });
768
- if (this.marketParams.id === target.marketParams.id) {
604
+ if (positionData.borrowShares <= 0n) {
605
+ throw new NonPositiveInputError("positionData.borrowShares", positionData.borrowShares);
606
+ }
607
+ if (this.marketParams.id === destination.marketParams.id) {
769
608
  throw new RefinanceSameMarketError(this.marketParams.id);
770
609
  }
771
- if (!isAddressEqual(this.marketParams.collateralToken, target.marketParams.collateralToken) ||
772
- !isAddressEqual(this.marketParams.loanToken, target.marketParams.loanToken)) {
773
- throw new RefinanceTokenMismatchError(this.marketParams.id, target.marketParams.id);
610
+ if (!isAddressEqual(this.marketParams.loanToken, destination.marketParams.loanToken) ||
611
+ !isAddressEqual(this.marketParams.collateralToken, destination.marketParams.collateralToken)) {
612
+ throw new RefinanceTokenMismatchError(this.marketParams.id, destination.marketParams.id);
613
+ }
614
+ if (destination.positionData == null) {
615
+ throw new MissingAccrualPositionError(destination.marketParams.id);
774
616
  }
775
617
  validateAccrualPosition({
776
- positionData: target.positionData,
777
- expectedMarketId: target.marketParams.id,
618
+ positionData: destination.positionData,
619
+ expectedMarketId: destination.marketParams.id,
778
620
  expectedUser: userAddress,
779
621
  });
780
- const sharesMode = requestedShares > 0n;
781
- const shouldMigrateBorrow = requestedAssets > 0n || sharesMode;
782
- if (collateralAmount > positionData.collateral) {
783
- throw new RefinanceExceedsCollateralError({
784
- market: this.marketParams.id,
785
- requested: collateralAmount,
786
- available: positionData.collateral,
787
- });
788
- }
789
- if (requestedShares > positionData.borrowShares) {
790
- throw new RefinanceExceedsBorrowSharesError({
791
- market: this.marketParams.id,
792
- requested: requestedShares,
793
- available: positionData.borrowShares,
794
- });
795
- }
796
- if (requestedAssets > positionData.borrowAssets) {
797
- throw new RefinanceExceedsBorrowAssetsError({
798
- market: this.marketParams.id,
799
- requested: requestedAssets,
800
- available: positionData.borrowAssets,
801
- });
802
- }
803
- // Forward-accrue both markets to now (clamped to lastUpdate). Source gets a 2h buffer in
804
- // shares mode (as in repay()) for repay headroom; target accrues without buffer to avoid
805
- // tightening minBorrowSharePrice past on-chain reality.
806
- const sourceAccrualTimestamp = MathLib.max(Time.timestamp(), positionData.market.lastUpdate) +
807
- (sharesMode ? Time.s.from.h(2n) : 0n);
808
- const targetAccrualTimestamp = MathLib.max(Time.timestamp(), target.positionData.market.lastUpdate);
809
- const accruedSource = positionData.market.accrueInterest(sourceAccrualTimestamp);
810
- const accruedTarget = target.positionData.market.accrueInterest(targetAccrualTimestamp);
811
- // Shares burned by the source repay: exact in shares mode, else mirror Morpho's toSharesDown.
812
- const repaidShares = sharesMode
813
- ? requestedShares
814
- : accruedSource.toBorrowShares(requestedAssets, "Down");
815
- // Post-state source health: any remaining debt must stay healthy (accrued market).
816
- const remainingCollateral = positionData.collateral - collateralAmount;
817
- const remainingShares = positionData.borrowShares - repaidShares;
818
- if (remainingShares > 0n) {
819
- const residualPosition = new AccrualPosition({
820
- user: positionData.user,
821
- supplyShares: positionData.supplyShares,
822
- borrowShares: remainingShares,
823
- collateral: remainingCollateral,
824
- }, accruedSource);
825
- validatePositionHealth({
826
- positionData: residualPosition,
827
- additionalCollateral: 0n,
828
- borrowAmount: 0n,
829
- marketId: this.marketParams.id,
830
- lltv: this.marketParams.lltv,
831
- });
832
- }
833
- const projectedBorrowAssets = sharesMode
834
- ? accruedSource.toBorrowAssets(requestedShares, "Up")
835
- : requestedAssets;
836
- // Shares-mode overshoot covers target drift + accrual on the borrow leg. Computed before the
837
- // LLTV check so health validates the actual on-chain borrow, not the smaller projected value.
838
- const borrowAssetsAdjusted = sharesMode
839
- ? MathLib.wMulUp(projectedBorrowAssets, MathLib.WAD + slippageTolerance)
840
- : projectedBorrowAssets;
841
- // Post-state target health: aggregate must respect LLTV − buffer. Skipped for collat-only
842
- // refinances, which can't degrade target health and would fail on missing-oracle markets.
843
- if (shouldMigrateBorrow) {
844
- const accruedTargetPosition = target.positionData.accrueInterest(targetAccrualTimestamp);
845
- validatePositionHealth({
846
- positionData: accruedTargetPosition,
847
- additionalCollateral: collateralAmount,
848
- borrowAmount: borrowAssetsAdjusted,
849
- marketId: target.marketParams.id,
850
- lltv: target.marketParams.lltv,
851
- });
852
- }
853
- // Share-price bounds only when a debt leg exists (helpers throw on zero inputs); else 0n.
854
- // Derived from borrowAssetsAdjusted (the encoded value) so rounding can't push the on-chain
855
- // ratio below a guard computed from the smaller projected amount.
856
- const minBorrowSharePrice = shouldMigrateBorrow
857
- ? computeMinBorrowSharePrice({
858
- borrowAmount: borrowAssetsAdjusted,
859
- market: accruedTarget,
860
- slippageTolerance,
861
- })
862
- : 0n;
863
- const maxRepaySharePrice = shouldMigrateBorrow
864
- ? computeMaxRepaySharePrice({
865
- repayAssets: requestedAssets,
866
- repayShares: requestedShares,
867
- market: accruedSource,
868
- slippageTolerance,
869
- })
870
- : 0n;
622
+ const reallocations = [...(params.reallocations ?? [])];
623
+ const publicAllocations = getBlueBundlesV1PublicAllocations(reallocations, destination.marketParams);
624
+ const penaltyAssets = getBlueBundlesV1PenaltyAssets(publicAllocations);
625
+ const accrualTimestamp = this.getBlueBundlesV1QuoteTimestamp(MathLib.max(positionData.market.lastUpdate, destination.positionData.market.lastUpdate));
626
+ const accruedSourcePosition = positionData.accrueInterest(accrualTimestamp);
627
+ const accruedDestinationPosition = destination.positionData.accrueInterest(accrualTimestamp);
628
+ const referralFeeAssets = getBlueBundlesV1ReferralFeeAssets(accruedSourcePosition.borrowAssets, referralFeePct);
629
+ validatePositionHealth({
630
+ positionData: accruedDestinationPosition,
631
+ additionalCollateral: accruedSourcePosition.collateral,
632
+ borrowAmount: accruedSourcePosition.borrowAssets + penaltyAssets + referralFeeAssets,
633
+ marketId: destination.marketParams.id,
634
+ lltv: destination.marketParams.lltv,
635
+ });
871
636
  return {
872
- getRequirements: async () => {
873
- const [penaltyRequirements, authTx] = await Promise.all([
874
- this.getReallocationPenaltyRequirements(userAddress, targetReallocationPlan),
875
- getBlueAuthorizationRequirement({
876
- viemClient: this.client.viemClient,
877
- chainId: this.chainId,
878
- userAddress,
879
- supportSignature: this.client.options.supportSignature,
880
- }),
881
- ]);
882
- return [...penaltyRequirements, ...(authTx ? [authTx] : [])];
883
- },
637
+ getRequirements: () => this.getAuthorizationRequirements({ userAddress, deadline }),
884
638
  buildTx: (signatures) => {
885
- const { authorization } = selectRequirementSignatures(signatures, {
639
+ const { authorization } = selectBlueBundlesV1RequirementSignatures(signatures, {
886
640
  authorization: true,
887
641
  });
888
642
  return blueRefinance({
889
- source: {
643
+ market: {
890
644
  chainId: this.chainId,
891
- marketParams: this.marketParams,
645
+ sourceMarketParams: this.marketParams,
646
+ destinationMarketParams: destination.marketParams,
892
647
  },
893
- target: { marketParams: target.marketParams },
894
648
  args: {
895
- user: userAddress,
896
- collateralAmount,
897
- borrowAssets: borrowAssetsAdjusted,
898
- borrowShares: requestedShares,
899
- minBorrowSharePrice,
900
- maxRepaySharePrice,
901
- targetReallocations: targetReallocationList,
649
+ userAddress,
650
+ maxLtv: this.getMaxLtv(destination.marketParams),
651
+ reallocations,
652
+ deadline,
653
+ referralFeePct,
654
+ referralFeeRecipient,
902
655
  authorizationSignature: authorization,
903
656
  },
904
657
  metadata: this.client.options.metadata,
@@ -1110,7 +863,7 @@ export class MorphoBlue {
1110
863
  * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
1111
864
  * @param params.borrowAmount - {@deprecated Pass `{ operation: "borrow", amount }` instead.}
1112
865
  * @param params.options - Optional allocator and utilization options.
1113
- * @returns Vault reallocations ready to pass to `borrow`, `supplyCollateralBorrow`, or `withdraw`.
866
+ * @returns Vault V1 reallocations for explicit low-level Bundler3 composition.
1114
867
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to a different chain than this market.
1115
868
  * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market.
1116
869
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets`.
@@ -1156,7 +909,7 @@ export class MorphoBlue {
1156
909
  * @param params.amount - The borrow or withdraw amount used to compute post-state utilization.
1157
910
  * @param params.borrowAmount - Deprecated borrow amount alias.
1158
911
  * @param params.options - Optional allocator and utilization options.
1159
- * @returns Vault V1 reallocations ready for a Blue action.
912
+ * @returns Vault V1 reallocations for explicit low-level Bundler3 composition.
1160
913
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
1161
914
  * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation.
1162
915
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.