@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,5 +1,6 @@
1
1
  export * from "./deposit.js";
2
2
  export * from "./forceRedeem.js";
3
3
  export * from "./forceWithdraw.js";
4
+ export * from "./inKindRedeem.js";
4
5
  export * from "./redeem.js";
5
6
  export * from "./withdraw.js";
@@ -17,5 +17,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
17
17
  __exportStar(require("./deposit.js"), exports);
18
18
  __exportStar(require("./forceRedeem.js"), exports);
19
19
  __exportStar(require("./forceWithdraw.js"), exports);
20
+ __exportStar(require("./inKindRedeem.js"), exports);
20
21
  __exportStar(require("./redeem.js"), exports);
21
22
  __exportStar(require("./withdraw.js"), exports);
@@ -21,8 +21,7 @@ export interface BundlerCall {
21
21
  *
22
22
  * @remarks
23
23
  * The namespace covers only the Bundler3 actions required by `morpho-sdk`.
24
- * It does not expose operation population or simulation helpers from
25
- * `@morpho-org/bundler-sdk-viem`.
24
+ * It does not expose operation population or broad simulation helpers.
26
25
  */
27
26
  export declare namespace BundlerAction {
28
27
  /**
@@ -44,8 +44,7 @@ const consumeCallValue = (state, call) => {
44
44
  *
45
45
  * @remarks
46
46
  * The namespace covers only the Bundler3 actions required by `morpho-sdk`.
47
- * It does not expose operation population or simulation helpers from
48
- * `@morpho-org/bundler-sdk-viem`.
47
+ * It does not expose operation population or broad simulation helpers.
49
48
  */
50
49
  var BundlerAction;
51
50
  (function (BundlerAction) {
@@ -373,7 +373,7 @@ export declare class MorphoBlue implements BlueActions {
373
373
  } & DepositAmountArgs): {
374
374
  getRequirements: (params?: {
375
375
  useSimplePermit?: boolean;
376
- }) => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
376
+ }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
377
377
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueSupplyAction>>;
378
378
  };
379
379
  withdraw(params: {
@@ -383,7 +383,7 @@ export declare class MorphoBlue implements BlueActions {
383
383
  slippageTolerance?: bigint;
384
384
  reallocations?: readonly VaultReallocation[];
385
385
  } & AssetsOrSharesArgs): {
386
- getRequirements: () => Promise<(Requirement<import("../../types/action.js").AuthorizationRequirementSignature, undefined> | Readonly<Transaction<BlueAuthorizationAction>>)[]>;
386
+ getRequirements: () => Promise<(Readonly<Transaction<BlueAuthorizationAction>> | Requirement<import("../../index.js").AuthorizationRequirementSignature, undefined>)[]>;
387
387
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueWithdrawAction>>;
388
388
  };
389
389
  supplyCollateral({ amount, userAddress, nativeAmount, }: {
@@ -391,7 +391,7 @@ export declare class MorphoBlue implements BlueActions {
391
391
  } & DepositAmountArgs): {
392
392
  getRequirements: (params?: {
393
393
  useSimplePermit?: boolean;
394
- }) => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
394
+ }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
395
395
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueSupplyCollateralAction>>;
396
396
  };
397
397
  borrow({ amount, userAddress, positionData, slippageTolerance, reallocations, }: {
@@ -401,7 +401,7 @@ export declare class MorphoBlue implements BlueActions {
401
401
  slippageTolerance?: bigint;
402
402
  reallocations?: readonly VaultReallocation[];
403
403
  }): {
404
- getRequirements: () => Promise<(Requirement<import("../../types/action.js").AuthorizationRequirementSignature, undefined> | Readonly<Transaction<BlueAuthorizationAction>>)[]>;
404
+ getRequirements: () => Promise<(Readonly<Transaction<BlueAuthorizationAction>> | Requirement<import("../../index.js").AuthorizationRequirementSignature, undefined>)[]>;
405
405
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueBorrowAction>>;
406
406
  };
407
407
  repay(params: {
@@ -411,7 +411,7 @@ export declare class MorphoBlue implements BlueActions {
411
411
  } & RepayAmountArgs): {
412
412
  getRequirements: (reqParams?: {
413
413
  useSimplePermit?: boolean;
414
- }) => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
414
+ }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
415
415
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueRepayAction>>;
416
416
  };
417
417
  withdrawCollateral({ userAddress, amount, positionData, }: {
@@ -429,7 +429,7 @@ export declare class MorphoBlue implements BlueActions {
429
429
  } & RepayAmountArgs): {
430
430
  getRequirements: (reqParams?: {
431
431
  useSimplePermit?: boolean;
432
- }) => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Requirement<import("../../types/action.js").AuthorizationRequirementSignature, undefined> | Readonly<Transaction<ERC20ApprovalAction>> | Readonly<Transaction<BlueAuthorizationAction>>)[]>;
432
+ }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<BlueAuthorizationAction>> | Readonly<Transaction<ERC20ApprovalAction>> | Requirement<import("../../index.js").AuthorizationRequirementSignature, undefined>)[]>;
433
433
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueRepayWithdrawCollateralAction>>;
434
434
  };
435
435
  supplyCollateralBorrow({ amount, userAddress, positionData, borrowAmount, nativeAmount, slippageTolerance, reallocations, }: {
@@ -441,7 +441,7 @@ export declare class MorphoBlue implements BlueActions {
441
441
  } & DepositAmountArgs): {
442
442
  getRequirements: (params?: {
443
443
  useSimplePermit?: boolean;
444
- }) => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Requirement<import("../../types/action.js").AuthorizationRequirementSignature, undefined> | Readonly<Transaction<ERC20ApprovalAction>> | Readonly<Transaction<BlueAuthorizationAction>>)[]>;
444
+ }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<BlueAuthorizationAction>> | Readonly<Transaction<ERC20ApprovalAction>> | Requirement<import("../../index.js").AuthorizationRequirementSignature, undefined>)[]>;
445
445
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueSupplyCollateralBorrowAction>>;
446
446
  };
447
447
  refinance({ userAddress, positionData, target, collateralAmount, borrowAssets, borrowShares, slippageTolerance, targetReallocations, }: {
@@ -457,7 +457,7 @@ export declare class MorphoBlue implements BlueActions {
457
457
  slippageTolerance?: bigint;
458
458
  targetReallocations?: readonly VaultReallocation[];
459
459
  }): {
460
- getRequirements: () => Promise<(Requirement<import("../../types/action.js").AuthorizationRequirementSignature, undefined> | Readonly<Transaction<BlueAuthorizationAction>>)[]>;
460
+ getRequirements: () => Promise<(Readonly<Transaction<BlueAuthorizationAction>> | Requirement<import("../../index.js").AuthorizationRequirementSignature, undefined>)[]>;
461
461
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<BlueRefinanceAction>>;
462
462
  };
463
463
  /**
@@ -109,8 +109,7 @@ export declare class ReallocationData implements InputReallocationData {
109
109
  *
110
110
  * Pass `options.timestamp` to evaluate market interest and pending public
111
111
  * allocator caps at the same block as the fetched reallocation data.
112
- * This method does not add the legacy one-hour delay margin that
113
- * `SimulationState.getMarketPublicReallocations` applied before measuring
112
+ * This method does not add an implicit delay margin before measuring
114
113
  * target-market vault headroom. If a transaction may land later than the
115
114
  * fetched block, pass a future `timestamp` or reserve your own headroom so
116
115
  * interest accrued before inclusion does not make `reallocateTo` exceed the
@@ -202,8 +202,7 @@ class ReallocationData {
202
202
  *
203
203
  * Pass `options.timestamp` to evaluate market interest and pending public
204
204
  * allocator caps at the same block as the fetched reallocation data.
205
- * This method does not add the legacy one-hour delay margin that
206
- * `SimulationState.getMarketPublicReallocations` applied before measuring
205
+ * This method does not add an implicit delay margin before measuring
207
206
  * target-market vault headroom. If a transaction may land later than the
208
207
  * fetched block, pass a future `timestamp` or reserve your own headroom so
209
208
  * interest accrued before inclusion does not make `reallocateTo` exceed the
@@ -1,8 +1,8 @@
1
- import { type AccrualVault, type AccrualVaultV2 } from "@morpho-org/blue-sdk";
1
+ import { type AccrualVault, type AccrualVaultV2, type MarketParams } from "@morpho-org/blue-sdk";
2
2
  import { fetchAccrualVault } 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 DepositAmountArgs, type ERC20ApprovalAction, type MorphoClientType, type PermitRequirementSignature, type Requirement, type RequirementSignature, type Transaction, type VaultV1DepositAction, type VaultV1MigrateToV2Action, type VaultV1RedeemAction, type VaultV1WithdrawAction } from "../../types/index.js";
5
+ import { type ActionOutput, type DepositAmountArgs, type ERC20ApprovalAction, type MorphoClientType, type PermitRequirementSignature, type Requirement, type RequirementSignature, type Transaction, type VaultV1DepositAction, type VaultV1InKindRedeemAction, type VaultV1MigrateToV2Action, type VaultV1RedeemAction, type VaultV1WithdrawAction } from "../../types/index.js";
6
6
  export interface VaultV1Actions {
7
7
  /**
8
8
  * Fetches the latest vault data with accrued interest.
@@ -63,6 +63,76 @@ export interface VaultV1Actions {
63
63
  }) => {
64
64
  buildTx: () => Readonly<Transaction<VaultV1RedeemAction>>;
65
65
  };
66
+ /**
67
+ * Prepares an illiquid Vault V1 exit into the vault's Morpho Blue supply positions.
68
+ *
69
+ * The caller controls market order and must call `getRequirements()` before `buildTx()` so the
70
+ * RPC-backed Blue-balance and Morpho-deployment checks run. The SDK validates market coverage but
71
+ * intentionally does not validate the user's share balance; size `amount` in asset terms against
72
+ * `previewRedeem(sharesHeld)`. The share allowance first accrues pending performance-fee shares,
73
+ * then uses the current rounded-up share preview; future interest can only reduce the required
74
+ * burn.
75
+ *
76
+ * Snapshot state can drift before inclusion, so a later reallocation may still make the on-chain
77
+ * loop under-cover even after pre-flight succeeds.
78
+ *
79
+ * @param params - In-kind redemption parameters.
80
+ * @param params.amount - Asset-denominated amount to exit.
81
+ * @param params.marketParamsList - Ordered vault markets consumed greedily by the contract;
82
+ * repeated entries cannot draw from the same vault position twice.
83
+ * @param params.vaultData - Pre-fetched Vault V1 accrual snapshot.
84
+ * @param params.userAddress - Account that signs and submits the exit.
85
+ * @param params.deadline - Optional shared permit/bundle deadline; defaults to two hours from now.
86
+ * @returns Lazy prerequisite resolution and a synchronous transaction builder.
87
+ * @throws {ChainIdMismatchError} when the client and entity target different chains.
88
+ * @throws {VaultAddressMismatchError} when `vaultData` belongs to another vault.
89
+ * @throws {NonPositiveInputError} when `amount` is not positive.
90
+ * @throws {EmptyMarketParamsListError} when the market list is empty.
91
+ * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
92
+ * requirement resolution.
93
+ * @throws {InKindRedeemCoverageError} when the ordered list cannot cover `amount` without
94
+ * assigning more than the vault owns in a repeated market.
95
+ * @throws {UnsupportedChainIdError} when no address registry exists for the target chain.
96
+ * @throws {UnknownAddressError} when VaultExitBundlesV1 is not registered on the target chain.
97
+ * @throws {viem.BaseError} from `getRequirements()` when an RPC or multicall contract read fails.
98
+ * @throws {VaultMorphoMismatchError} from `getRequirements()` when the vault uses another Morpho deployment.
99
+ * @throws {VaultIsBlueFeeRecipientError} from `getRequirements()` when Morpho Blue accrues protocol fees to the vault.
100
+ * @throws {InsufficientBlueBalanceForInKindRedeemError} from `getRequirements()` when Blue cannot fund the flash loan.
101
+ * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
102
+ * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
103
+ * @throws {VaultExitBundlesV1PermitMismatchError} from `buildTx()` when the requirement has the wrong permit kind, asset, or signature encoding.
104
+ * @example
105
+ * ```ts
106
+ * import { isRequirementSignature } from "@morpho-org/morpho-sdk";
107
+ *
108
+ * const vault = client.morpho.vaultV1(vaultAddress, 1);
109
+ * const vaultData = await vault.getData();
110
+ * const exit = vault.inKindRedeem({
111
+ * amount: 1_000_000n,
112
+ * marketParamsList,
113
+ * vaultData,
114
+ * userAddress,
115
+ * });
116
+ * const signatures = [];
117
+ * for (const requirement of await exit.getRequirements()) {
118
+ * if (isRequirementSignature(requirement)) {
119
+ * signatures.push(await requirement.sign(walletClient, userAddress));
120
+ * } else {
121
+ * const hash = await walletClient.sendTransaction(requirement);
122
+ * await client.waitForTransactionReceipt({ hash });
123
+ * }
124
+ * }
125
+ * const tx = exit.buildTx(signatures);
126
+ * // tx satisfies Readonly<Transaction<VaultV1InKindRedeemAction>>
127
+ * ```
128
+ */
129
+ readonly inKindRedeem: (params: {
130
+ readonly amount: bigint;
131
+ readonly marketParamsList: readonly MarketParams[];
132
+ readonly vaultData: AccrualVault;
133
+ readonly userAddress: Address;
134
+ readonly deadline?: bigint;
135
+ }) => ActionOutput<VaultV1InKindRedeemAction, readonly RequirementSignature[], undefined>;
66
136
  /**
67
137
  * Prepares a full migration from VaultV1 to VaultV2.
68
138
  *
@@ -101,7 +171,7 @@ export declare class MorphoVaultV1 implements VaultV1Actions {
101
171
  } & DepositAmountArgs): {
102
172
  getRequirements: (params?: {
103
173
  useSimplePermit?: boolean;
104
- }) => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
174
+ }) => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
105
175
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<VaultV1DepositAction>>;
106
176
  };
107
177
  withdraw({ amount, userAddress }: {
@@ -116,6 +186,14 @@ export declare class MorphoVaultV1 implements VaultV1Actions {
116
186
  }): {
117
187
  buildTx: () => Readonly<Transaction<VaultV1RedeemAction>>;
118
188
  };
189
+ /** {@inheritDoc VaultV1Actions.inKindRedeem} */
190
+ inKindRedeem({ amount, marketParamsList, vaultData, userAddress, deadline: deadlineOverride, }: {
191
+ readonly amount: bigint;
192
+ readonly marketParamsList: readonly MarketParams[];
193
+ readonly vaultData: AccrualVault;
194
+ readonly userAddress: Address;
195
+ readonly deadline?: bigint;
196
+ }): ActionOutput<VaultV1InKindRedeemAction, readonly RequirementSignature[], undefined>;
119
197
  migrateToV2({ userAddress, sourceVault, targetVault, shares, slippageTolerance, }: {
120
198
  userAddress: Address;
121
199
  sourceVault: AccrualVault;
@@ -123,7 +201,7 @@ export declare class MorphoVaultV1 implements VaultV1Actions {
123
201
  shares: bigint;
124
202
  slippageTolerance?: bigint;
125
203
  }): {
126
- getRequirements: () => Promise<(import("../../types/action.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
204
+ getRequirements: () => Promise<(import("../../index.js").Bundler3TokenSignatureRequirement | Readonly<Transaction<ERC20ApprovalAction>>)[]>;
127
205
  buildTx: (signatures?: readonly RequirementSignature[]) => Readonly<Transaction<VaultV1MigrateToV2Action>>;
128
206
  };
129
207
  }
@@ -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 constant_js_1 = require("../../helpers/constant.js");
10
11
  const index_js_2 = require("../../helpers/index.js");
@@ -131,6 +132,169 @@ class MorphoVaultV1 {
131
132
  }),
132
133
  };
133
134
  }
135
+ /** {@inheritDoc VaultV1Actions.inKindRedeem} */
136
+ inKindRedeem({ amount, marketParamsList, vaultData, userAddress, deadline: deadlineOverride, }) {
137
+ if (this.client.viemClient.chain?.id !== this.chainId) {
138
+ throw new index_js_3.ChainIdMismatchError(this.client.viemClient.chain?.id, this.chainId);
139
+ }
140
+ if (!(0, viem_1.isAddressEqual)(vaultData.address, this.vault)) {
141
+ throw new index_js_3.VaultAddressMismatchError(this.vault, vaultData.address);
142
+ }
143
+ if (amount <= 0n)
144
+ throw new index_js_3.NonPositiveInputError("amount", amount);
145
+ if (marketParamsList.length === 0)
146
+ throw new index_js_3.EmptyMarketParamsListError();
147
+ const marketParamsListSnapshot = marketParamsList.map(({ loanToken, collateralToken, oracle, irm, lltv }) => ({
148
+ loanToken,
149
+ collateralToken,
150
+ oracle,
151
+ irm,
152
+ lltv,
153
+ }));
154
+ const now = morpho_ts_1.Time.timestamp();
155
+ const deadline = deadlineOverride ?? now + morpho_ts_1.Time.s.from.h(2n);
156
+ if (deadline <= now)
157
+ throw new index_js_3.ExpiredDeadlineError(deadline, now);
158
+ const vaultExitBundlesV1 = (0, morpho_ts_1.getChainAddress)(this.chainId, "bundles.vaultExitBundlesV1");
159
+ const addresses = (0, blue_sdk_1.getChainAddresses)(this.chainId);
160
+ const blue = addresses.blue ?? addresses.morpho;
161
+ let covered = 0n;
162
+ const assignedByMarket = new Map();
163
+ for (const marketParams of marketParamsListSnapshot) {
164
+ if (covered === amount)
165
+ break;
166
+ const marketId = blue_sdk_1.MarketUtils.getMarketId(marketParams);
167
+ const allocation = vaultData.allocations.get(marketId);
168
+ if (allocation?.config.enabled !== true)
169
+ continue;
170
+ const market = allocation.position.market.accrueInterest(now);
171
+ const available = market.toSupplyAssets(allocation.position.supplyShares);
172
+ const assigned = assignedByMarket.get(marketId) ?? 0n;
173
+ const chunk = blue_sdk_1.MathLib.min(available, amount - covered);
174
+ if (assigned + chunk > available) {
175
+ throw new index_js_3.InKindRedeemCoverageError({
176
+ required: amount,
177
+ covered,
178
+ maxExitAssets: covered,
179
+ });
180
+ }
181
+ assignedByMarket.set(marketId, assigned + chunk);
182
+ covered += chunk;
183
+ }
184
+ if (covered < amount) {
185
+ throw new index_js_3.InKindRedeemCoverageError({
186
+ required: amount,
187
+ covered,
188
+ maxExitAssets: covered,
189
+ });
190
+ }
191
+ // Account for pending performance-fee shares before previewing the burn. Once accrued, future
192
+ // V1 interest cannot lower the share price, so this upper-bounds execution.
193
+ const requiredShareAllowance = vaultData
194
+ .accrueInterest(now)
195
+ .toShares(amount);
196
+ return {
197
+ getRequirements: async () => {
198
+ const requirementsTimestamp = morpho_ts_1.Time.timestamp();
199
+ if (deadline <= requirementsTimestamp) {
200
+ throw new index_js_3.ExpiredDeadlineError(deadline, requirementsTimestamp);
201
+ }
202
+ const [allowance, nonce, blueBalance, morpho, blueFeeRecipient] = await (0, actions_1.multicall)(this.client.viemClient, {
203
+ allowFailure: false,
204
+ contracts: [
205
+ {
206
+ address: this.vault,
207
+ abi: viem_1.erc20Abi,
208
+ functionName: "allowance",
209
+ args: [userAddress, vaultExitBundlesV1],
210
+ },
211
+ {
212
+ address: this.vault,
213
+ abi: blue_sdk_viem_1.erc2612Abi,
214
+ functionName: "nonces",
215
+ args: [userAddress],
216
+ },
217
+ {
218
+ address: vaultData.asset,
219
+ abi: viem_1.erc20Abi,
220
+ functionName: "balanceOf",
221
+ args: [blue],
222
+ },
223
+ {
224
+ address: this.vault,
225
+ abi: blue_sdk_viem_1.metaMorphoAbi,
226
+ functionName: "MORPHO",
227
+ },
228
+ {
229
+ address: blue,
230
+ abi: blue_sdk_viem_1.blueAbi,
231
+ functionName: "feeRecipient",
232
+ },
233
+ ],
234
+ });
235
+ if (!(0, viem_1.isAddressEqual)(morpho, blue)) {
236
+ throw new index_js_3.VaultMorphoMismatchError({
237
+ vault: this.vault,
238
+ expected: blue,
239
+ actual: morpho,
240
+ });
241
+ }
242
+ // Reject this unsupported configuration before authorizing vault shares:
243
+ // VaultExitBundlesV1 omits newly accrued Morpho fee shares when estimating the
244
+ // vault position, so its callback can exhaust marketParamsList and panic on-chain.
245
+ if ((0, viem_1.isAddressEqual)(blueFeeRecipient, this.vault)) {
246
+ throw new index_js_3.VaultIsBlueFeeRecipientError(this.vault, blue);
247
+ }
248
+ if (blueBalance < amount) {
249
+ throw new index_js_3.InsufficientBlueBalanceForInKindRedeemError({
250
+ asset: vaultData.asset,
251
+ available: blueBalance,
252
+ required: amount,
253
+ });
254
+ }
255
+ if (allowance >= requiredShareAllowance)
256
+ return [];
257
+ if (this.client.options.supportSignature) {
258
+ return [
259
+ (0, index_js_1.encodeVaultSharesPermit)({
260
+ vault: vaultData,
261
+ version: "vaultV1",
262
+ spender: vaultExitBundlesV1,
263
+ owner: userAddress,
264
+ chainId: this.chainId,
265
+ nonce,
266
+ amount: requiredShareAllowance,
267
+ deadline,
268
+ }),
269
+ ];
270
+ }
271
+ return [
272
+ (0, index_js_1.encodeErc20Approval)({
273
+ token: this.vault,
274
+ spender: vaultExitBundlesV1,
275
+ amount: requiredShareAllowance,
276
+ chainId: this.chainId,
277
+ }),
278
+ ];
279
+ },
280
+ buildTx: (signatures) => {
281
+ const { permit } = (0, index_js_3.selectRequirementSignatures)(signatures, {
282
+ permit: true,
283
+ });
284
+ return (0, index_js_1.vaultV1InKindRedeem)({
285
+ vault: { chainId: this.chainId, address: this.vault },
286
+ args: {
287
+ amount,
288
+ marketParamsList: marketParamsListSnapshot,
289
+ userAddress,
290
+ deadline,
291
+ requirementSignature: permit,
292
+ },
293
+ metadata: this.client.options.metadata,
294
+ });
295
+ },
296
+ };
297
+ }
134
298
  migrateToV2({ userAddress, sourceVault, targetVault, shares, slippageTolerance = blue_sdk_1.DEFAULT_SLIPPAGE_TOLERANCE, }) {
135
299
  (0, index_js_2.validateChainId)(this.client.viemClient.chain?.id, this.chainId);
136
300
  if (!(0, viem_1.isAddressEqual)(sourceVault.address, this.vault)) {
@@ -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
  *
@@ -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: {