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