@morpho-org/morpho-sdk 5.4.0 → 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
@@ -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
+ let requiredShareAllowance = 0n;
212
+ const consumedMarketIds = new Set();
213
+ const { vault: allowanceVault } = vaultData.accrueInterest(deadline);
214
+ // Interest can lower the burn, while management fees can raise it; bound both endpoints.
215
+ const previewAllowance = (assets) => blue_sdk_1.MathLib.max(vaultData.toShares(assets, "Up"), allowanceVault.toShares(assets, "Up"));
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);
@@ -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,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.validateRequirementSpender = exports.validateOfferSides = exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateMidnightMarketChainId = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinWithdrawSharePrice = exports.computeMinBorrowSharePrice = exports.computeMaxSupplySharePrice = exports.computeMaxRepaySharePrice = exports.signAndVerifyTypedData = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_LLTV_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = exports.computeReallocations = void 0;
3
+ exports.validateRequirementSpender = exports.validateOfferSides = exports.validateWithdrawShares = exports.validateWithdrawAmount = exports.validateUserAddress = exports.validateSlippageTolerance = exports.validateRepayShares = exports.validateRepayAmount = exports.validateReallocations = exports.validatePositionHealthAfterWithdraw = exports.validatePositionHealth = exports.validateNativeAsset = exports.validateMidnightMarketChainId = exports.validateChainId = exports.validateAccrualPosition = exports.computeMinWithdrawSharePrice = exports.computeMinBorrowSharePrice = exports.computeMaxSupplySharePrice = exports.computeMaxRepaySharePrice = exports.signAndVerifyTypedData = exports.previewVaultV2InKindRedeem = exports.addTransactionMetadata = exports.MAX_TOKEN_APPROVALS = exports.MAX_SLIPPAGE_TOLERANCE = exports.MAX_ABSOLUTE_SHARE_PRICE = exports.DEFAULT_WITHDRAWAL_TARGET_UTILIZATION = exports.DEFAULT_SUPPLY_TARGET_UTILIZATION = exports.DEFAULT_LLTV_BUFFER = exports.APPROVE_ONLY_ONCE_TOKENS = exports.computeReallocations = void 0;
4
4
  var computeReallocations_js_1 = require("./computeReallocations.js");
5
5
  Object.defineProperty(exports, "computeReallocations", { enumerable: true, get: function () { return computeReallocations_js_1.computeReallocations; } });
6
6
  var constant_js_1 = require("./constant.js");
@@ -13,6 +13,8 @@ Object.defineProperty(exports, "MAX_SLIPPAGE_TOLERANCE", { enumerable: true, get
13
13
  Object.defineProperty(exports, "MAX_TOKEN_APPROVALS", { enumerable: true, get: function () { return constant_js_1.MAX_TOKEN_APPROVALS; } });
14
14
  var metadata_js_1 = require("./metadata.js");
15
15
  Object.defineProperty(exports, "addTransactionMetadata", { enumerable: true, get: function () { return metadata_js_1.addTransactionMetadata; } });
16
+ var previewVaultV2InKindRedeem_js_1 = require("./previewVaultV2InKindRedeem.js");
17
+ Object.defineProperty(exports, "previewVaultV2InKindRedeem", { enumerable: true, get: function () { return previewVaultV2InKindRedeem_js_1.previewVaultV2InKindRedeem; } });
16
18
  var signAndVerifyTypedData_js_1 = require("./signAndVerifyTypedData.js");
17
19
  Object.defineProperty(exports, "signAndVerifyTypedData", { enumerable: true, get: function () { return signAndVerifyTypedData_js_1.signAndVerifyTypedData; } });
18
20
  var slippage_js_1 = require("./slippage.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,73 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.previewVaultV2InKindRedeem = previewVaultV2InKindRedeem;
4
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
5
+ /**
6
+ * Previews the single-market in-kind redemption choices needed by a Vault V2 frontend.
7
+ *
8
+ * Vaults with exactly one MorphoMarketV1AdapterV2 can produce choices. Their non-empty markets are
9
+ * returned in descending allocation order with the exact penalty-inclusive input ceiling, idle
10
+ * assets withdrawn directly, and resulting Blue position for `requestedExitAssets`.
11
+ *
12
+ * @param vaultData - Pre-fetched Vault V2 accrual snapshot.
13
+ * @param params - Preview parameters.
14
+ * @param params.requestedExitAssets - Positive penalty-inclusive amount the user wants to exit.
15
+ * @param params.timestamp - Timestamp used to accrue Morpho Blue markets before calculating capacity.
16
+ * @returns Frontend-ready market choices, or an empty list when no choices are available.
17
+ * @example
18
+ * ```ts
19
+ * import { previewVaultV2InKindRedeem } from "@morpho-org/morpho-sdk";
20
+ *
21
+ * const [market] = previewVaultV2InKindRedeem(vaultData, {
22
+ * requestedExitAssets,
23
+ * timestamp: block.timestamp,
24
+ * });
25
+ * // market?.exitAssets is ready to pass to vault.inKindRedeem(...)
26
+ * ```
27
+ */
28
+ function previewVaultV2InKindRedeem(vaultData, params) {
29
+ const { requestedExitAssets, timestamp } = params;
30
+ if (requestedExitAssets <= 0n) {
31
+ return [];
32
+ }
33
+ if (vaultData.accrualAdapters.length !== 1) {
34
+ return [];
35
+ }
36
+ const adapter = vaultData.accrualAdapters[0];
37
+ if (!(adapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)) {
38
+ return [];
39
+ }
40
+ const penalty = vaultData.forceDeallocatePenalties[adapter.address] ?? 0n;
41
+ const availableIdleAssets = vaultData.assetBalance;
42
+ const allocations = adapter.markets
43
+ .map((market) => ({
44
+ market,
45
+ allocationAssets: market
46
+ .accrueInterest(blue_sdk_1.MathLib.max(timestamp, market.lastUpdate))
47
+ .toSupplyAssets(adapter.supplyShares[market.id] ?? 0n),
48
+ }))
49
+ .filter(({ allocationAssets }) => allocationAssets > 0n)
50
+ .toSorted(({ allocationAssets: a }, { allocationAssets: b }) => a === b ? 0 : a > b ? -1 : 1);
51
+ return allocations.flatMap(({ market, allocationAssets }) => {
52
+ const maxExitAssets = availableIdleAssets +
53
+ blue_sdk_1.MathLib.wMulUp(allocationAssets + 1n, blue_sdk_1.MathLib.WAD + penalty) -
54
+ 1n;
55
+ const exitAssets = blue_sdk_1.MathLib.min(requestedExitAssets, maxExitAssets);
56
+ const idleAssets = blue_sdk_1.MathLib.min(exitAssets, availableIdleAssets);
57
+ const inKindExitAssets = exitAssets - idleAssets;
58
+ const netAssets = blue_sdk_1.MathLib.wDivDown(inKindExitAssets, blue_sdk_1.MathLib.WAD + penalty);
59
+ if (idleAssets === 0n && netAssets === 0n)
60
+ return [];
61
+ return [
62
+ {
63
+ marketParams: market.params,
64
+ maxExitAssets,
65
+ exitAssets,
66
+ remainingExitAssets: requestedExitAssets - exitAssets,
67
+ idleAssets,
68
+ netAssets,
69
+ feeAssets: blue_sdk_1.MathLib.wMulUp(netAssets, penalty),
70
+ },
71
+ ];
72
+ });
73
+ }
@@ -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
  *
@@ -26,12 +26,13 @@ const index_js_1 = require("../types/index.js");
26
26
  * ```
27
27
  */
28
28
  const validateRequirementSpender = (params) => {
29
- const { permit2, midnight, midnightBundles, bundler3: { generalAdapter1 }, } = (0, blue_sdk_1.getChainAddresses)(params.chainId);
29
+ const { permit2, midnight, midnightBundles, bundler3: { generalAdapter1 }, bundles, } = (0, blue_sdk_1.getChainAddresses)(params.chainId);
30
30
  const addresses = {
31
31
  generalAdapter1,
32
32
  permit2,
33
33
  midnight,
34
34
  midnightBundles,
35
+ vaultExitBundlesV1: bundles?.vaultExitBundlesV1,
35
36
  };
36
37
  const supportedSpenders = params.allowed.map((key) => addresses[key]);
37
38
  if (!supportedSpenders.some((supported) => supported != null && (0, viem_1.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;
@@ -44,6 +44,145 @@ export declare class NonPositiveInputError extends Error {
44
44
  */
45
45
  constructor(field: string, value: bigint);
46
46
  }
47
+ /** Thrown when an in-kind redemption does not include any Morpho Blue market parameters. */
48
+ export declare class EmptyMarketParamsListError extends Error {
49
+ constructor();
50
+ }
51
+ /** Thrown when an in-kind redemption deadline has already passed. */
52
+ export declare class ExpiredDeadlineError extends Error {
53
+ readonly deadline: bigint;
54
+ readonly timestamp: bigint;
55
+ /**
56
+ * @param deadline - Expired deadline supplied by the caller.
57
+ * @param timestamp - Current timestamp used for validation.
58
+ */
59
+ constructor(deadline: bigint, timestamp: bigint);
60
+ }
61
+ /** Thrown when Vault V2 in-kind redemption is attempted with anything other than one adapter. */
62
+ export declare class InKindRedeemRequiresSingleAdapterError extends Error {
63
+ readonly vault: Address;
64
+ readonly adapters: number;
65
+ /**
66
+ * @param vault - Vault V2 address.
67
+ * @param adapters - Number of adapters in the supplied vault snapshot.
68
+ */
69
+ constructor(vault: Address, adapters: number);
70
+ }
71
+ /** Thrown when a requested in-kind redemption adapter is not part of the Vault V2 snapshot. */
72
+ export declare class AdapterNotPartOfVaultError extends Error {
73
+ readonly vault: Address;
74
+ readonly adapter: Address;
75
+ /**
76
+ * @param vault - Vault V2 address.
77
+ * @param adapter - Adapter rejected by the vault snapshot.
78
+ */
79
+ constructor(vault: Address, adapter: Address);
80
+ }
81
+ /** Thrown when the Vault V2 adapter cannot expose MorphoMarketV1AdapterV2 market shares. */
82
+ export declare class UnsupportedInKindAdapterError extends Error {
83
+ readonly adapter: Address;
84
+ /**
85
+ * @param adapter - Unsupported Vault V2 adapter address.
86
+ */
87
+ constructor(adapter: Address);
88
+ }
89
+ /** Thrown when a Vault V2 in-kind redemption rounds to no deallocated assets. */
90
+ export declare class InKindRedeemZeroDeallocationError extends Error {
91
+ /**
92
+ * @param params - Values that caused the exit to round to zero deallocated assets.
93
+ * @param params.vault - Vault V2 address with no idle assets available for the exit.
94
+ * @param params.amount - Positive penalty-inclusive amount requested by the caller.
95
+ * @param params.penalty - WAD-scaled force-deallocation penalty applied by the adapter.
96
+ */
97
+ readonly vault: Address;
98
+ readonly amount: bigint;
99
+ readonly penalty: bigint;
100
+ constructor(params: {
101
+ readonly vault: Address;
102
+ readonly amount: bigint;
103
+ readonly penalty: bigint;
104
+ });
105
+ }
106
+ /** Thrown when the ordered market list cannot cover the requested in-kind redemption. */
107
+ export declare class InKindRedeemCoverageError extends Error {
108
+ /**
109
+ * @param params - Coverage values used to explain the rejected exit.
110
+ * @param params.required - Assets that must be deallocated from listed markets.
111
+ * @param params.covered - Assets covered by the supplied market list.
112
+ * @param params.maxExitAssets - Largest penalty-inclusive exit supported by the list.
113
+ */
114
+ readonly required: bigint;
115
+ readonly covered: bigint;
116
+ readonly maxExitAssets: bigint;
117
+ constructor(params: {
118
+ readonly required: bigint;
119
+ readonly covered: bigint;
120
+ readonly maxExitAssets: bigint;
121
+ });
122
+ }
123
+ /** Thrown when Morpho Blue lacks the physical loan-token balance needed during an exit callback. */
124
+ export declare class InsufficientBlueBalanceForInKindRedeemError extends Error {
125
+ /**
126
+ * @param params - Morpho Blue balance values used to explain the rejected exit.
127
+ * @param params.asset - Loan token required by the exit.
128
+ * @param params.available - Current token balance held by Morpho Blue.
129
+ * @param params.required - Peak token balance required by the exit.
130
+ */
131
+ readonly asset: Address;
132
+ readonly available: bigint;
133
+ readonly required: bigint;
134
+ constructor(params: {
135
+ readonly asset: Address;
136
+ readonly available: bigint;
137
+ readonly required: bigint;
138
+ });
139
+ }
140
+ /** Thrown when a MetaMorpho vault is connected to a different Morpho deployment. */
141
+ export declare class VaultMorphoMismatchError extends Error {
142
+ /**
143
+ * @param params - Vault and Morpho addresses used to explain the mismatch.
144
+ * @param params.vault - MetaMorpho vault address.
145
+ * @param params.expected - Morpho Blue address expected for the target chain.
146
+ * @param params.actual - Morpho address returned by the vault.
147
+ */
148
+ readonly vault: Address;
149
+ readonly expected: Address;
150
+ readonly actual: Address;
151
+ constructor(params: {
152
+ readonly vault: Address;
153
+ readonly expected: Address;
154
+ readonly actual: Address;
155
+ });
156
+ }
157
+ /** Thrown when a Vault V1 is Morpho Blue's fee recipient and cannot safely redeem in kind. */
158
+ export declare class VaultIsBlueFeeRecipientError extends Error {
159
+ readonly vault: Address;
160
+ readonly blue: Address;
161
+ /**
162
+ * @param vault - Unsupported Vault V1 address.
163
+ * @param blue - Morpho Blue deployment whose fees accrue to the vault.
164
+ */
165
+ constructor(vault: Address, blue: Address);
166
+ }
167
+ /** Thrown when a vault-shares requirement cannot be safely encoded as an ERC-2612 permit. */
168
+ export declare class VaultExitBundlesV1PermitMismatchError extends Error {
169
+ /**
170
+ * @param params - Permit mismatch values used to explain the rejection.
171
+ * @param params.field - Permit field that does not match the exit.
172
+ * @param params.expected - Value required by the exit.
173
+ * @param params.actual - Value supplied by the signature.
174
+ * @param params.cause - Original parser failure when signature decoding is wrapped.
175
+ */
176
+ readonly field: "type" | "asset" | "signature";
177
+ readonly expected: string;
178
+ readonly actual: string;
179
+ constructor(params: {
180
+ readonly field: "type" | "asset" | "signature";
181
+ readonly expected: string;
182
+ readonly actual: string;
183
+ readonly cause?: unknown;
184
+ });
185
+ }
47
186
  /** @deprecated Use {@link NonPositiveInputError}. */
48
187
  export declare const NonPositiveAssetAmountError: typeof NonPositiveInputError;
49
188
  /** @deprecated Use {@link NonPositiveInputError}. */