@morpho-org/morpho-sdk 10.5.0 → 10.6.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 (192) hide show
  1. package/README.md +44 -1
  2. package/lib/cjs/abis.d.ts +794 -1
  3. package/lib/cjs/abis.js +815 -1
  4. package/lib/cjs/actions/blue/close.d.ts +169 -0
  5. package/lib/cjs/actions/blue/close.js +270 -0
  6. package/lib/cjs/actions/blue/common.js +2 -2
  7. package/lib/cjs/actions/blue/delever.d.ts +156 -0
  8. package/lib/cjs/actions/blue/delever.js +223 -0
  9. package/lib/cjs/actions/blue/index.d.ts +3 -0
  10. package/lib/cjs/actions/blue/index.js +3 -0
  11. package/lib/cjs/actions/blue/lever.d.ts +184 -0
  12. package/lib/cjs/actions/blue/lever.js +272 -0
  13. package/lib/cjs/actions/blue/leverageIntent.d.ts +65 -0
  14. package/lib/cjs/actions/blue/leverageIntent.js +103 -0
  15. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  16. package/lib/cjs/actions/requirements/blue/encodeLeverageAuthorization.js +59 -0
  17. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  18. package/lib/cjs/actions/requirements/blue/getLeverageRequirements.js +193 -0
  19. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  20. package/lib/cjs/actions/requirements/blue/getLeverageRequirementsApproval.js +66 -0
  21. package/lib/cjs/actions/requirements/blue/index.d.ts +3 -0
  22. package/lib/cjs/actions/requirements/blue/index.js +17 -0
  23. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  24. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
  25. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +11 -6
  26. package/lib/cjs/actions/requirements/getRequirementsApproval.js +29 -5
  27. package/lib/cjs/addresses.d.ts +1 -1
  28. package/lib/cjs/addresses.js +6 -1
  29. package/lib/cjs/blue/abis.d.ts +1 -1
  30. package/lib/cjs/blue/abis.js +5 -1
  31. package/lib/cjs/blue/addresses.d.ts +1 -1
  32. package/lib/cjs/blue/addresses.js +6 -1
  33. package/lib/cjs/blue/entities.d.ts +4 -4
  34. package/lib/cjs/blue/entities.js +3 -1
  35. package/lib/cjs/blue/errors.d.ts +2 -2
  36. package/lib/cjs/blue/errors.js +5 -1
  37. package/lib/cjs/blue/fetch.d.ts +2 -2
  38. package/lib/cjs/blue/fetch.js +3 -1
  39. package/lib/cjs/blue/utils.d.ts +1 -1
  40. package/lib/cjs/blue/utils.js +2 -1
  41. package/lib/cjs/constants.d.ts +1 -1
  42. package/lib/cjs/constants.js +6 -2
  43. package/lib/cjs/entities/blue/blue.d.ts +486 -2
  44. package/lib/cjs/entities/blue/blue.js +529 -34
  45. package/lib/cjs/entities/index.d.ts +5 -5
  46. package/lib/cjs/entities/index.js +3 -1
  47. package/lib/cjs/entities/requirements/assertContractCode.d.ts +0 -23
  48. package/lib/cjs/entities/requirements/assertContractCode.js +3 -28
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +34 -8
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +39 -1
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +120 -2
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +232 -4
  53. package/lib/cjs/errors.d.ts +4 -4
  54. package/lib/cjs/errors.js +7 -5
  55. package/lib/cjs/fetch.d.ts +2 -2
  56. package/lib/cjs/fetch.js +3 -1
  57. package/lib/cjs/helpers/constant.d.ts +34 -0
  58. package/lib/cjs/helpers/constant.js +35 -1
  59. package/lib/cjs/helpers/deadShares.js +3 -0
  60. package/lib/cjs/helpers/getZeroExLeverageBundle.d.ts +13 -0
  61. package/lib/cjs/helpers/getZeroExLeverageBundle.js +27 -0
  62. package/lib/cjs/helpers/index.d.ts +4 -1
  63. package/lib/cjs/helpers/index.js +28 -1
  64. package/lib/cjs/helpers/leverage/index.d.ts +1 -0
  65. package/lib/cjs/helpers/leverage/index.js +11 -0
  66. package/lib/cjs/helpers/leverage/limits.d.ts +472 -0
  67. package/lib/cjs/helpers/leverage/limits.js +715 -0
  68. package/lib/cjs/helpers/leverage/positionMarket.d.ts +17 -0
  69. package/lib/cjs/helpers/leverage/positionMarket.js +28 -0
  70. package/lib/cjs/helpers/leverage/reallocations.d.ts +159 -0
  71. package/lib/cjs/helpers/leverage/reallocations.js +276 -0
  72. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  73. package/lib/cjs/helpers/validateRequirementSpender.js +4 -0
  74. package/lib/cjs/helpers/zeroExQuote.d.ts +250 -0
  75. package/lib/cjs/helpers/zeroExQuote.js +763 -0
  76. package/lib/cjs/index.d.ts +1 -0
  77. package/lib/cjs/index.js +5 -2
  78. package/lib/cjs/midnight/errors.d.ts +2 -1
  79. package/lib/cjs/midnight/errors.js +5 -4
  80. package/lib/cjs/reads/assertContractCode.d.ts +25 -0
  81. package/lib/cjs/reads/assertContractCode.js +30 -0
  82. package/lib/cjs/reads/fetchZeroExQuote.d.ts +123 -0
  83. package/lib/cjs/reads/fetchZeroExQuote.js +330 -0
  84. package/lib/cjs/types/action.d.ts +130 -1
  85. package/lib/cjs/types/error.d.ts +59 -0
  86. package/lib/cjs/types/error.js +82 -3
  87. package/lib/cjs/types/index.d.ts +2 -0
  88. package/lib/cjs/types/index.js +2 -0
  89. package/lib/cjs/types/leverageError.d.ts +1552 -0
  90. package/lib/cjs/types/leverageError.js +1711 -0
  91. package/lib/cjs/types/zeroEx.d.ts +171 -0
  92. package/lib/cjs/types/zeroEx.js +2 -0
  93. package/lib/cjs/utils.d.ts +2 -2
  94. package/lib/cjs/utils.js +4 -2
  95. package/lib/cjs/version.d.ts +1 -1
  96. package/lib/cjs/version.js +1 -1
  97. package/lib/esm/abis.d.ts +794 -1
  98. package/lib/esm/abis.js +810 -1
  99. package/lib/esm/actions/blue/close.d.ts +169 -0
  100. package/lib/esm/actions/blue/close.js +266 -0
  101. package/lib/esm/actions/blue/common.js +3 -3
  102. package/lib/esm/actions/blue/delever.d.ts +156 -0
  103. package/lib/esm/actions/blue/delever.js +219 -0
  104. package/lib/esm/actions/blue/index.d.ts +3 -0
  105. package/lib/esm/actions/blue/index.js +3 -0
  106. package/lib/esm/actions/blue/lever.d.ts +184 -0
  107. package/lib/esm/actions/blue/lever.js +268 -0
  108. package/lib/esm/actions/blue/leverageIntent.d.ts +65 -0
  109. package/lib/esm/actions/blue/leverageIntent.js +96 -0
  110. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.d.ts +39 -0
  111. package/lib/esm/actions/requirements/blue/encodeLeverageAuthorization.js +55 -0
  112. package/lib/esm/actions/requirements/blue/getLeverageRequirements.d.ts +104 -0
  113. package/lib/esm/actions/requirements/blue/getLeverageRequirements.js +189 -0
  114. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.d.ts +45 -0
  115. package/lib/esm/actions/requirements/blue/getLeverageRequirementsApproval.js +62 -0
  116. package/lib/esm/actions/requirements/blue/index.d.ts +3 -0
  117. package/lib/esm/actions/requirements/blue/index.js +3 -0
  118. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -2
  119. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  120. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +11 -6
  121. package/lib/esm/actions/requirements/getRequirementsApproval.js +29 -5
  122. package/lib/esm/addresses.d.ts +1 -1
  123. package/lib/esm/addresses.js +1 -1
  124. package/lib/esm/blue/abis.d.ts +1 -1
  125. package/lib/esm/blue/abis.js +1 -1
  126. package/lib/esm/blue/addresses.d.ts +1 -1
  127. package/lib/esm/blue/addresses.js +1 -1
  128. package/lib/esm/blue/entities.d.ts +4 -4
  129. package/lib/esm/blue/entities.js +2 -2
  130. package/lib/esm/blue/errors.d.ts +2 -2
  131. package/lib/esm/blue/errors.js +2 -2
  132. package/lib/esm/blue/fetch.d.ts +2 -2
  133. package/lib/esm/blue/fetch.js +2 -2
  134. package/lib/esm/blue/utils.d.ts +1 -1
  135. package/lib/esm/blue/utils.js +1 -1
  136. package/lib/esm/constants.d.ts +1 -1
  137. package/lib/esm/constants.js +1 -1
  138. package/lib/esm/entities/blue/blue.d.ts +486 -2
  139. package/lib/esm/entities/blue/blue.js +501 -6
  140. package/lib/esm/entities/index.d.ts +5 -5
  141. package/lib/esm/entities/index.js +2 -2
  142. package/lib/esm/entities/requirements/assertContractCode.d.ts +0 -23
  143. package/lib/esm/entities/requirements/assertContractCode.js +1 -25
  144. package/lib/esm/entities/vaultV2/vaultV2.d.ts +34 -8
  145. package/lib/esm/entities/vaultV2/vaultV2.js +40 -2
  146. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +120 -2
  147. package/lib/esm/entities/vaultV2BlueReallocationData.js +233 -5
  148. package/lib/esm/errors.d.ts +4 -4
  149. package/lib/esm/errors.js +4 -4
  150. package/lib/esm/fetch.d.ts +2 -2
  151. package/lib/esm/fetch.js +2 -2
  152. package/lib/esm/helpers/constant.d.ts +34 -0
  153. package/lib/esm/helpers/constant.js +34 -0
  154. package/lib/esm/helpers/deadShares.js +4 -1
  155. package/lib/esm/helpers/getZeroExLeverageBundle.d.ts +13 -0
  156. package/lib/esm/helpers/getZeroExLeverageBundle.js +23 -0
  157. package/lib/esm/helpers/index.d.ts +4 -1
  158. package/lib/esm/helpers/index.js +4 -1
  159. package/lib/esm/helpers/leverage/index.d.ts +1 -0
  160. package/lib/esm/helpers/leverage/index.js +1 -0
  161. package/lib/esm/helpers/leverage/limits.d.ts +472 -0
  162. package/lib/esm/helpers/leverage/limits.js +705 -0
  163. package/lib/esm/helpers/leverage/positionMarket.d.ts +17 -0
  164. package/lib/esm/helpers/leverage/positionMarket.js +24 -0
  165. package/lib/esm/helpers/leverage/reallocations.d.ts +159 -0
  166. package/lib/esm/helpers/leverage/reallocations.js +271 -0
  167. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  168. package/lib/esm/helpers/validateRequirementSpender.js +5 -1
  169. package/lib/esm/helpers/zeroExQuote.d.ts +250 -0
  170. package/lib/esm/helpers/zeroExQuote.js +754 -0
  171. package/lib/esm/index.d.ts +1 -0
  172. package/lib/esm/index.js +1 -0
  173. package/lib/esm/midnight/errors.d.ts +2 -1
  174. package/lib/esm/midnight/errors.js +2 -1
  175. package/lib/esm/reads/assertContractCode.d.ts +25 -0
  176. package/lib/esm/reads/assertContractCode.js +26 -0
  177. package/lib/esm/reads/fetchZeroExQuote.d.ts +123 -0
  178. package/lib/esm/reads/fetchZeroExQuote.js +326 -0
  179. package/lib/esm/types/action.d.ts +130 -1
  180. package/lib/esm/types/error.d.ts +59 -0
  181. package/lib/esm/types/error.js +76 -0
  182. package/lib/esm/types/index.d.ts +2 -0
  183. package/lib/esm/types/index.js +2 -0
  184. package/lib/esm/types/leverageError.d.ts +1552 -0
  185. package/lib/esm/types/leverageError.js +1660 -0
  186. package/lib/esm/types/zeroEx.d.ts +171 -0
  187. package/lib/esm/types/zeroEx.js +1 -0
  188. package/lib/esm/utils.d.ts +2 -2
  189. package/lib/esm/utils.js +2 -2
  190. package/lib/esm/version.d.ts +1 -1
  191. package/lib/esm/version.js +1 -1
  192. package/package.json +7 -7
@@ -8,6 +8,7 @@ const viem_1 = require("viem");
8
8
  const actions_1 = require("viem/actions");
9
9
  const abis_js_1 = require("../../abis.js");
10
10
  const common_js_1 = require("../../actions/blue/common.js");
11
+ const leverageIntent_js_1 = require("../../actions/blue/leverageIntent.js");
11
12
  const refinance_internal_js_1 = require("../../actions/blue/refinance.internal.js");
12
13
  const refinanceValidation_js_1 = require("../../actions/blue/refinanceValidation.js");
13
14
  const repayWithdrawCollateral_internal_js_1 = require("../../actions/blue/repayWithdrawCollateral.internal.js");
@@ -15,18 +16,229 @@ const supply_internal_js_1 = require("../../actions/blue/supply.internal.js");
15
16
  const supplyCollateralBorrow_internal_js_1 = require("../../actions/blue/supplyCollateralBorrow.internal.js");
16
17
  const withdraw_internal_js_1 = require("../../actions/blue/withdraw.internal.js");
17
18
  const withdrawBuyCallback_internal_js_1 = require("../../actions/blue/withdrawBuyCallback.internal.js");
19
+ const index_js_1 = require("../../actions/index.js");
18
20
  const getBlueAuthorizationRequirement_js_1 = require("../../actions/requirements/blue/getBlueAuthorizationRequirement.js");
19
21
  const chainCheck_js_1 = require("../../actions/requirements/chainCheck.js");
22
+ const validateClientChainId_js_1 = require("../../actions/requirements/validateClientChainId.js");
20
23
  const getBlueBundlesV1QuoteTimestamp_js_1 = require("../../helpers/getBlueBundlesV1QuoteTimestamp.js");
21
- const index_js_1 = require("../../helpers/index.js");
24
+ const index_js_2 = require("../../helpers/index.js");
25
+ const limits_js_1 = require("../../helpers/leverage/limits.js");
26
+ const positionMarket_js_1 = require("../../helpers/leverage/positionMarket.js");
22
27
  const metadata_js_1 = require("../../helpers/metadata.js");
23
28
  const parse_js_1 = require("../../helpers/parse.js");
24
29
  const quoteBlueRepay_js_1 = require("../../helpers/quoteBlueRepay.js");
25
- const index_js_2 = require("../../types/index.js");
30
+ const utilization_js_1 = require("../../helpers/utilization.js");
31
+ const index_js_3 = require("../../types/index.js");
26
32
  const assertContractCode_js_1 = require("../requirements/assertContractCode.js");
27
33
  const getBundlesTokenRequirements_js_1 = require("../requirements/getBundlesTokenRequirements.js");
28
34
  const validateNativeRequirements_js_1 = require("../requirements/validateNativeRequirements.js");
29
35
  const vaultV2BlueReallocationData_js_1 = require("../vaultV2BlueReallocationData.js");
36
+ /**
37
+ * Planning rounds of a Lever. A padded plan usually settles in the first round; when the vaults can
38
+ * fund only the unpadded borrow, each round closes the gap to the self-covering borrow at least
39
+ * a hundredfold (the penalty rate is at most 1%), so 32 rounds settle any `uint256` borrow.
40
+ */
41
+ const LEVER_REALLOCATION_PLAN_ROUNDS = 32;
42
+ /**
43
+ * Keeps the leading legs of a plan until they move `budget` assets, trimming the last kept leg. The
44
+ * planner sizes its free legs toward a 90% utilization target and can move more than the borrow,
45
+ * which the leverage guard refuses; every plan covers the borrow's shortfall, which never exceeds
46
+ * the borrow, so the trimmed plan still covers it, and its later, penalized legs shrink first.
47
+ */
48
+ const capLeverReallocations = (reallocations, budget) => {
49
+ const capped = [];
50
+ let remaining = budget;
51
+ for (const reallocation of reallocations) {
52
+ if (remaining === 0n) {
53
+ break;
54
+ }
55
+ const assets = blue_sdk_1.MathLib.min(reallocation.assets, remaining);
56
+ capped.push(assets === reallocation.assets
57
+ ? reallocation
58
+ : { ...reallocation, assets });
59
+ remaining -= assets;
60
+ }
61
+ return capped;
62
+ };
63
+ /**
64
+ * Trims a planned Lever to the borrow the market's liquidity leaves uncovered.
65
+ */
66
+ const trimLeverReallocations = ({ planned, borrow, liquidity, }) => capLeverReallocations(planned, blue_sdk_1.MathLib.zeroFloorSub(borrow, liquidity));
67
+ /**
68
+ * Base units below the bisected amount that a cap-breaking Lever leg scans for a smaller accepted amount,
69
+ * the window the planner gives its own shared-cap search.
70
+ */
71
+ const LEVER_CAP_SEARCH_STEPS = 1024n;
72
+ /**
73
+ * Checks a trimmed Lever plan against the vaults' caps by replaying it at the data block. A leg
74
+ * trimmed below the amount the planner chose can break a shared relative cap that a larger move
75
+ * meets, because the larger move donates a larger penalty and lifts the cap. Each leg that breaks a
76
+ * cap is raised to an amount that keeps it and every earlier leg within the caps: its planned amount
77
+ * must, a bisection between the trimmed and planned amounts narrows it to an accepted amount, and a scan of
78
+ * the `LEVER_CAP_SEARCH_STEPS` amounts below that one takes the smallest the replay accepts, since share
79
+ * rounding can make a cap accept an amount below one it refuses. The raised plan must still move no more
80
+ * than the borrow it needs.
81
+ *
82
+ * @throws {LeverageReallocationOutsideCapsError} when a leg breaks a cap even at its planned amount.
83
+ * @throws {LeverageReallocationExceedsBorrowError} when the raised plan moves more than the borrow it needs.
84
+ */
85
+ const fitLeverReallocationCaps = ({ planned, trimmed, getBorrow, findOutsideCaps, findFittingAssets, }) => {
86
+ let legs = trimmed;
87
+ for (let outside = findOutsideCaps(legs); outside != null; outside = findOutsideCaps(legs)) {
88
+ const broken = outside;
89
+ const index = legs.indexOf(broken);
90
+ const earlier = legs.slice(0, index);
91
+ const fits = (amounts) => findFittingAssets({
92
+ reallocations: earlier,
93
+ reallocation: broken,
94
+ amounts,
95
+ });
96
+ /* v8 ignore next: every leg keeps its planned leg's from and to objects, so the lookup always matches. */
97
+ const plannedAssets = planned.find(({ from, to }) => from === broken.from && to === broken.to)
98
+ ?.assets ?? broken.assets;
99
+ if (plannedAssets <= broken.assets || fits([plannedAssets]) == null) {
100
+ throw new index_js_3.LeverageReallocationOutsideCapsError({
101
+ vault: broken.vault,
102
+ assets: broken.assets,
103
+ });
104
+ }
105
+ let low = broken.assets;
106
+ let high = plannedAssets;
107
+ while (high - low > 1n) {
108
+ const middle = (low + high) / 2n;
109
+ if (fits([middle]) == null) {
110
+ low = middle;
111
+ }
112
+ else {
113
+ high = middle;
114
+ }
115
+ }
116
+ // Share rounding can make a shared cap accept an amount below one it refuses, so the bisection
117
+ // may skip a smaller fit: scan the window below its result upward, in one replay of the earlier legs.
118
+ const scanFrom = blue_sdk_1.MathLib.max(broken.assets + 1n, high - LEVER_CAP_SEARCH_STEPS);
119
+ const window = function* () {
120
+ for (let assets = scanFrom; assets < high; assets++) {
121
+ yield assets;
122
+ }
123
+ };
124
+ const assets = fits(window()) ?? high;
125
+ legs = legs.map((leg, i) => (i === index ? { ...leg, assets } : leg));
126
+ }
127
+ const total = legs.reduce((sum, { assets }) => sum + assets, 0n);
128
+ const maxBorrowAssets = getBorrow(legs);
129
+ if (total > maxBorrowAssets) {
130
+ throw new index_js_3.LeverageReallocationExceedsBorrowError({
131
+ total,
132
+ maxBorrowAssets,
133
+ });
134
+ }
135
+ return legs;
136
+ };
137
+ /**
138
+ * Plans the Vault V2 BluePublicAllocator reallocations of a Lever with `VaultV2BlueReallocationData`.
139
+ * The borrow is the penalty-free borrow plus the plan's own penalty. A market whose liquidity covers
140
+ * the penalty-free borrow needs no reallocation. Otherwise each plan is sized for the borrow plus its
141
+ * penalty tail at the `maxPenalty` ceiling, or for the unpadded borrow when the vaults cannot fund
142
+ * that, then trimmed to the part of the borrow the market's liquidity leaves uncovered: trimming
143
+ * lowers the penalty and so the borrow, until the two agree. A plan that needs more than it was sized for is replanned,
144
+ * at most 32 rounds; `blueLever` refuses a last plan that leaves the market short of the borrow and
145
+ * reruns the price and LTV checks on the final plan. The trimmed plan is replayed against the vaults'
146
+ * caps first: a trimmed leg that breaks one is raised toward its planned amount, to the smallest
147
+ * amount the replay accepts.
148
+ */
149
+ const planLeverReallocations = ({ marketParams, leverageData, options, limits, }) => {
150
+ if (options?.enabled === false ||
151
+ Object.keys(leverageData.reallocationData.vaults).length === 0) {
152
+ return [];
153
+ }
154
+ const maxPenalty = blue_sdk_1.MathLib.min(options?.maxPenalty ?? index_js_2.LEVERAGE_MAX_REALLOCATION_PENALTY, index_js_2.LEVERAGE_MAX_REALLOCATION_PENALTY);
155
+ // Every round replans with the same allowlist, so a one-shot iterable is read once.
156
+ const reallocatableVaults = options?.reallocatableVaults == null
157
+ ? undefined
158
+ : [...options.reallocatableVaults];
159
+ // The price and LTV checks only tighten as the penalty grows, so they run once here on the
160
+ // penalty-free borrow; `blueLever` reruns them on the final plan. Sizing below is arithmetic: the
161
+ // borrow is the penalty-free borrow plus the plan's penalty.
162
+ const borrowWithoutPenalty = (0, index_js_2.computeLeverLimits)({
163
+ ...limits,
164
+ penaltyAssets: 0n,
165
+ }).maxBorrowAssets;
166
+ const getBorrow = (legs) => borrowWithoutPenalty + (0, common_js_1.getBlueBundlesV1PenaltyAssets)(legs);
167
+ const { liquidity } = leverageData.position.market;
168
+ const fit = (planned, trimmed) => fitLeverReallocationCaps({
169
+ planned,
170
+ trimmed,
171
+ getBorrow,
172
+ findOutsideCaps: (legs) => leverageData.reallocationData.findVaultV2BlueReallocationOutsideCaps({
173
+ marketId: marketParams.id,
174
+ reallocations: legs,
175
+ timestamp: leverageData.block.timestamp,
176
+ capAccrualBuffer: options?.capAccrualBuffer,
177
+ }),
178
+ findFittingAssets: (search) => leverageData.reallocationData.findVaultV2BlueReallocationFittingAssets({
179
+ ...search,
180
+ marketId: marketParams.id,
181
+ timestamp: leverageData.block.timestamp,
182
+ capAccrualBuffer: options?.capAccrualBuffer,
183
+ }),
184
+ });
185
+ const trim = (planned, borrow) => trimLeverReallocations({
186
+ planned,
187
+ borrow,
188
+ liquidity,
189
+ });
190
+ const plan = (data) => {
191
+ if (borrowWithoutPenalty <= liquidity) {
192
+ return [];
193
+ }
194
+ const planBorrow = (amount) => data.computeVaultV2BlueReallocations(marketParams.id, {
195
+ ...options,
196
+ reallocatableVaults,
197
+ timestamp: leverageData.block.timestamp,
198
+ maxPenalty,
199
+ operation: { type: "borrow", amount },
200
+ }).reallocations;
201
+ // Each plan is first sized for the borrow plus its whole penalty tail at the `maxPenalty`
202
+ // ceiling, then trimmed back down; when the vaults cannot fund that padding, the unpadded
203
+ // borrow is planned instead.
204
+ const pad = (borrow, tail) => borrow + blue_sdk_1.MathLib.mulDivUp(tail, maxPenalty, blue_sdk_1.MathLib.WAD - maxPenalty);
205
+ let unpadded = borrowWithoutPenalty;
206
+ let target = pad(borrowWithoutPenalty, borrowWithoutPenalty);
207
+ let planned = [];
208
+ let reallocations = [];
209
+ for (let round = 0; round < LEVER_REALLOCATION_PLAN_ROUNDS; round++) {
210
+ const padded = (0, morpho_ts_1._try)(() => planBorrow(target), index_js_3.InsufficientSharedLiquidityError);
211
+ const sizedFor = padded === undefined ? unpadded : target;
212
+ planned = padded ?? planBorrow(unpadded);
213
+ // The plan is trimmed for the borrow it was sized for. A smaller borrow lowers the penalty, so
214
+ // the borrow it needs falls until the plan, trimmed for that borrow, needs exactly that borrow.
215
+ let borrow = sizedFor;
216
+ reallocations = trim(planned, borrow);
217
+ let needed = getBorrow(reallocations);
218
+ while (needed < borrow) {
219
+ borrow = needed;
220
+ reallocations = trim(planned, borrow);
221
+ needed = getBorrow(reallocations);
222
+ }
223
+ if (needed === borrow) {
224
+ return fit(planned, reallocations);
225
+ }
226
+ unpadded = needed;
227
+ target = pad(needed, needed - sizedFor);
228
+ }
229
+ return fit(planned, reallocations);
230
+ };
231
+ // Lever plans ignore Blue's loan-token balance by choice, so the planner's flash-loan funding check never
232
+ // refuses a Lever. ZeroExLeverageBundlesV1 still flash-loans `penaltyAssets - loanAssets` from Blue when the
233
+ // penalty exceeds the deposit, so a Lever that pays a penalty can revert onchain when Blue is short of cash.
234
+ const { reallocationData } = leverageData;
235
+ return plan(Object.values(reallocationData.blueBalances).every((balance) => balance == null)
236
+ ? reallocationData
237
+ : new vaultV2BlueReallocationData_js_1.VaultV2BlueReallocationData({
238
+ ...reallocationData,
239
+ blueBalances: {},
240
+ }));
241
+ };
30
242
  /** Binds a viem client to a Morpho Blue market's action builders. */
31
243
  class MorphoBlue {
32
244
  client;
@@ -48,14 +260,33 @@ class MorphoBlue {
48
260
  this.chainId = chainId;
49
261
  this.parsedMarket = (0, parse_js_1.parseBlueMarket)(marketParams);
50
262
  }
263
+ validateLeverageNow(now) {
264
+ if (now === undefined) {
265
+ return;
266
+ }
267
+ if (typeof now !== "bigint") {
268
+ throw new index_js_3.InvalidBigIntInputError("now", now);
269
+ }
270
+ if (now < 0n) {
271
+ throw new index_js_3.NegativeInputError("now", now);
272
+ }
273
+ }
274
+ elapsedLeverageNow(now, createdAt) {
275
+ return now === undefined ? undefined : now + morpho_ts_1.Time.timestamp() - createdAt;
276
+ }
51
277
  validateDeadline(deadline, now = morpho_ts_1.Time.timestamp()) {
52
278
  if (deadline <= now) {
53
- throw new index_js_2.ExpiredDeadlineError(deadline, now);
279
+ throw new index_js_3.ExpiredDeadlineError(deadline, now);
280
+ }
281
+ }
282
+ validateLeverageDeadline(deadline, now = morpho_ts_1.Time.timestamp()) {
283
+ if (deadline <= now) {
284
+ throw new index_js_3.ExpiredLeverageDeadlineError(deadline, now);
54
285
  }
55
286
  }
56
287
  validateWriteCommon(params, now) {
57
288
  // Reject cross-chain inputs before continuing.
58
- (0, index_js_1.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
289
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
59
290
  // Reject expiry before continuing this call.
60
291
  this.validateDeadline(params.deadline, now);
61
292
  // Resolve at handle creation so unsupported deployments fail before any RPC prerequisite work.
@@ -98,7 +329,7 @@ class MorphoBlue {
98
329
  }
99
330
  }
100
331
  getMaxLtv(marketParams = this.parsedMarket) {
101
- return blue_sdk_1.MathLib.zeroFloorSub(marketParams.lltv, index_js_1.DEFAULT_LLTV_BUFFER);
332
+ return blue_sdk_1.MathLib.zeroFloorSub(marketParams.lltv, index_js_2.DEFAULT_LLTV_BUFFER);
102
333
  }
103
334
  async getTokenRequirements(chainCheck, params) {
104
335
  // Reject expiry before continuing this call.
@@ -146,6 +377,270 @@ class MorphoBlue {
146
377
  deployless: this.client.options.supportDeployless,
147
378
  });
148
379
  }
380
+ /** {@inheritDoc BlueActions.getLeverageData} */
381
+ async getLeverageData({ userAddress, vaultAddresses = [], blockNumber, }) {
382
+ if (!(0, morpho_ts_1.isZeroExLeverageChain)(this.chainId)) {
383
+ throw new index_js_3.LeverageUnsupportedChainError({
384
+ chainId: this.chainId,
385
+ reason: morpho_ts_1.ZERO_EX_ALLOWANCE_HOLDER_CHAIN_IDS.has(this.chainId)
386
+ ? "noBundle"
387
+ : "noAllowanceHolder",
388
+ });
389
+ }
390
+ await (0, validateClientChainId_js_1.validateClientChainId)(this.client.viemClient, this.chainId);
391
+ // Read the caller's iterable once, before any parallel read starts, so an iterator that throws leaves
392
+ // no read without a handler. A repeated vault, in any casing, is read once; a malformed entry is kept for the
393
+ // reallocation read to refuse with its typed error.
394
+ const seenVaults = new Set();
395
+ const vaults = [...vaultAddresses].filter((vault) => {
396
+ const key = typeof vault === "string" ? vault.toLowerCase() : vault;
397
+ if (seenVaults.has(key)) {
398
+ return false;
399
+ }
400
+ seenVaults.add(key);
401
+ return true;
402
+ });
403
+ const client = this.client.viemClient;
404
+ const { number, timestamp } = await (0, actions_1.getBlock)(client, blockNumber == null ? {} : { blockNumber });
405
+ const block = { number, timestamp };
406
+ const allowanceHolderCode = await (0, actions_1.getCode)(client, {
407
+ address: morpho_ts_1.ZERO_EX_ALLOWANCE_HOLDER_ADDRESS,
408
+ blockNumber: block.number,
409
+ });
410
+ if (allowanceHolderCode == null || allowanceHolderCode === "0x") {
411
+ throw new index_js_3.LeverageUnsupportedChainError({
412
+ chainId: this.chainId,
413
+ reason: "noAllowanceHolder",
414
+ });
415
+ }
416
+ const [snapshotRead, reallocationRead] = await Promise.allSettled([
417
+ (0, blue_sdk_viem_1.fetchAccrualPosition)(userAddress, this.parsedMarket.id, client, {
418
+ blockNumber: block.number,
419
+ deployless: this.client.options.supportDeployless,
420
+ }),
421
+ this.getVaultV2BlueReallocationData({
422
+ vaultAddresses: vaults,
423
+ block,
424
+ }),
425
+ ]);
426
+ if (snapshotRead.status === "rejected") {
427
+ throw snapshotRead.reason;
428
+ }
429
+ const snapshot = snapshotRead.value;
430
+ // Morpho returns an all-zero, never-updated market for an id with no market at the block. Its id is the
431
+ // zero tuple's, which matches only an entity built from the zero tuple, so the last update is checked too.
432
+ // Checked before the sibling reads' errors, which such a market can also cause.
433
+ if (snapshot.market.id !== this.parsedMarket.id ||
434
+ snapshot.market.lastUpdate === 0n) {
435
+ throw new blue_sdk_1.UnknownMarketParamsError(this.parsedMarket.id);
436
+ }
437
+ if (reallocationRead.status === "rejected") {
438
+ throw reallocationRead.reason;
439
+ }
440
+ const reallocationData = reallocationRead.value;
441
+ return {
442
+ chainId: this.chainId,
443
+ block,
444
+ bundle: (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.zeroExLeverageBundlesV1"),
445
+ market: snapshot.market,
446
+ // Left as stored: Blue accrues once from its last update, and the leverage limits do the same.
447
+ position: snapshot,
448
+ borrowRate: snapshot.market
449
+ .accrueInterest(block.timestamp)
450
+ .getEndBorrowRate(block.timestamp),
451
+ reallocationData,
452
+ };
453
+ }
454
+ /** {@inheritDoc BlueActions.lever} */
455
+ lever({ userAddress, txOrigin, leverageData, quote, slippage, collateralAssets, loanAssets, nativeAmount, reallocationOptions, now, }) {
456
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
457
+ (0, index_js_2.validateChainId)(leverageData.chainId, this.chainId);
458
+ this.validateLeverageNow(now);
459
+ const createdAt = morpho_ts_1.Time.timestamp();
460
+ // Expired leverage data fails here first, so the caller is told to read a new one.
461
+ this.validateLeverageDeadline((0, limits_js_1.leverageDeadline)(leverageData), now);
462
+ // The planner computes limits from the snapshot before `blueLever`, so the snapshot's market and
463
+ // user and the intent are checked first to throw the same typed error with planning on or off.
464
+ (0, index_js_2.validateAccrualPosition)({
465
+ positionData: leverageData.position,
466
+ expectedMarketId: this.parsedMarket.id,
467
+ expectedUser: userAddress,
468
+ });
469
+ // Built from the snapshot, never the caller's object, which the caller can mutate after construction.
470
+ const marketParams = new blue_sdk_1.MarketParams(this.parsedMarket);
471
+ (0, positionMarket_js_1.validateLeveragePositionMarket)(leverageData.position, marketParams);
472
+ (0, leverageIntent_js_1.validateLeverageIntentAmount)("collateralAssets", collateralAssets);
473
+ (0, leverageIntent_js_1.validateLeverageIntentAmount)("loanAssets", loanAssets);
474
+ // Checked before the quote's slippage, so a requote advice never names a slippage the quote fetch refuses.
475
+ (0, leverageIntent_js_1.validateLeverSlippage)(slippage);
476
+ if (quote == null) {
477
+ throw new index_js_3.ZeroExQuoteRequiredError({ operation: "lever" });
478
+ }
479
+ (0, leverageIntent_js_1.validateLeverageQuoteSlippage)({
480
+ operation: "lever",
481
+ slippage,
482
+ quoteSlippage: quote.slippage,
483
+ });
484
+ const maxPenalty = reallocationOptions?.maxPenalty;
485
+ if (maxPenalty !== undefined && typeof maxPenalty !== "bigint") {
486
+ throw new index_js_3.InvalidBigIntInputError("reallocationOptions.maxPenalty", maxPenalty);
487
+ }
488
+ // Refused here so a bad setting fails on a liquid market too, where planning returns early.
489
+ if (maxPenalty !== undefined && maxPenalty < 0n) {
490
+ throw new index_js_3.NegativeInputError("reallocationOptions.maxPenalty", maxPenalty);
491
+ }
492
+ const { capAccrualBuffer, allocatorCapHeadroom, maxWithdrawalUtilization } = reallocationOptions ?? {};
493
+ for (const [field, value] of [
494
+ ["reallocationOptions.allocatorCapHeadroom", allocatorCapHeadroom],
495
+ [
496
+ "reallocationOptions.maxWithdrawalUtilization",
497
+ maxWithdrawalUtilization,
498
+ ],
499
+ ]) {
500
+ if (value !== undefined && typeof value !== "bigint") {
501
+ throw new index_js_3.InvalidBigIntInputError(field, value);
502
+ }
503
+ }
504
+ if (capAccrualBuffer != null) {
505
+ try {
506
+ BigInt(capAccrualBuffer);
507
+ }
508
+ catch {
509
+ throw new index_js_3.InvalidBigIntInputError("reallocationOptions.capAccrualBuffer", capAccrualBuffer);
510
+ }
511
+ }
512
+ (0, utilization_js_1.resolveCapAccrualBuffer)(reallocationOptions?.capAccrualBuffer);
513
+ (0, utilization_js_1.resolveAllocatorCapHeadroom)(reallocationOptions?.allocatorCapHeadroom);
514
+ (0, utilization_js_1.resolveMaxWithdrawalUtilization)(reallocationOptions?.maxWithdrawalUtilization);
515
+ const reallocations = planLeverReallocations({
516
+ marketParams,
517
+ leverageData,
518
+ options: reallocationOptions,
519
+ limits: {
520
+ intent: { collateralAssets, loanAssets },
521
+ quote,
522
+ slippage,
523
+ leverageData,
524
+ },
525
+ });
526
+ const transaction = (0, index_js_1.blueLever)({
527
+ market: { chainId: this.chainId, marketParams },
528
+ args: {
529
+ userAddress,
530
+ txOrigin,
531
+ leverageData,
532
+ quote,
533
+ slippage,
534
+ collateralAssets,
535
+ loanAssets,
536
+ reallocations,
537
+ nativeAmount,
538
+ },
539
+ metadata: (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, now),
540
+ });
541
+ const { maxBorrowAssets, deadline } = transaction.action.args;
542
+ return {
543
+ getRequirements: async () => {
544
+ this.validateLeverageDeadline(deadline, this.elapsedLeverageNow(now, createdAt));
545
+ // Morpho Blue keeps its code check. A shipped leverage bundle's check is waived (docs/EXCEPTIONS.md); a bundle
546
+ // registered with registerCustomAddresses has its code checked in getLeverageRequirements.
547
+ await (0, assertContractCode_js_1.assertRegistryTargetsHaveCode)(this.client.viemClient, this.chainId, [{ role: "blue", address: (0, morpho_ts_1.getChainAddress)(this.chainId, "blue") }]);
548
+ return (0, index_js_1.getLeverageRequirements)({
549
+ viemClient: this.client.viemClient,
550
+ chainId: this.chainId,
551
+ userAddress,
552
+ marketParams: this.parsedMarket,
553
+ operation: {
554
+ type: "lever",
555
+ collateralAssets,
556
+ loanAssets,
557
+ maxBorrowAssets,
558
+ },
559
+ });
560
+ },
561
+ buildTx: () => transaction,
562
+ };
563
+ }
564
+ /** {@inheritDoc BlueActions.delever} */
565
+ delever(params) {
566
+ const { userAddress, leverageData, now } = params;
567
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
568
+ (0, index_js_2.validateChainId)(leverageData.chainId, this.chainId);
569
+ if (leverageData.market.id !== this.parsedMarket.id) {
570
+ throw new index_js_3.MarketIdMismatchError(leverageData.market.id, this.parsedMarket.id);
571
+ }
572
+ this.validateLeverageNow(now);
573
+ const createdAt = morpho_ts_1.Time.timestamp();
574
+ // Expired leverage data fails here first, so the caller is told to read a new one.
575
+ this.validateLeverageDeadline((0, limits_js_1.leverageDeadline)(leverageData), now);
576
+ const tx = (0, index_js_1.blueDelever)({
577
+ market: {
578
+ chainId: this.chainId,
579
+ // Built from the snapshot, never the caller's object, which the caller can mutate after construction.
580
+ marketParams: new blue_sdk_1.MarketParams(this.parsedMarket),
581
+ },
582
+ args: {
583
+ leverageData,
584
+ userAddress,
585
+ txOrigin: params.txOrigin,
586
+ quote: params.quote,
587
+ slippage: params.slippage,
588
+ },
589
+ metadata: (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, now),
590
+ });
591
+ const { deadline } = tx.action.args;
592
+ return {
593
+ getRequirements: async () => {
594
+ this.validateLeverageDeadline(deadline, this.elapsedLeverageNow(now, createdAt));
595
+ // Morpho Blue keeps its code check. A shipped leverage bundle's check is waived (docs/EXCEPTIONS.md); a bundle
596
+ // registered with registerCustomAddresses has its code checked in getLeverageRequirements.
597
+ await (0, assertContractCode_js_1.assertRegistryTargetsHaveCode)(this.client.viemClient, this.chainId, [{ role: "blue", address: (0, morpho_ts_1.getChainAddress)(this.chainId, "blue") }]);
598
+ return (0, index_js_1.getLeverageRequirements)({
599
+ viemClient: this.client.viemClient,
600
+ chainId: this.chainId,
601
+ userAddress,
602
+ marketParams: this.parsedMarket,
603
+ operation: { type: "delever" },
604
+ });
605
+ },
606
+ buildTx: () => tx,
607
+ };
608
+ }
609
+ /** {@inheritDoc BlueActions.close} */
610
+ close(params) {
611
+ const { userAddress, leverageData, now } = params;
612
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
613
+ this.validateLeverageNow(now);
614
+ const createdAt = morpho_ts_1.Time.timestamp();
615
+ // Expired leverage data fails here first, so the caller is told to read a new one.
616
+ this.validateLeverageDeadline((0, limits_js_1.leverageDeadline)(leverageData), now);
617
+ const tx = (0, index_js_1.blueClose)({
618
+ market: {
619
+ chainId: this.chainId,
620
+ // Built from the snapshot, never the caller's object, which the caller can mutate after construction.
621
+ marketParams: new blue_sdk_1.MarketParams(this.parsedMarket),
622
+ },
623
+ args: params,
624
+ metadata: (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, now),
625
+ });
626
+ const { deadline } = tx.action.args;
627
+ return {
628
+ getRequirements: async () => {
629
+ this.validateLeverageDeadline(deadline, this.elapsedLeverageNow(now, createdAt));
630
+ // Morpho Blue keeps its code check. A shipped leverage bundle's check is waived (docs/EXCEPTIONS.md); a bundle
631
+ // registered with registerCustomAddresses has its code checked in getLeverageRequirements.
632
+ await (0, assertContractCode_js_1.assertRegistryTargetsHaveCode)(this.client.viemClient, this.chainId, [{ role: "blue", address: (0, morpho_ts_1.getChainAddress)(this.chainId, "blue") }]);
633
+ return (0, index_js_1.getLeverageRequirements)({
634
+ viemClient: this.client.viemClient,
635
+ chainId: this.chainId,
636
+ userAddress,
637
+ marketParams: this.parsedMarket,
638
+ operation: { type: "close" },
639
+ });
640
+ },
641
+ buildTx: () => tx,
642
+ };
643
+ }
149
644
  supply(params) {
150
645
  return this.supplyPrepared(this.parseSupplyParams(params));
151
646
  }
@@ -155,7 +650,7 @@ class MorphoBlue {
155
650
  const createdAt = params.now ?? morpho_ts_1.Time.timestamp();
156
651
  const normalized = this.validateWriteCommon(params, createdAt);
157
652
  if (assets <= 0n) {
158
- throw new index_js_2.NonPositiveInputError("assets", assets);
653
+ throw new index_js_3.NonPositiveInputError("assets", assets);
159
654
  }
160
655
  const nativeValue = (0, parse_js_1.parseNativeFunding)({
161
656
  chainId: this.chainId,
@@ -165,7 +660,7 @@ class MorphoBlue {
165
660
  });
166
661
  if (params.marketData != null &&
167
662
  params.marketData.id !== this.parsedMarket.id) {
168
- throw new index_js_2.MarketIdMismatchError(params.marketData.id, this.parsedMarket.id);
663
+ throw new index_js_3.MarketIdMismatchError(params.marketData.id, this.parsedMarket.id);
169
664
  }
170
665
  const input = {
171
666
  ...normalized,
@@ -227,17 +722,17 @@ class MorphoBlue {
227
722
  field: "assets or shares",
228
723
  });
229
724
  if (positionData == null) {
230
- throw new index_js_2.MissingAccrualPositionError(this.parsedMarket.id);
725
+ throw new index_js_3.MissingAccrualPositionError(this.parsedMarket.id);
231
726
  }
232
727
  // Reject a snapshot for another user or market.
233
- (0, index_js_1.validateAccrualPosition)({
728
+ (0, index_js_2.validateAccrualPosition)({
234
729
  positionData,
235
730
  expectedMarketId: this.parsedMarket.id,
236
731
  expectedUser: userAddress,
237
732
  });
238
733
  if (shares > 0n) {
239
734
  // Reject a withdrawal larger than the supplied share balance.
240
- (0, index_js_1.validateWithdrawShares)({
735
+ (0, index_js_2.validateWithdrawShares)({
241
736
  positionData,
242
737
  withdrawShares: shares,
243
738
  marketId: this.parsedMarket.id,
@@ -245,7 +740,7 @@ class MorphoBlue {
245
740
  }
246
741
  else {
247
742
  // Reject a withdrawal larger than the supplied asset balance.
248
- (0, index_js_1.validateWithdrawAmount)({
743
+ (0, index_js_2.validateWithdrawAmount)({
249
744
  positionData,
250
745
  withdrawAssets: assets,
251
746
  marketId: this.parsedMarket.id,
@@ -258,7 +753,7 @@ class MorphoBlue {
258
753
  const reallocationPenaltyAssets = allocations.penaltyAssets;
259
754
  const expectedWithdrawAssets = assets > 0n ? assets : positionData.market.toSupplyAssets(shares, "Down");
260
755
  if (shares > 0n && reallocationPenaltyAssets > expectedWithdrawAssets) {
261
- throw new index_js_2.InputExceedsMaxError({
756
+ throw new index_js_3.InputExceedsMaxError({
262
757
  field: "reallocationPenaltyAssets",
263
758
  value: reallocationPenaltyAssets,
264
759
  max: expectedWithdrawAssets,
@@ -312,19 +807,19 @@ class MorphoBlue {
312
807
  const metadata = (0, metadata_js_1.resolveTransactionMetadata)(this.client.options.metadata, params.now);
313
808
  const { userAddress, callbackAddress, positionData } = params;
314
809
  // Reject cross-chain inputs before continuing.
315
- (0, index_js_1.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
810
+ (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
316
811
  if (positionData == null) {
317
- throw new index_js_2.MissingAccrualPositionError(this.parsedMarket.id);
812
+ throw new index_js_3.MissingAccrualPositionError(this.parsedMarket.id);
318
813
  }
319
814
  // Reject a snapshot for another user or market.
320
- (0, index_js_1.validateAccrualPosition)({
815
+ (0, index_js_2.validateAccrualPosition)({
321
816
  positionData,
322
817
  expectedMarketId: this.parsedMarket.id,
323
818
  expectedUser: callbackAddress,
324
819
  });
325
820
  const shares = positionData.supplyShares;
326
821
  if (shares === 0n) {
327
- throw new index_js_2.EmptyBlueSupplyPositionError({
822
+ throw new index_js_3.EmptyBlueSupplyPositionError({
328
823
  market: this.parsedMarket.id,
329
824
  user: callbackAddress,
330
825
  });
@@ -332,7 +827,7 @@ class MorphoBlue {
332
827
  const assets = positionData.supplyAssets;
333
828
  const liquidity = positionData.market.liquidity;
334
829
  if (assets > liquidity) {
335
- throw new index_js_2.InsufficientBlueLiquidityError({
830
+ throw new index_js_3.InsufficientBlueLiquidityError({
336
831
  market: this.parsedMarket.id,
337
832
  assets,
338
833
  liquidity,
@@ -342,7 +837,7 @@ class MorphoBlue {
342
837
  const factory = (0, morpho_ts_1.getChainAddress)(this.chainId, "midnightBlueBuyCallbackFactory");
343
838
  const boundedShares = (0, parse_js_1.parseUint256)("shares", shares);
344
839
  if (boundedShares === 0n) {
345
- throw new index_js_2.NonPositiveInputError("shares", boundedShares);
840
+ throw new index_js_3.NonPositiveInputError("shares", boundedShares);
346
841
  }
347
842
  return {
348
843
  marketParams: this.parsedMarket,
@@ -376,7 +871,7 @@ class MorphoBlue {
376
871
  args: [callbackAddress],
377
872
  });
378
873
  if (!isBlueBuyCallback) {
379
- throw new index_js_2.NotBlueBuyCallbackError(callbackAddress);
874
+ throw new index_js_3.NotBlueBuyCallbackError(callbackAddress);
380
875
  }
381
876
  const [owner, isAuthorized] = await Promise.all([
382
877
  (0, actions_1.readContract)(viemClient, {
@@ -392,14 +887,14 @@ class MorphoBlue {
392
887
  }),
393
888
  ]);
394
889
  if (!(0, viem_1.isAddressEqual)(owner, userAddress)) {
395
- throw new index_js_2.BlueBuyCallbackOwnerMismatchError({
890
+ throw new index_js_3.BlueBuyCallbackOwnerMismatchError({
396
891
  callback: callbackAddress,
397
892
  owner,
398
893
  userAddress,
399
894
  });
400
895
  }
401
896
  if (!isAuthorized) {
402
- throw new index_js_2.BlueBuyCallbackUnauthorizedError({
897
+ throw new index_js_3.BlueBuyCallbackUnauthorizedError({
403
898
  callback: callbackAddress,
404
899
  userAddress,
405
900
  });
@@ -569,10 +1064,10 @@ class MorphoBlue {
569
1064
  const referralFeePct = normalized.referralFeePct;
570
1065
  const hasRepay = repayAssets > 0n || repayShares > 0n;
571
1066
  if (positionData == null) {
572
- throw new index_js_2.MissingAccrualPositionError(this.parsedMarket.id);
1067
+ throw new index_js_3.MissingAccrualPositionError(this.parsedMarket.id);
573
1068
  }
574
1069
  // Reject a snapshot for another user or market.
575
- (0, index_js_1.validateAccrualPosition)({
1070
+ (0, index_js_2.validateAccrualPosition)({
576
1071
  positionData,
577
1072
  expectedMarketId: this.parsedMarket.id,
578
1073
  expectedUser: userAddress,
@@ -605,7 +1100,7 @@ class MorphoBlue {
605
1100
  ? accruedPosition.repay(repayAssets, simulatedRepayShares).position
606
1101
  : accruedPosition;
607
1102
  // Reject collateral withdrawal that would leave unsafe debt.
608
- (0, index_js_1.validatePositionHealthAfterWithdraw)({
1103
+ (0, index_js_2.validatePositionHealthAfterWithdraw)({
609
1104
  positionData: postRepayPosition,
610
1105
  withdrawAmount: collateralAssets,
611
1106
  lltv: this.parsedMarket.lltv,
@@ -692,7 +1187,7 @@ class MorphoBlue {
692
1187
  const lowerCollateralAssets = (0, parse_js_1.parseNonnegative)("collateralAssets", collateralAssets);
693
1188
  const lowerBorrowAssets = (0, parse_js_1.parseNonnegative)("borrowAssets", borrowAssets);
694
1189
  if (collateralAssets === 0n && borrowAssets === 0n) {
695
- throw new index_js_2.NonPositiveInputError("collateralAssets or borrowAssets", 0n);
1190
+ throw new index_js_3.NonPositiveInputError("collateralAssets or borrowAssets", 0n);
696
1191
  }
697
1192
  const mode = (0, supplyCollateralBorrow_internal_js_1.parseBlueSupplyCollateralBorrowMode)({
698
1193
  collateralAssets,
@@ -703,16 +1198,16 @@ class MorphoBlue {
703
1198
  const allocations = (0, supplyCollateralBorrow_internal_js_1.parseBlueSupplyCollateralBorrowAllocations)(this.parsedMarket, mode);
704
1199
  if (borrowAssets > 0n) {
705
1200
  if (positionData == null) {
706
- throw new index_js_2.MissingAccrualPositionError(this.parsedMarket.id);
1201
+ throw new index_js_3.MissingAccrualPositionError(this.parsedMarket.id);
707
1202
  }
708
1203
  // Reject a snapshot for another user or market.
709
- (0, index_js_1.validateAccrualPosition)({
1204
+ (0, index_js_2.validateAccrualPosition)({
710
1205
  positionData,
711
1206
  expectedMarketId: this.parsedMarket.id,
712
1207
  expectedUser: userAddress,
713
1208
  });
714
1209
  // Reject resulting debt above the buffered LLTV.
715
- (0, index_js_1.validatePositionHealth)({
1210
+ (0, index_js_2.validatePositionHealth)({
716
1211
  positionData: positionData.accrueInterest((0, getBlueBundlesV1QuoteTimestamp_js_1.getBlueBundlesV1QuoteTimestamp)({
717
1212
  lastUpdate: positionData.market.lastUpdate,
718
1213
  now: createdAt,
@@ -801,26 +1296,26 @@ class MorphoBlue {
801
1296
  const destinationMarketParams = (0, parse_js_1.parseBlueMarket)(destination.marketParams);
802
1297
  const referralFeePct = normalized.referralFeePct;
803
1298
  if (positionData == null) {
804
- throw new index_js_2.MissingAccrualPositionError(this.parsedMarket.id);
1299
+ throw new index_js_3.MissingAccrualPositionError(this.parsedMarket.id);
805
1300
  }
806
1301
  // Reject a snapshot for another user or market.
807
- (0, index_js_1.validateAccrualPosition)({
1302
+ (0, index_js_2.validateAccrualPosition)({
808
1303
  positionData,
809
1304
  expectedMarketId: this.parsedMarket.id,
810
1305
  expectedUser: userAddress,
811
1306
  });
812
1307
  if (positionData.borrowShares <= 0n) {
813
- throw new index_js_2.NonPositiveInputError("positionData.borrowShares", positionData.borrowShares);
1308
+ throw new index_js_3.NonPositiveInputError("positionData.borrowShares", positionData.borrowShares);
814
1309
  }
815
1310
  const markets = (0, refinance_internal_js_1.parseBlueRefinanceMarkets)({
816
1311
  sourceMarketParams: this.parsedMarket,
817
1312
  destinationMarketParams,
818
1313
  });
819
1314
  if (destination.positionData == null) {
820
- throw new index_js_2.MissingAccrualPositionError(destinationMarketParams.id);
1315
+ throw new index_js_3.MissingAccrualPositionError(destinationMarketParams.id);
821
1316
  }
822
1317
  // Reject a snapshot for another user or market.
823
- (0, index_js_1.validateAccrualPosition)({
1318
+ (0, index_js_2.validateAccrualPosition)({
824
1319
  positionData: destination.positionData,
825
1320
  expectedMarketId: destinationMarketParams.id,
826
1321
  expectedUser: userAddress,
@@ -1042,7 +1537,7 @@ class MorphoBlue {
1042
1537
  */
1043
1538
  getVaultV2BlueReallocations({ reallocationData, options, }) {
1044
1539
  // Reject cross-chain inputs before continuing.
1045
- (0, index_js_1.validateChainId)(reallocationData.chainId, this.chainId);
1540
+ (0, index_js_2.validateChainId)(reallocationData.chainId, this.chainId);
1046
1541
  return reallocationData.computeVaultV2BlueReallocations(this.parsedMarket.id, options);
1047
1542
  }
1048
1543
  }