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