@morpho-org/morpho-sdk 5.4.1 → 5.6.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 (140) hide show
  1. package/README.md +23 -7
  2. package/lib/cjs/abis.d.ts +314 -1
  3. package/lib/cjs/abis.js +169 -1
  4. package/lib/cjs/actions/blue/borrow.d.ts +21 -15
  5. package/lib/cjs/actions/blue/borrow.js +25 -18
  6. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +1 -1
  7. package/lib/cjs/actions/blue/buildAssetFundingActions.js +1 -1
  8. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +62 -19
  9. package/lib/cjs/actions/blue/buildReallocationActions.js +123 -27
  10. package/lib/cjs/actions/blue/refinance.d.ts +14 -7
  11. package/lib/cjs/actions/blue/refinance.js +18 -10
  12. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  13. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +39 -23
  14. package/lib/cjs/actions/blue/withdraw.d.ts +20 -13
  15. package/lib/cjs/actions/blue/withdraw.js +23 -18
  16. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  17. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +9 -2
  18. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  19. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +131 -0
  20. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  21. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  22. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +3 -2
  23. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -3
  24. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  25. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +91 -0
  26. package/lib/cjs/actions/signatures/index.d.ts +1 -0
  27. package/lib/cjs/actions/signatures/index.js +1 -0
  28. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +54 -0
  29. package/lib/cjs/actions/vaultV1/inKindRedeem.js +96 -0
  30. package/lib/cjs/actions/vaultV1/index.d.ts +1 -0
  31. package/lib/cjs/actions/vaultV1/index.js +1 -0
  32. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +56 -0
  33. package/lib/cjs/actions/vaultV2/inKindRedeem.js +97 -0
  34. package/lib/cjs/actions/vaultV2/index.d.ts +1 -0
  35. package/lib/cjs/actions/vaultV2/index.js +1 -0
  36. package/lib/cjs/bundler/actions.d.ts +118 -2
  37. package/lib/cjs/bundler/actions.js +212 -6
  38. package/lib/cjs/bundler/types.d.ts +20 -0
  39. package/lib/cjs/constants.d.ts +1 -1
  40. package/lib/cjs/constants.js +3 -1
  41. package/lib/cjs/entities/blue/blue.d.ts +365 -76
  42. package/lib/cjs/entities/blue/blue.js +285 -52
  43. package/lib/cjs/entities/index.d.ts +2 -1
  44. package/lib/cjs/entities/index.js +6 -3
  45. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +82 -4
  46. package/lib/cjs/entities/vaultV1/vaultV1.js +164 -0
  47. package/lib/cjs/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +41 -17
  48. package/lib/cjs/entities/{reallocationData.js → vaultV1ReallocationData.js} +30 -18
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +89 -3
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +181 -0
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +511 -0
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1311 -0
  53. package/lib/{esm/helpers/computeReallocations.d.ts → cjs/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  54. package/lib/cjs/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +27 -13
  55. package/lib/cjs/helpers/constant.d.ts +5 -3
  56. package/lib/cjs/helpers/constant.js +6 -4
  57. package/lib/cjs/helpers/index.d.ts +3 -2
  58. package/lib/cjs/helpers/index.js +8 -3
  59. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  60. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +73 -0
  61. package/lib/cjs/helpers/validate.d.ts +31 -15
  62. package/lib/cjs/helpers/validate.js +140 -27
  63. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  64. package/lib/cjs/helpers/validateRequirementSpender.js +2 -1
  65. package/lib/cjs/types/action.d.ts +33 -1
  66. package/lib/cjs/types/error.d.ts +363 -5
  67. package/lib/cjs/types/error.js +455 -6
  68. package/lib/cjs/types/sharedLiquidity.d.ts +72 -8
  69. package/lib/cjs/utils.d.ts +2 -2
  70. package/lib/cjs/utils.js +6 -4
  71. package/lib/esm/abis.d.ts +314 -1
  72. package/lib/esm/abis.js +167 -1
  73. package/lib/esm/actions/blue/borrow.d.ts +21 -15
  74. package/lib/esm/actions/blue/borrow.js +26 -19
  75. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +1 -1
  76. package/lib/esm/actions/blue/buildAssetFundingActions.js +1 -1
  77. package/lib/esm/actions/blue/buildReallocationActions.d.ts +62 -19
  78. package/lib/esm/actions/blue/buildReallocationActions.js +119 -25
  79. package/lib/esm/actions/blue/refinance.d.ts +14 -7
  80. package/lib/esm/actions/blue/refinance.js +19 -11
  81. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  82. package/lib/esm/actions/blue/supplyCollateralBorrow.js +40 -24
  83. package/lib/esm/actions/blue/withdraw.d.ts +20 -13
  84. package/lib/esm/actions/blue/withdraw.js +24 -19
  85. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  86. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +9 -2
  87. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  88. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +127 -0
  89. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  90. package/lib/esm/actions/requirements/encode/index.js +1 -0
  91. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +3 -2
  92. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -3
  93. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  94. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +87 -0
  95. package/lib/esm/actions/signatures/index.d.ts +1 -0
  96. package/lib/esm/actions/signatures/index.js +1 -0
  97. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +54 -0
  98. package/lib/esm/actions/vaultV1/inKindRedeem.js +92 -0
  99. package/lib/esm/actions/vaultV1/index.d.ts +1 -0
  100. package/lib/esm/actions/vaultV1/index.js +1 -0
  101. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +56 -0
  102. package/lib/esm/actions/vaultV2/inKindRedeem.js +93 -0
  103. package/lib/esm/actions/vaultV2/index.d.ts +1 -0
  104. package/lib/esm/actions/vaultV2/index.js +1 -0
  105. package/lib/esm/bundler/actions.d.ts +118 -2
  106. package/lib/esm/bundler/actions.js +215 -9
  107. package/lib/esm/bundler/types.d.ts +20 -0
  108. package/lib/esm/constants.d.ts +1 -1
  109. package/lib/esm/constants.js +1 -1
  110. package/lib/esm/entities/blue/blue.d.ts +362 -73
  111. package/lib/esm/entities/blue/blue.js +288 -55
  112. package/lib/esm/entities/index.d.ts +2 -1
  113. package/lib/esm/entities/index.js +2 -1
  114. package/lib/esm/entities/vaultV1/vaultV1.d.ts +80 -2
  115. package/lib/esm/entities/vaultV1/vaultV1.js +170 -6
  116. package/lib/esm/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +41 -17
  117. package/lib/esm/entities/{reallocationData.js → vaultV1ReallocationData.js} +33 -16
  118. package/lib/esm/entities/vaultV2/vaultV2.d.ts +88 -2
  119. package/lib/esm/entities/vaultV2/vaultV2.js +187 -6
  120. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +511 -0
  121. package/lib/esm/entities/vaultV2BlueReallocationData.js +1307 -0
  122. package/lib/{cjs/helpers/computeReallocations.d.ts → esm/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  123. package/lib/esm/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +25 -11
  124. package/lib/esm/helpers/constant.d.ts +5 -3
  125. package/lib/esm/helpers/constant.js +5 -3
  126. package/lib/esm/helpers/index.d.ts +3 -2
  127. package/lib/esm/helpers/index.js +3 -2
  128. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  129. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +70 -0
  130. package/lib/esm/helpers/validate.d.ts +31 -15
  131. package/lib/esm/helpers/validate.js +141 -30
  132. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  133. package/lib/esm/helpers/validateRequirementSpender.js +2 -1
  134. package/lib/esm/types/action.d.ts +33 -1
  135. package/lib/esm/types/error.d.ts +363 -5
  136. package/lib/esm/types/error.js +428 -4
  137. package/lib/esm/types/sharedLiquidity.d.ts +72 -8
  138. package/lib/esm/utils.d.ts +2 -2
  139. package/lib/esm/utils.js +2 -2
  140. package/package.json +9 -11
@@ -0,0 +1,1307 @@
1
+ import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMarketV1Adapter, AccrualVaultV2MorphoMarketV1AdapterV2, AccrualVaultV2MorphoVaultV1Adapter, Market, MarketUtils, MathLib, UnsupportedVaultV2AdapterError, VaultV2BlueMarketPublicAllocatorConfig, VaultV2BluePublicAllocatorConfig, VaultV2BluePublicAllocatorConfigUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
2
+ import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
3
+ import { isAddressEqual } from "viem";
4
+ import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
5
+ import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
6
+ /** Creates isolated transaction-scoped state for one simulation. @internal */
7
+ const createSimulationContext = () => ({
8
+ donatedPenaltyAssets: {},
9
+ firstTotalAssets: {},
10
+ });
11
+ /**
12
+ * Finds an address key without changing its supplied casing.
13
+ *
14
+ * @param record - Address-keyed record to search.
15
+ * @param address - Address to match case-insensitively.
16
+ * @returns The stored key, or `undefined` when no address matches.
17
+ * @internal
18
+ */
19
+ const findAddressKey = (record, address) => {
20
+ if (Object.hasOwn(record, address))
21
+ return address;
22
+ return Object.keys(record).find((key) => isAddressEqual(key, address));
23
+ };
24
+ /**
25
+ * Returns cached allocation ids for one adapter-market pair.
26
+ *
27
+ * @param cache - Per-planning-call adapter id cache.
28
+ * @param adapter - Adapter that derives the allocation ids.
29
+ * @param market - Market whose params identify the allocations.
30
+ * @returns The adapter, collateral, and adapter-market cap ids.
31
+ * @internal
32
+ */
33
+ // biome-ignore lint/complexity/useMaxParams: cache lookup requires both adapter and market identity.
34
+ const getAdapterIds = (cache, adapter, market) => {
35
+ const key = `${adapter.address}:${market.id}`;
36
+ const cached = cache.get(key);
37
+ if (cached != null)
38
+ return cached;
39
+ const ids = adapter.ids(market.params);
40
+ cache.set(key, ids);
41
+ return ids;
42
+ };
43
+ const resolveMaxWithdrawalUtilization = (value) => {
44
+ const utilization = value ?? DEFAULT_WITHDRAWAL_TARGET_UTILIZATION;
45
+ if (utilization < 0n)
46
+ throw new NegativeInputError("maxWithdrawalUtilization", utilization);
47
+ if (utilization > MathLib.WAD)
48
+ throw new InputExceedsMaxError({
49
+ field: "maxWithdrawalUtilization",
50
+ value: utilization,
51
+ max: MathLib.WAD,
52
+ });
53
+ return utilization;
54
+ };
55
+ const resolveMaxPenalty = (value) => {
56
+ const penalty = value ?? DEFAULT_MAX_REALLOCATION_PENALTY;
57
+ if (penalty < 0n)
58
+ throw new NegativeInputError("maxPenalty", penalty);
59
+ if (penalty > MAX_REALLOCATION_PENALTY)
60
+ throw new InputExceedsMaxError({
61
+ field: "maxPenalty",
62
+ value: penalty,
63
+ max: MAX_REALLOCATION_PENALTY,
64
+ });
65
+ return penalty;
66
+ };
67
+ const getCanonicalMarket = (markets, market) => (markets[market.id] ??= new Market({ ...market }));
68
+ const clonePosition = (position, markets) => new AccrualPosition(position, getCanonicalMarket(markets, position.market));
69
+ const cloneAccrualVault = (vault, markets) => new AccrualVault({
70
+ ...vault,
71
+ pendingTimelock: { ...vault.pendingTimelock },
72
+ pendingGuardian: { ...vault.pendingGuardian },
73
+ supplyQueue: [...vault.supplyQueue],
74
+ publicAllocatorConfig: vault.publicAllocatorConfig == null
75
+ ? undefined
76
+ : { ...vault.publicAllocatorConfig },
77
+ }, [...vault.allocations.values()].map(({ config, position }) => ({
78
+ config: {
79
+ ...config,
80
+ pendingCap: { ...config.pendingCap },
81
+ publicAllocatorConfig: config.publicAllocatorConfig == null
82
+ ? undefined
83
+ : { ...config.publicAllocatorConfig },
84
+ },
85
+ position: clonePosition(position, markets),
86
+ })));
87
+ const cloneAdapter = (adapter, markets) => {
88
+ const base = {
89
+ address: adapter.address,
90
+ parentVault: adapter.parentVault,
91
+ skimRecipient: adapter.skimRecipient,
92
+ };
93
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)
94
+ return new AccrualVaultV2MorphoMarketV1AdapterV2({
95
+ ...base,
96
+ marketIds: [...adapter.marketIds],
97
+ adaptiveCurveIrm: adapter.adaptiveCurveIrm,
98
+ supplyShares: { ...adapter.supplyShares },
99
+ },
100
+ // V2 adapters can retain the canonical instance directly, so every
101
+ // adapter observes the same global Morpho market state.
102
+ adapter.markets.map((market) => getCanonicalMarket(markets, market)));
103
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter)
104
+ return new AccrualVaultV2MorphoMarketV1Adapter({ ...base, marketParamsList: [...adapter.marketParamsList] }, adapter.positions.map((position) => clonePosition(position, markets)));
105
+ if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter)
106
+ return new AccrualVaultV2MorphoVaultV1Adapter({ ...base, morphoVaultV1: adapter.morphoVaultV1 }, cloneAccrualVault(adapter.accrualVaultV1, markets), adapter.shares);
107
+ throw new UnsupportedVaultV2AdapterError(adapter.address);
108
+ };
109
+ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
110
+ const adapters = vault.accrualAdapters.map((adapter) => adapterKeysToClone == null ||
111
+ adapterKeysToClone.has(adapter.address.toLowerCase())
112
+ ? cloneAdapter(adapter, markets)
113
+ : adapter);
114
+ const liquidityAdapter = vault.accrualLiquidityAdapter == null
115
+ ? undefined
116
+ : (adapters.find((adapter) => isAddressEqual(adapter.address, vault.accrualLiquidityAdapter.address)) ??
117
+ (adapterKeysToClone == null ||
118
+ adapterKeysToClone.has(vault.accrualLiquidityAdapter.address.toLowerCase())
119
+ ? cloneAdapter(vault.accrualLiquidityAdapter, markets)
120
+ : vault.accrualLiquidityAdapter));
121
+ return new AccrualVaultV2({
122
+ ...vault,
123
+ liquidityAllocations: vault.liquidityAllocations?.map((allocation) => ({
124
+ ...allocation,
125
+ })),
126
+ }, liquidityAdapter, adapters, vault.assetBalance, { ...vault.forceDeallocatePenalties });
127
+ };
128
+ /**
129
+ * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
130
+ *
131
+ * Constructor inputs are cloned. Every simulated reallocation returns a new
132
+ * instance. Planning keeps the transaction-scoped `firstTotalAssets`
133
+ * denominator outside the durable snapshot while applying reallocations in
134
+ * contract order. Penalty donations update simulated vault accounting but are
135
+ * excluded from same-plan idle liquidity so round-up dust cannot create
136
+ * self-replenishing candidates.
137
+ * Address keys and values retain their supplied casing; lookups compare them
138
+ * case-insensitively.
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * import { markets } from "@morpho-org/morpho-test";
143
+ * import { createPublicClient, http } from "viem";
144
+ * import { mainnet } from "viem/chains";
145
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
146
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
147
+ *
148
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
149
+ * .extend(morphoViemExtension());
150
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
151
+ * const market = client.morpho.blue(marketParams, mainnet.id);
152
+ * const block = await client.getBlock();
153
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
154
+ * const data: VaultV2BlueReallocationData =
155
+ * await market.getVaultV2BlueReallocationData({
156
+ * vaultAddresses: [keyrockUsdcVaultV2],
157
+ * block: { number: block.number, timestamp: block.timestamp },
158
+ * });
159
+ * ```
160
+ */
161
+ export class VaultV2BlueReallocationData {
162
+ /** Mutable market state used only by cloned simulation transitions. */
163
+ mutableMarkets;
164
+ /** Mutable vault state used only by cloned simulation transitions. */
165
+ mutableVaults;
166
+ /** Mutable allocation state used only by cloned simulation transitions. */
167
+ mutableAllocations;
168
+ /** Chain id associated with this snapshot. */
169
+ chainId;
170
+ /** Markets indexed by market id. */
171
+ markets;
172
+ /** Vault V2 entities indexed by address. */
173
+ vaults;
174
+ /** Vault cap state indexed by vault and derived allocation id. */
175
+ allocations;
176
+ /** Vault-wide allocator configuration indexed by vault. */
177
+ publicAllocatorConfigs;
178
+ /** BluePublicAllocator-active adapters indexed by vault address, preserving vault and adapter casing. */
179
+ activeAdapters;
180
+ /** Adapter-market allocator configuration indexed by vault and market-params id. */
181
+ marketPublicAllocatorConfigs;
182
+ /**
183
+ * Creates a cloned Vault V2 reallocation snapshot.
184
+ *
185
+ * @param input - State fetched at one consistent block.
186
+ * @throws {UnsupportedVaultV2AdapterError} when a vault contains an unsupported adapter type.
187
+ */
188
+ constructor(input) {
189
+ const isClone = input instanceof VaultV2BlueReallocationData;
190
+ this.chainId = input.chainId;
191
+ this.mutableMarkets = {};
192
+ this.mutableVaults = {};
193
+ this.mutableAllocations = {};
194
+ this.markets = this.mutableMarkets;
195
+ this.vaults = this.mutableVaults;
196
+ this.allocations = this.mutableAllocations;
197
+ if (isClone) {
198
+ this.publicAllocatorConfigs = input.publicAllocatorConfigs;
199
+ this.activeAdapters = input.activeAdapters;
200
+ this.marketPublicAllocatorConfigs = input.marketPublicAllocatorConfigs;
201
+ }
202
+ else {
203
+ const publicAllocatorConfigs = {};
204
+ this.publicAllocatorConfigs = publicAllocatorConfigs;
205
+ const activeAdapters = {};
206
+ this.activeAdapters = activeAdapters;
207
+ const marketPublicAllocatorConfigs = {};
208
+ this.marketPublicAllocatorConfigs = marketPublicAllocatorConfigs;
209
+ for (const [vault, config] of Object.entries(input.publicAllocatorConfigs ?? {})) {
210
+ publicAllocatorConfigs[vault] =
211
+ config == null
212
+ ? undefined
213
+ : new VaultV2BluePublicAllocatorConfig(config);
214
+ }
215
+ for (const [vault, adapters] of Object.entries(input.activeAdapters ?? {})) {
216
+ activeAdapters[vault] =
217
+ adapters == null ? undefined : new Set(adapters);
218
+ }
219
+ for (const [vault, configs] of Object.entries(input.marketPublicAllocatorConfigs ?? {})) {
220
+ marketPublicAllocatorConfigs[vault] = {};
221
+ for (const [id, config] of Object.entries(configs ?? {})) {
222
+ marketPublicAllocatorConfigs[vault][id] =
223
+ config == null
224
+ ? undefined
225
+ : new VaultV2BlueMarketPublicAllocatorConfig(config);
226
+ }
227
+ }
228
+ }
229
+ for (const [marketId, market] of Object.entries(input.markets ?? {})) {
230
+ this.mutableMarkets[marketId] =
231
+ market == null ? undefined : new Market({ ...market });
232
+ }
233
+ for (const [address, vault] of Object.entries(input.vaults ?? {})) {
234
+ const clonedVault = vault == null
235
+ ? undefined
236
+ : cloneVault(vault, { markets: this.mutableMarkets });
237
+ this.mutableVaults[address] = clonedVault;
238
+ }
239
+ for (const [vault, allocations] of Object.entries(input.allocations ?? {})) {
240
+ if (isClone) {
241
+ this.mutableAllocations[vault] = { ...allocations };
242
+ continue;
243
+ }
244
+ this.mutableAllocations[vault] = {};
245
+ for (const [id, allocation] of Object.entries(allocations ?? {})) {
246
+ this.mutableAllocations[vault][id] =
247
+ allocation == null ? undefined : { ...allocation };
248
+ }
249
+ }
250
+ }
251
+ /**
252
+ * Clones the complete simulation snapshot.
253
+ *
254
+ * @returns A deep clone of this simulation state.
255
+ * @example
256
+ * ```ts
257
+ * import { markets } from "@morpho-org/morpho-test";
258
+ * import { createPublicClient, http } from "viem";
259
+ * import { mainnet } from "viem/chains";
260
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
261
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
262
+ *
263
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
264
+ * .extend(morphoViemExtension());
265
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
266
+ * const market = client.morpho.blue(marketParams, mainnet.id);
267
+ * const block = await client.getBlock();
268
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
269
+ * const data = await market.getVaultV2BlueReallocationData({
270
+ * vaultAddresses: [keyrockUsdcVaultV2],
271
+ * block: { number: block.number, timestamp: block.timestamp },
272
+ * });
273
+ * const cloned: VaultV2BlueReallocationData = data.clone();
274
+ * ```
275
+ */
276
+ clone() {
277
+ return new VaultV2BlueReallocationData(this);
278
+ }
279
+ /**
280
+ * Gets a market from this snapshot.
281
+ *
282
+ * @param marketId - Market id to read.
283
+ * @returns The market state.
284
+ * @throws {UnknownReallocationMarketError} when the market is absent.
285
+ * @example
286
+ * ```ts
287
+ * import { markets } from "@morpho-org/morpho-test";
288
+ * import { createPublicClient, http } from "viem";
289
+ * import { mainnet } from "viem/chains";
290
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
291
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
292
+ *
293
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
294
+ * .extend(morphoViemExtension());
295
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
296
+ * const market = client.morpho.blue(marketParams, mainnet.id);
297
+ * const block = await client.getBlock();
298
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
299
+ * const data = await market.getVaultV2BlueReallocationData({
300
+ * vaultAddresses: [keyrockUsdcVaultV2],
301
+ * block: { number: block.number, timestamp: block.timestamp },
302
+ * });
303
+ * const targetMarket: ReturnType<
304
+ * VaultV2BlueReallocationData["getMarket"]
305
+ * > = data.getMarket(marketParams.id);
306
+ * ```
307
+ */
308
+ getMarket(marketId) {
309
+ const market = this.mutableMarkets[marketId];
310
+ if (market == null)
311
+ throw new UnknownReallocationMarketError(marketId);
312
+ return market;
313
+ }
314
+ /**
315
+ * Gets a Vault V2 from this snapshot.
316
+ *
317
+ * @param vault - Vault V2 address.
318
+ * @returns The accrued Vault V2 state.
319
+ * @throws {UnknownReallocationVaultError} when the vault is absent.
320
+ * @example
321
+ * ```ts
322
+ * import { markets } from "@morpho-org/morpho-test";
323
+ * import { createPublicClient, http } from "viem";
324
+ * import { mainnet } from "viem/chains";
325
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
326
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
327
+ *
328
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
329
+ * .extend(morphoViemExtension());
330
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
331
+ * const market = client.morpho.blue(marketParams, mainnet.id);
332
+ * const block = await client.getBlock();
333
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
334
+ * const data = await market.getVaultV2BlueReallocationData({
335
+ * vaultAddresses: [keyrockUsdcVaultV2],
336
+ * block: { number: block.number, timestamp: block.timestamp },
337
+ * });
338
+ * const vault: ReturnType<VaultV2BlueReallocationData["getVault"]> =
339
+ * data.getVault(keyrockUsdcVaultV2);
340
+ * ```
341
+ */
342
+ getVault(vault) {
343
+ return this.getMutableVault(vault);
344
+ }
345
+ getMutableVault(vault) {
346
+ const key = findAddressKey(this.mutableVaults, vault);
347
+ const data = key == null ? undefined : this.mutableVaults[key];
348
+ if (data == null)
349
+ throw new UnknownReallocationVaultError(vault);
350
+ return data;
351
+ }
352
+ /**
353
+ * Gets one Vault V2 allocation record.
354
+ *
355
+ * @param vault - Vault V2 address.
356
+ * @param id - Derived allocation id.
357
+ * @returns The allocation and cap state.
358
+ * @throws {UnknownReallocationAllocationError} when the record is absent.
359
+ * @example
360
+ * ```ts
361
+ * import { markets } from "@morpho-org/morpho-test";
362
+ * import { createPublicClient, http, type Hash } from "viem";
363
+ * import { mainnet } from "viem/chains";
364
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
365
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
366
+ *
367
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
368
+ * .extend(morphoViemExtension());
369
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
370
+ * const market = client.morpho.blue(marketParams, mainnet.id);
371
+ * const block = await client.getBlock();
372
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
373
+ * const data = await market.getVaultV2BlueReallocationData({
374
+ * vaultAddresses: [keyrockUsdcVaultV2],
375
+ * block: { number: block.number, timestamp: block.timestamp },
376
+ * });
377
+ * const [allocationId] = Object.keys(
378
+ * data.allocations[keyrockUsdcVaultV2] ?? {},
379
+ * ) as Hash[];
380
+ * const allocation: ReturnType<
381
+ * VaultV2BlueReallocationData["getAllocation"]
382
+ * > = data.getAllocation(keyrockUsdcVaultV2, allocationId!);
383
+ * ```
384
+ */
385
+ getAllocation(vault, id) {
386
+ const key = findAddressKey(this.allocations, vault);
387
+ const allocation = key == null ? undefined : this.allocations[key]?.[id];
388
+ if (allocation == null)
389
+ throw new UnknownReallocationAllocationError(vault, id);
390
+ return allocation;
391
+ }
392
+ /**
393
+ * Gets one vault-wide BluePublicAllocator configuration.
394
+ *
395
+ * @param vault - Vault V2 address.
396
+ * @returns The vault-wide allocator configuration.
397
+ * @throws {UnknownReallocationPublicAllocatorConfigError} when it is absent.
398
+ * @example
399
+ * ```ts
400
+ * import { markets } from "@morpho-org/morpho-test";
401
+ * import { createPublicClient, http } from "viem";
402
+ * import { mainnet } from "viem/chains";
403
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
404
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
405
+ *
406
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
407
+ * .extend(morphoViemExtension());
408
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
409
+ * const market = client.morpho.blue(marketParams, mainnet.id);
410
+ * const block = await client.getBlock();
411
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
412
+ * const data = await market.getVaultV2BlueReallocationData({
413
+ * vaultAddresses: [keyrockUsdcVaultV2],
414
+ * block: { number: block.number, timestamp: block.timestamp },
415
+ * });
416
+ * const config: ReturnType<
417
+ * VaultV2BlueReallocationData["getPublicAllocatorConfig"]
418
+ * > = data.getPublicAllocatorConfig(keyrockUsdcVaultV2);
419
+ * ```
420
+ */
421
+ getPublicAllocatorConfig(vault) {
422
+ const config = this.getOptionalPublicAllocatorConfig(vault);
423
+ if (config == null)
424
+ throw new UnknownReallocationPublicAllocatorConfigError(vault);
425
+ return config;
426
+ }
427
+ /**
428
+ * Gets fetched allocator authorization state, including an explicit absent value.
429
+ *
430
+ * @param vault - Vault V2 address.
431
+ * @returns The allocator config, or `undefined` when the fetched vault has not authorized it.
432
+ * @throws {UnknownReallocationPublicAllocatorConfigError} when the fetch state is absent.
433
+ */
434
+ getOptionalPublicAllocatorConfig(vault) {
435
+ const key = findAddressKey(this.publicAllocatorConfigs, vault);
436
+ if (key == null)
437
+ throw new UnknownReallocationPublicAllocatorConfigError(vault);
438
+ return this.publicAllocatorConfigs[key];
439
+ }
440
+ /**
441
+ * Gets the BluePublicAllocator-active adapters for a Vault V2.
442
+ *
443
+ * @param vault - Vault V2 address.
444
+ * @returns The active adapter addresses in their supplied casing, or an empty set when none are active.
445
+ * @throws {UnknownReallocationActiveAdaptersError} when the active-adapter state is absent.
446
+ * @example
447
+ * ```ts
448
+ * import { markets } from "@morpho-org/morpho-test";
449
+ * import { createPublicClient, http, type Address } from "viem";
450
+ * import { mainnet } from "viem/chains";
451
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
452
+ *
453
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
454
+ * .extend(morphoViemExtension());
455
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
456
+ * const market = client.morpho.blue(marketParams, mainnet.id);
457
+ * const block = await client.getBlock();
458
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
459
+ * const data = await market.getVaultV2BlueReallocationData({
460
+ * vaultAddresses: [keyrockUsdcVaultV2],
461
+ * block: { number: block.number, timestamp: block.timestamp },
462
+ * });
463
+ * const activeAdapters: ReadonlySet<Address> =
464
+ * data.getActiveAdapters(keyrockUsdcVaultV2);
465
+ * ```
466
+ */
467
+ getActiveAdapters(vault) {
468
+ const key = findAddressKey(this.activeAdapters, vault);
469
+ const adapters = key == null ? undefined : this.activeAdapters[key];
470
+ if (adapters == null)
471
+ throw new UnknownReallocationActiveAdaptersError(vault);
472
+ return adapters;
473
+ }
474
+ /**
475
+ * Gets one adapter-market BluePublicAllocator configuration.
476
+ *
477
+ * @param vault - Vault V2 address.
478
+ * @param adapterMarketCapId - Adapter-scoped market cap id.
479
+ * @returns The allocator cap and permissions.
480
+ * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when it is absent.
481
+ * @example
482
+ * ```ts
483
+ * import { markets } from "@morpho-org/morpho-test";
484
+ * import { createPublicClient, http, type Hash } from "viem";
485
+ * import { mainnet } from "viem/chains";
486
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
487
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
488
+ *
489
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
490
+ * .extend(morphoViemExtension());
491
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
492
+ * const market = client.morpho.blue(marketParams, mainnet.id);
493
+ * const block = await client.getBlock();
494
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
495
+ * const data = await market.getVaultV2BlueReallocationData({
496
+ * vaultAddresses: [keyrockUsdcVaultV2],
497
+ * block: { number: block.number, timestamp: block.timestamp },
498
+ * });
499
+ * const [adapterMarketCapId] = Object.keys(
500
+ * data.marketPublicAllocatorConfigs[keyrockUsdcVaultV2] ?? {},
501
+ * ) as Hash[];
502
+ * const config: ReturnType<
503
+ * VaultV2BlueReallocationData["getMarketPublicAllocatorConfig"]
504
+ * > = data.getMarketPublicAllocatorConfig(
505
+ * keyrockUsdcVaultV2,
506
+ * adapterMarketCapId!,
507
+ * );
508
+ * ```
509
+ */
510
+ getMarketPublicAllocatorConfig(vault, adapterMarketCapId) {
511
+ const key = findAddressKey(this.marketPublicAllocatorConfigs, vault);
512
+ const config = key == null
513
+ ? undefined
514
+ : this.marketPublicAllocatorConfigs[key]?.[adapterMarketCapId];
515
+ if (config == null)
516
+ throw new UnknownReallocationMarketPublicAllocatorConfigError(vault, adapterMarketCapId);
517
+ return config;
518
+ }
519
+ /**
520
+ * Gets a supported MorphoMarketV1AdapterV2 from a Vault V2.
521
+ *
522
+ * @param vault - Vault V2 address.
523
+ * @param adapter - Adapter address.
524
+ * @returns The accrued adapter state.
525
+ * @throws {UnknownReallocationAdapterError} when it is absent or unsupported.
526
+ * @example
527
+ * ```ts
528
+ * import { markets } from "@morpho-org/morpho-test";
529
+ * import { createPublicClient, http } from "viem";
530
+ * import { mainnet } from "viem/chains";
531
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
532
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
533
+ *
534
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
535
+ * .extend(morphoViemExtension());
536
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
537
+ * const market = client.morpho.blue(marketParams, mainnet.id);
538
+ * const block = await client.getBlock();
539
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
540
+ * const data = await market.getVaultV2BlueReallocationData({
541
+ * vaultAddresses: [keyrockUsdcVaultV2],
542
+ * block: { number: block.number, timestamp: block.timestamp },
543
+ * });
544
+ * const [adapterAddress] = data.activeAdapters[keyrockUsdcVaultV2] ?? [];
545
+ * const adapter: ReturnType<VaultV2BlueReallocationData["getAdapter"]> =
546
+ * data.getAdapter(keyrockUsdcVaultV2, adapterAddress!);
547
+ * ```
548
+ */
549
+ getAdapter(vault, adapter) {
550
+ return this.getMutableAdapter(vault, adapter);
551
+ }
552
+ getMutableAdapter(vault, adapter) {
553
+ const data = this.getMutableVault(vault).accrualAdapters.find((candidate) => candidate instanceof AccrualVaultV2MorphoMarketV1AdapterV2 &&
554
+ isAddressEqual(candidate.address, adapter));
555
+ if (data == null)
556
+ throw new UnknownReallocationAdapterError(vault, adapter);
557
+ return data;
558
+ }
559
+ /**
560
+ * Computes Vault V2 BluePublicAllocator calls available for a target market.
561
+ *
562
+ * Without `options.operation`, discovers every friendly call. With an
563
+ * operation, targets the amount required by that borrow or loan-asset
564
+ * withdrawal and falls back to 100% source utilization only when friendly
565
+ * liquidity cannot cover the absolute shortfall. A shared relative-cap lower
566
+ * bound may require one call to exceed the targeted amount. Friendly source
567
+ * utilization defaults to 90% and is configurable through
568
+ * `options.maxWithdrawalUtilization`. Vaults whose configured penalty exceeds
569
+ * `options.maxPenalty` are ignored. By default, only zero-penalty vaults are
570
+ * considered.
571
+ *
572
+ * Shared-cap discovery is conservative: when the non-shared maximum violates
573
+ * a shared cap, the candidate is omitted instead of scanning smaller base-unit
574
+ * amounts for a rounding-only fit. This keeps planning bounded but can
575
+ * understate executable liquidity in an already-at-or-over-cap snapshot.
576
+ *
577
+ * @param marketId - Target Blue market id.
578
+ * @param options - Optional discovery controls and operation to support.
579
+ * @returns Flat action-ready reallocations and their post-simulation state.
580
+ * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
581
+ * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
582
+ * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
583
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
584
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
585
+ * @throws {UnknownReallocationPublicAllocatorConfigError} when allocator authorization state is absent.
586
+ * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
587
+ * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
588
+ * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
589
+ * @throws {ReallocationAllocationUnderflowError} when an inconsistent allocation snapshot underflows during the final transition.
590
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall.
591
+ * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
592
+ * @example
593
+ * ```ts
594
+ * import { markets } from "@morpho-org/morpho-test";
595
+ * import { createPublicClient, http } from "viem";
596
+ * import { mainnet } from "viem/chains";
597
+ * import {
598
+ * morphoViemExtension,
599
+ * type VaultV2BlueReallocation,
600
+ * } from "@morpho-org/morpho-sdk";
601
+ * import type { VaultV2BlueReallocationData } from "@morpho-org/morpho-sdk/entities";
602
+ *
603
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
604
+ * .extend(morphoViemExtension());
605
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
606
+ * const market = client.morpho.blue(marketParams, mainnet.id);
607
+ * const block = await client.getBlock();
608
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
609
+ * const data = await market.getVaultV2BlueReallocationData({
610
+ * vaultAddresses: [keyrockUsdcVaultV2],
611
+ * block: { number: block.number, timestamp: block.timestamp },
612
+ * });
613
+ * const result: {
614
+ * readonly reallocations: readonly VaultV2BlueReallocation[];
615
+ * readonly data: VaultV2BlueReallocationData;
616
+ * } = data.computeVaultV2BlueReallocations(marketParams.id, {
617
+ * timestamp: block.timestamp,
618
+ * });
619
+ * ```
620
+ */
621
+ computeVaultV2BlueReallocations(marketId, options = {}) {
622
+ if (options.enabled === false)
623
+ return { reallocations: [], data: this };
624
+ const maxWithdrawalUtilization = resolveMaxWithdrawalUtilization(options.maxWithdrawalUtilization);
625
+ const maxPenalty = resolveMaxPenalty(options.maxPenalty);
626
+ const resolvedOptions = { ...options, maxPenalty };
627
+ const operation = options.operation;
628
+ if (operation == null) {
629
+ const { reallocations, data } = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
630
+ context: createSimulationContext(),
631
+ marketId,
632
+ maxWithdrawalUtilization,
633
+ options: resolvedOptions,
634
+ });
635
+ return { reallocations, data };
636
+ }
637
+ const { amount, type } = operation;
638
+ if (amount <= 0n)
639
+ throw new NonPositiveInputError("amount", amount);
640
+ const timestamp = options.timestamp == null
641
+ ? this.getLatestSnapshotTimestamp()
642
+ : BigInt(options.timestamp);
643
+ const normalizedOptions = {
644
+ ...resolvedOptions,
645
+ timestamp,
646
+ reallocatableVaults: options.reallocatableVaults == null
647
+ ? undefined
648
+ : [...options.reallocatableVaults],
649
+ };
650
+ const market = this.getMarket(marketId).accrueInterest(timestamp);
651
+ if (type === "withdraw" && amount > market.totalSupplyAssets) {
652
+ throw new ReallocationWithdrawExceedsMarketSupplyError({
653
+ marketId,
654
+ withdrawAmount: amount,
655
+ totalSupplyAssets: market.totalSupplyAssets,
656
+ });
657
+ }
658
+ const newTotalBorrowAssets = type === "borrow"
659
+ ? market.totalBorrowAssets + amount
660
+ : market.totalBorrowAssets;
661
+ const newTotalSupplyAssets = type === "withdraw"
662
+ ? market.totalSupplyAssets - amount
663
+ : market.totalSupplyAssets;
664
+ if (MarketUtils.getUtilization({
665
+ totalSupplyAssets: newTotalSupplyAssets,
666
+ totalBorrowAssets: newTotalBorrowAssets,
667
+ }) <= DEFAULT_SUPPLY_TARGET_UTILIZATION)
668
+ return { reallocations: [], data: this };
669
+ const requiredAssets = MathLib.wDivUp(newTotalBorrowAssets, DEFAULT_SUPPLY_TARGET_UTILIZATION) -
670
+ newTotalSupplyAssets;
671
+ if (requiredAssets <= 0n)
672
+ return { reallocations: [], data: this };
673
+ const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
674
+ context: createSimulationContext(),
675
+ marketId,
676
+ maxWithdrawalUtilization,
677
+ maxAssets: requiredAssets,
678
+ options: normalizedOptions,
679
+ });
680
+ const reallocations = [...friendly.reallocations];
681
+ const data = friendly.data;
682
+ const friendlyMarket = friendly.data.getMarket(marketId);
683
+ const friendlyBorrow = type === "borrow"
684
+ ? friendlyMarket.totalBorrowAssets + amount
685
+ : friendlyMarket.totalBorrowAssets;
686
+ const friendlySupply = type === "withdraw"
687
+ ? friendlyMarket.totalSupplyAssets - amount
688
+ : friendlyMarket.totalSupplyAssets;
689
+ if (friendlyBorrow > friendlySupply) {
690
+ const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
691
+ context: friendly.context,
692
+ marketId,
693
+ maxWithdrawalUtilization: MathLib.WAD,
694
+ maxAssets: friendlyBorrow - friendlySupply,
695
+ options: normalizedOptions,
696
+ });
697
+ reallocations.push(...fallback.reallocations);
698
+ }
699
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
700
+ ? newTotalBorrowAssets - newTotalSupplyAssets
701
+ : 0n;
702
+ const reallocatedAssets = reallocations.reduce((total, { assets }) => total + assets, 0n);
703
+ if (reallocatedAssets < absoluteShortfall) {
704
+ throw new InsufficientSharedLiquidityError({
705
+ marketId,
706
+ shortfall: absoluteShortfall,
707
+ available: reallocatedAssets,
708
+ });
709
+ }
710
+ return { reallocations, data };
711
+ }
712
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, marketId, maxWithdrawalUtilization, maxAssets, options = {}, }) {
713
+ if (options.enabled === false)
714
+ return { reallocations: [], data: this, context };
715
+ this.getMarket(marketId);
716
+ const timestamp = options.timestamp == null
717
+ ? this.getLatestSnapshotTimestamp()
718
+ : BigInt(options.timestamp);
719
+ let data = this;
720
+ let simulationContext = context;
721
+ data.setMarkets(Object.values(data.markets)
722
+ .filter((market) => market != null)
723
+ .map((market) => market.accrueInterest(timestamp)));
724
+ const reallocations = [];
725
+ const configuredVaults = Object.keys(data.vaults);
726
+ const vaultKeyByLower = new Map(configuredVaults.map((vault) => [vault.toLowerCase(), vault]));
727
+ const vaults = Array.from(new Set([...(options.reallocatableVaults ?? configuredVaults)]
728
+ .map((vault) => vaultKeyByLower.get(vault.toLowerCase()))
729
+ .filter((vault) => vault != null)));
730
+ const normalizedMarketId = marketId.toLowerCase();
731
+ const adapterIdsCache = new Map();
732
+ const activeAdaptersCache = new Map();
733
+ let remainingAssets = maxAssets;
734
+ while (remainingAssets == null || remainingAssets > 0n) {
735
+ const candidates = vaults
736
+ .map((vaultAddress) => {
737
+ const targetMarket = data.getMarket(marketId);
738
+ const publicAllocatorConfig = data.getOptionalPublicAllocatorConfig(vaultAddress);
739
+ if (publicAllocatorConfig == null)
740
+ return;
741
+ const vault = data.getVault(vaultAddress);
742
+ if (!isAddressEqual(publicAllocatorConfig.vault, vaultAddress) ||
743
+ publicAllocatorConfig.penalty >
744
+ (options.maxPenalty ?? DEFAULT_MAX_REALLOCATION_PENALTY))
745
+ return;
746
+ const donatedPenaltyAssetsKey = findAddressKey(simulationContext.donatedPenaltyAssets, vaultAddress);
747
+ // Exclude rounded penalty dust from idle candidates so one donation
748
+ // cannot replenish liquidity for another same-plan reallocation.
749
+ const availableIdleAssets = MathLib.zeroFloorSub(vault.assetBalance, donatedPenaltyAssetsKey == null
750
+ ? 0n
751
+ : simulationContext.donatedPenaltyAssets[donatedPenaltyAssetsKey]);
752
+ let activeAdapters = activeAdaptersCache.get(vaultAddress);
753
+ if (activeAdapters == null) {
754
+ activeAdapters = new Set([...data.getActiveAdapters(vaultAddress)].map((adapter) => adapter.toLowerCase()));
755
+ activeAdaptersCache.set(vaultAddress, activeAdapters);
756
+ }
757
+ const targetSupplyHeadroom = MathLib.zeroFloorSub(MathLib.MAX_UINT_128, targetMarket.totalSupplyAssets);
758
+ const rawCandidates = [];
759
+ // Missing nested allocator state means the snapshot is incomplete, so
760
+ // typed getter errors below must propagate. Only explicit zero caps or
761
+ // disabled permissions make an adapter ineligible.
762
+ for (const adapter of vault.accrualAdapters) {
763
+ if (!(adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
764
+ continue;
765
+ if (!isAddressEqual(adapter.parentVault, vaultAddress))
766
+ continue;
767
+ if (!isAddressEqual(targetMarket.params.loanToken, vault.asset) ||
768
+ !isAddressEqual(targetMarket.params.irm, adapter.adaptiveCurveIrm))
769
+ continue;
770
+ const [adapterCapId, collateralCapId, adapterMarketCapId] = getAdapterIds(adapterIdsCache, adapter, targetMarket);
771
+ const marketPublicAllocatorConfig = data.getMarketPublicAllocatorConfig(vaultAddress, adapterMarketCapId);
772
+ if (!isAddressEqual(marketPublicAllocatorConfig.vault, vaultAddress) ||
773
+ !isAddressEqual(marketPublicAllocatorConfig.adapter, adapter.address) ||
774
+ !activeAdapters.has(adapter.address.toLowerCase()))
775
+ continue;
776
+ const adapterCapAllocation = data.getAllocation(vaultAddress, adapterCapId);
777
+ const collateralCapAllocation = data.getAllocation(vaultAddress, collateralCapId);
778
+ const adapterMarketCapAllocation = data.getAllocation(vaultAddress, adapterMarketCapId);
779
+ if ([
780
+ adapterCapAllocation,
781
+ collateralCapAllocation,
782
+ adapterMarketCapAllocation,
783
+ ].some(({ absoluteCap }) => absoluteCap === 0n))
784
+ continue;
785
+ const expectedSupplyAssets = targetMarket.toSupplyAssets(adapter.supplyShares[marketId] ?? 0n);
786
+ const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
787
+ const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation + untracked);
788
+ if (publicAllocatorConfig.canPullFromIdle &&
789
+ availableIdleAssets > 0n) {
790
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, availableIdleAssets);
791
+ if (assets > 0n) {
792
+ rawCandidates.push({
793
+ vault: vaultAddress,
794
+ from: { type: "idle" },
795
+ to: { adapter: adapter.address },
796
+ assets,
797
+ penalty: publicAllocatorConfig.penalty,
798
+ });
799
+ }
800
+ }
801
+ for (const sourceAdapter of vault.accrualAdapters) {
802
+ if (!(sourceAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2))
803
+ continue;
804
+ if (!isAddressEqual(sourceAdapter.parentVault, vaultAddress))
805
+ continue;
806
+ if (!activeAdapters.has(sourceAdapter.address.toLowerCase()))
807
+ continue;
808
+ for (const sourceMarketReference of sourceAdapter.markets) {
809
+ const sourceMarket = data.getMarket(sourceMarketReference.id);
810
+ if (!isAddressEqual(sourceMarket.params.loanToken, vault.asset) ||
811
+ !isAddressEqual(sourceMarket.params.irm, sourceAdapter.adaptiveCurveIrm))
812
+ continue;
813
+ if (sourceMarket.id.toLowerCase() === normalizedMarketId)
814
+ continue;
815
+ const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
816
+ const [, , sourceAdapterMarketCapId] = sourceIds;
817
+ const sourceConfig = data.getMarketPublicAllocatorConfig(vaultAddress, sourceAdapterMarketCapId);
818
+ if (!isAddressEqual(sourceConfig.vault, vaultAddress) ||
819
+ !isAddressEqual(sourceConfig.adapter, sourceAdapter.address) ||
820
+ !sourceConfig.canPullFromMarket)
821
+ continue;
822
+ const sourceAllocations = sourceIds.map((id) => data.getAllocation(vaultAddress, id));
823
+ if (sourceAllocations.some(({ allocation }) => allocation === 0n))
824
+ continue;
825
+ const expectedSourceSupplyAssets = sourceMarket.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n);
826
+ const assets = MathLib.min(MathLib.MAX_UINT_128, targetSupplyHeadroom, allocatorHeadroom, expectedSourceSupplyAssets, sourceMarket.getWithdrawToUtilization(maxWithdrawalUtilization));
827
+ if (assets <= 0n)
828
+ continue;
829
+ rawCandidates.push({
830
+ vault: vaultAddress,
831
+ from: {
832
+ type: "market",
833
+ adapter: sourceAdapter.address,
834
+ marketParams: sourceMarket.params,
835
+ },
836
+ to: { adapter: adapter.address },
837
+ assets,
838
+ penalty: publicAllocatorConfig.penalty,
839
+ });
840
+ }
841
+ }
842
+ }
843
+ const capCompatibleCandidates = [];
844
+ for (const reallocation of rawCandidates) {
845
+ let lower = 0n;
846
+ let upper = reallocation.assets;
847
+ // MorphoMarketV1AdapterV2 rejects supplies that mint fewer shares than assets.
848
+ if (targetMarket.toSupplyShares(upper, "Down") < upper)
849
+ continue;
850
+ const reallocationAdapter = data.getAdapter(reallocation.vault, reallocation.to.adapter);
851
+ const targetIds = getAdapterIds(adapterIdsCache, reallocationAdapter, targetMarket);
852
+ const sourceIds = new Set();
853
+ if (reallocation.from.type === "market") {
854
+ const sourceAdapter = data.getAdapter(reallocation.vault, reallocation.from.adapter);
855
+ const sourceMarket = data.getMarket(reallocation.from.marketParams.id);
856
+ for (const id of getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket))
857
+ sourceIds.add(id);
858
+ }
859
+ const probeReallocation = (assets) => {
860
+ if (targetMarket.totalSupplyShares +
861
+ targetMarket.toSupplyShares(assets, "Down") >
862
+ MathLib.MAX_UINT_128)
863
+ return;
864
+ const postTransition = _try(() => data.applyPublicReallocation({
865
+ context: simulationContext,
866
+ reallocation: { ...reallocation, assets },
867
+ targetMarketId: marketId,
868
+ timestamp: targetMarket.lastUpdate,
869
+ adapterIdsCache,
870
+ probe: true,
871
+ }), ReallocationAllocationUnderflowError, ReallocationAdapterSupplySharesUnderflowError);
872
+ if (postTransition == null)
873
+ return;
874
+ const postVault = postTransition.data.getVault(reallocation.vault);
875
+ // Vault V2 checks relative caps against the transient firstTotalAssets,
876
+ // which stays fixed after the vault's first allocation in a transaction.
877
+ const firstTotalAssetsKey = findAddressKey(postTransition.context.firstTotalAssets, reallocation.vault);
878
+ const firstTotalAssets = (firstTotalAssetsKey == null
879
+ ? undefined
880
+ : postTransition.context.firstTotalAssets[firstTotalAssetsKey]) ?? postVault._totalAssets;
881
+ let withinUpperBounds = true;
882
+ let withinAllCaps = true;
883
+ for (const id of targetIds) {
884
+ const allocation = postTransition.data.getAllocation(reallocation.vault, id);
885
+ const capacity = VaultV2Utils.allocationHeadroom({ ...allocation, allocation: 0n }, firstTotalAssets).value;
886
+ const withinCap = allocation.absoluteCap > 0n &&
887
+ allocation.allocation <= capacity;
888
+ if (!withinCap) {
889
+ withinAllCaps = false;
890
+ if (!sourceIds.has(id))
891
+ withinUpperBounds = false;
892
+ }
893
+ }
894
+ return { withinAllCaps, withinUpperBounds };
895
+ };
896
+ // Non-shared target IDs impose monotonic upper bounds. Shared IDs
897
+ // can impose lower bounds and non-monotonic rounding constraints,
898
+ // so validate them after selecting the non-shared maximum. If that
899
+ // maximum fails, omit the candidate instead of scanning base units.
900
+ let probeUpper = true;
901
+ while (lower < upper) {
902
+ const assets = probeUpper ? upper : (lower + upper + 1n) / 2n;
903
+ probeUpper = false;
904
+ if (probeReallocation(assets)?.withinUpperBounds === true)
905
+ lower = assets;
906
+ else
907
+ upper = assets - 1n;
908
+ }
909
+ let selectedAssets = MathLib.min(lower, remainingAssets ?? reallocation.assets);
910
+ let probe = selectedAssets > 0n
911
+ ? probeReallocation(selectedAssets)
912
+ : undefined;
913
+ if (remainingAssets != null &&
914
+ selectedAssets > 0n &&
915
+ probe?.withinAllCaps !== true &&
916
+ lower > selectedAssets &&
917
+ probeReallocation(lower)?.withinAllCaps === true) {
918
+ let infeasible = selectedAssets;
919
+ let feasible = lower;
920
+ while (infeasible + 1n < feasible) {
921
+ const midpoint = (infeasible + feasible) / 2n;
922
+ if (probeReallocation(midpoint)?.withinAllCaps === true) {
923
+ feasible = midpoint;
924
+ }
925
+ else {
926
+ infeasible = midpoint;
927
+ }
928
+ }
929
+ selectedAssets = feasible;
930
+ probe = probeReallocation(selectedAssets);
931
+ }
932
+ if (selectedAssets > 0n && probe?.withinAllCaps === true)
933
+ capCompatibleCandidates.push({
934
+ ...reallocation,
935
+ assets: selectedAssets,
936
+ });
937
+ }
938
+ return capCompatibleCandidates.sort(bigIntComparator(({ assets }) => assets, "desc"))[0];
939
+ })
940
+ .filter((candidate) => candidate != null)
941
+ .sort(bigIntComparator(({ assets }) => assets, "desc"));
942
+ const largest = candidates[0];
943
+ if (largest == null)
944
+ return { reallocations, data, context: simulationContext };
945
+ const reallocation = largest;
946
+ reallocations.push(reallocation);
947
+ const transition = data.applyPublicReallocation({
948
+ context: simulationContext,
949
+ reallocation,
950
+ targetMarketId: marketId,
951
+ timestamp,
952
+ adapterIdsCache,
953
+ });
954
+ data = transition.data;
955
+ simulationContext = transition.context;
956
+ if (remainingAssets != null)
957
+ remainingAssets -= reallocation.assets;
958
+ }
959
+ return { reallocations, data, context: simulationContext };
960
+ }
961
+ /**
962
+ * Sums friendly Vault V2 shared liquidity available to a target market.
963
+ *
964
+ * @param marketId - Target Blue market id.
965
+ * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
966
+ * @returns Reallocatable market and idle assets, or `0n` when none are available; rounding-only shared-cap fits may be conservatively omitted.
967
+ * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
968
+ * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
969
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
970
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
971
+ * @throws {UnknownReallocationPublicAllocatorConfigError} when allocator authorization state is absent.
972
+ * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
973
+ * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
974
+ * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
975
+ * @example
976
+ * ```ts
977
+ * import { markets } from "@morpho-org/morpho-test";
978
+ * import { createPublicClient, http } from "viem";
979
+ * import { mainnet } from "viem/chains";
980
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
981
+ *
982
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
983
+ * .extend(morphoViemExtension());
984
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
985
+ * const market = client.morpho.blue(marketParams, mainnet.id);
986
+ * const block = await client.getBlock();
987
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
988
+ * const data = await market.getVaultV2BlueReallocationData({
989
+ * vaultAddresses: [keyrockUsdcVaultV2],
990
+ * block: { number: block.number, timestamp: block.timestamp },
991
+ * });
992
+ * const liquidity: bigint = data.getPublicReallocationLiquidity(
993
+ * marketParams.id,
994
+ * { timestamp: block.timestamp },
995
+ * );
996
+ * ```
997
+ */
998
+ getPublicReallocationLiquidity(marketId, options) {
999
+ if (options?.enabled === false)
1000
+ return 0n;
1001
+ const maxPenalty = resolveMaxPenalty(options?.maxPenalty);
1002
+ return this.clone()
1003
+ .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1004
+ context: createSimulationContext(),
1005
+ marketId,
1006
+ maxWithdrawalUtilization: resolveMaxWithdrawalUtilization(options?.maxWithdrawalUtilization),
1007
+ options: { ...options, maxPenalty },
1008
+ })
1009
+ .reallocations.reduce((total, { assets }) => total + assets, 0n);
1010
+ }
1011
+ /**
1012
+ * Computes borrow liquidity to a target utilization, including friendly
1013
+ * Vault V2 public reallocations.
1014
+ *
1015
+ * @param marketId - Target Blue market id.
1016
+ * @param utilization - Desired utilization, scaled by WAD. Defaults to 90%.
1017
+ * @param options - Optional timestamp, enable flag, vault allowlist, source utilization ceiling, and maximum penalty.
1018
+ * @returns Borrowable assets while remaining at or below `utilization`; rounding-only shared-cap fits may be conservatively omitted.
1019
+ * @throws {NegativeInputError} when `maxWithdrawalUtilization` or `maxPenalty` is negative.
1020
+ * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
1021
+ * @throws {UnknownReallocationMarketError} when a required market is absent.
1022
+ * @throws {UnknownReallocationVaultError} when configured vault state is absent.
1023
+ * @throws {UnknownReallocationPublicAllocatorConfigError} when allocator authorization state is absent.
1024
+ * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
1025
+ * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
1026
+ * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
1027
+ * @example
1028
+ * ```ts
1029
+ * import { markets } from "@morpho-org/morpho-test";
1030
+ * import { createPublicClient, http, parseEther } from "viem";
1031
+ * import { mainnet } from "viem/chains";
1032
+ * import { morphoViemExtension } from "@morpho-org/morpho-sdk";
1033
+ *
1034
+ * const client = createPublicClient({ chain: mainnet, transport: http() })
1035
+ * .extend(morphoViemExtension());
1036
+ * const marketParams = markets[mainnet.id].usdc_wbtc;
1037
+ * const market = client.morpho.blue(marketParams, mainnet.id);
1038
+ * const block = await client.getBlock();
1039
+ * const keyrockUsdcVaultV2 = "0x04422053aDDbc9bB2759b248B574e3FCA76Bc145";
1040
+ * const data = await market.getVaultV2BlueReallocationData({
1041
+ * vaultAddresses: [keyrockUsdcVaultV2],
1042
+ * block: { number: block.number, timestamp: block.timestamp },
1043
+ * });
1044
+ * const liquidity: bigint = data.getAvailableLiquidityToUtilization(
1045
+ * marketParams.id,
1046
+ * parseEther("0.9"),
1047
+ * { timestamp: block.timestamp },
1048
+ * );
1049
+ * ```
1050
+ */
1051
+ // biome-ignore lint/complexity/useMaxParams: mirrors the existing V1 metric API
1052
+ getAvailableLiquidityToUtilization(marketId, utilization = DEFAULT_SUPPLY_TARGET_UTILIZATION, options) {
1053
+ const timestamp = options?.timestamp == null
1054
+ ? this.getLatestSnapshotTimestamp()
1055
+ : BigInt(options.timestamp);
1056
+ const market = this.getMarket(marketId).accrueInterest(timestamp);
1057
+ if (options?.enabled === false ||
1058
+ DEFAULT_SUPPLY_TARGET_UTILIZATION > utilization)
1059
+ return market.getBorrowToUtilization(utilization);
1060
+ const availableLiquidity = this.clone()
1061
+ .computeVaultV2BlueReallocationsAtUtilizationInPlace({
1062
+ context: createSimulationContext(),
1063
+ marketId,
1064
+ maxWithdrawalUtilization: resolveMaxWithdrawalUtilization(options?.maxWithdrawalUtilization),
1065
+ options: {
1066
+ ...options,
1067
+ timestamp,
1068
+ maxPenalty: resolveMaxPenalty(options?.maxPenalty),
1069
+ },
1070
+ })
1071
+ .reallocations.reduce((total, { assets }) => total + assets, 0n);
1072
+ return MarketUtils.getBorrowToUtilization({
1073
+ totalSupplyAssets: market.totalSupplyAssets + availableLiquidity,
1074
+ totalBorrowAssets: market.totalBorrowAssets,
1075
+ }, utilization);
1076
+ }
1077
+ getLatestSnapshotTimestamp() {
1078
+ let timestamp = 0n;
1079
+ for (const market of Object.values(this.markets)) {
1080
+ if (market != null)
1081
+ timestamp = MathLib.max(timestamp, market.lastUpdate);
1082
+ }
1083
+ for (const vault of Object.values(this.vaults)) {
1084
+ if (vault != null)
1085
+ timestamp = MathLib.max(timestamp, vault.lastUpdate);
1086
+ }
1087
+ return timestamp;
1088
+ }
1089
+ applyPublicReallocation({ context, reallocation, targetMarketId, timestamp, adapterIdsCache = new Map(), probe = false, }) {
1090
+ const sourceVaultKey = findAddressKey(this.mutableVaults, reallocation.vault);
1091
+ const sourceAllocationsKey = findAddressKey(this.mutableAllocations, reallocation.vault);
1092
+ const sourceVault = sourceVaultKey == null ? undefined : this.mutableVaults[sourceVaultKey];
1093
+ let data = this;
1094
+ if (probe) {
1095
+ const probeMarkets = { [targetMarketId]: this.getMarket(targetMarketId) };
1096
+ const adapterKeysToClone = new Set([
1097
+ reallocation.to.adapter.toLowerCase(),
1098
+ ]);
1099
+ const allocationIdsToClone = new Set(getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.to.adapter), this.getMarket(targetMarketId)));
1100
+ if (reallocation.from.type === "market") {
1101
+ const sourceMarket = this.getMarket(reallocation.from.marketParams.id);
1102
+ probeMarkets[sourceMarket.id] = sourceMarket;
1103
+ adapterKeysToClone.add(reallocation.from.adapter.toLowerCase());
1104
+ if (sourceVault != null) {
1105
+ const adaptersToRefresh = new Set(sourceVault.accrualAdapters);
1106
+ if (sourceVault.accrualLiquidityAdapter != null)
1107
+ adaptersToRefresh.add(sourceVault.accrualLiquidityAdapter);
1108
+ for (const adapter of adaptersToRefresh) {
1109
+ if ((adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2 &&
1110
+ adapter.markets.some(({ id }) => id === sourceMarket.id)) ||
1111
+ (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter &&
1112
+ adapter.positions.some(({ marketId }) => marketId === sourceMarket.id)) ||
1113
+ (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter &&
1114
+ adapter.accrualVaultV1.allocations.has(sourceMarket.id)))
1115
+ adapterKeysToClone.add(adapter.address.toLowerCase());
1116
+ }
1117
+ }
1118
+ for (const id of getAdapterIds(adapterIdsCache, this.getMutableAdapter(reallocation.vault, reallocation.from.adapter), sourceMarket))
1119
+ allocationIdsToClone.add(id);
1120
+ }
1121
+ data = new VaultV2BlueReallocationData({
1122
+ chainId: this.chainId,
1123
+ markets: probeMarkets,
1124
+ });
1125
+ if (sourceVaultKey != null) {
1126
+ data.mutableVaults[sourceVaultKey] =
1127
+ sourceVault == null
1128
+ ? undefined
1129
+ : cloneVault(sourceVault, {
1130
+ markets: data.mutableMarkets,
1131
+ adapterKeysToClone,
1132
+ });
1133
+ }
1134
+ if (sourceAllocationsKey != null) {
1135
+ const sourceAllocations = this.mutableAllocations[sourceAllocationsKey];
1136
+ const allocations = {};
1137
+ for (const id of allocationIdsToClone)
1138
+ allocations[id] = sourceAllocations?.[id];
1139
+ data.mutableAllocations[sourceAllocationsKey] = allocations;
1140
+ }
1141
+ }
1142
+ const vaultKey = findAddressKey(data.mutableVaults, reallocation.vault) ??
1143
+ reallocation.vault;
1144
+ const allocationsKey = findAddressKey(data.mutableAllocations, reallocation.vault) ??
1145
+ reallocation.vault;
1146
+ const firstTotalAssetsKey = findAddressKey(context.firstTotalAssets, reallocation.vault) ?? vaultKey;
1147
+ let nextContext = context;
1148
+ let vault = data.getMutableVault(vaultKey);
1149
+ const targetMarket = data.getMarket(targetMarketId);
1150
+ const penaltyAssets = VaultV2BluePublicAllocatorConfigUtils.getPenaltyAssets(reallocation, reallocation.assets);
1151
+ vault.assetBalance += penaltyAssets;
1152
+ if (penaltyAssets > 0n) {
1153
+ const donatedPenaltyAssetsKey = findAddressKey(context.donatedPenaltyAssets, reallocation.vault) ??
1154
+ vaultKey;
1155
+ // Track the donation separately so its rounded dust cannot replenish
1156
+ // same-plan idle candidates while remaining in simulated post-state.
1157
+ nextContext = {
1158
+ ...nextContext,
1159
+ donatedPenaltyAssets: {
1160
+ ...nextContext.donatedPenaltyAssets,
1161
+ [donatedPenaltyAssetsKey]: (nextContext.donatedPenaltyAssets[donatedPenaltyAssetsKey] ?? 0n) +
1162
+ penaltyAssets,
1163
+ },
1164
+ };
1165
+ }
1166
+ if (reallocation.from.type === "market") {
1167
+ const sourceAdapter = data.getMutableAdapter(reallocation.vault, reallocation.from.adapter);
1168
+ const sourceMarket = data.getMarket(reallocation.from.marketParams.id);
1169
+ const sourceIds = getAdapterIds(adapterIdsCache, sourceAdapter, sourceMarket);
1170
+ const [, , sourceAdapterMarketCapId] = sourceIds;
1171
+ const currentSupplyShares = sourceAdapter.supplyShares[sourceMarket.id] ?? 0n;
1172
+ const withdrawal = sourceMarket.withdraw(reallocation.assets, 0n, timestamp);
1173
+ if (withdrawal.shares > currentSupplyShares) {
1174
+ throw new ReallocationAdapterSupplySharesUnderflowError({
1175
+ vault: reallocation.vault,
1176
+ adapter: sourceAdapter.address,
1177
+ marketId: sourceMarket.id,
1178
+ supplyShares: currentSupplyShares,
1179
+ withdrawnShares: withdrawal.shares,
1180
+ });
1181
+ }
1182
+ sourceAdapter.supplyShares[sourceMarket.id] =
1183
+ currentSupplyShares - withdrawal.shares;
1184
+ data.setMarkets([withdrawal.market]);
1185
+ const sourceChange = withdrawal.market.toSupplyAssets(sourceAdapter.supplyShares[sourceMarket.id] ?? 0n) -
1186
+ data.getAllocation(reallocation.vault, sourceAdapterMarketCapId)
1187
+ .allocation;
1188
+ for (const id of sourceIds) {
1189
+ const allocation = data.getAllocation(reallocation.vault, id);
1190
+ const nextAllocation = allocation.allocation + sourceChange;
1191
+ if (nextAllocation < 0n) {
1192
+ throw new ReallocationAllocationUnderflowError({
1193
+ vault: reallocation.vault,
1194
+ id,
1195
+ allocation: allocation.allocation,
1196
+ change: sourceChange,
1197
+ });
1198
+ }
1199
+ data.mutableAllocations[allocationsKey][id] = {
1200
+ ...allocation,
1201
+ allocation: nextAllocation,
1202
+ };
1203
+ }
1204
+ vault.assetBalance += reallocation.assets;
1205
+ }
1206
+ if (context.firstTotalAssets[firstTotalAssetsKey] == null) {
1207
+ // Vault V2's transient firstTotalAssets tracks the first allocation in a
1208
+ // transaction independently from elapsed time. Later allocations must not
1209
+ // recompute the denominator, even if their simulated balances have changed.
1210
+ if (timestamp === vault.lastUpdate) {
1211
+ // AccrualVaultV2 skips zero-elapsed accruals, but the contract's first
1212
+ // touch still reads real adapter assets. With zero elapsed time, its
1213
+ // growth clamp leaves only existing losses to recognize.
1214
+ const realAssets = vault.accrualAdapters.reduce((assets, adapter) => assets + adapter.realAssets(timestamp), vault.assetBalance);
1215
+ vault._totalAssets = MathLib.min(realAssets, vault._totalAssets);
1216
+ }
1217
+ else {
1218
+ vault = vault.accrueInterest(timestamp).vault;
1219
+ }
1220
+ data.mutableVaults[vaultKey] = vault;
1221
+ nextContext = {
1222
+ ...nextContext,
1223
+ firstTotalAssets: {
1224
+ ...nextContext.firstTotalAssets,
1225
+ [firstTotalAssetsKey]: vault._totalAssets,
1226
+ },
1227
+ };
1228
+ }
1229
+ const targetAdapter = data.getMutableAdapter(reallocation.vault, reallocation.to.adapter);
1230
+ const targetIds = getAdapterIds(adapterIdsCache, targetAdapter, targetMarket);
1231
+ const [, , targetAdapterMarketCapId] = targetIds;
1232
+ const currentTargetMarket = data.getMarket(targetMarket.id);
1233
+ const oldTargetAllocation = data.getAllocation(reallocation.vault, targetAdapterMarketCapId).allocation;
1234
+ const supply = currentTargetMarket.supply(reallocation.assets, 0n, timestamp);
1235
+ const targetSupplyShares = (targetAdapter.supplyShares[targetMarket.id] ?? 0n) + supply.shares;
1236
+ targetAdapter.supplyShares[targetMarket.id] = targetSupplyShares;
1237
+ if (!targetAdapter.marketIds.includes(targetMarket.id))
1238
+ targetAdapter.marketIds.push(targetMarket.id);
1239
+ if (!targetAdapter.markets.some(({ id }) => id === targetMarket.id))
1240
+ targetAdapter.markets.push(supply.market);
1241
+ data.setMarkets([supply.market], probe ? [targetAdapter] : undefined);
1242
+ const targetChange = supply.market.toSupplyAssets(targetSupplyShares) - oldTargetAllocation;
1243
+ for (const id of targetIds) {
1244
+ const allocation = data.getAllocation(reallocation.vault, id);
1245
+ const nextAllocation = allocation.allocation + targetChange;
1246
+ if (nextAllocation < 0n) {
1247
+ throw new ReallocationAllocationUnderflowError({
1248
+ vault: reallocation.vault,
1249
+ id,
1250
+ allocation: allocation.allocation,
1251
+ change: targetChange,
1252
+ });
1253
+ }
1254
+ data.mutableAllocations[allocationsKey][id] = {
1255
+ ...allocation,
1256
+ allocation: nextAllocation,
1257
+ };
1258
+ }
1259
+ vault.assetBalance -= reallocation.assets;
1260
+ return { data, context: nextContext };
1261
+ }
1262
+ /** Updates canonical markets in bulk and refreshes only dependent adapter views. */
1263
+ setMarkets(markets, adaptersToRefresh) {
1264
+ const changedMarketIds = new Set();
1265
+ for (const market of markets) {
1266
+ this.mutableMarkets[market.id] = market;
1267
+ changedMarketIds.add(market.id);
1268
+ }
1269
+ if (changedMarketIds.size === 0)
1270
+ return;
1271
+ const adapters = new Set();
1272
+ if (adaptersToRefresh == null) {
1273
+ // A Morpho market is global state shared by every vault position. Legacy
1274
+ // AccrualPosition constructors copy their Market, so rebuild those adapter
1275
+ // views as well as repointing V2 adapters whenever the canonical state moves.
1276
+ for (const vault of Object.values(this.mutableVaults)) {
1277
+ if (vault == null)
1278
+ continue;
1279
+ for (const adapter of vault.accrualAdapters)
1280
+ adapters.add(adapter);
1281
+ if (vault.accrualLiquidityAdapter != null)
1282
+ adapters.add(vault.accrualLiquidityAdapter);
1283
+ }
1284
+ }
1285
+ else {
1286
+ for (const adapter of adaptersToRefresh)
1287
+ adapters.add(adapter);
1288
+ }
1289
+ for (const adapter of adapters) {
1290
+ if (adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2) {
1291
+ if (!adapter.markets.some(({ id }) => changedMarketIds.has(id)))
1292
+ continue;
1293
+ adapter.markets = adapter.markets.map((adapterMarket) => getCanonicalMarket(this.mutableMarkets, adapterMarket));
1294
+ }
1295
+ else if (adapter instanceof AccrualVaultV2MorphoMarketV1Adapter) {
1296
+ if (!adapter.positions.some(({ marketId }) => changedMarketIds.has(marketId)))
1297
+ continue;
1298
+ adapter.positions = adapter.positions.map((position) => clonePosition(position, this.mutableMarkets));
1299
+ }
1300
+ else if (adapter instanceof AccrualVaultV2MorphoVaultV1Adapter) {
1301
+ if (![...adapter.accrualVaultV1.allocations.keys()].some((marketId) => changedMarketIds.has(marketId)))
1302
+ continue;
1303
+ adapter.accrualVaultV1 = cloneAccrualVault(adapter.accrualVaultV1, this.mutableMarkets);
1304
+ }
1305
+ }
1306
+ }
1307
+ }