@morpho-org/morpho-sdk 6.5.0 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/MIGRATION-v6-to-v7.md +291 -0
  2. package/README.md +26 -12
  3. package/lib/cjs/abis.d.ts +1 -1
  4. package/lib/cjs/abis.js +3 -2
  5. package/lib/cjs/actions/bundles/common.d.ts +9 -5
  6. package/lib/cjs/actions/bundles/common.js +22 -13
  7. package/lib/cjs/actions/midnight/authorization.d.ts +3 -2
  8. package/lib/cjs/actions/midnight/authorization.js +3 -2
  9. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +153 -0
  10. package/lib/cjs/actions/midnight/cancelAndMake.js +292 -0
  11. package/lib/cjs/actions/midnight/index.d.ts +3 -3
  12. package/lib/cjs/actions/midnight/index.js +3 -3
  13. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +40 -23
  14. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +105 -69
  15. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +52 -27
  16. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +128 -71
  17. package/lib/cjs/actions/midnight/takeBorrow.d.ts +40 -28
  18. package/lib/cjs/actions/midnight/takeBorrow.js +95 -54
  19. package/lib/cjs/actions/midnight/takeLend.d.ts +51 -27
  20. package/lib/cjs/actions/midnight/takeLend.js +111 -54
  21. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +97 -0
  22. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +201 -0
  23. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +69 -0
  24. package/lib/cjs/actions/midnight/takeWithdraw.js +153 -0
  25. package/lib/cjs/actions/midnight/types.d.ts +7 -26
  26. package/lib/cjs/actions/midnight/types.js +0 -13
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +3 -2
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +4 -4
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +5 -5
  31. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +2 -2
  32. package/lib/cjs/actions/requirements/getRequirementsApproval.js +2 -2
  33. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +24 -8
  34. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +24 -13
  35. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -7
  36. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +11 -7
  37. package/lib/cjs/actions/requirements/midnight/index.d.ts +0 -1
  38. package/lib/cjs/actions/requirements/midnight/index.js +0 -1
  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 +10 -6
  42. package/lib/cjs/entities/blue/blue.js +5 -3
  43. package/lib/cjs/entities/index.d.ts +2 -2
  44. package/lib/cjs/entities/midnight/midnight.d.ts +582 -108
  45. package/lib/cjs/entities/midnight/midnight.js +981 -509
  46. package/lib/cjs/entities/midnight/types.d.ts +142 -60
  47. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +2 -1
  48. package/lib/cjs/entities/vaultV1/vaultV1.js +1 -0
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +2 -1
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +1 -0
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +11 -3
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +119 -43
  53. package/lib/cjs/helpers/callback.d.ts +54 -0
  54. package/lib/cjs/helpers/callback.js +73 -0
  55. package/lib/cjs/helpers/constant.d.ts +10 -0
  56. package/lib/cjs/helpers/constant.js +11 -1
  57. package/lib/cjs/helpers/index.d.ts +3 -2
  58. package/lib/cjs/helpers/index.js +7 -1
  59. package/lib/cjs/helpers/signAndVerifyTypedData.d.ts +3 -3
  60. package/lib/cjs/helpers/signAndVerifyTypedData.js +3 -3
  61. package/lib/cjs/helpers/utilization.d.ts +13 -0
  62. package/lib/cjs/helpers/utilization.js +26 -1
  63. package/lib/cjs/helpers/validate.d.ts +43 -2
  64. package/lib/cjs/helpers/validate.js +60 -3
  65. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
  66. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +3 -7
  67. package/lib/cjs/helpers/validateRequirementSpender.d.ts +3 -3
  68. package/lib/cjs/helpers/validateRequirementSpender.js +4 -5
  69. package/lib/cjs/midnight/abis.d.ts +1 -1
  70. package/lib/cjs/midnight/abis.js +3 -2
  71. package/lib/cjs/midnight/types.d.ts +1 -1
  72. package/lib/cjs/types/action.d.ts +117 -89
  73. package/lib/cjs/types/action.js +1 -19
  74. package/lib/cjs/types/error.d.ts +126 -40
  75. package/lib/cjs/types/error.js +154 -49
  76. package/lib/cjs/types/sharedLiquidity.d.ts +17 -0
  77. package/lib/esm/abis.d.ts +1 -1
  78. package/lib/esm/abis.js +1 -1
  79. package/lib/esm/actions/bundles/common.d.ts +9 -5
  80. package/lib/esm/actions/bundles/common.js +22 -13
  81. package/lib/esm/actions/midnight/authorization.d.ts +3 -2
  82. package/lib/esm/actions/midnight/authorization.js +3 -2
  83. package/lib/esm/actions/midnight/cancelAndMake.d.ts +153 -0
  84. package/lib/esm/actions/midnight/cancelAndMake.js +288 -0
  85. package/lib/esm/actions/midnight/index.d.ts +3 -3
  86. package/lib/esm/actions/midnight/index.js +3 -3
  87. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +40 -23
  88. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +108 -72
  89. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +52 -27
  90. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +131 -74
  91. package/lib/esm/actions/midnight/takeBorrow.d.ts +40 -28
  92. package/lib/esm/actions/midnight/takeBorrow.js +98 -57
  93. package/lib/esm/actions/midnight/takeLend.d.ts +51 -27
  94. package/lib/esm/actions/midnight/takeLend.js +114 -57
  95. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +97 -0
  96. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +197 -0
  97. package/lib/esm/actions/midnight/takeWithdraw.d.ts +69 -0
  98. package/lib/esm/actions/midnight/takeWithdraw.js +149 -0
  99. package/lib/esm/actions/midnight/types.d.ts +7 -26
  100. package/lib/esm/actions/midnight/types.js +1 -12
  101. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +2 -1
  102. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +3 -2
  103. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +4 -4
  104. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +5 -5
  105. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +2 -2
  106. package/lib/esm/actions/requirements/getRequirementsApproval.js +2 -2
  107. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +24 -8
  108. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +25 -14
  109. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +11 -7
  110. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +11 -7
  111. package/lib/esm/actions/requirements/midnight/index.d.ts +0 -1
  112. package/lib/esm/actions/requirements/midnight/index.js +0 -1
  113. package/lib/esm/constants.d.ts +1 -1
  114. package/lib/esm/constants.js +1 -1
  115. package/lib/esm/entities/blue/blue.d.ts +10 -6
  116. package/lib/esm/entities/blue/blue.js +5 -3
  117. package/lib/esm/entities/index.d.ts +2 -2
  118. package/lib/esm/entities/midnight/midnight.d.ts +582 -108
  119. package/lib/esm/entities/midnight/midnight.js +987 -515
  120. package/lib/esm/entities/midnight/types.d.ts +142 -60
  121. package/lib/esm/entities/vaultV1/vaultV1.d.ts +2 -1
  122. package/lib/esm/entities/vaultV1/vaultV1.js +1 -0
  123. package/lib/esm/entities/vaultV2/vaultV2.d.ts +2 -1
  124. package/lib/esm/entities/vaultV2/vaultV2.js +1 -0
  125. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +11 -3
  126. package/lib/esm/entities/vaultV2BlueReallocationData.js +120 -44
  127. package/lib/esm/helpers/callback.d.ts +54 -0
  128. package/lib/esm/helpers/callback.js +68 -0
  129. package/lib/esm/helpers/constant.d.ts +10 -0
  130. package/lib/esm/helpers/constant.js +10 -0
  131. package/lib/esm/helpers/index.d.ts +3 -2
  132. package/lib/esm/helpers/index.js +3 -2
  133. package/lib/esm/helpers/signAndVerifyTypedData.d.ts +3 -3
  134. package/lib/esm/helpers/signAndVerifyTypedData.js +3 -3
  135. package/lib/esm/helpers/utilization.d.ts +13 -0
  136. package/lib/esm/helpers/utilization.js +25 -1
  137. package/lib/esm/helpers/validate.d.ts +43 -2
  138. package/lib/esm/helpers/validate.js +58 -2
  139. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -1
  140. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +3 -7
  141. package/lib/esm/helpers/validateRequirementSpender.d.ts +3 -3
  142. package/lib/esm/helpers/validateRequirementSpender.js +4 -5
  143. package/lib/esm/midnight/abis.d.ts +1 -1
  144. package/lib/esm/midnight/abis.js +1 -1
  145. package/lib/esm/midnight/types.d.ts +1 -1
  146. package/lib/esm/types/action.d.ts +117 -89
  147. package/lib/esm/types/action.js +1 -18
  148. package/lib/esm/types/error.d.ts +126 -40
  149. package/lib/esm/types/error.js +135 -38
  150. package/lib/esm/types/sharedLiquidity.d.ts +17 -0
  151. package/package.json +9 -8
  152. package/lib/cjs/actions/midnight/cancelOffer.d.ts +0 -38
  153. package/lib/cjs/actions/midnight/cancelOffer.js +0 -73
  154. package/lib/cjs/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
  155. package/lib/cjs/actions/midnight/mempoolSubmitOffers.js +0 -72
  156. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
  157. package/lib/cjs/actions/midnight/setterRatifierRatifyRoot.js +0 -59
  158. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
  159. package/lib/cjs/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -70
  160. package/lib/esm/actions/midnight/cancelOffer.d.ts +0 -38
  161. package/lib/esm/actions/midnight/cancelOffer.js +0 -69
  162. package/lib/esm/actions/midnight/mempoolSubmitOffers.d.ts +0 -52
  163. package/lib/esm/actions/midnight/mempoolSubmitOffers.js +0 -68
  164. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.d.ts +0 -40
  165. package/lib/esm/actions/midnight/setterRatifierRatifyRoot.js +0 -55
  166. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.d.ts +0 -42
  167. package/lib/esm/actions/requirements/midnight/getSetterRatifierRatifyRootRequirement.js +0 -66
@@ -1,60 +1,95 @@
1
- import type { AccrualPosition, Market, MarketInput, MidnightFetchParams, Tree, TreeInput, TreeMempoolValidateParams } from "@morpho-org/midnight-sdk";
1
+ import type { InputMarketParams as BlueMarketParams } from "@morpho-org/blue-sdk";
2
+ import type { AccrualPosition, Market, MidnightFetchParams, PriceRatifierV1TreeCreateRequest, RateRatifierV1TreeCreateRequest, Tree, TreeMempoolValidateParams } from "@morpho-org/midnight-sdk";
2
3
  import type { Address, Hex } from "viem";
3
- import type { MidnightTakeableOffer } from "../../actions/midnight/types.js";
4
- import type { ActionOutput, BaseAction, MempoolSubmitOffersAction, MidnightOfferRootSignature } from "../../types/action.js";
4
+ import type { MidnightMakeBorrowCollateral } from "../../actions/midnight/cancelAndMake.js";
5
+ import type { MidnightReferralFeeParams, MidnightTakeableOffer } from "../../actions/midnight/types.js";
6
+ import type { ActionOutput, BaseAction, MidnightBuyTarget, MidnightCancelAndMakeAction, MidnightCollateralTransfer, MidnightGroupCancellation, MidnightRepay, MidnightSellTarget } from "../../types/action.js";
5
7
  /** Optional Midnight API validation controls for make-offer flows. */
6
- export type OfferValidationParams = Omit<TreeMempoolValidateParams, "chainId">;
8
+ export type OfferValidationParams = Omit<TreeMempoolValidateParams, "chainId" | "ratification">;
9
+ /**
10
+ * Offers accepted by Midnight maker flows: a PriceRatifierV1 or RateRatifierV1 tree, or
11
+ * the `Tree.create` request that builds one.
12
+ */
13
+ export type MidnightMakerTreeInput = PriceRatifierV1TreeCreateRequest | RateRatifierV1TreeCreateRequest | Tree<"priceV1"> | Tree<"rateV1">;
7
14
  /** Parameters for building and validating Midnight offer data. */
8
15
  export interface GetOffersDataParams {
9
16
  readonly accountAddress: Address;
10
- readonly offers: TreeInput;
17
+ readonly offers: MidnightMakerTreeInput;
11
18
  readonly validation?: OfferValidationParams;
12
19
  }
13
- interface OffersDataBase {
20
+ /** Prepared Midnight maker-offer data with the payload derived from its tree. */
21
+ export interface OffersData {
14
22
  readonly accountAddress: Address;
15
23
  readonly groups: readonly Hex[];
16
- readonly tree: Tree;
24
+ readonly tree: Tree<"priceV1"> | Tree<"rateV1">;
25
+ readonly ratifierType: "priceV1" | "rateV1";
17
26
  readonly ratifier: Address;
27
+ /** Encoded offer payload for `tree.root`. */
28
+ readonly payload: Hex;
18
29
  }
19
- /** Prepared Midnight maker-offer data discriminated by its ratifier execution path. */
20
- export type OffersData = (OffersDataBase & {
21
- readonly ratifierType: "ecrecover";
22
- readonly setterPayload?: never;
23
- }) | (OffersDataBase & {
24
- readonly ratifierType: "setter";
25
- readonly setterPayload: Hex;
26
- });
27
- /** Parameters shared by Midnight maker-offer flows. */
30
+ /** Parameters shared by Midnight maker flows. */
28
31
  export interface MakeOffersParams {
32
+ /** Maker expected on every offer. Must send the transaction: V2 acts on `msg.sender`. */
29
33
  readonly accountAddress: Address;
30
- readonly offers: TreeInput;
34
+ readonly offers: MidnightMakerTreeInput;
35
+ /** Previous offer groups to cancel atomically. Omit or pass `[]` for a new publication. */
36
+ readonly cancellations?: readonly MidnightGroupCancellation[];
37
+ /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
38
+ readonly deadline: bigint;
31
39
  readonly validation?: OfferValidationParams;
32
40
  }
33
- /** Parameters for the Midnight make-lend maker flow. */
41
+ /** Parameters for a Midnight lend maker flow. */
34
42
  export interface MakeLendParams extends MakeOffersParams {
35
43
  readonly loanToken: Address;
36
44
  /** New group loan reserve. For grouped OCA offers, pass the group reserve once instead of summing every leg. */
37
45
  readonly loanAssets: bigint;
38
- /** Existing loan assets reserved across the maker's other open groups, including consumed amounts when available. */
46
+ /** Existing loan assets reserved across the maker's other open groups, including consumed amounts when available. Leave out groups listed in `cancellations`; this transaction cancels them. */
39
47
  readonly reservedLoanAssets?: bigint;
40
48
  }
41
- /** Parameters for the Midnight supply-collateral-and-make-borrow maker flow. */
49
+ /** Parameters for the Midnight Blue-funded lend maker flow. */
50
+ export interface SupplyBlueMakeLendParams extends MakeOffersParams {
51
+ /**
52
+ * Morpho Blue market the parked assets are supplied to; its loan token must match every offer.
53
+ * The contract does not check supply share-price slippage: use only markets protected against
54
+ * supply-share-price inflation. Markets with no supply shares or parked amounts that mint zero
55
+ * shares are rejected.
56
+ */
57
+ readonly blueMarket: BlueMarketParams;
58
+ /** Loan assets pulled from the maker and supplied to `blueMarket` for the maker's callback. */
59
+ readonly assetsToPark: bigint;
60
+ /** Salt selecting the maker's `BlueBuyCallback`; the same salt reuses the same callback. */
61
+ readonly callbackSalt: Hex;
62
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
63
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
64
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
65
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
66
+ readonly nativeAmount?: bigint;
67
+ }
68
+ /** Parameters for the Midnight collateral-supplying borrow maker flow. */
42
69
  export interface SupplyCollateralMakeBorrowParams extends MakeOffersParams {
43
- readonly market: MarketInput;
44
- /** Collateral supplied before offer submission and the new group collateral reserve counted once for grouped offers. */
45
- readonly collateralAssets: bigint;
46
- /** Existing collateral assets reserved across the maker's other open groups, including consumed amounts when available. */
47
- readonly reservedCollateralAssets?: bigint;
48
- readonly collateralIndex?: bigint;
70
+ /** Required collateral supplied before activation; every offer must target `collateral.market`. */
71
+ readonly collateral: MidnightMakeBorrowCollateral;
72
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
73
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
74
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
75
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
76
+ readonly nativeAmount?: bigint;
77
+ }
78
+ /** Options for Midnight `getRequirements()`. */
79
+ export interface MidnightRequirementsParams {
80
+ /**
81
+ * ERC-20 allowance to set when an approval is needed. Defaults to `maxUint256` (capped per token by
82
+ * `MAX_TOKEN_APPROVALS`). Applies to every token the flow approves and must cover the amount each
83
+ * of them pulls. Flows that need no token approval ignore it.
84
+ */
85
+ readonly approvalAmount?: bigint;
49
86
  }
50
- /** Signatures accepted by Midnight action-output transaction builders. */
51
- export type MidnightActionSignatures = MidnightOfferRootSignature | readonly MidnightOfferRootSignature[];
52
87
  /**
53
88
  * Lazy Midnight entity result with async requirements and sync transaction building.
54
89
  *
55
- * Call `getRequirements()` first to collect approvals, authorizations, or
56
- * signatures. Once those are handled, pass any requirement signatures to
57
- * `buildTx`; the transaction builder itself performs no fetching or signing.
90
+ * Call `getRequirements()` first and send the approval and authorization
91
+ * transactions it returns. `buildTx()` takes no signatures and performs no
92
+ * fetching or signing.
58
93
  *
59
94
  * @example
60
95
  * ```ts
@@ -72,24 +107,19 @@ export type MidnightActionSignatures = MidnightOfferRootSignature | readonly Mid
72
107
  * const tx = output.buildTx();
73
108
  * ```
74
109
  */
75
- export type MidnightActionOutput<TAction extends BaseAction, TSignatures = undefined> = ActionOutput<TAction, TSignatures, undefined>;
110
+ export type MidnightActionOutput<TAction extends BaseAction, TSignatures = undefined> = ActionOutput<TAction, TSignatures, MidnightRequirementsParams>;
76
111
  /**
77
- * Output returned by maker-offer flows after offer-tree preparation.
112
+ * Output returned by Midnight maker flows after offer-tree preparation.
78
113
  *
79
- * Use `groups` and `root` for review UI, call `getRequirements()` to collect
80
- * ratifier approval or signature requirements, then call `buildTx(signatures)`
81
- * to publish the encoded payload to the Midnight mempool.
114
+ * Use `groups` and `root` for review UI, send the approval and authorization
115
+ * requirements from `getRequirements()`, then send `buildTx()` from the maker.
82
116
  *
83
117
  * @example
84
118
  * ```ts
85
- * const output = await midnight.makeLend(params);
119
+ * const output = await midnight.makeBorrow(params);
86
120
  * console.log(output.root, output.groups);
87
- * const requirements = await output.getRequirements();
88
- * const signatures = [];
89
- * for (const requirement of requirements) {
90
- * if ("sign" in requirement) {
91
- * signatures.push(await requirement.sign(walletClient, maker));
92
- * } else {
121
+ * for (const requirement of await output.getRequirements()) {
122
+ * if (!("sign" in requirement)) {
93
123
  * await walletClient.sendTransaction({
94
124
  * to: requirement.to,
95
125
  * data: requirement.data,
@@ -97,13 +127,13 @@ export type MidnightActionOutput<TAction extends BaseAction, TSignatures = undef
97
127
  * });
98
128
  * }
99
129
  * }
100
- * const tx = output.buildTx(signatures);
130
+ * await walletClient.sendTransaction(output.buildTx());
101
131
  * ```
102
132
  */
103
- export interface MakeOffersOutput extends MidnightActionOutput<MempoolSubmitOffersAction, MidnightActionSignatures> {
133
+ export interface MakeOffersOutput extends MidnightActionOutput<MidnightCancelAndMakeAction> {
104
134
  readonly groups: readonly Hex[];
105
135
  readonly root: Hex;
106
- readonly ratifierType: "ecrecover" | "setter";
136
+ readonly ratifierType: "priceV1" | "rateV1";
107
137
  }
108
138
  /** Parameters shared by Midnight market action flows. */
109
139
  export interface MarketActionParams {
@@ -111,25 +141,70 @@ export interface MarketActionParams {
111
141
  readonly marketData: Market;
112
142
  }
113
143
  /** Parameters for the Midnight take-lend taker flow. */
114
- export interface TakeLendParams extends MarketActionParams {
115
- readonly assets: bigint;
116
- readonly minUnits: bigint;
144
+ export interface TakeLendParams extends MarketActionParams, MidnightReferralFeeParams {
145
+ /** Loan assets paid with a unit floor, or units bought with a loan-asset cap. */
146
+ readonly target: MidnightBuyTarget;
147
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
148
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
149
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
150
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
151
+ readonly nativeAmount?: bigint;
117
152
  readonly takeableOffers: readonly MidnightTakeableOffer[];
118
- /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
153
+ /** Largest market continuous fee accepted when taking offers. Pass `maxUint256` explicitly for no cap. */
154
+ readonly maxContinuousFee: bigint;
155
+ /** Bounded bundle execution deadline timestamp. */
119
156
  readonly deadline: bigint;
120
157
  }
121
158
  /** Parameters for the Midnight take-borrow taker flow. */
122
- export interface TakeBorrowParams extends MarketActionParams {
123
- readonly loanAssets: bigint;
124
- readonly maxUnits: bigint;
159
+ export interface TakeBorrowParams extends MarketActionParams, MidnightReferralFeeParams {
160
+ /** Loan assets received with a unit cap, or units sold with a loan-asset floor. */
161
+ readonly target: MidnightSellTarget;
162
+ /** Recipient of the borrowed loan assets. Defaults to `accountAddress`. */
163
+ readonly receiver?: Address;
125
164
  readonly takeableOffers: readonly MidnightTakeableOffer[];
126
- /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
165
+ /** Bounded bundle execution deadline timestamp. */
166
+ readonly deadline: bigint;
167
+ }
168
+ /** Parameters for the Midnight credit-withdrawal taker flow. */
169
+ export interface TakeWithdrawParams extends MarketActionParams, MidnightReferralFeeParams {
170
+ /** Loan assets received with a credit-unit cap, or credit units sold with a loan-asset floor. */
171
+ readonly target: MidnightSellTarget;
172
+ /** Recipient of the withdrawn loan assets. Defaults to `accountAddress`. */
173
+ readonly receiver?: Address;
174
+ readonly takeableOffers: readonly MidnightTakeableOffer[];
175
+ /** Bounded bundle execution deadline timestamp. */
127
176
  readonly deadline: bigint;
128
177
  }
129
178
  /** Parameters for the Midnight supply-collateral-and-take-borrow taker flow. */
130
179
  export interface SupplyCollateralTakeBorrowParams extends TakeBorrowParams {
131
- readonly collateralAssets: bigint;
132
- readonly collateralIndex?: bigint;
180
+ /** Collateral supplied before borrowing; must not be empty. */
181
+ readonly collateralSupplies: readonly MidnightCollateralTransfer[];
182
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
183
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
184
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
185
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
186
+ readonly nativeAmount?: bigint;
187
+ }
188
+ /** Parameters for the Midnight offer-based repay-and-withdraw-collateral taker flow. */
189
+ export interface TakeRepayWithdrawCollateralParams extends MarketActionParams, MidnightReferralFeeParams {
190
+ /** Loan assets paid with a unit floor, or debt units repaid with a loan-asset cap. `units: maxUint256` targets the whole debt; `assets` and `maxBuyerAssets` bound the loan assets pulled and must be below `maxUint256`. */
191
+ readonly target: MidnightBuyTarget;
192
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
193
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
194
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
195
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
196
+ readonly nativeAmount?: bigint;
197
+ readonly takeableOffers: readonly MidnightTakeableOffer[];
198
+ /** Repays the rest of the target directly to Midnight when offers do not fill it. */
199
+ readonly repayEnabled: boolean;
200
+ /** Collateral withdrawn after repaying. Defaults to none. */
201
+ readonly collateralWithdrawals?: readonly MidnightCollateralTransfer[];
202
+ /** Recipient of withdrawn collateral. Defaults to `accountAddress`. */
203
+ readonly collateralReceiver?: Address;
204
+ /** Largest market continuous fee accepted when taking offers. Pass `maxUint256` explicitly for no cap. */
205
+ readonly maxContinuousFee: bigint;
206
+ /** Bounded bundle execution deadline timestamp. */
207
+ readonly deadline: bigint;
133
208
  }
134
209
  /** Parameters for the Midnight supply-collateral flow. */
135
210
  export interface SupplyCollateralParams extends MarketActionParams {
@@ -148,9 +223,17 @@ export interface RedeemParams {
148
223
  }
149
224
  /** Parameters for the Midnight repay-and-withdraw-collateral flow. */
150
225
  export interface RepayWithdrawCollateralParams extends MarketActionParams {
151
- readonly repayAssets: bigint;
152
- readonly withdrawCollateralAssets: bigint;
153
- readonly collateralIndex?: bigint;
226
+ /** `{ type: "assets", assets }` repays exactly `assets` (`0n` only withdraws); `{ type: "full", maxBuyerAssets }` repays the whole debt at execution with a finite asset cap. */
227
+ readonly repay: MidnightRepay;
228
+ /** Optional native ETH sent as `value`; the bundle wraps it into the chain's wNative and transfers
229
+ * it to `msg.sender` before pulling. It may cover part or all of the maximum wNative amount this
230
+ * call can pull, but not more. Any wrapped native not pulled stays in the sender's wallet as
231
+ * wNative. The wNative approval to `MidnightBundlesV2` is still required for the full pulled amount. */
232
+ readonly nativeAmount?: bigint;
233
+ /** `assets: maxUint256` withdraws the whole balance of that collateral. Defaults to none. */
234
+ readonly collateralWithdrawals?: readonly MidnightCollateralTransfer[];
235
+ /** Defaults to `accountAddress`. */
236
+ readonly collateralReceiver?: Address;
154
237
  /** Bundle execution deadline timestamp. Pass `maxUint256` explicitly for no expiry. */
155
238
  readonly deadline: bigint;
156
239
  }
@@ -161,4 +244,3 @@ export interface GetPositionDataParams {
161
244
  /** Optional fetch controls. Pass an externally fetched block number to coordinate this snapshot with other reads. */
162
245
  readonly parameters?: MidnightFetchParams;
163
246
  }
164
- export {};
@@ -144,7 +144,8 @@ export interface VaultV1Actions {
144
144
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
145
145
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permits are supplied.
146
146
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
147
- * its spender, amount or deadline differ from this operation's.
147
+ * its spender or deadline differ from this operation's, or its amount is outside
148
+ * `[cap, cap / (1 - slippageTolerance)]`.
148
149
  * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
149
150
  * @example
150
151
  * ```ts
@@ -178,6 +178,7 @@ export class MorphoVaultV1 {
178
178
  const permit = selectBundlesSharesPermitSignature(signatures, {
179
179
  spender,
180
180
  amount: requiredShareAllowance,
181
+ maxAmount: maxShareAllowance,
181
182
  deadline,
182
183
  });
183
184
  return vaultV1Withdraw({
@@ -150,7 +150,8 @@ export interface VaultV2Actions {
150
150
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
151
151
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permits are supplied.
152
152
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
153
- * its spender, amount or deadline differ from this operation's.
153
+ * its spender or deadline differ from this operation's, or its amount is outside
154
+ * `[cap, cap / (1 - slippageTolerance)]`.
154
155
  * @throws {viem.BaseError} when an allowance or nonce read or transaction encoding fails.
155
156
  * @example
156
157
  * ```ts
@@ -181,6 +181,7 @@ export class MorphoVaultV2 {
181
181
  const permit = selectBundlesSharesPermitSignature(signatures, {
182
182
  spender,
183
183
  amount: requiredShareAllowance,
184
+ maxAmount: maxShareAllowance,
184
185
  deadline,
185
186
  });
186
187
  return vaultV2Withdraw({
@@ -366,7 +366,15 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
366
366
  * considered. Market/vault state and the returned post-state stay at
367
367
  * `timestamp`; only target-market cap checks reserve interest the vault's
368
368
  * existing allocation would accrue through `timestamp + capAccrualBuffer`
369
- * (two hours by default; `0n` disables it). For market-source reallocations
369
+ * (two hours by default; `0n` disables it). When an operation's plan would
370
+ * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
371
+ * BluePublicAllocator cap, the plan is reduced to the larger of the
372
+ * operation's absolute shortfall and what vaults below their cap moved. The
373
+ * kept headroom absorbs other allocations up to that share of the cap landing
374
+ * before inclusion. The plan uses the full cap only when the shortfall needs
375
+ * it, and can then still revert if another allocation lands first. A plan of
376
+ * only the shortfall leaves the market fully utilized, so a competing borrow
377
+ * or withdraw landing first can also make it revert. For market-source reallocations
370
378
  * the source position's interest is also reserved on cap ids shared with the
371
379
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
372
380
  * or allocator capacity are skipped before projecting source interest. The
@@ -392,8 +400,8 @@ export declare class VaultV2BlueReallocationData implements InputVaultV2BlueReal
392
400
  * every leg of a plan.
393
401
  * @returns Flat action-ready reallocations and their post-simulation state.
394
402
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
395
- * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
396
- * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
403
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
404
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
397
405
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
398
406
  * @throws {UnknownReallocationMarketError} when a required market is absent.
399
407
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -2,7 +2,7 @@ import { AccrualPosition, AccrualVault, AccrualVaultV2, AccrualVaultV2MorphoMark
2
2
  import { _try, bigIntComparator } from "@morpho-org/morpho-ts";
3
3
  import { isAddressEqual } from "viem";
4
4
  import { DEFAULT_MAX_REALLOCATION_PENALTY, DEFAULT_SUPPLY_TARGET_UTILIZATION, MAX_REALLOCATION_PENALTY, } from "../helpers/constant.js";
5
- import { resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../helpers/utilization.js";
5
+ import { resolveAllocatorCapHeadroom, resolveCapAccrualBuffer, resolveMaxWithdrawalUtilization, } from "../helpers/utilization.js";
6
6
  import { InputExceedsMaxError, InsufficientSharedLiquidityError, NegativeInputError, NonPositiveInputError, ReallocationAdapterSupplySharesUnderflowError, ReallocationAllocationUnderflowError, ReallocationWithdrawExceedsMarketSupplyError, UnknownReallocationActiveAdaptersError, UnknownReallocationAdapterError, UnknownReallocationAllocationError, UnknownReallocationMarketError, UnknownReallocationMarketPublicAllocatorConfigError, UnknownReallocationPublicAllocatorConfigError, UnknownReallocationVaultError, } from "../types/index.js";
7
7
  const MAX_SHARED_CAP_SEARCH_STEPS = 1024n;
8
8
  const createCapReserveState = (markets) => ({
@@ -564,7 +564,15 @@ export class VaultV2BlueReallocationData {
564
564
  * considered. Market/vault state and the returned post-state stay at
565
565
  * `timestamp`; only target-market cap checks reserve interest the vault's
566
566
  * existing allocation would accrue through `timestamp + capAccrualBuffer`
567
- * (two hours by default; `0n` disables it). For market-source reallocations
567
+ * (two hours by default; `0n` disables it). When an operation's plan would
568
+ * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
569
+ * BluePublicAllocator cap, the plan is reduced to the larger of the
570
+ * operation's absolute shortfall and what vaults below their cap moved. The
571
+ * kept headroom absorbs other allocations up to that share of the cap landing
572
+ * before inclusion. The plan uses the full cap only when the shortfall needs
573
+ * it, and can then still revert if another allocation lands first. A plan of
574
+ * only the shortfall leaves the market fully utilized, so a competing borrow
575
+ * or withdraw landing first can also make it revert. For market-source reallocations
568
576
  * the source position's interest is also reserved on cap ids shared with the
569
577
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
570
578
  * or allocator capacity are skipped before projecting source interest. The
@@ -590,8 +598,8 @@ export class VaultV2BlueReallocationData {
590
598
  * every leg of a plan.
591
599
  * @returns Flat action-ready reallocations and their post-simulation state.
592
600
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
593
- * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
594
- * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
601
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
602
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
595
603
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
596
604
  * @throws {UnknownReallocationMarketError} when a required market is absent.
597
605
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -636,6 +644,7 @@ export class VaultV2BlueReallocationData {
636
644
  const maxWithdrawalUtilization = resolveMaxWithdrawalUtilization(options.maxWithdrawalUtilization);
637
645
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
638
646
  const capAccrualBuffer = resolveCapAccrualBuffer(options.capAccrualBuffer);
647
+ const allocatorCapHeadroom = resolveAllocatorCapHeadroom(options.allocatorCapHeadroom);
639
648
  const resolvedOptions = { ...options, maxPenalty };
640
649
  const operation = options.operation;
641
650
  if (operation == null) {
@@ -685,53 +694,103 @@ export class VaultV2BlueReallocationData {
685
694
  newTotalSupplyAssets;
686
695
  if (requiredAssets <= 0n)
687
696
  return { reallocations: [], data: this };
688
- const reserves = createCapReserveState(this.mutableMarkets);
689
- const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
690
- context: createSimulationContext(),
691
- reserves,
692
- marketId,
693
- maxWithdrawalUtilization,
694
- maxAssets: requiredAssets,
695
- capAccrualBuffer,
696
- options: normalizedOptions,
697
- });
698
- const reallocations = [...friendly.reallocations];
699
- const data = friendly.data;
700
- const friendlyMarket = friendly.data.getMarket(marketId);
701
- const friendlyBorrow = type === "borrow"
702
- ? friendlyMarket.totalBorrowAssets + amount
703
- : friendlyMarket.totalBorrowAssets;
704
- const friendlySupply = type === "withdraw"
705
- ? friendlyMarket.totalSupplyAssets - amount
706
- : friendlyMarket.totalSupplyAssets;
707
- if (friendlyBorrow > friendlySupply) {
708
- const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
709
- context: friendly.context,
697
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
698
+ ? newTotalBorrowAssets - newTotalSupplyAssets
699
+ : 0n;
700
+ const plan = (maxAssets, headroom) => {
701
+ const reserves = createCapReserveState(this.mutableMarkets);
702
+ const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
703
+ context: createSimulationContext(),
710
704
  reserves,
711
705
  marketId,
712
- maxWithdrawalUtilization: MathLib.WAD,
713
- maxAssets: friendlyBorrow - friendlySupply,
706
+ maxWithdrawalUtilization,
707
+ maxAssets,
714
708
  capAccrualBuffer,
709
+ allocatorCapHeadroom: headroom,
715
710
  options: normalizedOptions,
716
711
  });
717
- reallocations.push(...fallback.reallocations);
712
+ const reallocations = [...friendly.reallocations];
713
+ const data = friendly.data;
714
+ const friendlyMarket = data.getMarket(marketId);
715
+ const friendlyBorrow = type === "borrow"
716
+ ? friendlyMarket.totalBorrowAssets + amount
717
+ : friendlyMarket.totalBorrowAssets;
718
+ const friendlySupply = type === "withdraw"
719
+ ? friendlyMarket.totalSupplyAssets - amount
720
+ : friendlyMarket.totalSupplyAssets;
721
+ if (friendlyBorrow > friendlySupply) {
722
+ const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
723
+ context: friendly.context,
724
+ reserves,
725
+ marketId,
726
+ maxWithdrawalUtilization: MathLib.WAD,
727
+ maxAssets: friendlyBorrow - friendlySupply,
728
+ capAccrualBuffer,
729
+ allocatorCapHeadroom: headroom,
730
+ options: normalizedOptions,
731
+ });
732
+ reallocations.push(...fallback.reallocations);
733
+ }
734
+ // The fallback pass only runs when the plan moves exactly the absolute
735
+ // shortfall, which a reduced plan would move anyway.
736
+ const capBoundTargets = friendly.allocatorCapBoundTargets;
737
+ let reallocatedAssets = 0n;
738
+ let unboundAssets = 0n;
739
+ for (const { vault, to, assets } of reallocations) {
740
+ reallocatedAssets += assets;
741
+ const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
742
+ if (!capBoundTargets.has(key))
743
+ unboundAssets += assets;
744
+ }
745
+ return {
746
+ reallocations,
747
+ data,
748
+ capBound: capBoundTargets.size > 0,
749
+ reallocatedAssets,
750
+ unboundAssets,
751
+ };
752
+ };
753
+ // A leg that fills an allocator cap reverts once any other allocation to
754
+ // that market lands first. A cap-bound plan therefore moves only the
755
+ // operation's shortfall, or what vaults below their cap already moved.
756
+ const target = plan(requiredAssets, allocatorCapHeadroom);
757
+ let selected = target;
758
+ if (allocatorCapHeadroom > 0n && target.capBound) {
759
+ selected = plan(absoluteShortfall > target.unboundAssets
760
+ ? absoluteShortfall
761
+ : target.unboundAssets, allocatorCapHeadroom);
762
+ // Shared-cap fitting is not monotonic in the budget.
763
+ if (selected.reallocatedAssets < absoluteShortfall &&
764
+ target.reallocatedAssets >= absoluteShortfall)
765
+ selected = target;
718
766
  }
719
- const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
720
- ? newTotalBorrowAssets - newTotalSupplyAssets
721
- : 0n;
722
- const reallocatedAssets = reallocations.reduce((total, { assets }) => total + assets, 0n);
723
- if (reallocatedAssets < absoluteShortfall) {
767
+ let available = MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
768
+ // Without headroom, `target` already is the full-cap plan toward the target.
769
+ const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
770
+ for (const maxAssets of fullCapBudgets) {
771
+ if (selected.reallocatedAssets >= absoluteShortfall)
772
+ break;
773
+ selected = plan(maxAssets, 0n);
774
+ if (selected.reallocatedAssets > available)
775
+ available = selected.reallocatedAssets;
776
+ }
777
+ if (selected.reallocatedAssets < absoluteShortfall) {
724
778
  throw new InsufficientSharedLiquidityError({
725
779
  marketId,
726
780
  shortfall: absoluteShortfall,
727
- available: reallocatedAssets,
781
+ available,
728
782
  });
729
783
  }
730
- return { reallocations, data };
784
+ return { reallocations: selected.reallocations, data: selected.data };
731
785
  }
732
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, options = {}, }) {
786
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
733
787
  if (options.enabled === false)
734
- return { reallocations: [], data: this, context };
788
+ return {
789
+ reallocations: [],
790
+ data: this,
791
+ context,
792
+ allocatorCapBoundTargets: new Set(),
793
+ };
735
794
  this.getMarket(marketId);
736
795
  const timestamp = options.timestamp == null
737
796
  ? this.getLatestSnapshotTimestamp()
@@ -749,6 +808,7 @@ export class VaultV2BlueReallocationData {
749
808
  const adapterIdsCache = new Map();
750
809
  const activeAdaptersCache = new Map();
751
810
  let remainingAssets = maxAssets;
811
+ const allocatorCapBoundTargets = new Set();
752
812
  // Onchain, market interest is booked once at transaction start, on pre-plan
753
813
  // positions at pre-plan rates, and stays on touched positions' cap ids.
754
814
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -856,9 +916,9 @@ export class VaultV2BlueReallocationData {
856
916
  const adapterShares = adapter.supplyShares[marketId] ?? 0n;
857
917
  const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
858
918
  const untracked = MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
859
- const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
919
+ const allocatorHeadroom = MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
860
920
  untracked +
861
- targetPair.reserve());
921
+ targetPair.reserve()), MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
862
922
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
863
923
  const minimumAllocationChange = MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
864
924
  const blockedTargetIds = targetAllocations
@@ -891,6 +951,7 @@ export class VaultV2BlueReallocationData {
891
951
  penalty: publicAllocatorConfig.penalty,
892
952
  },
893
953
  targetPair,
954
+ allocatorHeadroom,
894
955
  });
895
956
  }
896
957
  }
@@ -945,12 +1006,13 @@ export class VaultV2BlueReallocationData {
945
1006
  },
946
1007
  targetPair,
947
1008
  sourcePair,
1009
+ allocatorHeadroom,
948
1010
  });
949
1011
  }
950
1012
  }
951
1013
  }
952
1014
  const capCompatibleCandidates = [];
953
- for (const { reallocation, targetPair, sourcePair, } of rawCandidates) {
1015
+ for (const { reallocation, targetPair, sourcePair, allocatorHeadroom, } of rawCandidates) {
954
1016
  let lower = 0n;
955
1017
  let upper = reallocation.assets;
956
1018
  const targetIds = targetPair.ids;
@@ -1025,6 +1087,7 @@ export class VaultV2BlueReallocationData {
1025
1087
  reallocation: { ...reallocation, assets: selectedAssets },
1026
1088
  targetPair,
1027
1089
  sourcePair,
1090
+ allocatorHeadroom,
1028
1091
  });
1029
1092
  }
1030
1093
  return capCompatibleCandidates.sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"))[0];
@@ -1033,8 +1096,16 @@ export class VaultV2BlueReallocationData {
1033
1096
  .sort(bigIntComparator(({ reallocation }) => reallocation.assets, "desc"));
1034
1097
  const largest = candidates[0];
1035
1098
  if (largest == null)
1036
- return { reallocations, data, context: simulationContext };
1037
- const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, } = largest;
1099
+ return {
1100
+ reallocations,
1101
+ data,
1102
+ context: simulationContext,
1103
+ allocatorCapBoundTargets,
1104
+ };
1105
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1106
+ if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1107
+ // BluePublicAllocator caps are per vault and target adapter.
1108
+ allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1038
1109
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1039
1110
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1040
1111
  if (touchedVaultPairs == null) {
@@ -1059,7 +1130,12 @@ export class VaultV2BlueReallocationData {
1059
1130
  if (remainingAssets != null)
1060
1131
  remainingAssets -= acceptedReallocation.assets;
1061
1132
  }
1062
- return { reallocations, data, context: simulationContext };
1133
+ return {
1134
+ reallocations,
1135
+ data,
1136
+ context: simulationContext,
1137
+ allocatorCapBoundTargets,
1138
+ };
1063
1139
  }
1064
1140
  /**
1065
1141
  * Sums friendly Vault V2 shared liquidity available to a target market.