@morpho-org/morpho-sdk 5.4.1 → 5.5.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 (84) hide show
  1. package/README.md +15 -1
  2. package/lib/cjs/abis.d.ts +313 -0
  3. package/lib/cjs/abis.js +167 -1
  4. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  5. package/lib/cjs/actions/requirements/encode/encodeErc20Approval.js +9 -2
  6. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  7. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +131 -0
  8. package/lib/cjs/actions/requirements/encode/index.d.ts +1 -0
  9. package/lib/cjs/actions/requirements/encode/index.js +1 -0
  10. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +3 -2
  11. package/lib/cjs/actions/requirements/getRequirementsApproval.js +3 -2
  12. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  13. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +91 -0
  14. package/lib/cjs/actions/signatures/index.d.ts +1 -0
  15. package/lib/cjs/actions/signatures/index.js +1 -0
  16. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +54 -0
  17. package/lib/cjs/actions/vaultV1/inKindRedeem.js +96 -0
  18. package/lib/cjs/actions/vaultV1/index.d.ts +1 -0
  19. package/lib/cjs/actions/vaultV1/index.js +1 -0
  20. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +56 -0
  21. package/lib/cjs/actions/vaultV2/inKindRedeem.js +97 -0
  22. package/lib/cjs/actions/vaultV2/index.d.ts +1 -0
  23. package/lib/cjs/actions/vaultV2/index.js +1 -0
  24. package/lib/cjs/bundler/actions.d.ts +1 -2
  25. package/lib/cjs/bundler/actions.js +1 -2
  26. package/lib/cjs/entities/blue/blue.d.ts +8 -8
  27. package/lib/cjs/entities/reallocationData.d.ts +1 -2
  28. package/lib/cjs/entities/reallocationData.js +1 -2
  29. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +82 -4
  30. package/lib/cjs/entities/vaultV1/vaultV1.js +164 -0
  31. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +89 -3
  32. package/lib/cjs/entities/vaultV2/vaultV2.js +181 -0
  33. package/lib/cjs/helpers/index.d.ts +1 -0
  34. package/lib/cjs/helpers/index.js +3 -1
  35. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  36. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +73 -0
  37. package/lib/cjs/helpers/validate.d.ts +1 -1
  38. package/lib/cjs/helpers/validateRequirementSpender.d.ts +1 -1
  39. package/lib/cjs/helpers/validateRequirementSpender.js +2 -1
  40. package/lib/cjs/types/action.d.ts +21 -1
  41. package/lib/cjs/types/error.d.ts +139 -0
  42. package/lib/cjs/types/error.js +189 -2
  43. package/lib/esm/abis.d.ts +313 -0
  44. package/lib/esm/abis.js +166 -0
  45. package/lib/esm/actions/requirements/encode/encodeErc20Approval.d.ts +1 -1
  46. package/lib/esm/actions/requirements/encode/encodeErc20Approval.js +9 -2
  47. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +64 -0
  48. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +127 -0
  49. package/lib/esm/actions/requirements/encode/index.d.ts +1 -0
  50. package/lib/esm/actions/requirements/encode/index.js +1 -0
  51. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +3 -2
  52. package/lib/esm/actions/requirements/getRequirementsApproval.js +3 -2
  53. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +52 -0
  54. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +87 -0
  55. package/lib/esm/actions/signatures/index.d.ts +1 -0
  56. package/lib/esm/actions/signatures/index.js +1 -0
  57. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +54 -0
  58. package/lib/esm/actions/vaultV1/inKindRedeem.js +92 -0
  59. package/lib/esm/actions/vaultV1/index.d.ts +1 -0
  60. package/lib/esm/actions/vaultV1/index.js +1 -0
  61. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +56 -0
  62. package/lib/esm/actions/vaultV2/inKindRedeem.js +93 -0
  63. package/lib/esm/actions/vaultV2/index.d.ts +1 -0
  64. package/lib/esm/actions/vaultV2/index.js +1 -0
  65. package/lib/esm/bundler/actions.d.ts +1 -2
  66. package/lib/esm/bundler/actions.js +1 -2
  67. package/lib/esm/entities/blue/blue.d.ts +5 -5
  68. package/lib/esm/entities/reallocationData.d.ts +1 -2
  69. package/lib/esm/entities/reallocationData.js +1 -2
  70. package/lib/esm/entities/vaultV1/vaultV1.d.ts +80 -2
  71. package/lib/esm/entities/vaultV1/vaultV1.js +170 -6
  72. package/lib/esm/entities/vaultV2/vaultV2.d.ts +88 -2
  73. package/lib/esm/entities/vaultV2/vaultV2.js +187 -6
  74. package/lib/esm/helpers/index.d.ts +1 -0
  75. package/lib/esm/helpers/index.js +1 -0
  76. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +49 -0
  77. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +70 -0
  78. package/lib/esm/helpers/validate.d.ts +1 -1
  79. package/lib/esm/helpers/validateRequirementSpender.d.ts +1 -1
  80. package/lib/esm/helpers/validateRequirementSpender.js +2 -1
  81. package/lib/esm/types/action.d.ts +21 -1
  82. package/lib/esm/types/error.d.ts +139 -0
  83. package/lib/esm/types/error.js +175 -0
  84. 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 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
  *
@@ -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: {
@@ -1,10 +1,11 @@
1
- import { DEFAULT_SLIPPAGE_TOLERANCE, getChainAddresses, MathLib, } from "@morpho-org/blue-sdk";
2
- import { fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
- import { Time } from "@morpho-org/morpho-ts";
4
- import { isAddressEqual } from "viem";
5
- import { getGeneralAdapterRequirements, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
1
+ import { AccrualVaultV2MorphoMarketV1AdapterV2, DEFAULT_SLIPPAGE_TOLERANCE, getChainAddresses, MarketUtils, MathLib, } from "@morpho-org/blue-sdk";
2
+ import { erc2612Abi, fetchAccrualVaultV2 } from "@morpho-org/blue-sdk-viem";
3
+ import { getChainAddress, Time } from "@morpho-org/morpho-ts";
4
+ import { erc20Abi, isAddressEqual } from "viem";
5
+ import { multicall } from "viem/actions";
6
+ import { encodeErc20Approval, encodeVaultSharesPermit, getGeneralAdapterRequirements, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
6
7
  import { validateSlippageTolerance } from "../../helpers/index.js";
7
- import { ChainIdMismatchError, ChainWNativeMissingError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, selectRequirementSignatures, VaultAddressMismatchError, } from "../../types/index.js";
8
+ import { AdapterNotPartOfVaultError, ChainIdMismatchError, ChainWNativeMissingError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemRequiresSingleAdapterError, InKindRedeemZeroDeallocationError, InsufficientBlueBalanceForInKindRedeemError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, selectRequirementSignatures, UnsupportedInKindAdapterError, VaultAddressMismatchError, } from "../../types/index.js";
8
9
  export class MorphoVaultV2 {
9
10
  client;
10
11
  vault;
@@ -131,6 +132,186 @@ export class MorphoVaultV2 {
131
132
  }),
132
133
  };
133
134
  }
135
+ /** {@inheritDoc VaultV2Actions.inKindRedeem} */
136
+ inKindRedeem({ amount, marketParamsList, vaultData, userAddress, adapter: adapterOverride, deadline: deadlineOverride, }) {
137
+ if (this.client.viemClient.chain?.id !== this.chainId) {
138
+ throw new ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
139
+ }
140
+ if (!isAddressEqual(vaultData.address, this.vault)) {
141
+ throw new VaultAddressMismatchError(this.vault, vaultData.address);
142
+ }
143
+ if (amount <= 0n)
144
+ throw new NonPositiveInputError("amount", amount);
145
+ const marketParamsListSnapshot = marketParamsList.map(({ loanToken, collateralToken, oracle, irm, lltv }) => ({
146
+ loanToken,
147
+ collateralToken,
148
+ oracle,
149
+ irm,
150
+ lltv,
151
+ }));
152
+ const marketIdListSnapshot = marketParamsListSnapshot.map((marketParams) => MarketUtils.getMarketId(marketParams));
153
+ const now = Time.timestamp();
154
+ const deadline = deadlineOverride ?? now + Time.s.from.h(2n);
155
+ if (deadline <= now)
156
+ throw new ExpiredDeadlineError(deadline, now);
157
+ if (vaultData.accrualAdapters.length !== 1) {
158
+ throw new InKindRedeemRequiresSingleAdapterError(this.vault, vaultData.accrualAdapters.length);
159
+ }
160
+ const soleAdapter = vaultData.accrualAdapters[0];
161
+ if (soleAdapter == null) {
162
+ throw new InKindRedeemRequiresSingleAdapterError(this.vault, 0);
163
+ }
164
+ const adapter = adapterOverride ?? soleAdapter.address;
165
+ if (!isAddressEqual(adapter, soleAdapter.address)) {
166
+ throw new AdapterNotPartOfVaultError(this.vault, adapter);
167
+ }
168
+ if (!(soleAdapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
169
+ throw new UnsupportedInKindAdapterError(adapter);
170
+ }
171
+ const penalty = vaultData.forceDeallocatePenalties[soleAdapter.address] ?? 0n;
172
+ const idleAssets = MathLib.min(vaultData.assetBalance, amount);
173
+ const assetsToDeallocate = MathLib.wDivDown(amount - idleAssets, MathLib.WAD + penalty);
174
+ if (idleAssets === 0n && assetsToDeallocate === 0n) {
175
+ throw new InKindRedeemZeroDeallocationError({
176
+ vault: this.vault,
177
+ amount,
178
+ penalty,
179
+ });
180
+ }
181
+ if (assetsToDeallocate > 0n && marketParamsListSnapshot.length === 0) {
182
+ throw new EmptyMarketParamsListError();
183
+ }
184
+ const assetsByMarket = new Map(soleAdapter.markets.map((market) => [
185
+ market.id,
186
+ market
187
+ .accrueInterest(now)
188
+ .toSupplyAssets(soleAdapter.supplyShares[market.id] ?? 0n),
189
+ ]));
190
+ const uniqueMarketIds = new Set(marketIdListSnapshot);
191
+ let covered = 0n;
192
+ for (const id of uniqueMarketIds)
193
+ covered += assetsByMarket.get(id) ?? 0n;
194
+ if (covered < assetsToDeallocate) {
195
+ const maxExitAssets = covered === 0n
196
+ ? idleAssets
197
+ : idleAssets +
198
+ MathLib.wMulUp(covered + 1n, MathLib.WAD + penalty) -
199
+ 1n;
200
+ throw new InKindRedeemCoverageError({
201
+ required: assetsToDeallocate,
202
+ covered,
203
+ maxExitAssets,
204
+ });
205
+ }
206
+ let remaining = assetsToDeallocate;
207
+ let peak = 0n;
208
+ let requiredShareAllowance = 0n;
209
+ const consumedMarketIds = new Set();
210
+ const { vault: allowanceVault } = vaultData.accrueInterest(deadline);
211
+ // Interest can lower the burn, while management fees can raise it; bound both endpoints.
212
+ const previewAllowance = (assets) => MathLib.max(vaultData.toShares(assets, "Up"), allowanceVault.toShares(assets, "Up"));
213
+ // Pre-burn previews upper-bound each separately rounded idle, penalty, and main burn.
214
+ requiredShareAllowance += previewAllowance(idleAssets);
215
+ for (const id of marketIdListSnapshot) {
216
+ const available = consumedMarketIds.has(id)
217
+ ? 0n
218
+ : (assetsByMarket.get(id) ?? 0n);
219
+ consumedMarketIds.add(id);
220
+ const chunk = MathLib.min(available, remaining);
221
+ peak = MathLib.max(peak, chunk);
222
+ requiredShareAllowance += previewAllowance(MathLib.wMulUp(chunk, penalty));
223
+ requiredShareAllowance += previewAllowance(chunk);
224
+ remaining -= chunk;
225
+ }
226
+ const vaultExitBundlesV1 = getChainAddress(this.chainId, "bundles.vaultExitBundlesV1");
227
+ const addresses = getChainAddresses(this.chainId);
228
+ const blue = addresses.blue ?? addresses.morpho;
229
+ return {
230
+ getRequirements: async () => {
231
+ const requirementsTimestamp = Time.timestamp();
232
+ if (deadline <= requirementsTimestamp) {
233
+ throw new ExpiredDeadlineError(deadline, requirementsTimestamp);
234
+ }
235
+ // Vault gates are intentionally left to the final transaction. A receive gate may inspect
236
+ // VaultExitBundlesV1's transient `initiator`, which is populated only during the actual
237
+ // periphery call. A send-share gate is arbitrary external code and is evaluated repeatedly
238
+ // after intermediate penalty share burns, so one standalone read is not execution-equivalent
239
+ // either. Simulate the finalized transaction after authorization when gate compatibility
240
+ // must be checked before submission.
241
+ const [allowance, nonce, blueBalance] = await multicall(this.client.viemClient, {
242
+ allowFailure: false,
243
+ contracts: [
244
+ {
245
+ address: this.vault,
246
+ abi: erc20Abi,
247
+ functionName: "allowance",
248
+ args: [userAddress, vaultExitBundlesV1],
249
+ },
250
+ {
251
+ address: this.vault,
252
+ abi: erc2612Abi,
253
+ functionName: "nonces",
254
+ args: [userAddress],
255
+ },
256
+ {
257
+ address: vaultData.asset,
258
+ abi: erc20Abi,
259
+ functionName: "balanceOf",
260
+ args: [blue],
261
+ },
262
+ ],
263
+ });
264
+ if (blueBalance < peak) {
265
+ throw new InsufficientBlueBalanceForInKindRedeemError({
266
+ asset: vaultData.asset,
267
+ available: blueBalance,
268
+ required: peak,
269
+ });
270
+ }
271
+ if (allowance >= requiredShareAllowance)
272
+ return [];
273
+ if (this.client.options.supportSignature) {
274
+ return [
275
+ encodeVaultSharesPermit({
276
+ vault: vaultData,
277
+ version: "vaultV2",
278
+ spender: vaultExitBundlesV1,
279
+ owner: userAddress,
280
+ chainId: this.chainId,
281
+ nonce,
282
+ amount: requiredShareAllowance,
283
+ deadline,
284
+ }),
285
+ ];
286
+ }
287
+ return [
288
+ encodeErc20Approval({
289
+ token: this.vault,
290
+ spender: vaultExitBundlesV1,
291
+ amount: requiredShareAllowance,
292
+ chainId: this.chainId,
293
+ }),
294
+ ];
295
+ },
296
+ buildTx: (signatures) => {
297
+ const { permit } = selectRequirementSignatures(signatures, {
298
+ permit: true,
299
+ });
300
+ return vaultV2InKindRedeem({
301
+ vault: { chainId: this.chainId, address: this.vault },
302
+ args: {
303
+ adapter,
304
+ amount,
305
+ marketParamsList: marketParamsListSnapshot,
306
+ userAddress,
307
+ deadline,
308
+ requirementSignature: permit,
309
+ },
310
+ metadata: this.client.options.metadata,
311
+ });
312
+ },
313
+ };
314
+ }
134
315
  forceWithdraw({ deallocations, withdraw, userAddress, }) {
135
316
  if (this.client.viemClient.chain?.id !== this.chainId) {
136
317
  throw new ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
@@ -1,6 +1,7 @@
1
1
  export { computeReallocations } from "./computeReallocations.js";
2
2
  export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
3
3
  export { addTransactionMetadata } from "./metadata.js";
4
+ export { type PreviewVaultV2InKindRedeemParams, previewVaultV2InKindRedeem, type VaultV2InKindRedeemMarketPreview, } from "./previewVaultV2InKindRedeem.js";
4
5
  export { signAndVerifyTypedData } from "./signAndVerifyTypedData.js";
5
6
  export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
6
7
  export { validateAccrualPosition, validateChainId, validateMidnightMarketChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
@@ -1,6 +1,7 @@
1
1
  export { computeReallocations } from "./computeReallocations.js";
2
2
  export { APPROVE_ONLY_ONCE_TOKENS, DEFAULT_LLTV_BUFFER, DEFAULT_SUPPLY_TARGET_UTILIZATION, DEFAULT_WITHDRAWAL_TARGET_UTILIZATION, MAX_ABSOLUTE_SHARE_PRICE, MAX_SLIPPAGE_TOLERANCE, MAX_TOKEN_APPROVALS, } from "./constant.js";
3
3
  export { addTransactionMetadata } from "./metadata.js";
4
+ export { previewVaultV2InKindRedeem, } from "./previewVaultV2InKindRedeem.js";
4
5
  export { signAndVerifyTypedData } from "./signAndVerifyTypedData.js";
5
6
  export { computeMaxRepaySharePrice, computeMaxSupplySharePrice, computeMinBorrowSharePrice, computeMinWithdrawSharePrice, } from "./slippage.js";
6
7
  export { validateAccrualPosition, validateChainId, validateMidnightMarketChainId, validateNativeAsset, validatePositionHealth, validatePositionHealthAfterWithdraw, validateReallocations, validateRepayAmount, validateRepayShares, validateSlippageTolerance, validateUserAddress, validateWithdrawAmount, validateWithdrawShares, } from "./validate.js";
@@ -0,0 +1,49 @@
1
+ import { type AccrualVaultV2, type MarketParams } from "@morpho-org/blue-sdk";
2
+ /** Inputs used to preview Vault V2 in-kind redemption market choices. */
3
+ export interface PreviewVaultV2InKindRedeemParams {
4
+ /** Positive penalty-inclusive amount the user wants to exit. */
5
+ readonly requestedExitAssets: bigint;
6
+ /** Timestamp used to accrue every Morpho Blue market before converting adapter shares. */
7
+ readonly timestamp: bigint;
8
+ }
9
+ /** Frontend-ready preview of a Vault V2 in-kind redemption through one Morpho Blue market. */
10
+ export interface VaultV2InKindRedeemMarketPreview {
11
+ /** Morpho Blue market parameters to pass to the in-kind redemption action. */
12
+ readonly marketParams: MarketParams;
13
+ /** Maximum penalty-inclusive exit amount supported by this market and the vault's idle assets. */
14
+ readonly maxExitAssets: bigint;
15
+ /** Penalty-inclusive exit amount assigned to this market choice. */
16
+ readonly exitAssets: bigint;
17
+ /** Requested penalty-inclusive exit amount not covered by this market choice. */
18
+ readonly remainingExitAssets: bigint;
19
+ /** Portion of `exitAssets` withdrawn directly from the vault's idle assets. */
20
+ readonly idleAssets: bigint;
21
+ /** Morpho Blue supply assets received after the force-deallocation penalty. */
22
+ readonly netAssets: bigint;
23
+ /** Assets charged as the force-deallocation penalty. */
24
+ readonly feeAssets: bigint;
25
+ }
26
+ /**
27
+ * Previews the single-market in-kind redemption choices needed by a Vault V2 frontend.
28
+ *
29
+ * Vaults with exactly one MorphoMarketV1AdapterV2 can produce choices. Their non-empty markets are
30
+ * returned in descending allocation order with the exact penalty-inclusive input ceiling, idle
31
+ * assets withdrawn directly, and resulting Blue position for `requestedExitAssets`.
32
+ *
33
+ * @param vaultData - Pre-fetched Vault V2 accrual snapshot.
34
+ * @param params - Preview parameters.
35
+ * @param params.requestedExitAssets - Positive penalty-inclusive amount the user wants to exit.
36
+ * @param params.timestamp - Timestamp used to accrue Morpho Blue markets before calculating capacity.
37
+ * @returns Frontend-ready market choices, or an empty list when no choices are available.
38
+ * @example
39
+ * ```ts
40
+ * import { previewVaultV2InKindRedeem } from "@morpho-org/morpho-sdk";
41
+ *
42
+ * const [market] = previewVaultV2InKindRedeem(vaultData, {
43
+ * requestedExitAssets,
44
+ * timestamp: block.timestamp,
45
+ * });
46
+ * // market?.exitAssets is ready to pass to vault.inKindRedeem(...)
47
+ * ```
48
+ */
49
+ export declare function previewVaultV2InKindRedeem(vaultData: AccrualVaultV2, params: PreviewVaultV2InKindRedeemParams): readonly VaultV2InKindRedeemMarketPreview[];
@@ -0,0 +1,70 @@
1
+ import { AccrualVaultV2MorphoMarketV1AdapterV2, MathLib, } from "@morpho-org/blue-sdk";
2
+ /**
3
+ * Previews the single-market in-kind redemption choices needed by a Vault V2 frontend.
4
+ *
5
+ * Vaults with exactly one MorphoMarketV1AdapterV2 can produce choices. Their non-empty markets are
6
+ * returned in descending allocation order with the exact penalty-inclusive input ceiling, idle
7
+ * assets withdrawn directly, and resulting Blue position for `requestedExitAssets`.
8
+ *
9
+ * @param vaultData - Pre-fetched Vault V2 accrual snapshot.
10
+ * @param params - Preview parameters.
11
+ * @param params.requestedExitAssets - Positive penalty-inclusive amount the user wants to exit.
12
+ * @param params.timestamp - Timestamp used to accrue Morpho Blue markets before calculating capacity.
13
+ * @returns Frontend-ready market choices, or an empty list when no choices are available.
14
+ * @example
15
+ * ```ts
16
+ * import { previewVaultV2InKindRedeem } from "@morpho-org/morpho-sdk";
17
+ *
18
+ * const [market] = previewVaultV2InKindRedeem(vaultData, {
19
+ * requestedExitAssets,
20
+ * timestamp: block.timestamp,
21
+ * });
22
+ * // market?.exitAssets is ready to pass to vault.inKindRedeem(...)
23
+ * ```
24
+ */
25
+ export function previewVaultV2InKindRedeem(vaultData, params) {
26
+ const { requestedExitAssets, timestamp } = params;
27
+ if (requestedExitAssets <= 0n) {
28
+ return [];
29
+ }
30
+ if (vaultData.accrualAdapters.length !== 1) {
31
+ return [];
32
+ }
33
+ const adapter = vaultData.accrualAdapters[0];
34
+ if (!(adapter instanceof AccrualVaultV2MorphoMarketV1AdapterV2)) {
35
+ return [];
36
+ }
37
+ const penalty = vaultData.forceDeallocatePenalties[adapter.address] ?? 0n;
38
+ const availableIdleAssets = vaultData.assetBalance;
39
+ const allocations = adapter.markets
40
+ .map((market) => ({
41
+ market,
42
+ allocationAssets: market
43
+ .accrueInterest(MathLib.max(timestamp, market.lastUpdate))
44
+ .toSupplyAssets(adapter.supplyShares[market.id] ?? 0n),
45
+ }))
46
+ .filter(({ allocationAssets }) => allocationAssets > 0n)
47
+ .toSorted(({ allocationAssets: a }, { allocationAssets: b }) => a === b ? 0 : a > b ? -1 : 1);
48
+ return allocations.flatMap(({ market, allocationAssets }) => {
49
+ const maxExitAssets = availableIdleAssets +
50
+ MathLib.wMulUp(allocationAssets + 1n, MathLib.WAD + penalty) -
51
+ 1n;
52
+ const exitAssets = MathLib.min(requestedExitAssets, maxExitAssets);
53
+ const idleAssets = MathLib.min(exitAssets, availableIdleAssets);
54
+ const inKindExitAssets = exitAssets - idleAssets;
55
+ const netAssets = MathLib.wDivDown(inKindExitAssets, MathLib.WAD + penalty);
56
+ if (idleAssets === 0n && netAssets === 0n)
57
+ return [];
58
+ return [
59
+ {
60
+ marketParams: market.params,
61
+ maxExitAssets,
62
+ exitAssets,
63
+ remainingExitAssets: requestedExitAssets - exitAssets,
64
+ idleAssets,
65
+ netAssets,
66
+ feeAssets: MathLib.wMulUp(netAssets, penalty),
67
+ },
68
+ ];
69
+ });
70
+ }
@@ -3,7 +3,7 @@ import type { MarketInput as MidnightMarketInput } from "@morpho-org/midnight-sd
3
3
  import { type Address } from "viem";
4
4
  import { type VaultReallocation } from "../types/index.js";
5
5
  /** @internal */
6
- export declare const compareMarketIds: (idA: MarketId, idB: MarketId) => 1 | 0 | -1;
6
+ export declare const compareMarketIds: (idA: MarketId, idB: MarketId) => -1 | 0 | 1;
7
7
  /**
8
8
  * Validates that a raw or hydrated Midnight market belongs to the expected chain.
9
9
  *
@@ -1,6 +1,6 @@
1
1
  import { type Address } from "@morpho-org/blue-sdk";
2
2
  /** Supported spender slots that can be validated against the chain address registry. */
3
- export type RequirementSpenderKey = "generalAdapter1" | "permit2" | "midnight" | "midnightBundles";
3
+ export type RequirementSpenderKey = "generalAdapter1" | "permit2" | "midnight" | "midnightBundles" | "vaultExitBundlesV1";
4
4
  /**
5
5
  * Validates that a requirement encoder spender matches one of the allowed chain addresses.
6
6
  *
@@ -23,12 +23,13 @@ import { UnsupportedErc20ApprovalSpenderError } from "../types/index.js";
23
23
  * ```
24
24
  */
25
25
  export const validateRequirementSpender = (params) => {
26
- const { permit2, midnight, midnightBundles, bundler3: { generalAdapter1 }, } = getChainAddresses(params.chainId);
26
+ const { permit2, midnight, midnightBundles, bundler3: { generalAdapter1 }, bundles, } = getChainAddresses(params.chainId);
27
27
  const addresses = {
28
28
  generalAdapter1,
29
29
  permit2,
30
30
  midnight,
31
31
  midnightBundles,
32
+ vaultExitBundlesV1: bundles?.vaultExitBundlesV1,
32
33
  };
33
34
  const supportedSpenders = params.allowed.map((key) => addresses[key]);
34
35
  if (!supportedSpenders.some((supported) => supported != null && isAddressEqual(params.spender, supported))) {
@@ -1,3 +1,4 @@
1
+ import type { InputMarketParams } from "@morpho-org/blue-sdk";
1
2
  import type { Address, Hex, WalletClient } from "viem";
2
3
  import type { Deallocation } from "./deallocation.js";
3
4
  export interface BaseAction<TType extends string = string, TArgs extends Record<string, unknown> = Record<string, unknown>> {
@@ -32,6 +33,16 @@ export interface VaultV2RedeemAction extends BaseAction<"vaultV2Redeem", {
32
33
  recipient: Address;
33
34
  }> {
34
35
  }
36
+ /** Metadata for a Vault V2 in-kind redemption into Morpho Blue supply positions. */
37
+ export interface VaultV2InKindRedeemAction extends BaseAction<"vaultV2InKindRedeem", {
38
+ readonly vault: Address;
39
+ readonly adapter: Address;
40
+ readonly amount: bigint;
41
+ readonly marketParamsList: readonly InputMarketParams[];
42
+ readonly onBehalf: Address;
43
+ readonly deadline: bigint;
44
+ }> {
45
+ }
35
46
  export interface VaultV2ForceWithdrawAction extends BaseAction<"vaultV2ForceWithdraw", {
36
47
  vault: Address;
37
48
  deallocations: readonly Deallocation[];
@@ -72,6 +83,15 @@ export interface VaultV1RedeemAction extends BaseAction<"vaultV1Redeem", {
72
83
  recipient: Address;
73
84
  }> {
74
85
  }
86
+ /** Metadata for a Vault V1 in-kind redemption into Morpho Blue supply positions. */
87
+ export interface VaultV1InKindRedeemAction extends BaseAction<"vaultV1InKindRedeem", {
88
+ readonly vault: Address;
89
+ readonly amount: bigint;
90
+ readonly marketParamsList: readonly InputMarketParams[];
91
+ readonly onBehalf: Address;
92
+ readonly deadline: bigint;
93
+ }> {
94
+ }
75
95
  export interface VaultV1MigrateToV2Action extends BaseAction<"vaultV1MigrateToV2", {
76
96
  sourceVault: Address;
77
97
  targetVault: Address;
@@ -326,7 +346,7 @@ export interface MidnightCancelOfferAction extends BaseAction<"midnightCancelOff
326
346
  readonly onBehalf: Address;
327
347
  }> {
328
348
  }
329
- export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueWithdrawAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | SetterRatifierRatifyRootAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MempoolSubmitOffersAction | MidnightRedeemAction | MidnightRepayWithdrawCollateralAction | MidnightCancelOfferAction;
349
+ export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2InKindRedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1InKindRedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueWithdrawAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | SetterRatifierRatifyRootAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MempoolSubmitOffersAction | MidnightRedeemAction | MidnightRepayWithdrawCollateralAction | MidnightCancelOfferAction;
330
350
  export interface Transaction<TAction extends BaseAction = TransactionAction> {
331
351
  readonly to: Address;
332
352
  readonly value: bigint;