@morpho-org/morpho-sdk 2.1.1 → 3.0.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 (188) hide show
  1. package/lib/cjs/abis.d.ts +2816 -0
  2. package/lib/cjs/abis.js +1951 -0
  3. package/lib/cjs/actions/index.d.ts +3 -0
  4. package/lib/cjs/actions/marketV1/borrow.js +7 -10
  5. package/lib/cjs/actions/marketV1/buildReallocationActions.d.ts +2 -3
  6. package/lib/cjs/actions/marketV1/buildReallocationActions.js +1 -2
  7. package/lib/cjs/actions/marketV1/repay.d.ts +2 -0
  8. package/lib/cjs/actions/marketV1/repay.js +7 -8
  9. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  10. package/lib/cjs/actions/marketV1/repayWithdrawCollateral.js +9 -10
  11. package/lib/cjs/actions/marketV1/supplyCollateral.d.ts +2 -0
  12. package/lib/cjs/actions/marketV1/supplyCollateral.js +11 -12
  13. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.d.ts +2 -0
  14. package/lib/cjs/actions/marketV1/supplyCollateralBorrow.js +13 -14
  15. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +2 -2
  16. package/lib/cjs/actions/requirements/getRequirementsAction.d.ts +1 -1
  17. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
  18. package/lib/cjs/actions/vaultV1/deposit.d.ts +2 -0
  19. package/lib/cjs/actions/vaultV1/deposit.js +13 -14
  20. package/lib/cjs/actions/vaultV1/migrateToV2.d.ts +2 -0
  21. package/lib/cjs/actions/vaultV1/migrateToV2.js +11 -9
  22. package/lib/cjs/actions/vaultV2/deposit.d.ts +2 -0
  23. package/lib/cjs/actions/vaultV2/deposit.js +13 -14
  24. package/lib/cjs/addresses.d.ts +2 -0
  25. package/lib/cjs/addresses.js +18 -0
  26. package/lib/cjs/augment/AccrualPosition.d.ts +9 -0
  27. package/lib/cjs/augment/AccrualPosition.js +8 -0
  28. package/lib/cjs/augment/AccrualVault.d.ts +8 -0
  29. package/lib/cjs/augment/AccrualVault.js +7 -0
  30. package/lib/cjs/augment/Holding.d.ts +8 -0
  31. package/lib/cjs/augment/Holding.js +7 -0
  32. package/lib/cjs/augment/Market.d.ts +8 -0
  33. package/lib/cjs/augment/Market.js +7 -0
  34. package/lib/cjs/augment/MarketParams.d.ts +8 -0
  35. package/lib/cjs/augment/MarketParams.js +7 -0
  36. package/lib/cjs/augment/Position.d.ts +8 -0
  37. package/lib/cjs/augment/Position.js +7 -0
  38. package/lib/cjs/augment/Token.d.ts +8 -0
  39. package/lib/cjs/augment/Token.js +7 -0
  40. package/lib/cjs/augment/User.d.ts +8 -0
  41. package/lib/cjs/augment/User.js +7 -0
  42. package/lib/cjs/augment/Vault.d.ts +8 -0
  43. package/lib/cjs/augment/Vault.js +7 -0
  44. package/lib/cjs/augment/VaultConfig.d.ts +8 -0
  45. package/lib/cjs/augment/VaultConfig.js +7 -0
  46. package/lib/cjs/augment/VaultMarketAllocation.d.ts +8 -0
  47. package/lib/cjs/augment/VaultMarketAllocation.js +7 -0
  48. package/lib/cjs/augment/VaultMarketConfig.d.ts +8 -0
  49. package/lib/cjs/augment/VaultMarketConfig.js +7 -0
  50. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  51. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.js +8 -0
  52. package/lib/cjs/augment/VaultUser.d.ts +8 -0
  53. package/lib/cjs/augment/VaultUser.js +7 -0
  54. package/lib/cjs/augment.d.ts +14 -0
  55. package/lib/cjs/augment.js +16 -0
  56. package/lib/cjs/bundler/actions.d.ts +555 -0
  57. package/lib/cjs/bundler/actions.js +953 -0
  58. package/lib/cjs/bundler/index.d.ts +2 -0
  59. package/lib/cjs/bundler/index.js +18 -0
  60. package/lib/cjs/bundler/types.d.ts +181 -0
  61. package/lib/cjs/bundler/types.js +2 -0
  62. package/lib/cjs/constants.d.ts +3 -0
  63. package/lib/cjs/constants.js +32 -0
  64. package/lib/cjs/entities/index.d.ts +6 -3
  65. package/lib/cjs/entities/index.js +41 -17
  66. package/lib/cjs/entities/marketV1/marketV1.d.ts +45 -11
  67. package/lib/cjs/entities/marketV1/marketV1.js +27 -12
  68. package/lib/cjs/entities/reallocationData.d.ts +193 -0
  69. package/lib/cjs/entities/reallocationData.js +406 -0
  70. package/lib/cjs/errors.d.ts +2 -0
  71. package/lib/cjs/errors.js +18 -0
  72. package/lib/cjs/fetch.d.ts +1 -0
  73. package/lib/cjs/fetch.js +30 -0
  74. package/lib/cjs/format.d.ts +2 -0
  75. package/lib/cjs/format.js +22 -0
  76. package/lib/cjs/helpers/computeReallocations.d.ts +48 -8
  77. package/lib/cjs/helpers/computeReallocations.js +120 -32
  78. package/lib/cjs/helpers/constant.d.ts +17 -0
  79. package/lib/cjs/helpers/constant.js +30 -1
  80. package/lib/cjs/helpers/index.d.ts +1 -0
  81. package/lib/cjs/helpers/index.js +9 -1
  82. package/lib/cjs/helpers/validate.d.ts +2 -0
  83. package/lib/cjs/helpers/validate.js +14 -2
  84. package/lib/cjs/index.d.ts +0 -1
  85. package/lib/cjs/index.js +0 -1
  86. package/lib/cjs/types/client.d.ts +1 -1
  87. package/lib/cjs/types/error.d.ts +87 -1
  88. package/lib/cjs/types/error.js +119 -1
  89. package/lib/cjs/types/sharedLiquidity.d.ts +43 -3
  90. package/lib/cjs/types.d.ts +3 -0
  91. package/lib/cjs/types.js +17 -0
  92. package/lib/cjs/utils.d.ts +9 -0
  93. package/lib/cjs/utils.js +65 -0
  94. package/lib/esm/abis.d.ts +2816 -0
  95. package/lib/esm/abis.js +1922 -0
  96. package/lib/esm/actions/index.d.ts +3 -0
  97. package/lib/esm/actions/marketV1/borrow.js +2 -5
  98. package/lib/esm/actions/marketV1/buildReallocationActions.d.ts +2 -3
  99. package/lib/esm/actions/marketV1/buildReallocationActions.js +1 -2
  100. package/lib/esm/actions/marketV1/repay.d.ts +2 -0
  101. package/lib/esm/actions/marketV1/repay.js +4 -5
  102. package/lib/esm/actions/marketV1/repayWithdrawCollateral.d.ts +2 -0
  103. package/lib/esm/actions/marketV1/repayWithdrawCollateral.js +4 -5
  104. package/lib/esm/actions/marketV1/supplyCollateral.d.ts +2 -0
  105. package/lib/esm/actions/marketV1/supplyCollateral.js +4 -5
  106. package/lib/esm/actions/marketV1/supplyCollateralBorrow.d.ts +2 -0
  107. package/lib/esm/actions/marketV1/supplyCollateralBorrow.js +4 -5
  108. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +1 -1
  109. package/lib/esm/actions/requirements/getRequirementsAction.d.ts +1 -1
  110. package/lib/esm/actions/requirements/getRequirementsApproval.js +1 -1
  111. package/lib/esm/actions/vaultV1/deposit.d.ts +2 -0
  112. package/lib/esm/actions/vaultV1/deposit.js +3 -4
  113. package/lib/esm/actions/vaultV1/migrateToV2.d.ts +2 -0
  114. package/lib/esm/actions/vaultV1/migrateToV2.js +3 -1
  115. package/lib/esm/actions/vaultV2/deposit.d.ts +2 -0
  116. package/lib/esm/actions/vaultV2/deposit.js +3 -4
  117. package/lib/esm/addresses.d.ts +2 -0
  118. package/lib/esm/addresses.js +1 -0
  119. package/lib/esm/augment/AccrualPosition.d.ts +9 -0
  120. package/lib/esm/augment/AccrualPosition.js +5 -0
  121. package/lib/esm/augment/AccrualVault.d.ts +8 -0
  122. package/lib/esm/augment/AccrualVault.js +4 -0
  123. package/lib/esm/augment/Holding.d.ts +8 -0
  124. package/lib/esm/augment/Holding.js +4 -0
  125. package/lib/esm/augment/Market.d.ts +8 -0
  126. package/lib/esm/augment/Market.js +4 -0
  127. package/lib/esm/augment/MarketParams.d.ts +8 -0
  128. package/lib/esm/augment/MarketParams.js +4 -0
  129. package/lib/esm/augment/Position.d.ts +8 -0
  130. package/lib/esm/augment/Position.js +4 -0
  131. package/lib/esm/augment/Token.d.ts +8 -0
  132. package/lib/esm/augment/Token.js +4 -0
  133. package/lib/esm/augment/User.d.ts +8 -0
  134. package/lib/esm/augment/User.js +4 -0
  135. package/lib/esm/augment/Vault.d.ts +8 -0
  136. package/lib/esm/augment/Vault.js +4 -0
  137. package/lib/esm/augment/VaultConfig.d.ts +8 -0
  138. package/lib/esm/augment/VaultConfig.js +4 -0
  139. package/lib/esm/augment/VaultMarketAllocation.d.ts +8 -0
  140. package/lib/esm/augment/VaultMarketAllocation.js +4 -0
  141. package/lib/esm/augment/VaultMarketConfig.d.ts +8 -0
  142. package/lib/esm/augment/VaultMarketConfig.js +4 -0
  143. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +8 -0
  144. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +5 -0
  145. package/lib/esm/augment/VaultUser.d.ts +8 -0
  146. package/lib/esm/augment/VaultUser.js +4 -0
  147. package/lib/esm/augment.d.ts +14 -0
  148. package/lib/esm/augment.js +14 -0
  149. package/lib/esm/bundler/actions.d.ts +555 -0
  150. package/lib/esm/bundler/actions.js +950 -0
  151. package/lib/esm/bundler/index.d.ts +2 -0
  152. package/lib/esm/bundler/index.js +2 -0
  153. package/lib/esm/bundler/types.d.ts +181 -0
  154. package/lib/esm/bundler/types.js +1 -0
  155. package/lib/esm/constants.d.ts +3 -0
  156. package/lib/esm/constants.js +3 -0
  157. package/lib/esm/entities/index.d.ts +6 -3
  158. package/lib/esm/entities/index.js +5 -3
  159. package/lib/esm/entities/marketV1/marketV1.d.ts +45 -11
  160. package/lib/esm/entities/marketV1/marketV1.js +28 -13
  161. package/lib/esm/entities/reallocationData.d.ts +193 -0
  162. package/lib/esm/entities/reallocationData.js +402 -0
  163. package/lib/esm/errors.d.ts +2 -0
  164. package/lib/esm/errors.js +1 -0
  165. package/lib/esm/fetch.d.ts +1 -0
  166. package/lib/esm/fetch.js +1 -0
  167. package/lib/esm/format.d.ts +2 -0
  168. package/lib/esm/format.js +1 -0
  169. package/lib/esm/helpers/computeReallocations.d.ts +48 -8
  170. package/lib/esm/helpers/computeReallocations.js +119 -31
  171. package/lib/esm/helpers/constant.d.ts +17 -0
  172. package/lib/esm/helpers/constant.js +30 -1
  173. package/lib/esm/helpers/index.d.ts +1 -0
  174. package/lib/esm/helpers/index.js +1 -0
  175. package/lib/esm/helpers/validate.d.ts +2 -0
  176. package/lib/esm/helpers/validate.js +12 -1
  177. package/lib/esm/index.d.ts +0 -1
  178. package/lib/esm/index.js +0 -1
  179. package/lib/esm/types/client.d.ts +1 -1
  180. package/lib/esm/types/error.d.ts +87 -1
  181. package/lib/esm/types/error.js +112 -0
  182. package/lib/esm/types/sharedLiquidity.d.ts +43 -3
  183. package/lib/esm/types.d.ts +3 -0
  184. package/lib/esm/types.js +1 -0
  185. package/lib/esm/utils.d.ts +9 -0
  186. package/lib/esm/utils.js +7 -0
  187. package/package.json +118 -11
  188. package/src/index.ts +0 -1
@@ -0,0 +1,402 @@
1
+ import { _try, AccrualPosition, Market, MathLib, Position, UnknownDataError, Vault, VaultMarketConfig, VaultMarketPublicAllocatorConfig, } from "@morpho-org/blue-sdk";
2
+ import { bigIntComparator } from "@morpho-org/morpho-ts";
3
+ import { DEFAULT_WITHDRAWAL_TARGET_UTILIZATION } from "../helpers/constant.js";
4
+ import { DisabledReallocationMarketError, MissingPublicAllocatorConfigError, UnknownReallocationMarketError, UnknownReallocationPositionError, UnknownReallocationVaultError, UnknownReallocationVaultMarketConfigError, } from "../types/index.js";
5
+ /**
6
+ * Clones a market so simulated interest and liquidity changes never mutate caller input.
7
+ *
8
+ * @internal
9
+ */
10
+ const cloneMarket = (market) => new Market({ ...market });
11
+ /**
12
+ * Clones a market position before simulated supply or withdrawal changes are applied.
13
+ *
14
+ * @internal
15
+ */
16
+ const clonePosition = (position) => new Position({ ...position });
17
+ /**
18
+ * Clones vault state, including queue arrays and public allocator accounting.
19
+ *
20
+ * @internal
21
+ */
22
+ const cloneVault = (vault) => new Vault({
23
+ ...vault,
24
+ pendingTimelock: { ...vault.pendingTimelock },
25
+ pendingGuardian: { ...vault.pendingGuardian },
26
+ supplyQueue: [...vault.supplyQueue],
27
+ withdrawQueue: [...vault.withdrawQueue],
28
+ publicAllocatorConfig: vault.publicAllocatorConfig == null
29
+ ? undefined
30
+ : { ...vault.publicAllocatorConfig },
31
+ });
32
+ /**
33
+ * Clones a vault-market config, including nested public allocator limits.
34
+ *
35
+ * @internal
36
+ */
37
+ const cloneVaultMarketConfig = (config) => new VaultMarketConfig({
38
+ ...config,
39
+ pendingCap: { ...config.pendingCap },
40
+ publicAllocatorConfig: config.publicAllocatorConfig == null
41
+ ? undefined
42
+ : new VaultMarketPublicAllocatorConfig({
43
+ ...config.publicAllocatorConfig,
44
+ }),
45
+ });
46
+ /**
47
+ * Narrow state container for computing public allocator reallocations.
48
+ *
49
+ * @remarks
50
+ * The class owns only the market, vault, position, vault-market-config,
51
+ * and chain data needed by the shared-liquidity algorithm. Constructor inputs
52
+ * are cloned, and simulation steps return cloned `ReallocationData` instances
53
+ * so fetched caller inputs are not mutated.
54
+ *
55
+ * Public records are exposed for inspection and snapshotting only. Treat
56
+ * `markets`, `vaults`, `positions`, and `vaultMarketConfigs` as a read
57
+ * contract keyed by market id or address; use the getters for typed absence
58
+ * errors and use simulation methods to produce updated state.
59
+ */
60
+ export class ReallocationData {
61
+ /** Chain id associated with the fetched reallocation data. */
62
+ chainId;
63
+ /** Markets indexed by market id. */
64
+ markets;
65
+ /** Vaults indexed by vault address. */
66
+ vaults;
67
+ /** Positions indexed by user or vault address, then by market id. */
68
+ positions;
69
+ /** Vault market configs indexed by vault address, then by market id. */
70
+ vaultMarketConfigs;
71
+ /**
72
+ * Creates a cloned reallocation state from fetched market, vault, position,
73
+ * and vault-market-config data.
74
+ *
75
+ * @param input - Reallocation input data fetched at a consistent chain state.
76
+ */
77
+ constructor(input) {
78
+ const { chainId, markets, vaults, positions, vaultMarketConfigs } = input;
79
+ this.chainId = chainId;
80
+ this.markets = {};
81
+ this.vaults = {};
82
+ this.positions = {};
83
+ this.vaultMarketConfigs = {};
84
+ for (const [id, market] of Object.entries(markets ?? {})) {
85
+ this.markets[id] = market == null ? undefined : cloneMarket(market);
86
+ }
87
+ for (const [address, vault] of Object.entries(vaults ?? {})) {
88
+ this.vaults[address] = vault == null ? undefined : cloneVault(vault);
89
+ }
90
+ for (const [user, byMarket] of Object.entries(positions ?? {})) {
91
+ this.positions[user] = {};
92
+ for (const [id, position] of Object.entries(byMarket)) {
93
+ this.positions[user][id] =
94
+ position == null ? undefined : clonePosition(position);
95
+ }
96
+ }
97
+ for (const [vault, byMarket] of Object.entries(vaultMarketConfigs ?? {})) {
98
+ this.vaultMarketConfigs[vault] = {};
99
+ for (const [id, config] of Object.entries(byMarket)) {
100
+ this.vaultMarketConfigs[vault][id] =
101
+ config == null ? undefined : cloneVaultMarketConfig(config);
102
+ }
103
+ }
104
+ }
105
+ /**
106
+ * Creates a deep clone of this reallocation state.
107
+ *
108
+ * @returns A new `ReallocationData` instance with cloned entity objects.
109
+ */
110
+ clone() {
111
+ return new ReallocationData(this);
112
+ }
113
+ forkAliasedState() {
114
+ const data = new ReallocationData({ chainId: this.chainId });
115
+ Object.assign(data.markets, this.markets);
116
+ Object.assign(data.vaults, this.vaults);
117
+ for (const [user, positions] of Object.entries(this.positions)) {
118
+ data.positions[user] = positions;
119
+ }
120
+ for (const [vault, configs] of Object.entries(this.vaultMarketConfigs)) {
121
+ data.vaultMarketConfigs[vault] = configs;
122
+ }
123
+ return data;
124
+ }
125
+ /**
126
+ * Gets a market by id.
127
+ *
128
+ * @param marketId - Market id to read.
129
+ * @returns The cloned market data.
130
+ * @throws {@link UnknownReallocationMarketError} when the market is absent.
131
+ */
132
+ getMarket(marketId) {
133
+ const market = this.markets[marketId];
134
+ if (market == null)
135
+ throw new UnknownReallocationMarketError(marketId);
136
+ return market;
137
+ }
138
+ /**
139
+ * Gets a vault by address.
140
+ *
141
+ * @param vault - Vault address to read.
142
+ * @returns The cloned vault data.
143
+ * @throws {@link UnknownReallocationVaultError} when the vault is absent.
144
+ */
145
+ getVault(vault) {
146
+ const data = this.vaults[vault];
147
+ if (data == null)
148
+ throw new UnknownReallocationVaultError(vault);
149
+ return data;
150
+ }
151
+ /**
152
+ * Gets a raw market position.
153
+ *
154
+ * @param user - Position owner address, usually a MetaMorpho vault.
155
+ * @param marketId - Market id for the position.
156
+ * @returns The cloned position data.
157
+ * @throws {@link UnknownReallocationPositionError} when the position is absent.
158
+ */
159
+ getPosition(user, marketId) {
160
+ const position = this.positions[user]?.[marketId];
161
+ if (position == null)
162
+ throw new UnknownReallocationPositionError(user, marketId);
163
+ return position;
164
+ }
165
+ /**
166
+ * Gets a position wrapped with its market accrual helpers.
167
+ *
168
+ * @param user - Position owner address, usually a MetaMorpho vault.
169
+ * @param marketId - Market id for the position.
170
+ * @returns Accrual-aware position data.
171
+ * @throws {@link UnknownReallocationPositionError} when the position is absent.
172
+ * @throws {@link UnknownReallocationMarketError} when the market is absent.
173
+ */
174
+ getAccrualPosition(user, marketId) {
175
+ return new AccrualPosition(this.getPosition(user, marketId), this.getMarket(marketId));
176
+ }
177
+ /**
178
+ * Gets a vault-market config.
179
+ *
180
+ * @param vault - Vault address.
181
+ * @param marketId - Market id configured by the vault.
182
+ * @returns The cloned vault-market config.
183
+ * @throws {@link UnknownReallocationVaultMarketConfigError} when the config is absent.
184
+ */
185
+ getVaultMarketConfig(vault, marketId) {
186
+ const config = this.vaultMarketConfigs[vault]?.[marketId];
187
+ if (config == null)
188
+ throw new UnknownReallocationVaultMarketConfigError(vault, marketId);
189
+ return config;
190
+ }
191
+ /**
192
+ * Calculates public reallocations that can supply liquidity to `marketId`.
193
+ *
194
+ * @remarks
195
+ * The algorithm repeatedly chooses the single largest currently available
196
+ * source-market withdrawal across reallocatable vaults, applies that
197
+ * withdrawal to a cloned state, and repeats until no valid withdrawal remains.
198
+ *
199
+ * Pass `options.timestamp` to evaluate market interest and pending public
200
+ * allocator caps at the same block as the fetched reallocation data.
201
+ * This method does not add the legacy one-hour delay margin that
202
+ * `SimulationState.getMarketPublicReallocations` applied before measuring
203
+ * target-market vault headroom. If a transaction may land later than the
204
+ * fetched block, pass a future `timestamp` or reserve your own headroom so
205
+ * interest accrued before inclusion does not make `reallocateTo` exceed the
206
+ * target market cap.
207
+ * Returned `data` normalizes `vault.publicAllocatorConfig.accruedFee` to the
208
+ * on-chain `reallocateTo` fee semantics: one fee charge per vault with at
209
+ * least one computed withdrawal.
210
+ *
211
+ * @param marketId - Target market to supply with shared liquidity.
212
+ * @param options - Optional allocator discovery options.
213
+ * @returns Computed source-market withdrawals and the post-reallocation state.
214
+ * @throws {@link UnknownReallocationMarketError} when the target market is absent.
215
+ * @example
216
+ * ```ts
217
+ * import { createPublicClient, http } from "viem";
218
+ * import { mainnet } from "viem/chains";
219
+ * import { markets, vaults } from "@morpho-org/morpho-test";
220
+ * import {
221
+ * morphoViemExtension,
222
+ * type PublicReallocation,
223
+ * } from "@morpho-org/morpho-sdk";
224
+ * import type { ReallocationData } from "@morpho-org/morpho-sdk/entities";
225
+ *
226
+ * const client = createPublicClient({
227
+ * chain: mainnet,
228
+ * transport: http(),
229
+ * }).extend(morphoViemExtension());
230
+ *
231
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
232
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
233
+ * const block = await client.getBlock();
234
+ * const reallocationData = await market.getReallocationData({
235
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
236
+ * block: { number: block.number, timestamp: block.timestamp },
237
+ * });
238
+ *
239
+ * const result: {
240
+ * withdrawals: readonly PublicReallocation[];
241
+ * data: ReallocationData;
242
+ * } = reallocationData.getMarketPublicReallocations(marketParams.id, {
243
+ * timestamp: block.timestamp,
244
+ * });
245
+ * ```
246
+ */
247
+ getMarketPublicReallocations(marketId, options = {}) {
248
+ const { enabled = true, timestamp, reallocatableVaults, defaultMaxWithdrawalUtilization = DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, maxWithdrawalUtilization = {}, } = options;
249
+ if (!enabled)
250
+ return { withdrawals: [], data: this };
251
+ const accrualTimestamp = BigInt(timestamp ?? this.getMarket(marketId).lastUpdate);
252
+ const configuredVaults = Object.keys(this.vaultMarketConfigs);
253
+ const vaultKeyByLower = new Map(configuredVaults.map((vault) => [vault.toLowerCase(), vault]));
254
+ const vaults = Array.from(new Set((reallocatableVaults ?? configuredVaults)
255
+ .map((vault) => vaultKeyByLower.get(vault.toLowerCase()))
256
+ .filter((vault) => vault != null))).filter((vault) => {
257
+ const vaultMarketConfig = this.vaultMarketConfigs[vault]?.[marketId];
258
+ return (vaultMarketConfig?.enabled === true &&
259
+ this.vaults[vault]?.publicAllocatorConfig != null);
260
+ });
261
+ let data = this.clone();
262
+ const withdrawals = [];
263
+ while (true) {
264
+ const vaultWithdrawals = vaults
265
+ .map((vaultAddress) => data.getLargestVaultWithdrawal({
266
+ vault: vaultAddress,
267
+ marketId,
268
+ withdrawals,
269
+ defaultMaxWithdrawalUtilization,
270
+ maxWithdrawalUtilization,
271
+ timestamp: accrualTimestamp,
272
+ }))
273
+ .filter((withdrawal) => withdrawal?.largestWithdrawal != null)
274
+ .sort(bigIntComparator((withdrawal) => withdrawal.largestWithdrawal.assets, "desc"));
275
+ const largestVaultWithdrawal = vaultWithdrawals[0];
276
+ if (largestVaultWithdrawal?.largestWithdrawal == null) {
277
+ const withdrawalCountsByVault = new Map();
278
+ for (const { vault } of withdrawals) {
279
+ withdrawalCountsByVault.set(vault, (withdrawalCountsByVault.get(vault) ?? 0) + 1);
280
+ }
281
+ for (const [vault, count] of withdrawalCountsByVault) {
282
+ if (count <= 1)
283
+ continue;
284
+ const vaultPublicAllocatorConfig = data.getVault(vault).publicAllocatorConfig;
285
+ if (vaultPublicAllocatorConfig == null)
286
+ throw new MissingPublicAllocatorConfigError(vault);
287
+ vaultPublicAllocatorConfig.accruedFee -=
288
+ BigInt(count - 1) * vaultPublicAllocatorConfig.fee;
289
+ }
290
+ return { withdrawals, data };
291
+ }
292
+ const { vault, largestWithdrawal } = largestVaultWithdrawal;
293
+ withdrawals.push({ ...largestWithdrawal, vault });
294
+ data = data.applyPublicReallocation({
295
+ vault,
296
+ supplyMarketId: marketId,
297
+ withdrawal: largestWithdrawal,
298
+ timestamp: accrualTimestamp,
299
+ });
300
+ }
301
+ }
302
+ /**
303
+ * Gets the largest currently valid source-market withdrawal for a vault.
304
+ *
305
+ * @param params - Candidate vault, target market, prior withdrawals, and allocator limits.
306
+ * @returns The largest withdrawal candidate, or `undefined` if required data is missing.
307
+ *
308
+ * @internal
309
+ */
310
+ getLargestVaultWithdrawal({ vault, marketId, withdrawals, defaultMaxWithdrawalUtilization, maxWithdrawalUtilization, timestamp, }) {
311
+ return _try(() => {
312
+ const { cap, pendingCap, publicAllocatorConfig } = this.getVaultMarketConfig(vault, marketId);
313
+ const validCap = pendingCap.validAt >= timestamp
314
+ ? MathLib.min(pendingCap.value, cap)
315
+ : cap;
316
+ const suppliable = MathLib.zeroFloorSub(validCap, this.getAccrualPosition(vault, marketId).accrueInterest(timestamp)
317
+ .supplyAssets);
318
+ const marketWithdrawals = this.getVault(vault)
319
+ .withdrawQueue.filter((srcMarketId) => srcMarketId !== marketId &&
320
+ !withdrawals.some((withdrawal) => withdrawal.id === srcMarketId && withdrawal.vault === vault))
321
+ .map((srcMarketId) => {
322
+ const withdrawal = _try(() => {
323
+ const srcPosition = this.getAccrualPosition(vault, srcMarketId).accrueInterest(timestamp);
324
+ const targetUtilizationLiquidity = srcPosition.market.getWithdrawToUtilization(maxWithdrawalUtilization[srcMarketId] ??
325
+ defaultMaxWithdrawalUtilization);
326
+ const srcConfig = this.getVaultMarketConfig(vault, srcMarketId);
327
+ if (!srcConfig.enabled)
328
+ return { id: srcMarketId, assets: 0n };
329
+ return {
330
+ id: srcMarketId,
331
+ assets: MathLib.min(srcPosition.supplyAssets, targetUtilizationLiquidity, suppliable, publicAllocatorConfig?.maxIn ?? 0n, srcConfig.publicAllocatorConfig?.maxOut ?? 0n),
332
+ };
333
+ }, UnknownDataError);
334
+ return withdrawal ?? { id: srcMarketId, assets: 0n };
335
+ })
336
+ .filter(({ assets }) => assets > 0n)
337
+ .sort(bigIntComparator(({ assets }) => assets, "desc"));
338
+ return { vault, largestWithdrawal: marketWithdrawals[0] };
339
+ }, UnknownDataError);
340
+ }
341
+ /**
342
+ * Applies one public allocator withdrawal and corresponding target-market supply.
343
+ *
344
+ * @param vault - Vault performing the public reallocation.
345
+ * @param supplyMarketId - Target market that receives the withdrawn assets.
346
+ * @param withdrawal - Source market id and asset amount to withdraw.
347
+ * @param timestamp - Timestamp used to accrue source and target positions.
348
+ * @returns A cloned state after applying the simulated reallocation.
349
+ * @throws {@link MissingPublicAllocatorConfigError} when the vault allocator config is absent.
350
+ * @throws {@link UnknownReallocationVaultMarketConfigError} when source or target allocator limits are absent.
351
+ *
352
+ * @internal
353
+ */
354
+ applyPublicReallocation({ vault, supplyMarketId, withdrawal, timestamp, }) {
355
+ const data = this.forkAliasedState();
356
+ data.vaults[vault] = cloneVault(this.getVault(vault));
357
+ data.positions[vault] = { ...(this.positions[vault] ?? {}) };
358
+ data.vaultMarketConfigs[vault] = {
359
+ ...(this.vaultMarketConfigs[vault] ?? {}),
360
+ };
361
+ const vaultPublicAllocatorConfig = data.getVault(vault).publicAllocatorConfig;
362
+ if (vaultPublicAllocatorConfig == null)
363
+ throw new MissingPublicAllocatorConfigError(vault);
364
+ vaultPublicAllocatorConfig.accruedFee += vaultPublicAllocatorConfig.fee;
365
+ const sourceConfig = cloneVaultMarketConfig(this.getVaultMarketConfig(vault, withdrawal.id));
366
+ data.vaultMarketConfigs[vault][withdrawal.id] = sourceConfig;
367
+ if (!sourceConfig.enabled)
368
+ throw new DisabledReallocationMarketError(vault, withdrawal.id);
369
+ const sourcePublicAllocatorConfig = sourceConfig.publicAllocatorConfig;
370
+ if (sourcePublicAllocatorConfig == null)
371
+ throw new UnknownReallocationVaultMarketConfigError(vault, withdrawal.id);
372
+ const supplyConfig = supplyMarketId === withdrawal.id
373
+ ? sourceConfig
374
+ : cloneVaultMarketConfig(this.getVaultMarketConfig(vault, supplyMarketId));
375
+ data.vaultMarketConfigs[vault][supplyMarketId] = supplyConfig;
376
+ if (!supplyConfig.enabled)
377
+ throw new DisabledReallocationMarketError(vault, supplyMarketId);
378
+ const supplyPublicAllocatorConfig = supplyConfig.publicAllocatorConfig;
379
+ if (supplyPublicAllocatorConfig == null)
380
+ throw new UnknownReallocationVaultMarketConfigError(vault, supplyMarketId);
381
+ sourcePublicAllocatorConfig.maxIn += withdrawal.assets;
382
+ sourcePublicAllocatorConfig.maxOut -= withdrawal.assets;
383
+ supplyPublicAllocatorConfig.maxIn -= withdrawal.assets;
384
+ supplyPublicAllocatorConfig.maxOut += withdrawal.assets;
385
+ const { position: sourcePosition } = data
386
+ .getAccrualPosition(vault, withdrawal.id)
387
+ .withdraw(withdrawal.assets, 0n, timestamp);
388
+ data.markets[withdrawal.id] = cloneMarket(sourcePosition.market);
389
+ data.positions[vault] ??= {};
390
+ data.positions[vault][withdrawal.id] = clonePosition(sourcePosition);
391
+ const { position: supplyPosition } = data
392
+ .getAccrualPosition(vault, supplyMarketId)
393
+ .supply(withdrawal.assets, 0n, timestamp);
394
+ data.markets[supplyMarketId] = cloneMarket(supplyPosition.market);
395
+ data.positions[vault][supplyMarketId] = clonePosition(supplyPosition);
396
+ void _try(() => {
397
+ const vaultData = data.getVault(vault);
398
+ vaultData.totalAssets = vaultData.withdrawQueue.reduce((total, marketId) => total + data.getAccrualPosition(vault, marketId).supplyAssets, 0n);
399
+ }, UnknownDataError);
400
+ return data;
401
+ }
402
+ }
@@ -0,0 +1,2 @@
1
+ export type { ErrorClass } from "@morpho-org/blue-sdk";
2
+ export { _try, BlueErrors, InvalidMarketParamsError, UnknownDataError, UnknownFactory, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
@@ -0,0 +1 @@
1
+ export { _try, BlueErrors, InvalidMarketParamsError, UnknownDataError, UnknownFactory, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
@@ -0,0 +1 @@
1
+ export { fetchAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket, fetchMarketParams, fetchPosition, fetchPreLiquidationParams, fetchPreLiquidationPosition, fetchToken, fetchUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultMarketPublicAllocatorConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
@@ -0,0 +1 @@
1
+ export { fetchAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket, fetchMarketParams, fetchPosition, fetchPreLiquidationParams, fetchPreLiquidationPosition, fetchToken, fetchUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultMarketPublicAllocatorConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
@@ -0,0 +1,2 @@
1
+ export type { LocaleParts } from "@morpho-org/morpho-ts";
2
+ export { BaseFormatter, CommasFormatter, CommonFormatter, convertNumStrFromEffectiveTo, convertNumStrToLocal, createFormat, Format, format, formatEnumeration, formatLongString, formatUnion, getEffectiveLocale, getEnUSNumberToLocalParts, getLocaleSymbols, HexFormatter, NumberFormatter, PercentFormatter, ShortFormatter, } from "@morpho-org/morpho-ts";
@@ -0,0 +1 @@
1
+ export { BaseFormatter, CommasFormatter, CommonFormatter, convertNumStrFromEffectiveTo, convertNumStrToLocal, createFormat, Format, format, formatEnumeration, formatLongString, formatUnion, getEffectiveLocale, getEnUSNumberToLocalParts, getLocaleSymbols, HexFormatter, NumberFormatter, PercentFormatter, ShortFormatter, } from "@morpho-org/morpho-ts";
@@ -1,23 +1,63 @@
1
1
  import { type MarketId } from "@morpho-org/blue-sdk";
2
- import type { SimulationState } from "@morpho-org/simulation-sdk";
2
+ import type { ReallocationData } from "../entities/reallocationData.js";
3
3
  import { type ReallocationComputeOptions, type VaultReallocation } from "../types/index.js";
4
4
  /**
5
5
  * Computes vault reallocations for a borrow operation on a target market.
6
6
  *
7
- * Replicates the shared liquidity algorithm from `populateSubBundle` in
8
- * `@morpho-org/bundler-sdk-viem`. First attempts "friendly" reallocations
9
- * respecting withdrawal utilization targets, then falls back to aggressive
10
- * reallocations (100% withdrawal utilization) if liquidity is still insufficient.
7
+ * First attempts "friendly" reallocations respecting withdrawal utilization
8
+ * targets, then falls back to aggressive reallocations (100% withdrawal
9
+ * utilization) if liquidity is still insufficient.
11
10
  *
12
- * @param params.reallocationData - The simulation state containing market, vault, and position data.
11
+ * @remarks Pass `options.timestamp` from the same block used to fetch `reallocationData`; when omitted, market accrual falls back to the target market's `lastUpdate`, which can diverge from the source rows' fetch block. Per-market `maxWithdrawalUtilization` overrides apply only to phase 1; phase 2 forces 100% utilization on every source market.
12
+ * @param params.reallocationData - The local state containing market, vault, and position data.
13
13
  * @param params.marketId - The target market to reallocate liquidity into.
14
14
  * @param params.borrowAmount - The intended borrow amount (used to compute post-borrow utilization).
15
15
  * @param params.options - Optional reallocation computation options.
16
16
  * @returns Array of vault reallocations, sorted with withdrawals in ascending market id order.
17
- * @throws {InsufficientSharedLiquidityError} If shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
17
+ * @throws {InsufficientSharedLiquidityError} when shared liquidity cannot cover the borrow shortfall on the target market — preventing fee-bearing reallocations from being attached to a borrow that would still revert onchain.
18
+ * @throws {MissingPublicAllocatorConfigError} when a selected vault is missing its public allocator config.
19
+ * @example
20
+ * ```ts
21
+ * import { createPublicClient, http, parseUnits } from "viem";
22
+ * import { mainnet } from "viem/chains";
23
+ * import { markets, vaults } from "@morpho-org/morpho-test";
24
+ * import {
25
+ * computeReallocations,
26
+ * morphoViemExtension,
27
+ * } from "@morpho-org/morpho-sdk";
28
+ *
29
+ * const client = createPublicClient({
30
+ * chain: mainnet,
31
+ * transport: http(),
32
+ * }).extend(morphoViemExtension());
33
+ *
34
+ * const userAddress = "0x000000000000000000000000000000000000dEaD";
35
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
36
+ * const market = client.morpho.marketV1(marketParams, mainnet.id);
37
+ * const block = await client.getBlock();
38
+ * const reallocationData = await market.getReallocationData({
39
+ * vaultAddresses: [vaults[mainnet.id].steakUsdc.address],
40
+ * block: { number: block.number, timestamp: block.timestamp },
41
+ * });
42
+ * const borrowAmount = parseUnits("1000", 6);
43
+ * const reallocations = computeReallocations({
44
+ * reallocationData,
45
+ * marketId: marketParams.id,
46
+ * borrowAmount,
47
+ * options: { timestamp: block.timestamp },
48
+ * });
49
+ * const positionData = await market.getPositionData(userAddress);
50
+ * const borrow = market.borrow({
51
+ * userAddress,
52
+ * amount: borrowAmount,
53
+ * positionData,
54
+ * reallocations,
55
+ * });
56
+ * // borrow.buildTx() includes any required PublicAllocator reallocations.
57
+ * ```
18
58
  */
19
59
  export declare const computeReallocations: ({ reallocationData: data, marketId, borrowAmount, options, }: {
20
- readonly reallocationData: SimulationState;
60
+ readonly reallocationData: ReallocationData;
21
61
  readonly marketId: MarketId;
22
62
  readonly borrowAmount: bigint;
23
63
  readonly options?: ReallocationComputeOptions;