@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
@@ -181,6 +181,7 @@ class MorphoVaultV1 {
181
181
  const permit = (0, common_js_1.selectBundlesSharesPermitSignature)(signatures, {
182
182
  spender,
183
183
  amount: requiredShareAllowance,
184
+ maxAmount: maxShareAllowance,
184
185
  deadline,
185
186
  });
186
187
  return (0, index_js_1.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
@@ -184,6 +184,7 @@ class MorphoVaultV2 {
184
184
  const permit = (0, common_js_1.selectBundlesSharesPermitSignature)(signatures, {
185
185
  spender,
186
186
  amount: requiredShareAllowance,
187
+ maxAmount: maxShareAllowance,
187
188
  deadline,
188
189
  });
189
190
  return (0, index_js_1.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.
@@ -567,7 +567,15 @@ class VaultV2BlueReallocationData {
567
567
  * considered. Market/vault state and the returned post-state stay at
568
568
  * `timestamp`; only target-market cap checks reserve interest the vault's
569
569
  * existing allocation would accrue through `timestamp + capAccrualBuffer`
570
- * (two hours by default; `0n` disables it). For market-source reallocations
570
+ * (two hours by default; `0n` disables it). When an operation's plan would
571
+ * come within `allocatorCapHeadroom` (1% of the cap by default) of a target
572
+ * BluePublicAllocator cap, the plan is reduced to the larger of the
573
+ * operation's absolute shortfall and what vaults below their cap moved. The
574
+ * kept headroom absorbs other allocations up to that share of the cap landing
575
+ * before inclusion. The plan uses the full cap only when the shortfall needs
576
+ * it, and can then still revert if another allocation lands first. A plan of
577
+ * only the shortfall leaves the market fully utilized, so a competing borrow
578
+ * or withdraw landing first can also make it revert. For market-source reallocations
571
579
  * the source position's interest is also reserved on cap ids shared with the
572
580
  * target, and reserves persist across every leg of a plan. Targets with no remaining supply
573
581
  * or allocator capacity are skipped before projecting source interest. The
@@ -593,8 +601,8 @@ class VaultV2BlueReallocationData {
593
601
  * every leg of a plan.
594
602
  * @returns Flat action-ready reallocations and their post-simulation state.
595
603
  * @throws {UnsupportedBlueMarketIrmError} when a market with positive debt uses an unsupported IRM.
596
- * @throws {NegativeInputError} when `capAccrualBuffer`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
597
- * @throws {InputExceedsMaxError} when `maxWithdrawalUtilization` or `maxPenalty` exceeds WAD.
604
+ * @throws {NegativeInputError} when `capAccrualBuffer`, `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` is negative.
605
+ * @throws {InputExceedsMaxError} when `allocatorCapHeadroom`, `maxWithdrawalUtilization`, or `maxPenalty` exceeds WAD.
598
606
  * @throws {NonPositiveInputError} when the operation amount is not positive and planning is enabled.
599
607
  * @throws {UnknownReallocationMarketError} when a required market is absent.
600
608
  * @throws {UnknownReallocationVaultError} when configured vault state is absent.
@@ -639,6 +647,7 @@ class VaultV2BlueReallocationData {
639
647
  const maxWithdrawalUtilization = (0, utilization_js_1.resolveMaxWithdrawalUtilization)(options.maxWithdrawalUtilization);
640
648
  const maxPenalty = resolveMaxPenalty(options.maxPenalty);
641
649
  const capAccrualBuffer = (0, utilization_js_1.resolveCapAccrualBuffer)(options.capAccrualBuffer);
650
+ const allocatorCapHeadroom = (0, utilization_js_1.resolveAllocatorCapHeadroom)(options.allocatorCapHeadroom);
642
651
  const resolvedOptions = { ...options, maxPenalty };
643
652
  const operation = options.operation;
644
653
  if (operation == null) {
@@ -688,53 +697,103 @@ class VaultV2BlueReallocationData {
688
697
  newTotalSupplyAssets;
689
698
  if (requiredAssets <= 0n)
690
699
  return { reallocations: [], data: this };
691
- const reserves = createCapReserveState(this.mutableMarkets);
692
- const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
693
- context: createSimulationContext(),
694
- reserves,
695
- marketId,
696
- maxWithdrawalUtilization,
697
- maxAssets: requiredAssets,
698
- capAccrualBuffer,
699
- options: normalizedOptions,
700
- });
701
- const reallocations = [...friendly.reallocations];
702
- const data = friendly.data;
703
- const friendlyMarket = friendly.data.getMarket(marketId);
704
- const friendlyBorrow = type === "borrow"
705
- ? friendlyMarket.totalBorrowAssets + amount
706
- : friendlyMarket.totalBorrowAssets;
707
- const friendlySupply = type === "withdraw"
708
- ? friendlyMarket.totalSupplyAssets - amount
709
- : friendlyMarket.totalSupplyAssets;
710
- if (friendlyBorrow > friendlySupply) {
711
- const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
712
- context: friendly.context,
700
+ const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
701
+ ? newTotalBorrowAssets - newTotalSupplyAssets
702
+ : 0n;
703
+ const plan = (maxAssets, headroom) => {
704
+ const reserves = createCapReserveState(this.mutableMarkets);
705
+ const friendly = this.clone().computeVaultV2BlueReallocationsAtUtilizationInPlace({
706
+ context: createSimulationContext(),
713
707
  reserves,
714
708
  marketId,
715
- maxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
716
- maxAssets: friendlyBorrow - friendlySupply,
709
+ maxWithdrawalUtilization,
710
+ maxAssets,
717
711
  capAccrualBuffer,
712
+ allocatorCapHeadroom: headroom,
718
713
  options: normalizedOptions,
719
714
  });
720
- reallocations.push(...fallback.reallocations);
715
+ const reallocations = [...friendly.reallocations];
716
+ const data = friendly.data;
717
+ const friendlyMarket = data.getMarket(marketId);
718
+ const friendlyBorrow = type === "borrow"
719
+ ? friendlyMarket.totalBorrowAssets + amount
720
+ : friendlyMarket.totalBorrowAssets;
721
+ const friendlySupply = type === "withdraw"
722
+ ? friendlyMarket.totalSupplyAssets - amount
723
+ : friendlyMarket.totalSupplyAssets;
724
+ if (friendlyBorrow > friendlySupply) {
725
+ const fallback = data.computeVaultV2BlueReallocationsAtUtilizationInPlace({
726
+ context: friendly.context,
727
+ reserves,
728
+ marketId,
729
+ maxWithdrawalUtilization: blue_sdk_1.MathLib.WAD,
730
+ maxAssets: friendlyBorrow - friendlySupply,
731
+ capAccrualBuffer,
732
+ allocatorCapHeadroom: headroom,
733
+ options: normalizedOptions,
734
+ });
735
+ reallocations.push(...fallback.reallocations);
736
+ }
737
+ // The fallback pass only runs when the plan moves exactly the absolute
738
+ // shortfall, which a reduced plan would move anyway.
739
+ const capBoundTargets = friendly.allocatorCapBoundTargets;
740
+ let reallocatedAssets = 0n;
741
+ let unboundAssets = 0n;
742
+ for (const { vault, to, assets } of reallocations) {
743
+ reallocatedAssets += assets;
744
+ const key = `${vault.toLowerCase()}:${to.adapter.toLowerCase()}`;
745
+ if (!capBoundTargets.has(key))
746
+ unboundAssets += assets;
747
+ }
748
+ return {
749
+ reallocations,
750
+ data,
751
+ capBound: capBoundTargets.size > 0,
752
+ reallocatedAssets,
753
+ unboundAssets,
754
+ };
755
+ };
756
+ // A leg that fills an allocator cap reverts once any other allocation to
757
+ // that market lands first. A cap-bound plan therefore moves only the
758
+ // operation's shortfall, or what vaults below their cap already moved.
759
+ const target = plan(requiredAssets, allocatorCapHeadroom);
760
+ let selected = target;
761
+ if (allocatorCapHeadroom > 0n && target.capBound) {
762
+ selected = plan(absoluteShortfall > target.unboundAssets
763
+ ? absoluteShortfall
764
+ : target.unboundAssets, allocatorCapHeadroom);
765
+ // Shared-cap fitting is not monotonic in the budget.
766
+ if (selected.reallocatedAssets < absoluteShortfall &&
767
+ target.reallocatedAssets >= absoluteShortfall)
768
+ selected = target;
721
769
  }
722
- const absoluteShortfall = newTotalBorrowAssets > newTotalSupplyAssets
723
- ? newTotalBorrowAssets - newTotalSupplyAssets
724
- : 0n;
725
- const reallocatedAssets = reallocations.reduce((total, { assets }) => total + assets, 0n);
726
- if (reallocatedAssets < absoluteShortfall) {
770
+ let available = blue_sdk_1.MathLib.max(target.reallocatedAssets, selected.reallocatedAssets);
771
+ // Without headroom, `target` already is the full-cap plan toward the target.
772
+ const fullCapBudgets = allocatorCapHeadroom > 0n ? [absoluteShortfall, requiredAssets] : [];
773
+ for (const maxAssets of fullCapBudgets) {
774
+ if (selected.reallocatedAssets >= absoluteShortfall)
775
+ break;
776
+ selected = plan(maxAssets, 0n);
777
+ if (selected.reallocatedAssets > available)
778
+ available = selected.reallocatedAssets;
779
+ }
780
+ if (selected.reallocatedAssets < absoluteShortfall) {
727
781
  throw new index_js_1.InsufficientSharedLiquidityError({
728
782
  marketId,
729
783
  shortfall: absoluteShortfall,
730
- available: reallocatedAssets,
784
+ available,
731
785
  });
732
786
  }
733
- return { reallocations, data };
787
+ return { reallocations: selected.reallocations, data: selected.data };
734
788
  }
735
- computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, options = {}, }) {
789
+ computeVaultV2BlueReallocationsAtUtilizationInPlace({ context, reserves, marketId, maxWithdrawalUtilization, maxAssets, capAccrualBuffer, allocatorCapHeadroom = 0n, options = {}, }) {
736
790
  if (options.enabled === false)
737
- return { reallocations: [], data: this, context };
791
+ return {
792
+ reallocations: [],
793
+ data: this,
794
+ context,
795
+ allocatorCapBoundTargets: new Set(),
796
+ };
738
797
  this.getMarket(marketId);
739
798
  const timestamp = options.timestamp == null
740
799
  ? this.getLatestSnapshotTimestamp()
@@ -752,6 +811,7 @@ class VaultV2BlueReallocationData {
752
811
  const adapterIdsCache = new Map();
753
812
  const activeAdaptersCache = new Map();
754
813
  let remainingAssets = maxAssets;
814
+ const allocatorCapBoundTargets = new Set();
755
815
  // Onchain, market interest is booked once at transaction start, on pre-plan
756
816
  // positions at pre-plan rates, and stays on touched positions' cap ids.
757
817
  // This reserve state is shared across every planner pass and leg of the plan.
@@ -859,9 +919,9 @@ class VaultV2BlueReallocationData {
859
919
  const adapterShares = adapter.supplyShares[marketId] ?? 0n;
860
920
  const expectedSupplyAssets = targetMarket.toSupplyAssets(adapterShares);
861
921
  const untracked = blue_sdk_1.MathLib.zeroFloorSub(expectedSupplyAssets, adapterMarketCapAllocation.allocation);
862
- const allocatorHeadroom = marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
922
+ const allocatorHeadroom = blue_sdk_1.MathLib.zeroFloorSub(marketPublicAllocatorConfig.getMaxIn(adapterMarketCapAllocation.allocation +
863
923
  untracked +
864
- targetPair.reserve());
924
+ targetPair.reserve()), blue_sdk_1.MathLib.wMulUp(marketPublicAllocatorConfig.absoluteCap, allocatorCapHeadroom));
865
925
  const minimumAllocation = minimumSupply.market.toSupplyAssets(adapterShares + minimumSupply.shares);
866
926
  const minimumAllocationChange = blue_sdk_1.MathLib.max(minimumAllocation - adapterMarketCapAllocation.allocation, minimumSupply.assets);
867
927
  const blockedTargetIds = targetAllocations
@@ -894,6 +954,7 @@ class VaultV2BlueReallocationData {
894
954
  penalty: publicAllocatorConfig.penalty,
895
955
  },
896
956
  targetPair,
957
+ allocatorHeadroom,
897
958
  });
898
959
  }
899
960
  }
@@ -948,12 +1009,13 @@ class VaultV2BlueReallocationData {
948
1009
  },
949
1010
  targetPair,
950
1011
  sourcePair,
1012
+ allocatorHeadroom,
951
1013
  });
952
1014
  }
953
1015
  }
954
1016
  }
955
1017
  const capCompatibleCandidates = [];
956
- for (const { reallocation, targetPair, sourcePair, } of rawCandidates) {
1018
+ for (const { reallocation, targetPair, sourcePair, allocatorHeadroom, } of rawCandidates) {
957
1019
  let lower = 0n;
958
1020
  let upper = reallocation.assets;
959
1021
  const targetIds = targetPair.ids;
@@ -1028,6 +1090,7 @@ class VaultV2BlueReallocationData {
1028
1090
  reallocation: { ...reallocation, assets: selectedAssets },
1029
1091
  targetPair,
1030
1092
  sourcePair,
1093
+ allocatorHeadroom,
1031
1094
  });
1032
1095
  }
1033
1096
  return capCompatibleCandidates.sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"))[0];
@@ -1036,8 +1099,16 @@ class VaultV2BlueReallocationData {
1036
1099
  .sort((0, morpho_ts_1.bigIntComparator)(({ reallocation }) => reallocation.assets, "desc"));
1037
1100
  const largest = candidates[0];
1038
1101
  if (largest == null)
1039
- return { reallocations, data, context: simulationContext };
1040
- const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, } = largest;
1102
+ return {
1103
+ reallocations,
1104
+ data,
1105
+ context: simulationContext,
1106
+ allocatorCapBoundTargets,
1107
+ };
1108
+ const { reallocation: acceptedReallocation, targetPair: acceptedTargetPair, sourcePair: acceptedSourcePair, allocatorHeadroom: acceptedAllocatorHeadroom, } = largest;
1109
+ if (acceptedReallocation.assets >= acceptedAllocatorHeadroom)
1110
+ // BluePublicAllocator caps are per vault and target adapter.
1111
+ allocatorCapBoundTargets.add(`${acceptedReallocation.vault.toLowerCase()}:${acceptedReallocation.to.adapter.toLowerCase()}`);
1041
1112
  const touchedVaultKey = acceptedReallocation.vault.toLowerCase();
1042
1113
  let touchedVaultPairs = reserves.touchedPairs.get(touchedVaultKey);
1043
1114
  if (touchedVaultPairs == null) {
@@ -1062,7 +1133,12 @@ class VaultV2BlueReallocationData {
1062
1133
  if (remainingAssets != null)
1063
1134
  remainingAssets -= acceptedReallocation.assets;
1064
1135
  }
1065
- return { reallocations, data, context: simulationContext };
1136
+ return {
1137
+ reallocations,
1138
+ data,
1139
+ context: simulationContext,
1140
+ allocatorCapBoundTargets,
1141
+ };
1066
1142
  }
1067
1143
  /**
1068
1144
  * Sums friendly Vault V2 shared liquidity available to a target market.