@morpho-org/morpho-sdk 5.8.0 → 6.0.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/MIGRATION-v5-to-v6.md +201 -0
  2. package/README.md +62 -40
  3. package/lib/cjs/abis.d.ts +543 -0
  4. package/lib/cjs/abis.js +738 -0
  5. package/lib/cjs/actions/blue/borrow.d.ts +62 -58
  6. package/lib/cjs/actions/blue/borrow.js +48 -80
  7. package/lib/cjs/actions/blue/common.d.ts +99 -0
  8. package/lib/cjs/actions/blue/common.js +318 -0
  9. package/lib/cjs/actions/blue/refinance.d.ts +72 -107
  10. package/lib/cjs/actions/blue/refinance.js +97 -197
  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 -86
  20. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +133 -119
  21. package/lib/cjs/actions/blue/withdraw.d.ts +68 -78
  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/index.d.ts +1 -1
  26. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  27. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +60 -19
  28. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  29. package/lib/cjs/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +207 -0
  30. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  31. package/lib/cjs/actions/requirements/blue/getUnusedPermit2Nonce.js +72 -0
  32. package/lib/cjs/actions/requirements/blue/index.d.ts +2 -0
  33. package/lib/cjs/actions/requirements/blue/index.js +2 -0
  34. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  35. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +30 -5
  36. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  37. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +7 -2
  38. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  39. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +33 -6
  40. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  41. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +123 -0
  42. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  43. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  44. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  45. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +5 -4
  46. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -4
  47. package/lib/cjs/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  48. package/lib/cjs/actions/signatures/getTokenRequirementActions.js +4 -0
  49. package/lib/cjs/blue/types.d.ts +3 -1
  50. package/lib/cjs/blue/utils.d.ts +3 -1
  51. package/lib/cjs/blue/utils.js +1 -0
  52. package/lib/cjs/bundler/actions.d.ts +6 -4
  53. package/lib/cjs/bundler/actions.js +6 -4
  54. package/lib/cjs/bundler/types.d.ts +10 -1
  55. package/lib/cjs/client/morphoViemExtension.d.ts +2 -1
  56. package/lib/cjs/client/morphoViemExtension.js +2 -1
  57. package/lib/cjs/entities/blue/blue.d.ts +817 -360
  58. package/lib/cjs/entities/blue/blue.js +455 -698
  59. package/lib/cjs/entities/index.d.ts +1 -0
  60. package/lib/cjs/entities/vaultV1/vaultV1.js +4 -12
  61. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +18 -3
  62. package/lib/cjs/entities/vaultV1ReallocationData.js +11 -1
  63. package/lib/cjs/entities/vaultV2/vaultV2.js +6 -18
  64. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +7 -10
  65. package/lib/cjs/helpers/computeVaultV1Reallocations.js +7 -10
  66. package/lib/cjs/helpers/validate.d.ts +16 -23
  67. package/lib/cjs/helpers/validate.js +32 -48
  68. package/lib/cjs/helpers/validateRequirementSpender.d.ts +2 -1
  69. package/lib/cjs/helpers/validateRequirementSpender.js +2 -0
  70. package/lib/cjs/types/action.d.ts +146 -162
  71. package/lib/cjs/types/action.js +29 -2
  72. package/lib/cjs/types/client.d.ts +9 -0
  73. package/lib/cjs/types/error.d.ts +173 -18
  74. package/lib/cjs/types/error.js +230 -25
  75. package/lib/cjs/types/sharedLiquidity.d.ts +20 -4
  76. package/lib/cjs/types.d.ts +3 -1
  77. package/lib/cjs/utils.d.ts +3 -1
  78. package/lib/cjs/utils.js +1 -0
  79. package/lib/esm/abis.d.ts +543 -0
  80. package/lib/esm/abis.js +737 -0
  81. package/lib/esm/actions/blue/borrow.d.ts +62 -58
  82. package/lib/esm/actions/blue/borrow.js +48 -80
  83. package/lib/esm/actions/blue/common.d.ts +99 -0
  84. package/lib/esm/actions/blue/common.js +306 -0
  85. package/lib/esm/actions/blue/refinance.d.ts +72 -107
  86. package/lib/esm/actions/blue/refinance.js +98 -198
  87. package/lib/esm/actions/blue/repay.d.ts +72 -68
  88. package/lib/esm/actions/blue/repay.js +56 -118
  89. package/lib/esm/actions/blue/repayWithdrawCollateral.d.ts +85 -90
  90. package/lib/esm/actions/blue/repayWithdrawCollateral.js +149 -138
  91. package/lib/esm/actions/blue/supply.d.ts +62 -45
  92. package/lib/esm/actions/blue/supply.js +94 -70
  93. package/lib/esm/actions/blue/supplyCollateral.d.ts +63 -40
  94. package/lib/esm/actions/blue/supplyCollateral.js +52 -69
  95. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +82 -86
  96. package/lib/esm/actions/blue/supplyCollateralBorrow.js +134 -120
  97. package/lib/esm/actions/blue/withdraw.d.ts +68 -78
  98. package/lib/esm/actions/blue/withdraw.js +100 -96
  99. package/lib/esm/actions/blue/withdrawCollateral.d.ts +56 -28
  100. package/lib/esm/actions/blue/withdrawCollateral.js +45 -50
  101. package/lib/esm/actions/index.d.ts +1 -1
  102. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +29 -17
  103. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +63 -22
  104. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.d.ts +80 -0
  105. package/lib/esm/actions/requirements/blue/getBlueBundlesV1TokenRequirements.js +203 -0
  106. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.d.ts +48 -0
  107. package/lib/esm/actions/requirements/blue/getUnusedPermit2Nonce.js +68 -0
  108. package/lib/esm/actions/requirements/blue/index.d.ts +2 -0
  109. package/lib/esm/actions/requirements/blue/index.js +2 -0
  110. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +10 -7
  111. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +31 -6
  112. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  113. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +8 -3
  114. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  115. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +34 -7
  116. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.d.ts +61 -0
  117. package/lib/esm/actions/requirements/encode/encodeErc20Permit2TransferFrom.js +119 -0
  118. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  119. package/lib/esm/actions/requirements/encode/index.js +1 -0
  120. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +1 -1
  121. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +5 -4
  122. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -4
  123. package/lib/esm/actions/signatures/getTokenRequirementActions.d.ts +1 -0
  124. package/lib/esm/actions/signatures/getTokenRequirementActions.js +5 -1
  125. package/lib/esm/blue/types.d.ts +3 -1
  126. package/lib/esm/blue/utils.d.ts +3 -1
  127. package/lib/esm/blue/utils.js +3 -1
  128. package/lib/esm/bundler/actions.d.ts +6 -4
  129. package/lib/esm/bundler/actions.js +6 -4
  130. package/lib/esm/bundler/types.d.ts +10 -1
  131. package/lib/esm/client/morphoViemExtension.d.ts +2 -1
  132. package/lib/esm/client/morphoViemExtension.js +2 -1
  133. package/lib/esm/entities/blue/blue.d.ts +817 -360
  134. package/lib/esm/entities/blue/blue.js +461 -704
  135. package/lib/esm/entities/index.d.ts +1 -0
  136. package/lib/esm/entities/vaultV1/vaultV1.js +4 -12
  137. package/lib/esm/entities/vaultV1ReallocationData.d.ts +18 -3
  138. package/lib/esm/entities/vaultV1ReallocationData.js +13 -2
  139. package/lib/esm/entities/vaultV2/vaultV2.js +7 -19
  140. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +7 -10
  141. package/lib/esm/helpers/computeVaultV1Reallocations.js +7 -10
  142. package/lib/esm/helpers/validate.d.ts +16 -23
  143. package/lib/esm/helpers/validate.js +32 -48
  144. package/lib/esm/helpers/validateRequirementSpender.d.ts +2 -1
  145. package/lib/esm/helpers/validateRequirementSpender.js +2 -0
  146. package/lib/esm/types/action.d.ts +146 -162
  147. package/lib/esm/types/action.js +28 -2
  148. package/lib/esm/types/client.d.ts +9 -0
  149. package/lib/esm/types/error.d.ts +173 -18
  150. package/lib/esm/types/error.js +216 -21
  151. package/lib/esm/types/sharedLiquidity.d.ts +20 -4
  152. package/lib/esm/types.d.ts +3 -1
  153. package/lib/esm/utils.d.ts +3 -1
  154. package/lib/esm/utils.js +3 -1
  155. package/package.json +7 -6
  156. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +0 -47
  157. package/lib/cjs/actions/blue/buildAssetFundingActions.js +0 -63
  158. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +0 -69
  159. package/lib/cjs/actions/blue/buildReallocationActions.js +0 -141
  160. package/lib/cjs/actions/blue/resolveRepayFunding.d.ts +0 -66
  161. package/lib/cjs/actions/blue/resolveRepayFunding.js +0 -85
  162. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +0 -47
  163. package/lib/esm/actions/blue/buildAssetFundingActions.js +0 -59
  164. package/lib/esm/actions/blue/buildReallocationActions.d.ts +0 -69
  165. package/lib/esm/actions/blue/buildReallocationActions.js +0 -135
  166. package/lib/esm/actions/blue/resolveRepayFunding.d.ts +0 -66
  167. package/lib/esm/actions/blue/resolveRepayFunding.js +0 -81
@@ -5,9 +5,9 @@ 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
12
  const vaultV1ReallocationData_js_1 = require("../vaultV1ReallocationData.js");
13
13
  const vaultV2BlueReallocationData_js_1 = require("../vaultV2BlueReallocationData.js");
@@ -21,22 +21,60 @@ class MorphoBlue {
21
21
  this.marketParams = marketParams;
22
22
  this.chainId = chainId;
23
23
  }
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,
24
+ validateDeadline(deadline) {
25
+ const timestamp = morpho_ts_1.Time.timestamp();
26
+ if (deadline <= timestamp) {
27
+ throw new index_js_3.ExpiredDeadlineError(deadline, timestamp);
28
+ }
29
+ }
30
+ validateWriteCommon(params) {
31
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
32
+ this.validateDeadline(params.deadline);
33
+ // Resolve at handle creation so unsupported deployments fail before any RPC prerequisite work.
34
+ (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.blueBundlesV1");
35
+ // Validate the referral inputs eagerly; the normalized result is intentionally discarded here
36
+ // because the pure action re-normalizes it at encode time.
37
+ (0, common_js_1.normalizeBlueBundlesV1CommonParams)({
35
38
  chainId: this.chainId,
36
- supportSignature: false,
37
- args: { amount, from: userAddress },
39
+ userAddress: params.userAddress,
40
+ deadline: params.deadline,
41
+ referralFeePct: params.referralFeePct,
42
+ referralFeeRecipient: params.referralFeeRecipient,
38
43
  });
39
44
  }
45
+ getMaxLtv(marketParams = this.marketParams) {
46
+ return blue_sdk_1.MathLib.zeroFloorSub(marketParams.lltv, index_js_2.DEFAULT_LLTV_BUFFER);
47
+ }
48
+ getBlueBundlesV1QuoteTimestamp(lastUpdate) {
49
+ return blue_sdk_1.MathLib.max(morpho_ts_1.Time.timestamp(), lastUpdate) + morpho_ts_1.Time.s.from.h(2n);
50
+ }
51
+ async getTokenRequirements(params) {
52
+ this.validateDeadline(params.deadline);
53
+ return (0, index_js_1.getBlueBundlesV1TokenRequirements)(this.client.viemClient, {
54
+ token: params.token,
55
+ amount: params.amount,
56
+ owner: params.userAddress,
57
+ chainId: this.chainId,
58
+ deadline: params.deadline,
59
+ supportSignature: this.client.options.supportSignature,
60
+ supportDeployless: this.client.options.supportDeployless,
61
+ useSimplePermit: params.useSimplePermit,
62
+ permit2Nonce: params.permit2Nonce,
63
+ approvalAmount: params.approvalAmount,
64
+ });
65
+ }
66
+ async getAuthorizationRequirements(params) {
67
+ this.validateDeadline(params.deadline);
68
+ const requirement = await (0, index_js_1.getBlueAuthorizationRequirement)({
69
+ viemClient: this.client.viemClient,
70
+ chainId: this.chainId,
71
+ userAddress: params.userAddress,
72
+ supportSignature: this.client.options.supportSignature,
73
+ authorized: (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.blueBundlesV1"),
74
+ deadline: params.deadline,
75
+ });
76
+ return requirement == null ? [] : [requirement];
77
+ }
40
78
  async getMarketData(parameters) {
41
79
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
42
80
  return (0, blue_sdk_viem_1.fetchMarket)(this.marketParams.id, this.client.viemClient, {
@@ -53,91 +91,70 @@ class MorphoBlue {
53
91
  chainId: this.chainId,
54
92
  });
55
93
  }
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,
94
+ /** {@inheritDoc BlueActions.supply} */
95
+ supply(params) {
96
+ const { userAddress, assets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
97
+ this.validateWriteCommon(params);
98
+ if (assets <= 0n)
99
+ throw new index_js_3.NonPositiveInputError("assets", assets);
100
+ const nativeValue = (0, common_js_1.validateBlueBundlesV1NativeFunding)({
101
+ chainId: this.chainId,
102
+ token: this.marketParams.loanToken,
103
+ fundedAmount: assets,
104
+ nativeAmount,
82
105
  });
83
106
  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
- }),
107
+ getRequirements: (requirementsParams) => {
108
+ this.validateDeadline(deadline);
109
+ if (nativeValue > 0n)
110
+ return Promise.resolve([]);
111
+ return this.getTokenRequirements({
112
+ token: this.marketParams.loanToken,
113
+ amount: assets,
114
+ userAddress,
115
+ deadline,
116
+ useSimplePermit: requirementsParams?.useSimplePermit,
117
+ permit2Nonce: requirementsParams?.permit2Nonce,
118
+ approvalAmount: requirementsParams?.approvalAmount,
119
+ });
120
+ },
92
121
  buildTx: (signatures) => {
93
- const { permit } = (0, index_js_3.selectRequirementSignatures)(signatures, {
94
- permit: true,
122
+ const { token } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, {
123
+ token: nativeValue === 0n,
95
124
  });
96
125
  return (0, index_js_1.blueSupply)({
97
126
  market: { chainId: this.chainId, marketParams: this.marketParams },
98
127
  args: {
99
- amount,
100
- nativeAmount,
101
- onBehalf: userAddress,
102
- maxSharePrice,
103
- requirementSignature: permit,
128
+ userAddress,
129
+ assets,
130
+ nativeAmount: nativeValue > 0n ? nativeValue : undefined,
131
+ deadline,
132
+ referralFeePct,
133
+ referralFeeRecipient,
134
+ requirementSignature: token,
104
135
  },
105
136
  metadata: this.client.options.metadata,
106
137
  });
107
138
  },
108
139
  };
109
140
  }
141
+ /** {@inheritDoc BlueActions.withdraw} */
110
142
  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.
143
+ const { userAddress, positionData, deadline, referralFeePct, referralFeeRecipient, } = params;
144
+ this.validateWriteCommon(params);
121
145
  const assets = ("assets" in params ? params.assets : undefined) ?? 0n;
122
146
  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) {
147
+ if (assets < 0n)
131
148
  throw new index_js_3.NegativeInputError("assets", assets);
132
- }
133
- if (shares < 0n) {
149
+ if (shares < 0n)
134
150
  throw new index_js_3.NegativeInputError("shares", shares);
151
+ if (assets > 0n && shares > 0n) {
152
+ throw new index_js_3.MutuallyExclusiveWithdrawAmountsError(this.marketParams.id);
135
153
  }
136
154
  if (assets === 0n && shares === 0n) {
137
155
  throw new index_js_3.NonPositiveInputError("assets or shares", 0n);
138
156
  }
139
- (0, index_js_2.validateSlippageTolerance)(slippageTolerance);
140
- if (!positionData) {
157
+ if (positionData == null) {
141
158
  throw new index_js_3.MissingAccrualPositionError(this.marketParams.id);
142
159
  }
143
160
  (0, index_js_2.validateAccrualPosition)({
@@ -159,37 +176,34 @@ class MorphoBlue {
159
176
  marketId: this.marketParams.id,
160
177
  });
161
178
  }
162
- const minSharePrice = (0, index_js_2.computeMinWithdrawSharePrice)({
163
- withdrawAssets: assets,
164
- withdrawShares: shares,
165
- market: positionData.market,
166
- slippageTolerance,
167
- });
179
+ const reallocations = [...(params.reallocations ?? [])];
180
+ // Validate the exact PublicAllocations mapping before requirement reads.
181
+ const publicAllocations = (0, common_js_1.getBlueBundlesV1PublicAllocations)(reallocations, this.marketParams);
182
+ const reallocationPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(publicAllocations);
183
+ const expectedWithdrawAssets = assets > 0n ? assets : positionData.market.toSupplyAssets(shares, "Down");
184
+ if (reallocationPenaltyAssets > expectedWithdrawAssets) {
185
+ throw new index_js_3.InputExceedsMaxError({
186
+ field: "reallocationPenaltyAssets",
187
+ value: reallocationPenaltyAssets,
188
+ max: expectedWithdrawAssets,
189
+ });
190
+ }
168
191
  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
- },
192
+ getRequirements: () => this.getAuthorizationRequirements({ userAddress, deadline }),
181
193
  buildTx: (signatures) => {
182
- const { authorization } = (0, index_js_3.selectRequirementSignatures)(signatures, {
194
+ const { authorization } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, {
183
195
  authorization: true,
184
196
  });
185
197
  return (0, index_js_1.blueWithdraw)({
186
198
  market: { chainId: this.chainId, marketParams: this.marketParams },
187
199
  args: {
188
- assets,
189
- shares,
190
- receiver,
191
- minSharePrice,
192
- reallocations: reallocationList,
200
+ userAddress,
201
+ withdrawAssets: assets,
202
+ withdrawShares: shares,
203
+ reallocations,
204
+ deadline,
205
+ referralFeePct,
206
+ referralFeeRecipient,
193
207
  authorizationSignature: authorization,
194
208
  },
195
209
  metadata: this.client.options.metadata,
@@ -197,109 +211,68 @@ class MorphoBlue {
197
211
  },
198
212
  };
199
213
  }
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
- }
214
+ /** {@inheritDoc BlueActions.supplyCollateral} */
215
+ supplyCollateral(params) {
216
+ const { userAddress, collateralAssets, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
217
+ const combinedAction = this.supplyCollateralBorrow({
218
+ userAddress,
219
+ collateralAssets,
220
+ borrowAssets: 0n,
221
+ nativeAmount,
222
+ deadline,
223
+ referralFeePct,
224
+ referralFeeRecipient,
225
+ });
215
226
  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
- }),
227
+ getRequirements: combinedAction.getRequirements,
224
228
  buildTx: (signatures) => {
225
- const { permit } = (0, index_js_3.selectRequirementSignatures)(signatures, {
226
- permit: true,
229
+ const { token } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, {
230
+ token: (nativeAmount ?? 0n) === 0n,
227
231
  });
228
232
  return (0, index_js_1.blueSupplyCollateral)({
229
- market: {
230
- chainId: this.chainId,
231
- marketParams: this.marketParams,
232
- },
233
+ market: { chainId: this.chainId, marketParams: this.marketParams },
233
234
  args: {
234
- amount,
235
+ userAddress,
236
+ collateralAssets,
235
237
  nativeAmount,
236
- onBehalf: userAddress,
237
- requirementSignature: permit,
238
+ deadline,
239
+ referralFeePct,
240
+ referralFeeRecipient,
241
+ requirementSignature: token,
238
242
  },
239
243
  metadata: this.client.options.metadata,
240
244
  });
241
245
  },
242
246
  };
243
247
  }
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)({
248
+ /** {@inheritDoc BlueActions.borrow} */
249
+ borrow(params) {
250
+ const { userAddress, borrowAssets, positionData, reallocations, deadline, referralFeePct, referralFeeRecipient, } = params;
251
+ const normalizedReallocations = [...(reallocations ?? [])];
252
+ const combinedAction = this.supplyCollateralBorrow({
253
+ userAddress,
254
+ collateralAssets: 0n,
255
+ borrowAssets,
260
256
  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,
257
+ reallocations: normalizedReallocations,
258
+ deadline,
259
+ referralFeePct,
260
+ referralFeeRecipient,
275
261
  });
276
262
  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
- },
263
+ getRequirements: () => combinedAction.getRequirements(),
289
264
  buildTx: (signatures) => {
290
- const { authorization } = (0, index_js_3.selectRequirementSignatures)(signatures, {
291
- authorization: true,
292
- });
265
+ const { authorization } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, { authorization: true });
293
266
  return (0, index_js_1.blueBorrow)({
294
- market: {
295
- chainId: this.chainId,
296
- marketParams: this.marketParams,
297
- },
267
+ market: { chainId: this.chainId, marketParams: this.marketParams },
298
268
  args: {
299
- amount,
300
- receiver: userAddress,
301
- minSharePrice,
302
- reallocations: reallocationList,
269
+ userAddress,
270
+ borrowAssets,
271
+ maxLtv: this.getMaxLtv(),
272
+ reallocations: normalizedReallocations,
273
+ deadline,
274
+ referralFeePct,
275
+ referralFeeRecipient,
303
276
  authorizationSignature: authorization,
304
277
  },
305
278
  metadata: this.client.options.metadata,
@@ -307,209 +280,98 @@ class MorphoBlue {
307
280
  },
308
281
  };
309
282
  }
283
+ /** {@inheritDoc BlueActions.repay} */
310
284
  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,
285
+ const combinedAction = this.repayWithdrawCollateral({
286
+ ...params,
287
+ collateralAssets: 0n,
389
288
  });
390
289
  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
- },
290
+ getRequirements: combinedAction.getRequirements,
404
291
  buildTx: (signatures) => {
405
- const { permit } = (0, index_js_3.selectRequirementSignatures)(signatures, {
406
- permit: true,
292
+ const combinedTransaction = combinedAction.buildTx(signatures);
293
+ const { token } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, {
294
+ token: combinedTransaction.value === 0n,
407
295
  });
296
+ const { repayAssets, repayShares, maxRepayAssets, nativeAmount, referralFeePct, referralFeeRecipient, deadline, } = combinedTransaction.action.args;
408
297
  return (0, index_js_1.blueRepay)({
409
- market: {
410
- chainId: this.chainId,
411
- marketParams: this.marketParams,
298
+ market: { chainId: this.chainId, marketParams: this.marketParams },
299
+ args: {
300
+ userAddress: params.userAddress,
301
+ repayAssets,
302
+ repayShares,
303
+ maxRepayAssets,
304
+ nativeAmount,
305
+ deadline,
306
+ referralFeePct,
307
+ referralFeeRecipient,
308
+ requirementSignature: token,
412
309
  },
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
310
  metadata: this.client.options.metadata,
435
311
  });
436
312
  },
437
313
  };
438
314
  }
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)({
315
+ /** {@inheritDoc BlueActions.withdrawCollateral} */
316
+ withdrawCollateral(params) {
317
+ const { userAddress, positionData, collateralAssets, deadline, referralFeePct, referralFeeRecipient, } = params;
318
+ const combinedAction = this.repayWithdrawCollateral({
319
+ userAddress,
448
320
  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,
321
+ repayAssets: 0n,
322
+ collateralAssets,
323
+ deadline,
324
+ referralFeePct,
325
+ referralFeeRecipient,
464
326
  });
465
327
  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
- }),
328
+ getRequirements: () => combinedAction.getRequirements(),
329
+ buildTx: (signatures) => {
330
+ const combinedTransaction = combinedAction.buildTx(signatures);
331
+ const { authorization } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, { authorization: true });
332
+ const combinedArgs = combinedTransaction.action.args;
333
+ return (0, index_js_1.blueWithdrawCollateral)({
334
+ market: { chainId: this.chainId, marketParams: this.marketParams },
335
+ args: {
336
+ userAddress,
337
+ collateralAssets: combinedArgs.collateralAssets,
338
+ maxLtv: combinedArgs.maxLtv,
339
+ deadline: combinedArgs.deadline,
340
+ referralFeePct: combinedArgs.referralFeePct,
341
+ referralFeeRecipient: combinedArgs.referralFeeRecipient,
342
+ authorizationSignature: authorization,
343
+ },
344
+ metadata: this.client.options.metadata,
345
+ });
346
+ },
478
347
  };
479
348
  }
349
+ /** {@inheritDoc BlueActions.repayWithdrawCollateral} */
480
350
  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) {
351
+ const { userAddress, positionData, collateralAssets, nativeAmount, deadline, referralFeeRecipient, } = params;
352
+ this.validateWriteCommon(params);
353
+ // `validateWriteCommon` returns void, so default an omitted `referralFeePct` to `0n`
354
+ // here, matching the pure action's normalization.
355
+ const referralFeePct = params.referralFeePct ?? 0n;
356
+ const repayAssets = params.repayAssets ?? 0n;
357
+ const repayShares = params.repayShares ?? 0n;
358
+ if (repayAssets < 0n) {
359
+ throw new index_js_3.NegativeInputError("repayAssets", repayAssets);
360
+ }
361
+ if (repayShares < 0n) {
362
+ throw new index_js_3.NegativeInputError("repayShares", repayShares);
363
+ }
364
+ if (collateralAssets < 0n) {
365
+ throw new index_js_3.NegativeInputError("collateralAssets", collateralAssets);
366
+ }
367
+ if (repayAssets > 0n && repayShares > 0n) {
496
368
  throw new index_js_3.MutuallyExclusiveRepayAmountsError(this.marketParams.id);
497
369
  }
498
- if ("shares" in params) {
499
- if (shares === 0n) {
500
- throw new index_js_3.NonPositiveInputError("shares", shares);
501
- }
370
+ const hasRepay = repayAssets > 0n || repayShares > 0n;
371
+ if (!hasRepay && collateralAssets === 0n) {
372
+ throw new index_js_3.NonPositiveInputError("repayAssets, repayShares, or collateralAssets", 0n);
502
373
  }
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) {
374
+ if (positionData == null) {
513
375
  throw new index_js_3.MissingAccrualPositionError(this.marketParams.id);
514
376
  }
515
377
  (0, index_js_2.validateAccrualPosition)({
@@ -517,250 +379,222 @@ class MorphoBlue {
517
379
  expectedMarketId: this.marketParams.id,
518
380
  expectedUser: userAddress,
519
381
  });
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)({
382
+ const saturatedRepay = repayShares === viem_1.maxUint256;
383
+ const simulatedRepayShares = saturatedRepay
384
+ ? positionData.borrowShares
385
+ : repayShares;
386
+ if (repayAssets > 0n) {
387
+ (0, index_js_2.validateRepayAmount)({
532
388
  positionData,
533
- repayShares: shares,
389
+ repayAssets,
534
390
  marketId: this.marketParams.id,
535
391
  });
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
392
  }
546
- else {
547
- // Assets mode is additive, like supply: repaid = amount + nativeAmount.
548
- repayAssets = amount + nativeAmount;
549
- (0, index_js_2.validateRepayAmount)({
393
+ else if (repayShares > 0n && !saturatedRepay) {
394
+ (0, index_js_2.validateRepayShares)({
550
395
  positionData,
551
- repayAssets,
396
+ repayShares,
552
397
  marketId: this.marketParams.id,
553
398
  });
554
- repayShares = 0n;
555
- erc20Amount = amount;
556
399
  }
557
- if (withdrawAmount > positionData.collateral) {
558
- throw new index_js_3.WithdrawExceedsCollateralError({
559
- withdrawAmount,
560
- available: positionData.collateral,
561
- market: positionData.marketId,
400
+ const quoteHorizon = this.getBlueBundlesV1QuoteTimestamp(positionData.market.lastUpdate);
401
+ if (repayShares > 0n && deadline > quoteHorizon) {
402
+ throw new index_js_3.InputExceedsMaxError({
403
+ field: "deadline",
404
+ value: deadline,
405
+ max: quoteHorizon,
562
406
  });
563
407
  }
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,
408
+ const accrualTimestamp = repayShares > 0n ? deadline : quoteHorizon;
409
+ const accruedPosition = positionData.accrueInterest(accrualTimestamp);
410
+ const expectedRepayAssets = repayAssets > 0n
411
+ ? repayAssets
412
+ : hasRepay
413
+ ? accruedPosition.market.toBorrowAssets(simulatedRepayShares, "Up")
414
+ : 0n;
415
+ const referralFeeAssets = (0, common_js_1.getBlueBundlesV1ReferralFeeAssets)(expectedRepayAssets, referralFeePct);
416
+ const maxRepayAssets = expectedRepayAssets + referralFeeAssets;
417
+ const nativeValue = (0, common_js_1.validateBlueBundlesV1NativeFunding)({
418
+ chainId: this.chainId,
419
+ token: this.marketParams.loanToken,
420
+ fundedAmount: maxRepayAssets,
421
+ nativeAmount,
576
422
  });
423
+ if (collateralAssets > 0n) {
424
+ const postRepayPosition = hasRepay
425
+ ? accruedPosition.repay(repayAssets, simulatedRepayShares).position
426
+ : accruedPosition;
427
+ (0, index_js_2.validatePositionHealthAfterWithdraw)({
428
+ positionData: postRepayPosition,
429
+ withdrawAmount: collateralAssets,
430
+ lltv: this.marketParams.lltv,
431
+ marketId: this.marketParams.id,
432
+ });
433
+ }
577
434
  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
- }),
435
+ getRequirements: async (requirementsParams) => {
436
+ this.validateDeadline(deadline);
437
+ const [tokenRequirements, authorizationRequirements] = await Promise.all([
438
+ hasRepay && nativeValue === 0n
439
+ ? this.getTokenRequirements({
440
+ token: this.marketParams.loanToken,
441
+ amount: maxRepayAssets,
442
+ // A caller-requested reusable approval wins; a full repay otherwise defaults to
443
+ // the token's reusable cap. Checksum the key so a differently-cased loan token
444
+ // (common from subgraphs/APIs) resolves that cap instead of falling back to
445
+ // maxUint256, which UNI/ONDO/COMP/FLUID reject.
446
+ approvalAmount: requirementsParams?.approvalAmount ??
447
+ (saturatedRepay
448
+ ? (index_js_2.MAX_TOKEN_APPROVALS[this.chainId]?.[(0, viem_1.getAddress)(this.marketParams.loanToken)] ?? viem_1.maxUint256)
449
+ : undefined),
450
+ userAddress,
451
+ deadline,
452
+ useSimplePermit: requirementsParams?.useSimplePermit,
453
+ permit2Nonce: requirementsParams?.permit2Nonce,
454
+ })
455
+ : Promise.resolve([]),
456
+ collateralAssets > 0n
457
+ ? this.getAuthorizationRequirements({ userAddress, deadline })
458
+ : Promise.resolve([]),
597
459
  ]);
598
- return [...erc20Requirements, ...(authTx ? [authTx] : [])];
460
+ return [...tokenRequirements, ...authorizationRequirements];
599
461
  },
600
462
  buildTx: (signatures) => {
601
- const { permit, authorization } = (0, index_js_3.selectRequirementSignatures)(signatures, { permit: true, authorization: true });
463
+ const { token, authorization } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, {
464
+ token: hasRepay && nativeValue === 0n,
465
+ authorization: collateralAssets > 0n,
466
+ });
467
+ const selectedMaxRepayAssets = repayShares > 0n && token != null
468
+ ? token.args.amount
469
+ : maxRepayAssets;
470
+ if (selectedMaxRepayAssets < maxRepayAssets) {
471
+ throw new index_js_3.MaxRepayAssetsBelowRepayAssetsError(selectedMaxRepayAssets, maxRepayAssets);
472
+ }
602
473
  return (0, index_js_1.blueRepayWithdrawCollateral)({
603
- market: {
604
- chainId: this.chainId,
605
- marketParams: this.marketParams,
474
+ market: { chainId: this.chainId, marketParams: this.marketParams },
475
+ args: {
476
+ userAddress,
477
+ repayAssets,
478
+ repayShares,
479
+ maxRepayAssets: selectedMaxRepayAssets,
480
+ collateralAssets,
481
+ maxLtv: collateralAssets > 0n ? this.getMaxLtv() : viem_1.maxUint256,
482
+ nativeAmount: nativeValue > 0n ? nativeValue : undefined,
483
+ deadline,
484
+ referralFeePct,
485
+ referralFeeRecipient,
486
+ requirementSignature: token,
487
+ authorizationSignature: authorization,
606
488
  },
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
489
  metadata: this.client.options.metadata,
633
490
  });
634
491
  },
635
492
  };
636
493
  }
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);
494
+ /** {@inheritDoc BlueActions.supplyCollateralBorrow} */
495
+ supplyCollateralBorrow(params) {
496
+ const { userAddress, collateralAssets, borrowAssets, positionData, nativeAmount, deadline, referralFeePct, referralFeeRecipient, } = params;
497
+ this.validateWriteCommon(params);
498
+ if (collateralAssets < 0n) {
499
+ throw new index_js_3.NegativeInputError("collateralAssets", collateralAssets);
500
+ }
501
+ if (borrowAssets < 0n) {
502
+ throw new index_js_3.NegativeInputError("borrowAssets", borrowAssets);
503
+ }
504
+ if (collateralAssets === 0n && borrowAssets === 0n) {
505
+ throw new index_js_3.NonPositiveInputError("collateralAssets or borrowAssets", 0n);
506
+ }
507
+ const reallocations = [...(params.reallocations ?? [])];
508
+ if (borrowAssets === 0n && reallocations.length > 0) {
509
+ throw new index_js_3.ReallocationsRequireBorrowError();
510
+ }
511
+ // Validate the exact PublicAllocations mapping before requirement reads.
512
+ const publicAllocations = (0, common_js_1.getBlueBundlesV1PublicAllocations)(reallocations, this.marketParams);
513
+ const reallocationPenaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(publicAllocations);
514
+ if (reallocationPenaltyAssets > borrowAssets) {
515
+ throw new index_js_3.InputExceedsMaxError({
516
+ field: "reallocationPenaltyAssets",
517
+ value: reallocationPenaltyAssets,
518
+ max: borrowAssets,
519
+ });
661
520
  }
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);
521
+ if (borrowAssets > 0n) {
522
+ if (positionData == null) {
523
+ throw new index_js_3.MissingAccrualPositionError(this.marketParams.id);
524
+ }
525
+ (0, index_js_2.validateAccrualPosition)({
526
+ positionData,
527
+ expectedMarketId: this.marketParams.id,
528
+ expectedUser: userAddress,
529
+ });
530
+ (0, index_js_2.validatePositionHealth)({
531
+ positionData: positionData.accrueInterest(this.getBlueBundlesV1QuoteTimestamp(positionData.market.lastUpdate)),
532
+ additionalCollateral: collateralAssets,
533
+ borrowAmount: borrowAssets,
534
+ marketId: this.marketParams.id,
535
+ lltv: this.marketParams.lltv,
536
+ });
669
537
  }
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,
538
+ const nativeValue = (0, common_js_1.validateBlueBundlesV1NativeFunding)({
539
+ chainId: this.chainId,
540
+ token: this.marketParams.collateralToken,
541
+ fundedAmount: collateralAssets,
542
+ nativeAmount,
681
543
  });
682
544
  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
- }),
545
+ getRequirements: async (requirementsParams) => {
546
+ this.validateDeadline(deadline);
547
+ const [tokenRequirements, authorizationRequirements] = await Promise.all([
548
+ collateralAssets > 0n && nativeValue === 0n
549
+ ? this.getTokenRequirements({
550
+ token: this.marketParams.collateralToken,
551
+ amount: collateralAssets,
552
+ approvalAmount: requirementsParams?.approvalAmount,
553
+ userAddress,
554
+ deadline,
555
+ useSimplePermit: requirementsParams?.useSimplePermit,
556
+ permit2Nonce: requirementsParams?.permit2Nonce,
557
+ })
558
+ : Promise.resolve([]),
559
+ borrowAssets > 0n
560
+ ? this.getAuthorizationRequirements({ userAddress, deadline })
561
+ : Promise.resolve([]),
710
562
  ]);
711
- return [
712
- ...erc20Requirements,
713
- ...penaltyRequirements,
714
- ...(authTx ? [authTx] : []),
715
- ];
563
+ return [...tokenRequirements, ...authorizationRequirements];
716
564
  },
717
565
  buildTx: (signatures) => {
718
- const { permit, authorization } = (0, index_js_3.selectRequirementSignatures)(signatures, { permit: true, authorization: true });
566
+ const { token, authorization } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, {
567
+ token: collateralAssets > 0n && nativeValue === 0n,
568
+ authorization: borrowAssets > 0n,
569
+ });
719
570
  return (0, index_js_1.blueSupplyCollateralBorrow)({
720
- market: {
721
- chainId: this.chainId,
722
- marketParams: this.marketParams,
723
- },
571
+ market: { chainId: this.chainId, marketParams: this.marketParams },
724
572
  args: {
725
- amount,
726
- nativeAmount,
727
- borrowAmount,
728
- onBehalf: userAddress,
729
- receiver: userAddress,
730
- minSharePrice,
731
- requirementSignature: permit,
573
+ userAddress,
574
+ collateralAssets,
575
+ borrowAssets,
576
+ maxLtv: borrowAssets > 0n ? this.getMaxLtv() : viem_1.maxUint256,
577
+ nativeAmount: nativeValue > 0n ? nativeValue : undefined,
578
+ reallocations,
579
+ deadline,
580
+ referralFeePct,
581
+ referralFeeRecipient,
582
+ requirementSignature: token,
732
583
  authorizationSignature: authorization,
733
- reallocations: reallocationList,
734
584
  },
735
585
  metadata: this.client.options.metadata,
736
586
  });
737
587
  },
738
588
  };
739
589
  }
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) {
590
+ /** {@inheritDoc BlueActions.refinance} */
591
+ refinance(params) {
592
+ const { userAddress, positionData, destination, deadline, referralFeeRecipient, } = params;
593
+ this.validateWriteCommon(params);
594
+ // `validateWriteCommon` returns void, so default an omitted `referralFeePct` to `0n`
595
+ // here, matching the pure action's normalization.
596
+ const referralFeePct = params.referralFeePct ?? 0n;
597
+ if (positionData == null) {
764
598
  throw new index_js_3.MissingAccrualPositionError(this.marketParams.id);
765
599
  }
766
600
  (0, index_js_2.validateAccrualPosition)({
@@ -768,140 +602,57 @@ class MorphoBlue {
768
602
  expectedMarketId: this.marketParams.id,
769
603
  expectedUser: userAddress,
770
604
  });
771
- if (this.marketParams.id === target.marketParams.id) {
605
+ if (positionData.borrowShares <= 0n) {
606
+ throw new index_js_3.NonPositiveInputError("positionData.borrowShares", positionData.borrowShares);
607
+ }
608
+ if (this.marketParams.id === destination.marketParams.id) {
772
609
  throw new index_js_3.RefinanceSameMarketError(this.marketParams.id);
773
610
  }
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);
611
+ if (!(0, viem_1.isAddressEqual)(this.marketParams.loanToken, destination.marketParams.loanToken) ||
612
+ !(0, viem_1.isAddressEqual)(this.marketParams.collateralToken, destination.marketParams.collateralToken)) {
613
+ throw new index_js_3.RefinanceTokenMismatchError(this.marketParams.id, destination.marketParams.id);
614
+ }
615
+ if (destination.positionData == null) {
616
+ throw new index_js_3.MissingAccrualPositionError(destination.marketParams.id);
777
617
  }
778
618
  (0, index_js_2.validateAccrualPosition)({
779
- positionData: target.positionData,
780
- expectedMarketId: target.marketParams.id,
619
+ positionData: destination.positionData,
620
+ expectedMarketId: destination.marketParams.id,
781
621
  expectedUser: userAddress,
782
622
  });
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;
623
+ const reallocations = [...(params.reallocations ?? [])];
624
+ const publicAllocations = (0, common_js_1.getBlueBundlesV1PublicAllocations)(reallocations, destination.marketParams);
625
+ const penaltyAssets = (0, common_js_1.getBlueBundlesV1PenaltyAssets)(publicAllocations);
626
+ const accrualTimestamp = this.getBlueBundlesV1QuoteTimestamp(blue_sdk_1.MathLib.max(positionData.market.lastUpdate, destination.positionData.market.lastUpdate));
627
+ const accruedSourcePosition = positionData.accrueInterest(accrualTimestamp);
628
+ const accruedDestinationPosition = destination.positionData.accrueInterest(accrualTimestamp);
629
+ const referralFeeAssets = (0, common_js_1.getBlueBundlesV1ReferralFeeAssets)(accruedSourcePosition.borrowAssets, referralFeePct);
630
+ (0, index_js_2.validatePositionHealth)({
631
+ positionData: accruedDestinationPosition,
632
+ additionalCollateral: accruedSourcePosition.collateral,
633
+ borrowAmount: accruedSourcePosition.borrowAssets + penaltyAssets + referralFeeAssets,
634
+ marketId: destination.marketParams.id,
635
+ lltv: destination.marketParams.lltv,
636
+ });
874
637
  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
- },
638
+ getRequirements: () => this.getAuthorizationRequirements({ userAddress, deadline }),
887
639
  buildTx: (signatures) => {
888
- const { authorization } = (0, index_js_3.selectRequirementSignatures)(signatures, {
640
+ const { authorization } = (0, common_js_1.selectBlueBundlesV1RequirementSignatures)(signatures, {
889
641
  authorization: true,
890
642
  });
891
643
  return (0, index_js_1.blueRefinance)({
892
- source: {
644
+ market: {
893
645
  chainId: this.chainId,
894
- marketParams: this.marketParams,
646
+ sourceMarketParams: this.marketParams,
647
+ destinationMarketParams: destination.marketParams,
895
648
  },
896
- target: { marketParams: target.marketParams },
897
649
  args: {
898
- user: userAddress,
899
- collateralAmount,
900
- borrowAssets: borrowAssetsAdjusted,
901
- borrowShares: requestedShares,
902
- minBorrowSharePrice,
903
- maxRepaySharePrice,
904
- targetReallocations: targetReallocationList,
650
+ userAddress,
651
+ maxLtv: this.getMaxLtv(destination.marketParams),
652
+ reallocations,
653
+ deadline,
654
+ referralFeePct,
655
+ referralFeeRecipient,
905
656
  authorizationSignature: authorization,
906
657
  },
907
658
  metadata: this.client.options.metadata,
@@ -917,6 +668,8 @@ class MorphoBlue {
917
668
  * @param params.block.timestamp - Timestamp corresponding to the fetched block.
918
669
  * @returns Reallocation data ready for {@link getVaultV1Reallocations}.
919
670
  * @throws {ChainIdMismatchError} when the client chain does not match this market.
671
+ * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
672
+ * {@link getVaultV2BlueReallocationData}.
920
673
  * @example
921
674
  * ```ts
922
675
  * import { markets, vaults } from "@morpho-org/morpho-test";
@@ -1010,7 +763,8 @@ class MorphoBlue {
1010
763
  * @param params.block.timestamp - Timestamp corresponding to the fetched block.
1011
764
  * @returns A `VaultV1ReallocationData` snapshot populated from one block.
1012
765
  * @throws {ChainIdMismatchError} when the client chain does not match this market.
1013
- * @deprecated Use {@link getVaultV1ReallocationData} instead.
766
+ * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
767
+ * {@link getVaultV2BlueReallocationData}.
1014
768
  * @example
1015
769
  * ```ts
1016
770
  * const data = await market.getReallocationData({ vaultAddresses, block });
@@ -1110,12 +864,14 @@ class MorphoBlue {
1110
864
  * @param params.amount - The borrow or withdraw amount used to compute the post-state utilization.
1111
865
  * @param params.borrowAmount - {@deprecated Pass `{ operation: "borrow", amount }` instead.}
1112
866
  * @param params.options - Optional allocator and utilization options.
1113
- * @returns Vault reallocations ready to pass to `borrow`, `supplyCollateralBorrow`, or `withdraw`.
867
+ * @returns Vault V1 reallocations for explicit low-level Bundler3 composition.
1114
868
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to a different chain than this market.
1115
869
  * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation's absolute shortfall on the target market.
1116
870
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when `operation === "withdraw"` and `amount` exceeds the target market's `totalSupplyAssets`.
1117
871
  * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
1118
872
  * @throws {UnknownReallocationMarketError} when the target market is absent from the reallocation data.
873
+ * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
874
+ * {@link getVaultV2BlueReallocations}.
1119
875
  * @example
1120
876
  * ```ts
1121
877
  * const reallocations = market.getVaultV1Reallocations({
@@ -1154,13 +910,14 @@ class MorphoBlue {
1154
910
  * @param params.amount - The borrow or withdraw amount used to compute post-state utilization.
1155
911
  * @param params.borrowAmount - Deprecated borrow amount alias.
1156
912
  * @param params.options - Optional allocator and utilization options.
1157
- * @returns Vault V1 reallocations ready for a Blue action.
913
+ * @returns Vault V1 reallocations for explicit low-level Bundler3 composition.
1158
914
  * @throws {ChainIdMismatchError} when `reallocationData` belongs to another chain.
1159
915
  * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the operation.
1160
916
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdrawal exceeds market supply.
1161
917
  * @throws {MissingPublicAllocatorConfigError} when a selected vault lacks allocator state.
1162
918
  * @throws {UnknownReallocationMarketError} when the target market is absent.
1163
- * @deprecated Use {@link getVaultV1Reallocations} instead.
919
+ * @deprecated Vault V1 shared-liquidity planning will be removed in the next major. Use
920
+ * {@link getVaultV2BlueReallocations}.
1164
921
  * @example
1165
922
  * ```ts
1166
923
  * const reallocations = market.getReallocations({