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