@morpho-org/morpho-sdk 5.4.1 → 5.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/README.md +23 -7
  2. package/lib/cjs/abis.d.ts +314 -1
  3. package/lib/cjs/abis.js +169 -1
  4. package/lib/cjs/actions/blue/borrow.d.ts +21 -15
  5. package/lib/cjs/actions/blue/borrow.js +25 -18
  6. package/lib/cjs/actions/blue/buildAssetFundingActions.d.ts +1 -1
  7. package/lib/cjs/actions/blue/buildAssetFundingActions.js +1 -1
  8. package/lib/cjs/actions/blue/buildReallocationActions.d.ts +62 -19
  9. package/lib/cjs/actions/blue/buildReallocationActions.js +123 -27
  10. package/lib/cjs/actions/blue/refinance.d.ts +14 -7
  11. package/lib/cjs/actions/blue/refinance.js +18 -10
  12. package/lib/cjs/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  13. package/lib/cjs/actions/blue/supplyCollateralBorrow.js +39 -23
  14. package/lib/cjs/actions/blue/withdraw.d.ts +20 -13
  15. package/lib/cjs/actions/blue/withdraw.js +23 -18
  16. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  17. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +9 -2
  18. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  19. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +131 -0
  20. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  21. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  22. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +3 -2
  23. package/lib/cjs/actions/requirements/getRequirementsApproval.js +5 -3
  24. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  25. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +91 -0
  26. package/lib/cjs/actions/signatures/index.d.ts +1 -0
  27. package/lib/cjs/actions/signatures/index.js +1 -0
  28. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +54 -0
  29. package/lib/cjs/actions/vaultV1/inKindRedeem.js +96 -0
  30. package/lib/cjs/actions/vaultV1/index.d.ts +1 -0
  31. package/lib/cjs/actions/vaultV1/index.js +1 -0
  32. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +56 -0
  33. package/lib/cjs/actions/vaultV2/inKindRedeem.js +97 -0
  34. package/lib/cjs/actions/vaultV2/index.d.ts +1 -0
  35. package/lib/cjs/actions/vaultV2/index.js +1 -0
  36. package/lib/cjs/bundler/actions.d.ts +118 -2
  37. package/lib/cjs/bundler/actions.js +212 -6
  38. package/lib/cjs/bundler/types.d.ts +20 -0
  39. package/lib/cjs/constants.d.ts +1 -1
  40. package/lib/cjs/constants.js +3 -1
  41. package/lib/cjs/entities/blue/blue.d.ts +365 -76
  42. package/lib/cjs/entities/blue/blue.js +285 -52
  43. package/lib/cjs/entities/index.d.ts +2 -1
  44. package/lib/cjs/entities/index.js +6 -3
  45. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +82 -4
  46. package/lib/cjs/entities/vaultV1/vaultV1.js +164 -0
  47. package/lib/cjs/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +41 -17
  48. package/lib/cjs/entities/{reallocationData.js → vaultV1ReallocationData.js} +30 -18
  49. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +89 -3
  50. package/lib/cjs/entities/vaultV2/vaultV2.js +181 -0
  51. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +511 -0
  52. package/lib/cjs/entities/vaultV2BlueReallocationData.js +1311 -0
  53. package/lib/{esm/helpers/computeReallocations.d.ts → cjs/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  54. package/lib/cjs/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +27 -13
  55. package/lib/cjs/helpers/constant.d.ts +5 -3
  56. package/lib/cjs/helpers/constant.js +6 -4
  57. package/lib/cjs/helpers/index.d.ts +3 -2
  58. package/lib/cjs/helpers/index.js +8 -3
  59. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  60. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +73 -0
  61. package/lib/cjs/helpers/validate.d.ts +31 -15
  62. package/lib/cjs/helpers/validate.js +140 -27
  63. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  64. package/lib/cjs/helpers/validateRequirementSpender.js +2 -1
  65. package/lib/cjs/types/action.d.ts +33 -1
  66. package/lib/cjs/types/error.d.ts +363 -5
  67. package/lib/cjs/types/error.js +455 -6
  68. package/lib/cjs/types/sharedLiquidity.d.ts +72 -8
  69. package/lib/cjs/utils.d.ts +2 -2
  70. package/lib/cjs/utils.js +6 -4
  71. package/lib/esm/abis.d.ts +314 -1
  72. package/lib/esm/abis.js +167 -1
  73. package/lib/esm/actions/blue/borrow.d.ts +21 -15
  74. package/lib/esm/actions/blue/borrow.js +26 -19
  75. package/lib/esm/actions/blue/buildAssetFundingActions.d.ts +1 -1
  76. package/lib/esm/actions/blue/buildAssetFundingActions.js +1 -1
  77. package/lib/esm/actions/blue/buildReallocationActions.d.ts +62 -19
  78. package/lib/esm/actions/blue/buildReallocationActions.js +119 -25
  79. package/lib/esm/actions/blue/refinance.d.ts +14 -7
  80. package/lib/esm/actions/blue/refinance.js +19 -11
  81. package/lib/esm/actions/blue/supplyCollateralBorrow.d.ts +28 -19
  82. package/lib/esm/actions/blue/supplyCollateralBorrow.js +40 -24
  83. package/lib/esm/actions/blue/withdraw.d.ts +20 -13
  84. package/lib/esm/actions/blue/withdraw.js +24 -19
  85. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  86. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +9 -2
  87. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  88. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +127 -0
  89. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  90. package/lib/esm/actions/requirements/encode/index.js +1 -0
  91. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +3 -2
  92. package/lib/esm/actions/requirements/getRequirementsApproval.js +5 -3
  93. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  94. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +87 -0
  95. package/lib/esm/actions/signatures/index.d.ts +1 -0
  96. package/lib/esm/actions/signatures/index.js +1 -0
  97. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +54 -0
  98. package/lib/esm/actions/vaultV1/inKindRedeem.js +92 -0
  99. package/lib/esm/actions/vaultV1/index.d.ts +1 -0
  100. package/lib/esm/actions/vaultV1/index.js +1 -0
  101. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +56 -0
  102. package/lib/esm/actions/vaultV2/inKindRedeem.js +93 -0
  103. package/lib/esm/actions/vaultV2/index.d.ts +1 -0
  104. package/lib/esm/actions/vaultV2/index.js +1 -0
  105. package/lib/esm/bundler/actions.d.ts +118 -2
  106. package/lib/esm/bundler/actions.js +215 -9
  107. package/lib/esm/bundler/types.d.ts +20 -0
  108. package/lib/esm/constants.d.ts +1 -1
  109. package/lib/esm/constants.js +1 -1
  110. package/lib/esm/entities/blue/blue.d.ts +362 -73
  111. package/lib/esm/entities/blue/blue.js +288 -55
  112. package/lib/esm/entities/index.d.ts +2 -1
  113. package/lib/esm/entities/index.js +2 -1
  114. package/lib/esm/entities/vaultV1/vaultV1.d.ts +80 -2
  115. package/lib/esm/entities/vaultV1/vaultV1.js +170 -6
  116. package/lib/esm/entities/{reallocationData.d.ts → vaultV1ReallocationData.d.ts} +41 -17
  117. package/lib/esm/entities/{reallocationData.js → vaultV1ReallocationData.js} +33 -16
  118. package/lib/esm/entities/vaultV2/vaultV2.d.ts +88 -2
  119. package/lib/esm/entities/vaultV2/vaultV2.js +187 -6
  120. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +511 -0
  121. package/lib/esm/entities/vaultV2BlueReallocationData.js +1307 -0
  122. package/lib/{cjs/helpers/computeReallocations.d.ts → esm/helpers/computeVaultV1Reallocations.d.ts} +14 -8
  123. package/lib/esm/helpers/{computeReallocations.js → computeVaultV1Reallocations.js} +25 -11
  124. package/lib/esm/helpers/constant.d.ts +5 -3
  125. package/lib/esm/helpers/constant.js +5 -3
  126. package/lib/esm/helpers/index.d.ts +3 -2
  127. package/lib/esm/helpers/index.js +3 -2
  128. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  129. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +70 -0
  130. package/lib/esm/helpers/validate.d.ts +31 -15
  131. package/lib/esm/helpers/validate.js +141 -30
  132. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  133. package/lib/esm/helpers/validateRequirementSpender.js +2 -1
  134. package/lib/esm/types/action.d.ts +33 -1
  135. package/lib/esm/types/error.d.ts +363 -5
  136. package/lib/esm/types/error.js +428 -4
  137. package/lib/esm/types/sharedLiquidity.d.ts +72 -8
  138. package/lib/esm/utils.d.ts +2 -2
  139. package/lib/esm/utils.js +2 -2
  140. package/package.json +9 -11
@@ -1,8 +1,8 @@
1
- import { type AccrualVaultV2 } from "@morpho-org/blue-sdk";
1
+ import { type AccrualVaultV2, type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
3
  import { type Address } from "viem";
4
4
  import type { FetchParameters } from "../../types/data.js";
5
- import { type Deallocation, type DepositAmountArgs, type ERC20ApprovalAction, type MorphoClientType, type PermitRequirementSignature, type Requirement, type RequirementSignature, type Transaction, type VaultV2DepositAction, type VaultV2ForceRedeemAction, type VaultV2ForceWithdrawAction, type VaultV2RedeemAction, type VaultV2WithdrawAction } from "../../types/index.js";
5
+ import { type ActionOutput, type Deallocation, type DepositAmountArgs, type ERC20ApprovalAction, type MorphoClientType, type PermitRequirementSignature, type Requirement, type RequirementSignature, type Transaction, type VaultV2DepositAction, type VaultV2ForceRedeemAction, type VaultV2ForceWithdrawAction, type VaultV2InKindRedeemAction, type VaultV2RedeemAction, type VaultV2WithdrawAction } from "../../types/index.js";
6
6
  export interface VaultV2Actions {
7
7
  /**
8
8
  * Fetches the latest vault data.
@@ -75,6 +75,83 @@ export interface VaultV2Actions {
75
75
  }) => {
76
76
  buildTx: () => Readonly<Transaction<VaultV2RedeemAction>>;
77
77
  };
78
+ /**
79
+ * Prepares an illiquid Vault V2 exit into idle assets and Morpho Blue supply positions.
80
+ *
81
+ * The vault must have exactly one `MorphoMarketV1AdapterV2`. `amount` is penalty-inclusive and
82
+ * the caller controls market order. Call `getRequirements()` before `buildTx()` so Blue balance,
83
+ * allowance, and nonce are checked on-chain. Vault gates are enforced by the final transaction
84
+ * and are not preflighted: receive gates may depend on VaultExitBundlesV1's transient initiator,
85
+ * while arbitrary send-share gates may depend on intermediate state changed by the exit's
86
+ * multiple share burns. The SDK intentionally does not validate the user's share balance; size
87
+ * it so `amount + BigInt(marketParamsList.length) <= vault.previewRedeem(sharesHeld)`. The
88
+ * per-market term covers V2 withdrawal rounding and is not needed for V1. The share allowance
89
+ * includes that buffer, the penalty burns, and accrual through the bundle deadline.
90
+ *
91
+ * Idle balance, penalty, and adapter positions can drift after the snapshot, so an on-chain
92
+ * under-coverage panic remains possible if vault state changes between preparation and inclusion.
93
+ *
94
+ * @param params - In-kind redemption parameters.
95
+ * @param params.amount - Penalty-inclusive, asset-denominated amount to exit.
96
+ * @param params.marketParamsList - Ordered adapter markets consumed greedily after idle assets;
97
+ * its length is also the V2 share-sufficiency rounding buffer.
98
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
99
+ * @param params.userAddress - Account that signs and submits the exit.
100
+ * @param params.adapter - Optional adapter override; defaults to the vault's sole adapter.
101
+ * @param params.deadline - Optional shared permit/bundle deadline; defaults to two hours from now.
102
+ * @returns Lazy prerequisite resolution and a synchronous transaction builder.
103
+ * @throws {ChainIdMismatchError} when the client and entity target different chains.
104
+ * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
105
+ * @throws {NonPositiveInputError} when `amount` is not positive.
106
+ * @throws {InKindRedeemZeroDeallocationError} when the vault has no idle assets and the
107
+ * penalty-adjusted amount rounds to zero deallocated assets.
108
+ * @throws {EmptyMarketParamsListError} when assets must be deallocated and the market list is empty.
109
+ * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
110
+ * requirement resolution.
111
+ * @throws {InKindRedeemRequiresSingleAdapterError} when the vault does not have one adapter.
112
+ * @throws {AdapterNotPartOfVaultError} when `adapter` is not the vault's adapter.
113
+ * @throws {UnsupportedInKindAdapterError} when the adapter is not a MorphoMarketV1AdapterV2.
114
+ * @throws {InKindRedeemCoverageError} when the deduplicated list cannot cover the exit.
115
+ * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
116
+ * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
117
+ * @throws {viem.BaseError} from `getRequirements()` when an RPC or multicall contract read fails.
118
+ * @throws {InsufficientBlueBalanceForInKindRedeemError} from `getRequirements()` when Blue cannot fund the largest callback.
119
+ * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
120
+ * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
121
+ * @throws {VaultExitBundlesV1PermitMismatchError} from `buildTx()` when the requirement has the wrong permit kind, asset, or signature encoding.
122
+ * @example
123
+ * ```ts
124
+ * import { isRequirementSignature } from "@morpho-org/morpho-sdk";
125
+ *
126
+ * const vault = client.morpho.vaultV2(vaultAddress, 1);
127
+ * const vaultData = await vault.getData();
128
+ * const exit = vault.inKindRedeem({
129
+ * amount: 1_000_000n,
130
+ * marketParamsList,
131
+ * vaultData,
132
+ * userAddress,
133
+ * });
134
+ * const signatures = [];
135
+ * for (const requirement of await exit.getRequirements()) {
136
+ * if (isRequirementSignature(requirement)) {
137
+ * signatures.push(await requirement.sign(walletClient, userAddress));
138
+ * } else {
139
+ * const hash = await walletClient.sendTransaction(requirement);
140
+ * await client.waitForTransactionReceipt({ hash });
141
+ * }
142
+ * }
143
+ * const tx = exit.buildTx(signatures);
144
+ * // tx satisfies Readonly<Transaction<VaultV2InKindRedeemAction>>
145
+ * ```
146
+ */
147
+ readonly inKindRedeem: (params: {
148
+ readonly amount: bigint;
149
+ readonly marketParamsList: readonly MarketParams[];
150
+ readonly vaultData: AccrualVaultV2;
151
+ readonly userAddress: Address;
152
+ readonly adapter?: Address;
153
+ readonly deadline?: bigint;
154
+ }) => ActionOutput<VaultV2InKindRedeemAction, readonly RequirementSignature[], undefined>;
78
155
  /**
79
156
  * Prepares a force withdraw transaction for the VaultV2 contract using the vault's native multicall.
80
157
  *
@@ -144,7 +221,7 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
144
221
  } & DepositAmountArgs): {
145
222
  getRequirements: (params?: {
146
223
  useSimplePermit?: boolean;
147
- }) => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
224
+ }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
148
225
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<VaultV2DepositAction>>;
149
226
  };
150
227
  withdraw({ amount, userAddress }: {
@@ -159,6 +236,15 @@ export declare class MorphoVaultV2 implements VaultV2Actions {
159
236
  }): {
160
237
  buildTx: () => Readonly<Transaction<VaultV2RedeemAction>>;
161
238
  };
239
+ /** {@inheritDoc VaultV2Actions.inKindRedeem} */
240
+ inKindRedeem({ amount, marketParamsList, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, }: {
241
+ readonly amount: bigint;
242
+ readonly marketParamsList: readonly MarketParams[];
243
+ readonly vaultData: AccrualVaultV2;
244
+ readonly userAddress: Address;
245
+ readonly adapter?: Address;
246
+ readonly deadline?: bigint;
247
+ }): ActionOutput<VaultV2InKindRedeemAction, readonly RequirementSignature[], undefined>;
162
248
  forceWithdraw({ deallocations, withdraw, userAddress, }: {
163
249
  deallocations: readonly Deallocation[];
164
250
  withdraw: {
@@ -5,6 +5,7 @@ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  const blue_sdk_viem_1 = require("@morpho-org/blue-sdk-viem");
6
6
  const morpho_ts_1 = require("@morpho-org/morpho-ts");
7
7
  const viem_1 = require("viem");
8
+ const actions_1 = require("viem/actions");
8
9
  const index_js_1 = require("../../actions/index.js");
9
10
  const index_js_2 = require("../../helpers/index.js");
10
11
  const index_js_3 = require("../../types/index.js");
@@ -134,6 +135,186 @@ class MorphoVaultV2 {
134
135
  }),
135
136
  };
136
137
  }
138
+ /** {@inheritDoc VaultV2Actions.inKindRedeem} */
139
+ inKindRedeem({ amount, marketParamsList, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, }) {
140
+ if (this.client.viemClient.chain?.id !== this.chainId) {
141
+ throw new index_js_3.ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
142
+ }
143
+ if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
144
+ throw new index_js_3.VaultAddressMismatchError(this.vault, vaultData.address);
145
+ }
146
+ if (amount <= 0n)
147
+ throw new index_js_3.NonPositiveInputError("amount", amount);
148
+ const marketParamsListSnapshot = marketParamsList.map(({ loanToken, collateralToken, oracle, irm, lltv }) => ({
149
+ loanToken,
150
+ collateralToken,
151
+ oracle,
152
+ irm,
153
+ lltv,
154
+ }));
155
+ const marketIdListSnapshot = marketParamsListSnapshot.map((marketParams) => blue_sdk_1.MarketUtils.getMarketId(marketParams));
156
+ const now = morpho_ts_1.Time.timestamp();
157
+ const deadline = deadlineOverride ?? now + morpho_ts_1.Time.s.from.h(2n);
158
+ if (deadline <= now)
159
+ throw new index_js_3.ExpiredDeadlineError(deadline, now);
160
+ if (vaultData.accrualAdapters.length !== 1) {
161
+ throw new index_js_3.InKindRedeemRequiresSingleAdapterError(this.vault, vaultData.accrualAdapters.length);
162
+ }
163
+ const soleAdapter = vaultData.accrualAdapters[0];
164
+ if (soleAdapter == null) {
165
+ throw new index_js_3.InKindRedeemRequiresSingleAdapterError(this.vault, 0);
166
+ }
167
+ const adapter = adapterOverride ?? soleAdapter.address;
168
+ if (!(0, viem_1.isAddressEqual)(adapter, soleAdapter.address)) {
169
+ throw new index_js_3.AdapterNotPartOfVaultError(this.vault, adapter);
170
+ }
171
+ if (!(soleAdapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)) {
172
+ throw new index_js_3.UnsupportedInKindAdapterError(adapter);
173
+ }
174
+ const penalty = vaultData.forceDeallocatePenalties[soleAdapter.address] ?? 0n;
175
+ const idleAssets = blue_sdk_1.MathLib.min(vaultData.assetBalance, amount);
176
+ const assetsToDeallocate = blue_sdk_1.MathLib.wDivDown(amount - idleAssets, blue_sdk_1.MathLib.WAD + penalty);
177
+ if (idleAssets === 0n && assetsToDeallocate === 0n) {
178
+ throw new index_js_3.InKindRedeemZeroDeallocationError({
179
+ vault: this.vault,
180
+ amount,
181
+ penalty,
182
+ });
183
+ }
184
+ if (assetsToDeallocate > 0n && marketParamsListSnapshot.length === 0) {
185
+ throw new index_js_3.EmptyMarketParamsListError();
186
+ }
187
+ const assetsByMarket = new Map(soleAdapter.markets.map((market) => [
188
+ market.id,
189
+ market
190
+ .accrueInterest(now)
191
+ .toSupplyAssets(soleAdapter.supplyShares[market.id] ?? 0n),
192
+ ]));
193
+ const uniqueMarketIds = new Set(marketIdListSnapshot);
194
+ let covered = 0n;
195
+ for (const id of uniqueMarketIds)
196
+ covered += assetsByMarket.get(id) ?? 0n;
197
+ if (covered < assetsToDeallocate) {
198
+ const maxExitAssets = covered === 0n
199
+ ? idleAssets
200
+ : idleAssets +
201
+ blue_sdk_1.MathLib.wMulUp(covered + 1n, blue_sdk_1.MathLib.WAD + penalty) -
202
+ 1n;
203
+ throw new index_js_3.InKindRedeemCoverageError({
204
+ required: assetsToDeallocate,
205
+ covered,
206
+ maxExitAssets,
207
+ });
208
+ }
209
+ let remaining = assetsToDeallocate;
210
+ let peak = 0n;
211
+ const consumedMarketIds = new Set();
212
+ const { vault: allowanceVault } = vaultData.accrueInterest(deadline);
213
+ // Interest can lower the burn, while management fees can raise it; bound both endpoints.
214
+ const previewAllowance = (assets) => blue_sdk_1.MathLib.max(vaultData.toShares(assets, "Up"), allowanceVault.toShares(assets, "Up"));
215
+ let requiredShareAllowance = previewAllowance(BigInt(marketParamsListSnapshot.length));
216
+ // Pre-burn previews upper-bound each separately rounded idle, penalty, and main burn.
217
+ requiredShareAllowance += previewAllowance(idleAssets);
218
+ for (const id of marketIdListSnapshot) {
219
+ const available = consumedMarketIds.has(id)
220
+ ? 0n
221
+ : (assetsByMarket.get(id) ?? 0n);
222
+ consumedMarketIds.add(id);
223
+ const chunk = blue_sdk_1.MathLib.min(available, remaining);
224
+ peak = blue_sdk_1.MathLib.max(peak, chunk);
225
+ requiredShareAllowance += previewAllowance(blue_sdk_1.MathLib.wMulUp(chunk, penalty));
226
+ requiredShareAllowance += previewAllowance(chunk);
227
+ remaining -= chunk;
228
+ }
229
+ const vaultExitBundlesV1 = (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.vaultExitBundlesV1");
230
+ const addresses = (0, blue_sdk_1.getChainAddresses)(this.chainId);
231
+ const blue = addresses.blue ?? addresses.morpho;
232
+ return {
233
+ getRequirements: async () => {
234
+ const requirementsTimestamp = morpho_ts_1.Time.timestamp();
235
+ if (deadline <= requirementsTimestamp) {
236
+ throw new index_js_3.ExpiredDeadlineError(deadline, requirementsTimestamp);
237
+ }
238
+ // Vault gates are intentionally left to the final transaction. A receive gate may inspect
239
+ // VaultExitBundlesV1's transient `initiator`, which is populated only during the actual
240
+ // periphery call. A send-share gate is arbitrary external code and is evaluated repeatedly
241
+ // after intermediate penalty share burns, so one standalone read is not execution-equivalent
242
+ // either. Simulate the finalized transaction after authorization when gate compatibility
243
+ // must be checked before submission.
244
+ const [allowance, nonce, blueBalance] = await (0, actions_1.multicall)(this.client.viemClient, {
245
+ allowFailure: false,
246
+ contracts: [
247
+ {
248
+ address: this.vault,
249
+ abi: viem_1.erc20Abi,
250
+ functionName: "allowance",
251
+ args: [userAddress, vaultExitBundlesV1],
252
+ },
253
+ {
254
+ address: this.vault,
255
+ abi: blue_sdk_viem_1.erc2612Abi,
256
+ functionName: "nonces",
257
+ args: [userAddress],
258
+ },
259
+ {
260
+ address: vaultData.asset,
261
+ abi: viem_1.erc20Abi,
262
+ functionName: "balanceOf",
263
+ args: [blue],
264
+ },
265
+ ],
266
+ });
267
+ if (blueBalance < peak) {
268
+ throw new index_js_3.InsufficientBlueBalanceForInKindRedeemError({
269
+ asset: vaultData.asset,
270
+ available: blueBalance,
271
+ required: peak,
272
+ });
273
+ }
274
+ if (allowance >= requiredShareAllowance)
275
+ return [];
276
+ if (this.client.options.supportSignature) {
277
+ return [
278
+ (0, index_js_1.encodeVaultSharesPermit)({
279
+ vault: vaultData,
280
+ version: "vaultV2",
281
+ spender: vaultExitBundlesV1,
282
+ owner: userAddress,
283
+ chainId: this.chainId,
284
+ nonce,
285
+ amount: requiredShareAllowance,
286
+ deadline,
287
+ }),
288
+ ];
289
+ }
290
+ return [
291
+ (0, index_js_1.encodeErc20Approval)({
292
+ token: this.vault,
293
+ spender: vaultExitBundlesV1,
294
+ amount: requiredShareAllowance,
295
+ chainId: this.chainId,
296
+ }),
297
+ ];
298
+ },
299
+ buildTx: (signatures) => {
300
+ const { permit } = (0, index_js_3.selectRequirementSignatures)(signatures, {
301
+ permit: true,
302
+ });
303
+ return (0, index_js_1.vaultV2InKindRedeem)({
304
+ vault: { chainId: this.chainId, address: this.vault },
305
+ args: {
306
+ adapter,
307
+ amount,
308
+ marketParamsList: marketParamsListSnapshot,
309
+ userAddress,
310
+ deadline,
311
+ requirementSignature: permit,
312
+ },
313
+ metadata: this.client.options.metadata,
314
+ });
315
+ },
316
+ };
317
+ }
137
318
  forceWithdraw({ deallocations, withdraw, userAddress, }) {
138
319
  if (this.client.viemClient.chain?.id !== this.chainId) {
139
320
  throw new index_js_3.ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);