@morpho-org/morpho-sdk 9.1.0 → 9.3.0-next.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +5 -1
  2. package/lib/cjs/abis.d.ts +2 -2
  3. package/lib/cjs/abis.js +7 -1
  4. package/lib/cjs/actions/midnight/index.d.ts +1 -0
  5. package/lib/cjs/actions/midnight/index.js +1 -0
  6. package/lib/cjs/actions/midnight/withdrawCollateral.d.ts +50 -0
  7. package/lib/cjs/actions/midnight/withdrawCollateral.js +105 -0
  8. package/lib/cjs/blue/abis.d.ts +1 -1
  9. package/lib/cjs/blue/abis.js +5 -1
  10. package/lib/cjs/blue/constants.d.ts +1 -1
  11. package/lib/cjs/blue/constants.js +2 -1
  12. package/lib/cjs/blue/entities.d.ts +4 -4
  13. package/lib/cjs/blue/entities.js +3 -1
  14. package/lib/cjs/blue/errors.d.ts +2 -2
  15. package/lib/cjs/blue/errors.js +5 -1
  16. package/lib/cjs/blue/fetch.d.ts +2 -2
  17. package/lib/cjs/blue/fetch.js +3 -1
  18. package/lib/cjs/blue/utils.d.ts +1 -1
  19. package/lib/cjs/blue/utils.js +2 -1
  20. package/lib/cjs/constants.d.ts +2 -2
  21. package/lib/cjs/constants.js +4 -1
  22. package/lib/cjs/entities/blue/blue.d.ts +71 -16
  23. package/lib/cjs/entities/blue/blue.js +32 -4
  24. package/lib/cjs/entities/index.d.ts +5 -5
  25. package/lib/cjs/entities/index.js +3 -1
  26. package/lib/cjs/entities/midnight/midnight.d.ts +58 -11
  27. package/lib/cjs/entities/midnight/midnight.js +103 -11
  28. package/lib/cjs/entities/midnight/publication.d.ts +2 -1
  29. package/lib/cjs/entities/midnight/publication.js +44 -64
  30. package/lib/cjs/entities/midnight/types.d.ts +8 -0
  31. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +8 -0
  32. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -0
  33. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +37 -9
  34. package/lib/cjs/entities/vaultV2/vaultV2.js +36 -1
  35. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +42 -7
  36. package/lib/cjs/entities/vaultV2BlueReallocationData.js +206 -35
  37. package/lib/cjs/errors.d.ts +4 -4
  38. package/lib/cjs/errors.js +10 -5
  39. package/lib/cjs/fetch.d.ts +2 -2
  40. package/lib/cjs/fetch.js +3 -1
  41. package/lib/cjs/helpers/constant.d.ts +7 -0
  42. package/lib/cjs/helpers/constant.js +8 -1
  43. package/lib/cjs/helpers/deadShares.d.ts +82 -0
  44. package/lib/cjs/helpers/deadShares.js +202 -0
  45. package/lib/cjs/helpers/index.d.ts +2 -1
  46. package/lib/cjs/helpers/index.js +7 -1
  47. package/lib/cjs/midnight/abis.d.ts +1 -1
  48. package/lib/cjs/midnight/abis.js +3 -1
  49. package/lib/cjs/midnight/errors.d.ts +2 -1
  50. package/lib/cjs/midnight/errors.js +5 -4
  51. package/lib/cjs/types/action.d.ts +10 -1
  52. package/lib/cjs/types/error.d.ts +54 -5
  53. package/lib/cjs/types/error.js +60 -6
  54. package/lib/cjs/types/sharedLiquidity.d.ts +10 -6
  55. package/lib/cjs/utils.d.ts +2 -2
  56. package/lib/cjs/utils.js +4 -2
  57. package/lib/esm/abis.d.ts +2 -2
  58. package/lib/esm/abis.js +2 -2
  59. package/lib/esm/actions/midnight/index.d.ts +1 -0
  60. package/lib/esm/actions/midnight/index.js +1 -0
  61. package/lib/esm/actions/midnight/withdrawCollateral.d.ts +50 -0
  62. package/lib/esm/actions/midnight/withdrawCollateral.js +101 -0
  63. package/lib/esm/blue/abis.d.ts +1 -1
  64. package/lib/esm/blue/abis.js +1 -1
  65. package/lib/esm/blue/constants.d.ts +1 -1
  66. package/lib/esm/blue/constants.js +1 -1
  67. package/lib/esm/blue/entities.d.ts +4 -4
  68. package/lib/esm/blue/entities.js +2 -2
  69. package/lib/esm/blue/errors.d.ts +2 -2
  70. package/lib/esm/blue/errors.js +2 -2
  71. package/lib/esm/blue/fetch.d.ts +2 -2
  72. package/lib/esm/blue/fetch.js +2 -2
  73. package/lib/esm/blue/utils.d.ts +1 -1
  74. package/lib/esm/blue/utils.js +1 -1
  75. package/lib/esm/constants.d.ts +2 -2
  76. package/lib/esm/constants.js +2 -2
  77. package/lib/esm/entities/blue/blue.d.ts +71 -16
  78. package/lib/esm/entities/blue/blue.js +34 -6
  79. package/lib/esm/entities/index.d.ts +5 -5
  80. package/lib/esm/entities/index.js +2 -2
  81. package/lib/esm/entities/midnight/midnight.d.ts +58 -11
  82. package/lib/esm/entities/midnight/midnight.js +105 -13
  83. package/lib/esm/entities/midnight/publication.d.ts +2 -1
  84. package/lib/esm/entities/midnight/publication.js +45 -65
  85. package/lib/esm/entities/midnight/types.d.ts +8 -0
  86. package/lib/esm/entities/vaultV1/vaultV1.d.ts +8 -0
  87. package/lib/esm/entities/vaultV1/vaultV1.js +5 -0
  88. package/lib/esm/entities/vaultV2/vaultV2.d.ts +37 -9
  89. package/lib/esm/entities/vaultV2/vaultV2.js +36 -1
  90. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +42 -7
  91. package/lib/esm/entities/vaultV2BlueReallocationData.js +206 -35
  92. package/lib/esm/errors.d.ts +4 -4
  93. package/lib/esm/errors.js +4 -4
  94. package/lib/esm/fetch.d.ts +2 -2
  95. package/lib/esm/fetch.js +2 -2
  96. package/lib/esm/helpers/constant.d.ts +7 -0
  97. package/lib/esm/helpers/constant.js +7 -0
  98. package/lib/esm/helpers/deadShares.d.ts +82 -0
  99. package/lib/esm/helpers/deadShares.js +197 -0
  100. package/lib/esm/helpers/index.d.ts +2 -1
  101. package/lib/esm/helpers/index.js +2 -1
  102. package/lib/esm/midnight/abis.d.ts +1 -1
  103. package/lib/esm/midnight/abis.js +1 -1
  104. package/lib/esm/midnight/errors.d.ts +2 -1
  105. package/lib/esm/midnight/errors.js +2 -1
  106. package/lib/esm/types/action.d.ts +10 -1
  107. package/lib/esm/types/error.d.ts +54 -5
  108. package/lib/esm/types/error.js +57 -5
  109. package/lib/esm/types/sharedLiquidity.d.ts +10 -6
  110. package/lib/esm/utils.d.ts +2 -2
  111. package/lib/esm/utils.js +2 -2
  112. package/package.json +9 -8
@@ -26,6 +26,16 @@ export interface InputVaultV2BlueReallocationData {
26
26
  * defaults to the latest market/vault `lastUpdate`.
27
27
  */
28
28
  readonly timestamp?: BigIntish;
29
+ /**
30
+ * Morpho Blue's ERC-20 balances at the snapshot block, indexed by token address.
31
+ * Explicit balances increase with idle-sourced reallocations in returned
32
+ * post-states. Sizing has zero margin over the snapshot balance, so activity
33
+ * on other Blue markets with the same loan token can make a plan revert;
34
+ * refetch close to submission. A missing token uses summed non-negative
35
+ * snapshot-market supply-minus-borrow only to size plans; balance-based
36
+ * rejection requires an explicit balance.
37
+ */
38
+ readonly blueBalances?: Readonly<Record<Address, BigIntish | undefined>>;
29
39
  /** Markets indexed by market id. */
30
40
  readonly markets?: Readonly<Record<MarketId, ReadonlyMarketSnapshot | undefined>>;
31
41
  /** Accrued Vault V2 entities indexed by vault address. */
@@ -46,8 +56,9 @@ export interface InputVaultV2BlueReallocationData {
46
56
  /**
47
57
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
48
58
  *
49
- * Constructor inputs are cloned. Every simulated reallocation returns a new
50
- * instance. Planning keeps the transaction-scoped `firstTotalAssets`
59
+ * Constructor inputs are cloned, except Midnight adapter snapshots: those are
60
+ * shared by reference and must be treated as read-only. Every simulated
61
+ * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
51
62
  * denominator outside the durable snapshot while applying reallocations in
52
63
  * contract order. Penalty donations update simulated vault accounting but are
53
64
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -83,10 +94,22 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
83
94
  private readonly mutableVaults;
84
95
  /** Mutable allocation state used only by cloned simulation transitions. */
85
96
  private readonly mutableAllocations;
97
+ /** Mutable Blue token balances used only by cloned simulation transitions. */
98
+ private readonly mutableBlueBalances;
86
99
  /** Chain id associated with this snapshot. */
87
100
  readonly chainId: number;
88
101
  /** Timestamp of the block the state was fetched at. */
89
102
  readonly timestamp?: bigint;
103
+ /**
104
+ * Morpho Blue's ERC-20 balances at the snapshot block, indexed by token address.
105
+ * Explicit balances increase with idle-sourced reallocations in returned
106
+ * post-states. Sizing has zero margin over the snapshot balance, so activity
107
+ * on other Blue markets with the same loan token can make a plan revert;
108
+ * refetch close to submission. A missing token uses summed non-negative
109
+ * snapshot-market supply-minus-borrow only to size plans; balance-based
110
+ * rejection requires an explicit balance.
111
+ */
112
+ readonly blueBalances: Readonly<Record<Address, bigint | undefined>>;
90
113
  /** Markets indexed by market id. */
91
114
  readonly markets: Readonly<Record<MarketId, ReadonlyMarketSnapshot | undefined>>;
92
115
  /** Vault V2 entities indexed by address. */
@@ -109,7 +132,8 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
109
132
  /**
110
133
  * Clones the complete simulation snapshot.
111
134
  *
112
- * @returns A deep clone of this simulation state.
135
+ * @returns A deep clone of this simulation state. Midnight adapter snapshots are
136
+ * shared by reference and must be treated as read-only.
113
137
  * @example
114
138
  * ```ts
115
139
  * import { markets } from "@morpho-org/morpho-test";
@@ -367,8 +391,9 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
367
391
  * Without `options.operation`, discovers every friendly call. With an
368
392
  * operation, penalty tiers are considered ascending, starting with free
369
393
  * vaults. The free tier aims to bring the target market back to 90%
370
- * utilization; positive tiers cover only the remaining absolute shortfall
371
- * (borrows minus supply). Within each tier, source markets go to the
394
+ * utilization; positive tiers cover the remaining absolute shortfall or,
395
+ * when larger, Blue's loan-token balance deficit while the penalty is
396
+ * flash-loaned. Within each tier, source markets go to the
372
397
  * friendly source utilization (90% by default) before 100%. Free capacity
373
398
  * inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
374
399
  * it instead. Discovery and liquidity getters still count every vault up to
@@ -382,6 +407,16 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
382
407
  * The planner includes the referral fee and its allocator-leg penalties in
383
408
  * destination debt, so penalized legs also cover their own penalty.
384
409
  * Refinance never uses vaults with a 100% penalty.
410
+ * BlueBundlesV1 flash-loans the plan's penalty from Blue before executing
411
+ * reallocation legs. When an explicit `blueBalances` value is supplied, plans
412
+ * throw `InsufficientSharedLiquidityError` if Blue cannot fund that flash
413
+ * loan or a market-sourced leg's withdrawal before later idle legs arrive.
414
+ * Legs are not reordered. A missing balance falls back to summed snapshot-
415
+ * market liquidity only to size plans and may make them larger; it cannot
416
+ * cause rejection for Blue-balance constraints.
417
+ * Sizing has zero margin over the snapshot balance; activity on other Blue
418
+ * markets with the same loan token can make a plan revert. Refetch close to
419
+ * submission; there is no balance-buffer option.
385
420
  * Friendly source utilization defaults to 90% and is configurable through
386
421
  * `options.maxWithdrawalUtilization`. Market/vault state and the returned
387
422
  * post-state stay at `timestamp`. An enabled operation that needs no
@@ -429,7 +464,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
429
464
  * @returns Flat action-ready reallocations and their post-simulation state.
430
465
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
431
466
  * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
432
- * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
467
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD, or an enabled borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
433
468
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
434
469
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
435
470
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -438,7 +473,7 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
438
473
  * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
439
474
  * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
440
475
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
441
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall and, for refinance, its planned allocator penalties.
476
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund the penalty flash loan, an earlier market-sourced withdrawal, or the final operation transfer.
442
477
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
443
478
  * @example
444
479
  * ```ts
@@ -87,6 +87,10 @@ const cloneAccrualVault = (vault, markets) => new AccrualVault({
87
87
  position: clonePosition(position, markets),
88
88
  })));
89
89
  const cloneAdapter = (adapter, markets) => {
90
+ // BluePublicAllocator never moves Midnight liquidity, and reallocation never mutates a Midnight
91
+ // adapter, so its read-only snapshot is shared as-is.
92
+ if (adapter.type === "VaultV2MidnightAdapter")
93
+ return adapter;
90
94
  const base = {
91
95
  address: adapter.address,
92
96
  parentVault: adapter.parentVault,
@@ -134,8 +138,9 @@ const cloneVault = (vault, { markets, adapterKeysToClone, }) => {
134
138
  /**
135
139
  * Immutable-by-convention state container for Vault V2 BluePublicAllocator simulations.
136
140
  *
137
- * Constructor inputs are cloned. Every simulated reallocation returns a new
138
- * instance. Planning keeps the transaction-scoped `firstTotalAssets`
141
+ * Constructor inputs are cloned, except Midnight adapter snapshots: those are
142
+ * shared by reference and must be treated as read-only. Every simulated
143
+ * reallocation returns a new instance. Planning keeps the transaction-scoped `firstTotalAssets`
139
144
  * denominator outside the durable snapshot while applying reallocations in
140
145
  * contract order. Penalty donations update simulated vault accounting but are
141
146
  * excluded from same-plan idle liquidity so round-up dust cannot create
@@ -171,10 +176,22 @@ export class VaultV2BlueReallocationData {
171
176
  mutableVaults;
172
177
  /** Mutable allocation state used only by cloned simulation transitions. */
173
178
  mutableAllocations;
179
+ /** Mutable Blue token balances used only by cloned simulation transitions. */
180
+ mutableBlueBalances;
174
181
  /** Chain id associated with this snapshot. */
175
182
  chainId;
176
183
  /** Timestamp of the block the state was fetched at. */
177
184
  timestamp;
185
+ /**
186
+ * Morpho Blue's ERC-20 balances at the snapshot block, indexed by token address.
187
+ * Explicit balances increase with idle-sourced reallocations in returned
188
+ * post-states. Sizing has zero margin over the snapshot balance, so activity
189
+ * on other Blue markets with the same loan token can make a plan revert;
190
+ * refetch close to submission. A missing token uses summed non-negative
191
+ * snapshot-market supply-minus-borrow only to size plans; balance-based
192
+ * rejection requires an explicit balance.
193
+ */
194
+ blueBalances;
178
195
  /** Markets indexed by market id. */
179
196
  markets;
180
197
  /** Vault V2 entities indexed by address. */
@@ -201,9 +218,11 @@ export class VaultV2BlueReallocationData {
201
218
  this.mutableMarkets = {};
202
219
  this.mutableVaults = {};
203
220
  this.mutableAllocations = {};
221
+ this.mutableBlueBalances = {};
204
222
  this.markets = this.mutableMarkets;
205
223
  this.vaults = this.mutableVaults;
206
224
  this.allocations = this.mutableAllocations;
225
+ this.blueBalances = this.mutableBlueBalances;
207
226
  if (isClone) {
208
227
  this.publicAllocatorConfigs = input.publicAllocatorConfigs;
209
228
  this.activeAdapters = input.activeAdapters;
@@ -240,6 +259,10 @@ export class VaultV2BlueReallocationData {
240
259
  this.mutableMarkets[marketId] =
241
260
  market == null ? undefined : new Market({ ...market });
242
261
  }
262
+ for (const [token, balance] of Object.entries(input.blueBalances ?? {})) {
263
+ this.mutableBlueBalances[token] =
264
+ balance == null ? undefined : BigInt(balance);
265
+ }
243
266
  for (const [address, vault] of Object.entries(input.vaults ?? {})) {
244
267
  const clonedVault = vault == null
245
268
  ? undefined
@@ -261,7 +284,8 @@ export class VaultV2BlueReallocationData {
261
284
  /**
262
285
  * Clones the complete simulation snapshot.
263
286
  *
264
- * @returns A deep clone of this simulation state.
287
+ * @returns A deep clone of this simulation state. Midnight adapter snapshots are
288
+ * shared by reference and must be treated as read-only.
265
289
  * @example
266
290
  * ```ts
267
291
  * import { markets } from "@morpho-org/morpho-test";
@@ -572,8 +596,9 @@ export class VaultV2BlueReallocationData {
572
596
  * Without `options.operation`, discovers every friendly call. With an
573
597
  * operation, penalty tiers are considered ascending, starting with free
574
598
  * vaults. The free tier aims to bring the target market back to 90%
575
- * utilization; positive tiers cover only the remaining absolute shortfall
576
- * (borrows minus supply). Within each tier, source markets go to the
599
+ * utilization; positive tiers cover the remaining absolute shortfall or,
600
+ * when larger, Blue's loan-token balance deficit while the penalty is
601
+ * flash-loaned. Within each tier, source markets go to the
577
602
  * friendly source utilization (90% by default) before 100%. Free capacity
578
603
  * inside `allocatorCapHeadroom` is kept unused, so a penalized leg can cover
579
604
  * it instead. Discovery and liquidity getters still count every vault up to
@@ -587,6 +612,16 @@ export class VaultV2BlueReallocationData {
587
612
  * The planner includes the referral fee and its allocator-leg penalties in
588
613
  * destination debt, so penalized legs also cover their own penalty.
589
614
  * Refinance never uses vaults with a 100% penalty.
615
+ * BlueBundlesV1 flash-loans the plan's penalty from Blue before executing
616
+ * reallocation legs. When an explicit `blueBalances` value is supplied, plans
617
+ * throw `InsufficientSharedLiquidityError` if Blue cannot fund that flash
618
+ * loan or a market-sourced leg's withdrawal before later idle legs arrive.
619
+ * Legs are not reordered. A missing balance falls back to summed snapshot-
620
+ * market liquidity only to size plans and may make them larger; it cannot
621
+ * cause rejection for Blue-balance constraints.
622
+ * Sizing has zero margin over the snapshot balance; activity on other Blue
623
+ * markets with the same loan token can make a plan revert. Refetch close to
624
+ * submission; there is no balance-buffer option.
590
625
  * Friendly source utilization defaults to 90% and is configurable through
591
626
  * `options.maxWithdrawalUtilization`. Market/vault state and the returned
592
627
  * post-state stay at `timestamp`. An enabled operation that needs no
@@ -634,7 +669,7 @@ export class VaultV2BlueReallocationData {
634
669
  * @returns Flat action-ready reallocations and their post-simulation state.
635
670
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
636
671
  * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, `maxPenalty`, or `referralFeePct` is negative.
637
- * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
672
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD, or an enabled borrow/withdraw plan otherwise covers its shortfall but its planned penalty exceeds the operation amount.
638
673
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is at least WAD.
639
674
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
640
675
  * @throws {UnknownReallocationMarketError} when a required market is absent.
@@ -643,7 +678,7 @@ export class VaultV2BlueReallocationData {
643
678
  * @throws {UnknownReallocationActiveAdaptersError} when active-adapter state is absent for a vault.
644
679
  * @throws {UnknownReallocationMarketPublicAllocatorConfigError} when an adapter-market allocator configuration is absent.
645
680
  * @throws {UnknownReallocationAllocationError} when required allocation state is absent.
646
- * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the absolute shortfall and, for refinance, its planned allocator penalties.
681
+ * @throws {InsufficientSharedLiquidityError} when selected liquidity cannot cover the operation shortfall or refinance penalties, or an explicit Blue balance cannot fund the penalty flash loan, an earlier market-sourced withdrawal, or the final operation transfer.
647
682
  * @throws {ReallocationWithdrawExceedsMarketSupplyError} when a withdraw exceeds market supply.
648
683
  * @example
649
684
  * ```ts
@@ -716,6 +751,31 @@ export class VaultV2BlueReallocationData {
716
751
  : [...options.reallocatableVaults],
717
752
  };
718
753
  const market = this.getMarket(marketId).accrueInterest(timestamp);
754
+ const blueBalanceKey = findAddressKey(this.mutableBlueBalances, market.params.loanToken);
755
+ const explicitBlueBalance = blueBalanceKey == null
756
+ ? undefined
757
+ : this.mutableBlueBalances[blueBalanceKey];
758
+ const hasExplicitBlueBalance = explicitBlueBalance !== undefined;
759
+ const blueBalance = explicitBlueBalance ??
760
+ Object.values(this.mutableMarkets).reduce((total, snapshotMarket) => snapshotMarket != null &&
761
+ isAddressEqual(snapshotMarket.params.loanToken, market.params.loanToken)
762
+ ? total +
763
+ MathLib.zeroFloorSub(snapshotMarket.totalSupplyAssets, snapshotMarket.totalBorrowAssets)
764
+ : total, 0n);
765
+ const getTransferShortfall = (reallocations) => {
766
+ const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
767
+ if (penaltyAssets === 0n)
768
+ return 0n;
769
+ let shortfall = MathLib.zeroFloorSub(penaltyAssets, blueBalance);
770
+ let balance = MathLib.zeroFloorSub(blueBalance, penaltyAssets);
771
+ for (const { from, assets } of reallocations) {
772
+ if (from.type === "idle")
773
+ balance += assets;
774
+ else
775
+ shortfall = MathLib.max(shortfall, MathLib.zeroFloorSub(assets, balance));
776
+ }
777
+ return shortfall;
778
+ };
719
779
  if (type === "withdraw" && amount > market.totalSupplyAssets) {
720
780
  throw new ReallocationWithdrawExceedsMarketSupplyError({
721
781
  marketId,
@@ -757,25 +817,30 @@ export class VaultV2BlueReallocationData {
757
817
  let data = this.clone();
758
818
  let context = createSimulationContext();
759
819
  let remainingShortfall = absoluteShortfall;
820
+ let accountingShortfall = absoluteShortfall;
760
821
  let allocatorCapBoundTargets = new Set();
761
822
  let idleBoundVaults = new Set();
762
823
  for (const penalty of penaltyTiers) {
763
824
  if (type === "refinance" && penalty === MathLib.WAD)
764
825
  continue;
765
826
  let isFriendlyPass = true;
827
+ let triedFullCapacityAttempt = false;
766
828
  for (const utilization of [maxWithdrawalUtilization, MathLib.WAD]) {
767
829
  const isFreeFriendlyPass = penalty === 0n && isFriendlyPass;
768
830
  isFriendlyPass = false;
769
831
  if (remainingShortfall === 0n && !isFreeFriendlyPass)
770
832
  continue;
771
- let passMaxAssets = isFreeFriendlyPass
772
- ? maxAssets
773
- : remainingShortfall;
774
- const retryPaidPass = type === "refinance" && penalty > 0n;
775
- if (retryPaidPass) {
776
- passMaxAssets = MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
777
- }
833
+ let passMaxAssets = type === "refinance" && penalty > 0n
834
+ ? MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty)
835
+ : isFreeFriendlyPass
836
+ ? maxAssets
837
+ : remainingShortfall;
838
+ const retryPaidPass = penalty > 0n;
778
839
  let lo = retryPaidPass ? passMaxAssets - 1n : 0n;
840
+ let tryFullCapacityAttempt = false;
841
+ let isFullCapacityRetryPath = false;
842
+ const beforePassRemainingShortfall = remainingShortfall;
843
+ const beforePassAccountingShortfall = accountingShortfall;
779
844
  // Grow by grossed-up gaps, bisect to the smallest found, and keep the best for non-monotonic shared-cap fitting.
780
845
  const passStart = retryPaidPass
781
846
  ? {
@@ -786,9 +851,12 @@ export class VaultV2BlueReallocationData {
786
851
  }
787
852
  : undefined;
788
853
  let previousPassReallocatedAssets = 0n;
854
+ let previousPhysicalShortfall;
789
855
  let hi;
790
856
  let bestAttempt;
791
857
  while (true) {
858
+ const isFullCapacityAttempt = tryFullCapacityAttempt;
859
+ tryFullCapacityAttempt = false;
792
860
  if (passStart != null) {
793
861
  data = passStart.data.clone();
794
862
  context = passStart.context;
@@ -800,7 +868,7 @@ export class VaultV2BlueReallocationData {
800
868
  reserves,
801
869
  marketId,
802
870
  maxWithdrawalUtilization: utilization,
803
- maxAssets: passMaxAssets,
871
+ maxAssets: isFullCapacityAttempt ? undefined : passMaxAssets,
804
872
  capAccrualBuffer,
805
873
  allocatorCapHeadroom: headroom,
806
874
  penalty,
@@ -828,23 +896,56 @@ export class VaultV2BlueReallocationData {
828
896
  const supply = type === "withdraw"
829
897
  ? currentMarket.totalSupplyAssets - amount
830
898
  : currentMarket.totalSupplyAssets;
831
- remainingShortfall = borrow > supply ? borrow - supply : 0n;
899
+ accountingShortfall = borrow > supply ? borrow - supply : 0n;
900
+ const penaltyForPhysicalShortfall = getBlueBundlesV1PenaltyAssets(reallocations);
901
+ const idleAssetsForPhysicalShortfall = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
902
+ const physicalShortfall = penaltyForPhysicalShortfall === 0n
903
+ ? 0n
904
+ : MathLib.zeroFloorSub((type === "refinance"
905
+ ? amount + feeAssets + penaltyForPhysicalShortfall
906
+ : amount) + penaltyForPhysicalShortfall, blueBalance + idleAssetsForPhysicalShortfall);
907
+ remainingShortfall = MathLib.max(accountingShortfall, physicalShortfall);
908
+ const attemptTransferShortfall = hasExplicitBlueBalance && isFullCapacityRetryPath
909
+ ? getTransferShortfall(reallocations)
910
+ : 0n;
911
+ const attemptCoversShortfall = remainingShortfall === 0n;
832
912
  const passReallocatedAssets = pass.reallocations.reduce((total, { assets }) => total + assets, 0n);
833
913
  if (passStart == null)
834
914
  break;
835
- if (bestAttempt == null ||
836
- remainingShortfall < bestAttempt.remainingShortfall ||
837
- (remainingShortfall === bestAttempt.remainingShortfall &&
838
- passReallocatedAssets < bestAttempt.passReallocatedAssets))
915
+ if (isFullCapacityAttempt)
916
+ passMaxAssets = passReallocatedAssets;
917
+ const improvesAccounting = accountingShortfall < beforePassAccountingShortfall;
918
+ const attemptPriority = hasExplicitBlueBalance
919
+ ? [0n, remainingShortfall, 0n, passReallocatedAssets]
920
+ : [
921
+ improvesAccounting ? 0n : 1n,
922
+ improvesAccounting ? accountingShortfall : 0n,
923
+ remainingShortfall,
924
+ passReallocatedAssets,
925
+ ];
926
+ const previousBestAttempt = bestAttempt;
927
+ let isBetterAttempt = previousBestAttempt == null;
928
+ if (previousBestAttempt != null) {
929
+ const firstDifference = attemptPriority.findIndex((priority, index) => priority !== previousBestAttempt.priority[index]);
930
+ isBetterAttempt =
931
+ firstDifference !== -1 &&
932
+ attemptPriority[firstDifference] <
933
+ previousBestAttempt.priority[firstDifference];
934
+ }
935
+ if (isBetterAttempt &&
936
+ (!isFullCapacityRetryPath ||
937
+ (attemptCoversShortfall && attemptTransferShortfall === 0n)))
839
938
  bestAttempt = {
840
939
  data,
841
940
  context,
842
941
  reserves: cloneCapReserveState(reserves),
843
942
  reallocations: pass.reallocations,
844
943
  remainingShortfall,
944
+ accountingShortfall,
845
945
  passReallocatedAssets,
946
+ priority: attemptPriority,
846
947
  };
847
- if (remainingShortfall === 0n)
948
+ if (attemptCoversShortfall)
848
949
  hi = hi == null ? passMaxAssets : MathLib.min(hi, passMaxAssets);
849
950
  else
850
951
  lo = MathLib.max(lo, passMaxAssets);
@@ -854,18 +955,52 @@ export class VaultV2BlueReallocationData {
854
955
  passMaxAssets = (lo + hi) / 2n;
855
956
  continue;
856
957
  }
857
- if (passReallocatedAssets <= previousPassReallocatedAssets)
958
+ if (isFullCapacityAttempt && !attemptCoversShortfall)
959
+ break;
960
+ if (accountingShortfall === 0n &&
961
+ previousPhysicalShortfall != null &&
962
+ physicalShortfall >= previousPhysicalShortfall) {
963
+ if (!triedFullCapacityAttempt &&
964
+ passReallocatedAssets === passMaxAssets) {
965
+ triedFullCapacityAttempt = true;
966
+ tryFullCapacityAttempt = true;
967
+ isFullCapacityRetryPath = true;
968
+ continue;
969
+ }
970
+ break;
971
+ }
972
+ previousPhysicalShortfall = physicalShortfall;
973
+ if (passReallocatedAssets <= previousPassReallocatedAssets ||
974
+ penalty === MathLib.WAD)
858
975
  break;
859
976
  previousPassReallocatedAssets = passReallocatedAssets;
860
977
  passMaxAssets += MathLib.mulDivUp(remainingShortfall, MathLib.WAD, MathLib.WAD - penalty);
861
978
  }
862
- if (passStart != null && bestAttempt != null) {
863
- data = bestAttempt.data;
864
- context = bestAttempt.context;
865
- reserves = cloneCapReserveState(bestAttempt.reserves);
866
- reallocations.length = passStart.reallocationCount;
867
- reallocations.push(...bestAttempt.reallocations);
868
- remainingShortfall = bestAttempt.remainingShortfall;
979
+ if (passStart != null) {
980
+ const improved = bestAttempt != null &&
981
+ (hasExplicitBlueBalance
982
+ ? bestAttempt.remainingShortfall < beforePassRemainingShortfall
983
+ : bestAttempt.accountingShortfall <
984
+ beforePassAccountingShortfall ||
985
+ bestAttempt.remainingShortfall <
986
+ beforePassRemainingShortfall);
987
+ if (improved && bestAttempt != null) {
988
+ data = bestAttempt.data;
989
+ context = bestAttempt.context;
990
+ reserves = cloneCapReserveState(bestAttempt.reserves);
991
+ reallocations.length = passStart.reallocationCount;
992
+ reallocations.push(...bestAttempt.reallocations);
993
+ remainingShortfall = bestAttempt.remainingShortfall;
994
+ accountingShortfall = bestAttempt.accountingShortfall;
995
+ }
996
+ else {
997
+ data = passStart.data;
998
+ context = passStart.context;
999
+ reserves = cloneCapReserveState(passStart.reserves);
1000
+ reallocations.length = passStart.reallocationCount;
1001
+ remainingShortfall = beforePassRemainingShortfall;
1002
+ accountingShortfall = beforePassAccountingShortfall;
1003
+ }
869
1004
  }
870
1005
  }
871
1006
  }
@@ -878,16 +1013,28 @@ export class VaultV2BlueReallocationData {
878
1013
  !(from.type === "idle" && idleBoundVaults.has(vault.toLowerCase())))
879
1014
  unboundAssets += assets;
880
1015
  }
1016
+ const penaltyAssets = getBlueBundlesV1PenaltyAssets(reallocations);
1017
+ const idleAssets = reallocations.reduce((total, { from, assets }) => from.type === "idle" ? total + assets : total, 0n);
1018
+ const physicalShortfall = penaltyAssets === 0n
1019
+ ? 0n
1020
+ : MathLib.zeroFloorSub((type === "refinance"
1021
+ ? amount + feeAssets + penaltyAssets
1022
+ : amount) + penaltyAssets, blueBalance + idleAssets);
1023
+ const transferShortfall = getTransferShortfall(reallocations);
1024
+ const coversAccountingShortfall = type === "refinance"
1025
+ ? reallocatedAssets >= absoluteShortfall + penaltyAssets
1026
+ : reallocatedAssets >= absoluteShortfall;
881
1027
  return {
882
1028
  reallocations,
883
1029
  data,
884
1030
  liquidityBound: allocatorCapBoundTargets.size > 0 || idleBoundVaults.size > 0,
885
1031
  reallocatedAssets,
886
1032
  unboundAssets,
887
- coversShortfall: type === "refinance"
888
- ? reallocatedAssets >=
889
- absoluteShortfall + getBlueBundlesV1PenaltyAssets(reallocations)
890
- : reallocatedAssets >= absoluteShortfall,
1033
+ physicalShortfall,
1034
+ coversShortfall: coversAccountingShortfall &&
1035
+ (type === "refinance" || penaltyAssets <= amount) &&
1036
+ (!hasExplicitBlueBalance ||
1037
+ (physicalShortfall === 0n && transferShortfall === 0n)),
891
1038
  };
892
1039
  };
893
1040
  // A leg that fills an allocator cap, or idle legs that together take
@@ -915,12 +1062,30 @@ export class VaultV2BlueReallocationData {
915
1062
  available = selected.reallocatedAssets;
916
1063
  }
917
1064
  if (!selected.coversShortfall) {
1065
+ const selectedTransferShortfall = hasExplicitBlueBalance
1066
+ ? getTransferShortfall(selected.reallocations)
1067
+ : 0n;
1068
+ const selectedPenaltyAssets = getBlueBundlesV1PenaltyAssets(selected.reallocations);
1069
+ if (type !== "refinance" &&
1070
+ selectedPenaltyAssets > amount &&
1071
+ selected.reallocatedAssets >= absoluteShortfall &&
1072
+ (!hasExplicitBlueBalance ||
1073
+ (selected.physicalShortfall === 0n &&
1074
+ selectedTransferShortfall === 0n)))
1075
+ throw new InputExceedsMaxError({
1076
+ field: "reallocationPenaltyAssets",
1077
+ value: selectedPenaltyAssets,
1078
+ max: amount,
1079
+ });
918
1080
  throw new InsufficientSharedLiquidityError({
919
1081
  marketId,
920
- shortfall: absoluteShortfall +
1082
+ shortfall: MathLib.max(absoluteShortfall +
921
1083
  (type === "refinance"
922
1084
  ? getBlueBundlesV1PenaltyAssets(selected.reallocations)
923
- : 0n),
1085
+ : 0n), selected.reallocatedAssets +
1086
+ (hasExplicitBlueBalance
1087
+ ? MathLib.max(selected.physicalShortfall, selectedTransferShortfall)
1088
+ : 0n)),
924
1089
  available,
925
1090
  });
926
1091
  }
@@ -1569,6 +1734,12 @@ export class VaultV2BlueReallocationData {
1569
1734
  }
1570
1735
  vault.assetBalance += reallocation.assets;
1571
1736
  }
1737
+ if (reallocation.from.type === "idle") {
1738
+ const blueBalanceKey = findAddressKey(data.mutableBlueBalances, targetMarket.params.loanToken);
1739
+ if (blueBalanceKey != null &&
1740
+ data.mutableBlueBalances[blueBalanceKey] != null)
1741
+ data.mutableBlueBalances[blueBalanceKey] += reallocation.assets;
1742
+ }
1572
1743
  if (firstTotalAssets == null) {
1573
1744
  // Vault V2's transient firstTotalAssets tracks the first allocation in a
1574
1745
  // transaction independently from elapsed time. Later allocations must not
@@ -1,7 +1,7 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
6
  export type { ErrorClass } from "@morpho-org/morpho-ts";
7
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
7
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
package/lib/esm/errors.js CHANGED
@@ -1,6 +1,6 @@
1
- export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
1
+ export { BlueErrors, IncompleteChainRegistryError, InvalidMarketParamsError as InvalidBlueMarketParamsError, InvalidVaultV2MidnightAdapterMarketsError as InvalidBlueVaultV2MidnightAdapterMarketsError, UnknownAddressError, UnknownDataError as UnknownBlueDataError, UnknownFactory as UnknownBlueFactory, UnknownMarketAllocationError as UnknownBlueMarketAllocationError, UnknownMarketParamsError as UnknownBlueMarketParamsError, UnknownOfFactory as UnknownBlueOfFactory, UnknownTokenError as UnknownBlueTokenError, UnknownTokenPriceError as UnknownBlueTokenPriceError, UnknownVaultConfigError as UnknownBlueVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError as UnsupportedBlueMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError as UnsupportedBluePreLiquidationParamsError, UnsupportedVaultV2AdapterError as UnsupportedBlueVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
- export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
- export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
4
+ export { getUnsupportedVaultV2Adapter as getBlueUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError as isBlueUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError as BlueMarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, Permit2ExpirationOutOfRangeError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError as BlueUnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
5
+ export { ChainIdMismatchError as MidnightChainIdMismatchError, InvalidEcrecoverSignatureVError as InvalidMidnightEcrecoverSignatureVError, InvalidMarketParameterError as InvalidMidnightMarketParameterError, InvalidMidnightApiQuoteTargetError, InvalidMidnightApiResponseError, InvalidOfferGroupError as InvalidMidnightOfferGroupError, InvalidOfferParameterError as InvalidMidnightOfferParameterError, InvalidRateRatifierV1RateError as InvalidMidnightRateRatifierV1RateError, InvalidRateRatifierV1TickError as InvalidMidnightRateRatifierV1TickError, InvalidRateRatifierV1TimeError as InvalidMidnightRateRatifierV1TimeError, InvalidRatifierV1AddressError as InvalidMidnightRatifierV1AddressError, InvalidTickSpacingError as InvalidMidnightTickSpacingError, InvalidTreeError as InvalidMidnightTreeError, InvalidTreeHeightError as InvalidMidnightTreeHeightError, InvalidTypedDataSignatureError as InvalidMidnightTypedDataSignatureError, MidnightApiError, MidnightMempoolValidationError, PayloadDecodeError as MidnightPayloadDecodeError, PriceGreaterThanOneError as MidnightPriceGreaterThanOneError, RateRatifierV1BoundOverflowError as MidnightRateRatifierV1BoundOverflowError, RatifierV1TakerNotAllowedError as MidnightRatifierV1TakerNotAllowedError, SettlementFeeExceedsPriceError as MidnightSettlementFeeExceedsPriceError, TickOutOfRangeError as MidnightTickOutOfRangeError, UnknownCollateralIndexError as UnknownMidnightCollateralIndexError, } from "@morpho-org/midnight-sdk";
6
+ export { _try, DivisionByZeroError, InvalidAddressError, InvalidBitLengthError, InvalidPositionAccrualStateError, InvalidPositionAccrualStateError as InvalidMidnightPositionAccrualStateError, InvalidPositionAccrualTimestampError, InvalidPositionAccrualTimestampError as InvalidMidnightPositionAccrualTimestampError, InvalidPositionLossFactorError, InvalidPositionLossFactorError as InvalidMidnightPositionLossFactorError, NegativeValueError, RegistryValueAlreadyRegisteredError, } from "@morpho-org/morpho-ts";
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
package/lib/esm/fetch.js CHANGED
@@ -1,6 +1,6 @@
1
- export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
1
+ export { fetchAccrualPosition as fetchBlueAccrualPosition, fetchAccrualVault, fetchAccrualVaultV2, fetchAccrualVaultV2Adapter, fetchAccrualVaultV2MidnightAdapter, fetchAccrualVaultV2MorphoMarketV1Adapter, fetchAccrualVaultV2MorphoMarketV1AdapterV2, fetchAccrualVaultV2MorphoVaultV1Adapter, fetchHolding, fetchMarket as fetchBlueMarket, fetchMarketParams as fetchBlueMarketParams, fetchPosition as fetchBluePosition,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  fetchPreLiquidationParams as fetchBluePreLiquidationParams,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
- fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
5
+ fetchPreLiquidationPosition as fetchBluePreLiquidationPosition, fetchToken, fetchUser as fetchBlueUser, fetchVault, fetchVaultConfig, fetchVaultMarketAllocation, fetchVaultMarketConfig, fetchVaultUser, fetchVaultV2, fetchVaultV2Adapter, fetchVaultV2BlueMarketPublicAllocatorConfig, fetchVaultV2BluePublicAllocatorConfig, fetchVaultV2BluePublicAllocatorData, fetchVaultV2MidnightAdapter, fetchVaultV2MorphoMarketV1Adapter, fetchVaultV2MorphoMarketV1AdapterV2, fetchVaultV2MorphoVaultV1Adapter, } from "@morpho-org/blue-sdk-viem";
6
6
  export { fetchAccrualPosition as fetchMidnightAccrualPosition, fetchMarket as fetchMidnightMarket, fetchMarketParams as fetchMidnightMarketParams, fetchPosition as fetchMidnightPosition, fetchRatifierInfo as fetchMidnightRatifierInfo, } from "@morpho-org/midnight-sdk";
@@ -30,6 +30,13 @@ export declare const DEFAULT_CAP_ACCRUAL_BUFFER: bigint;
30
30
  * `VaultV2BluePublicAllocatorOptions.allocatorCapHeadroom`.
31
31
  */
32
32
  export declare const DEFAULT_ALLOCATOR_CAP_HEADROOM: bigint;
33
+ /**
34
+ * Minimum shares a Morpho Blue market, Vault V1 or Vault V2 must hold at `DEAD_ADDRESS` to count as
35
+ * protected against share-price inflation (1e9, Protocol team rule).
36
+ */
37
+ export declare const MIN_DEAD_SHARES = 1000000000n;
38
+ /** Minimum assets, in the vault asset's smallest unit, a Vault V2's dead shares must be worth (1e6). */
39
+ export declare const MIN_VAULT_V2_DEAD_ASSETS = 1000000n;
33
40
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
34
41
  export declare const MAX_ABSOLUTE_SHARE_PRICE: bigint;
35
42
  /**
@@ -32,6 +32,13 @@ export const DEFAULT_CAP_ACCRUAL_BUFFER = Time.s.from.h(2n);
32
32
  * `VaultV2BluePublicAllocatorOptions.allocatorCapHeadroom`.
33
33
  */
34
34
  export const DEFAULT_ALLOCATOR_CAP_HEADROOM = MathLib.WAD / 100n;
35
+ /**
36
+ * Minimum shares a Morpho Blue market, Vault V1 or Vault V2 must hold at `DEAD_ADDRESS` to count as
37
+ * protected against share-price inflation (1e9, Protocol team rule).
38
+ */
39
+ export const MIN_DEAD_SHARES = 1000000000n;
40
+ /** Minimum assets, in the vault asset's smallest unit, a Vault V2's dead shares must be worth (1e6). */
41
+ export const MIN_VAULT_V2_DEAD_ASSETS = 1000000n;
35
42
  /** Maximum absolute share price cap (100 RAY). Prevents absurd maxSharePrice values in repay. */
36
43
  export const MAX_ABSOLUTE_SHARE_PRICE = 100n * MathLib.RAY;
37
44
  /**