@morpho-org/morpho-sdk 6.0.0-next.1 → 6.0.0-next.2

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 (174) hide show
  1. package/MIGRATION-v5-to-v6.md +127 -16
  2. package/README.md +17 -11
  3. package/lib/cjs/abis.d.ts +17 -2
  4. package/lib/cjs/abis.js +14 -1
  5. package/lib/cjs/actions/blue/common.js +5 -26
  6. package/lib/cjs/actions/blue/supply.js +2 -7
  7. package/lib/cjs/actions/bundles/common.d.ts +32 -2
  8. package/lib/cjs/actions/bundles/common.js +68 -30
  9. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -0
  10. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +6 -10
  11. package/lib/cjs/actions/requirements/blue/index.d.ts +0 -1
  12. package/lib/cjs/actions/requirements/blue/index.js +0 -1
  13. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +15 -8
  14. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +20 -20
  15. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  16. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +33 -27
  17. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +4 -2
  18. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2Approve.js +15 -10
  19. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +4 -2
  20. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +14 -9
  21. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +9 -6
  22. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +22 -17
  23. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +1 -0
  24. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +4 -1
  25. package/lib/cjs/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +5 -2
  26. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +6 -0
  27. package/lib/cjs/actions/signatures/getVaultExitBundlesV1PermitStruct.js +2 -0
  28. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +1 -0
  29. package/lib/cjs/actions/vaultV1/inKindRedeem.js +3 -2
  30. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +58 -39
  31. package/lib/cjs/actions/vaultV2/forceWithdraw.js +87 -60
  32. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +1 -0
  33. package/lib/cjs/actions/vaultV2/inKindRedeem.js +3 -2
  34. package/lib/cjs/augment/VaultMarketPublicAllocatorConfig.d.ts +4 -1
  35. package/lib/cjs/blue/abis.d.ts +5 -1
  36. package/lib/cjs/blue/abis.js +2 -0
  37. package/lib/cjs/blue/entities.d.ts +8 -2
  38. package/lib/cjs/blue/entities.js +1 -0
  39. package/lib/cjs/blue/errors.d.ts +1 -1
  40. package/lib/cjs/blue/errors.js +2 -1
  41. package/lib/cjs/blue/fetch.d.ts +3 -1
  42. package/lib/cjs/blue/fetch.js +1 -0
  43. package/lib/cjs/entities/blue/blue.d.ts +15 -6
  44. package/lib/cjs/entities/blue/blue.js +3 -0
  45. package/lib/cjs/entities/index.d.ts +8 -2
  46. package/lib/cjs/entities/index.js +1 -0
  47. package/lib/cjs/entities/midnight/midnight.js +20 -24
  48. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +7 -6
  49. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +19 -14
  50. package/lib/cjs/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.js +3 -3
  51. package/lib/cjs/entities/requirements/index.d.ts +1 -0
  52. package/lib/cjs/entities/requirements/index.js +1 -0
  53. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +10 -5
  54. package/lib/cjs/entities/vaultV1/vaultV1.js +13 -1
  55. package/lib/cjs/entities/vaultV1ReallocationData.d.ts +6 -0
  56. package/lib/cjs/entities/vaultV1ReallocationData.js +20 -5
  57. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +140 -34
  58. package/lib/cjs/entities/vaultV2/vaultV2.js +229 -16
  59. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +8 -1
  60. package/lib/cjs/entities/vaultV2BlueReallocationData.js +46 -13
  61. package/lib/cjs/errors.d.ts +1 -1
  62. package/lib/cjs/errors.js +3 -2
  63. package/lib/cjs/fetch.d.ts +3 -1
  64. package/lib/cjs/fetch.js +1 -0
  65. package/lib/cjs/helpers/computeVaultV1Reallocations.d.ts +2 -0
  66. package/lib/cjs/helpers/computeVaultV1Reallocations.js +2 -0
  67. package/lib/cjs/helpers/index.d.ts +3 -1
  68. package/lib/cjs/helpers/index.js +10 -1
  69. package/lib/cjs/helpers/metadata.d.ts +3 -5
  70. package/lib/cjs/helpers/metadata.js +4 -6
  71. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.d.ts +107 -0
  72. package/lib/cjs/helpers/previewVaultV2ForceWithdraw.js +164 -0
  73. package/lib/cjs/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  74. package/lib/cjs/helpers/previewVaultV2InKindRedeem.js +2 -0
  75. package/lib/cjs/helpers/slippage.d.ts +46 -0
  76. package/lib/cjs/helpers/slippage.js +65 -0
  77. package/lib/cjs/helpers/validate.d.ts +65 -8
  78. package/lib/cjs/helpers/validate.js +83 -9
  79. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.d.ts +274 -0
  80. package/lib/cjs/helpers/vaultV2ForceWithdrawPlan.js +369 -0
  81. package/lib/cjs/types/action.d.ts +95 -13
  82. package/lib/cjs/types/error.d.ts +290 -12
  83. package/lib/cjs/types/error.js +312 -24
  84. package/lib/cjs/types/sharedLiquidity.d.ts +2 -2
  85. package/lib/cjs/utils.d.ts +3 -1
  86. package/lib/cjs/utils.js +10 -1
  87. package/lib/esm/abis.d.ts +17 -2
  88. package/lib/esm/abis.js +17 -2
  89. package/lib/esm/actions/blue/common.js +7 -28
  90. package/lib/esm/actions/blue/supply.js +4 -9
  91. package/lib/esm/actions/bundles/common.d.ts +32 -2
  92. package/lib/esm/actions/bundles/common.js +68 -31
  93. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +3 -0
  94. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +8 -12
  95. package/lib/esm/actions/requirements/blue/index.d.ts +0 -1
  96. package/lib/esm/actions/requirements/blue/index.js +0 -1
  97. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +15 -8
  98. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +21 -21
  99. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +16 -7
  100. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +34 -28
  101. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.d.ts +4 -2
  102. package/lib/esm/actions/requirements/encode/encodeErc20Permit2Approve.js +15 -10
  103. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +4 -2
  104. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +14 -9
  105. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +9 -6
  106. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +22 -17
  107. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirements.js +1 -0
  108. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.d.ts +4 -1
  109. package/lib/esm/actions/requirements/generalAdapter/getGeneralAdapterRequirementsPermit.js +5 -2
  110. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.d.ts +6 -0
  111. package/lib/esm/actions/signatures/getVaultExitBundlesV1PermitStruct.js +2 -0
  112. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +1 -0
  113. package/lib/esm/actions/vaultV1/inKindRedeem.js +3 -2
  114. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +58 -39
  115. package/lib/esm/actions/vaultV2/forceWithdraw.js +89 -62
  116. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +1 -0
  117. package/lib/esm/actions/vaultV2/inKindRedeem.js +3 -2
  118. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.d.ts +4 -1
  119. package/lib/esm/augment/VaultMarketPublicAllocatorConfig.js +3 -1
  120. package/lib/esm/blue/abis.d.ts +5 -1
  121. package/lib/esm/blue/abis.js +5 -1
  122. package/lib/esm/blue/entities.d.ts +8 -2
  123. package/lib/esm/blue/entities.js +3 -1
  124. package/lib/esm/blue/errors.d.ts +1 -1
  125. package/lib/esm/blue/errors.js +1 -1
  126. package/lib/esm/blue/fetch.d.ts +3 -1
  127. package/lib/esm/blue/fetch.js +3 -1
  128. package/lib/esm/entities/blue/blue.d.ts +15 -6
  129. package/lib/esm/entities/blue/blue.js +3 -0
  130. package/lib/esm/entities/index.d.ts +8 -2
  131. package/lib/esm/entities/index.js +3 -1
  132. package/lib/esm/entities/midnight/midnight.js +20 -24
  133. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +7 -6
  134. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +20 -15
  135. package/lib/esm/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.js +3 -3
  136. package/lib/esm/entities/requirements/index.d.ts +1 -0
  137. package/lib/esm/entities/requirements/index.js +1 -0
  138. package/lib/esm/entities/vaultV1/vaultV1.d.ts +10 -5
  139. package/lib/esm/entities/vaultV1/vaultV1.js +14 -2
  140. package/lib/esm/entities/vaultV1ReallocationData.d.ts +6 -0
  141. package/lib/esm/entities/vaultV1ReallocationData.js +20 -5
  142. package/lib/esm/entities/vaultV2/vaultV2.d.ts +140 -34
  143. package/lib/esm/entities/vaultV2/vaultV2.js +234 -21
  144. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +8 -1
  145. package/lib/esm/entities/vaultV2BlueReallocationData.js +46 -13
  146. package/lib/esm/errors.d.ts +1 -1
  147. package/lib/esm/errors.js +1 -1
  148. package/lib/esm/fetch.d.ts +3 -1
  149. package/lib/esm/fetch.js +3 -1
  150. package/lib/esm/helpers/computeVaultV1Reallocations.d.ts +2 -0
  151. package/lib/esm/helpers/computeVaultV1Reallocations.js +2 -0
  152. package/lib/esm/helpers/index.d.ts +3 -1
  153. package/lib/esm/helpers/index.js +3 -1
  154. package/lib/esm/helpers/metadata.d.ts +3 -5
  155. package/lib/esm/helpers/metadata.js +4 -6
  156. package/lib/esm/helpers/previewVaultV2ForceWithdraw.d.ts +107 -0
  157. package/lib/esm/helpers/previewVaultV2ForceWithdraw.js +161 -0
  158. package/lib/esm/helpers/previewVaultV2InKindRedeem.d.ts +1 -0
  159. package/lib/esm/helpers/previewVaultV2InKindRedeem.js +2 -0
  160. package/lib/esm/helpers/slippage.d.ts +46 -0
  161. package/lib/esm/helpers/slippage.js +65 -1
  162. package/lib/esm/helpers/validate.d.ts +65 -8
  163. package/lib/esm/helpers/validate.js +82 -10
  164. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.d.ts +274 -0
  165. package/lib/esm/helpers/vaultV2ForceWithdrawPlan.js +362 -0
  166. package/lib/esm/types/action.d.ts +95 -13
  167. package/lib/esm/types/error.d.ts +290 -12
  168. package/lib/esm/types/error.js +301 -19
  169. package/lib/esm/types/sharedLiquidity.d.ts +2 -2
  170. package/lib/esm/utils.d.ts +3 -1
  171. package/lib/esm/utils.js +3 -1
  172. package/package.json +7 -7
  173. /package/lib/cjs/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.d.ts +0 -0
  174. /package/lib/esm/{actions/requirements/blue → entities/requirements}/getUnusedPermit2Nonce.d.ts +0 -0
@@ -0,0 +1,369 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveVaultV2ForceWithdrawEligibility = resolveVaultV2ForceWithdrawEligibility;
4
+ exports.computeVaultV2ForceWithdrawFeeSharesMinted = computeVaultV2ForceWithdrawFeeSharesMinted;
5
+ exports.computeVaultV2ForceWithdrawPlan = computeVaultV2ForceWithdrawPlan;
6
+ exports.computeVaultV2ForceWithdrawSharesBurnt = computeVaultV2ForceWithdrawSharesBurnt;
7
+ exports.computeVaultV2ForceWithdrawMinSharesBurnt = computeVaultV2ForceWithdrawMinSharesBurnt;
8
+ const blue_sdk_1 = require("@morpho-org/blue-sdk");
9
+ const viem_1 = require("viem");
10
+ const index_js_1 = require("../types/index.js");
11
+ /**
12
+ * Resolves whether a Vault V2 snapshot can be force-withdrawn through VaultExitBundlesV1.
13
+ *
14
+ * Mirrors the contract's four preconditions: `adaptersLength() == 1`, `isAdapter(adapter)`,
15
+ * `adapter.morpho() == BLUE` (implied by the adapter type, whose factory pins Blue), and a
16
+ * `liquidityAdapter` the contract can cast to `IMorphoMarketV1AdapterV2` and whose `liquidityData`
17
+ * decodes as `MarketParams`. Because the exit already requires a single adapter, the only
18
+ * resolvable liquidity configurations are unset or that same adapter.
19
+ *
20
+ * Pure: reads only the supplied snapshot and never throws.
21
+ *
22
+ * @param vaultData - Pre-fetched Vault V2 accrual snapshot.
23
+ * @param adapterOverride - Optional adapter the caller expects; defaults to the vault's sole adapter.
24
+ * @returns The `"eligible"` variant with the resolved adapter and liquidity market, or the tag
25
+ * describing which precondition failed.
26
+ * @example
27
+ * ```ts
28
+ * import { resolveVaultV2ForceWithdrawEligibility } from "@morpho-org/morpho-sdk";
29
+ *
30
+ * const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData);
31
+ * if (eligibility.type === "eligible") {
32
+ * console.log(eligibility.adapter.address, eligibility.liquidityMarketId);
33
+ * }
34
+ * ```
35
+ */
36
+ function resolveVaultV2ForceWithdrawEligibility(vaultData, adapterOverride) {
37
+ const [soleAdapter] = vaultData.accrualAdapters;
38
+ if (vaultData.accrualAdapters.length !== 1 || soleAdapter == null) {
39
+ return { type: "adapterCount", adapters: vaultData.accrualAdapters.length };
40
+ }
41
+ const adapter = adapterOverride ?? soleAdapter.address;
42
+ if (!(0, viem_1.isAddressEqual)(adapter, soleAdapter.address)) {
43
+ return { type: "adapterMismatch", adapter };
44
+ }
45
+ if (!(soleAdapter instanceof blue_sdk_1.AccrualVaultV2MorphoMarketV1AdapterV2)) {
46
+ return { type: "unsupportedAdapter", adapter };
47
+ }
48
+ const { liquidityAdapter } = vaultData;
49
+ if ((0, viem_1.isAddressEqual)(liquidityAdapter, viem_1.zeroAddress)) {
50
+ return {
51
+ type: "eligible",
52
+ adapter: soleAdapter,
53
+ liquidityMarketId: undefined,
54
+ };
55
+ }
56
+ if (!(0, viem_1.isAddressEqual)(liquidityAdapter, soleAdapter.address)) {
57
+ return { type: "unsupportedLiquidityAdapter", liquidityAdapter, adapter };
58
+ }
59
+ let liquidityMarketId;
60
+ try {
61
+ liquidityMarketId = blue_sdk_1.MarketParams.fromHex(vaultData.liquidityData).id;
62
+ }
63
+ catch (cause) {
64
+ // Undecodable `liquidityData` reverts the contract's `abi.decode`. Reported separately from a
65
+ // foreign adapter: the adapter here is the right one, only its stored market params are unusable.
66
+ return {
67
+ type: "undecodableLiquidityData",
68
+ liquidityAdapter,
69
+ liquidityData: vaultData.liquidityData,
70
+ cause,
71
+ };
72
+ }
73
+ return { type: "eligible", adapter: soleAdapter, liquidityMarketId };
74
+ }
75
+ /**
76
+ * Computes the Vault V2 shares that accruing a vault snapshot mints to its owner as management
77
+ * and/or performance fees.
78
+ *
79
+ * Fee shares are minted to the matching recipient during the first withdrawal after accrual.
80
+ * When the owner is both recipients, both fee-share amounts are included. Timestamps before the
81
+ * snapshot's last update are clamped because Vault V2 cannot accrue backwards.
82
+ *
83
+ * @param params - Vault fee-share accrual inputs.
84
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
85
+ * @param params.owner - Account whose fee-recipient share mints are measured.
86
+ * @param params.timestamp - Target accrual timestamp, clamped to `vaultData.lastUpdate`.
87
+ * @returns Shares minted to `owner` by the management and/or performance fees, or `0n` when the
88
+ * owner is not a fee recipient.
89
+ * @example
90
+ * ```ts
91
+ * import { computeVaultV2ForceWithdrawFeeSharesMinted } from "@morpho-org/morpho-sdk";
92
+ *
93
+ * const feeShares = computeVaultV2ForceWithdrawFeeSharesMinted({
94
+ * vaultData,
95
+ * owner,
96
+ * timestamp,
97
+ * });
98
+ * ```
99
+ */
100
+ function computeVaultV2ForceWithdrawFeeSharesMinted(params) {
101
+ const { vault: accruedVault, managementFeeShares, performanceFeeShares, } = params.vaultData.accrueInterest(blue_sdk_1.MathLib.max(params.timestamp, params.vaultData.lastUpdate));
102
+ return (((0, viem_1.isAddressEqual)(accruedVault.managementFeeRecipient, params.owner)
103
+ ? managementFeeShares
104
+ : 0n) +
105
+ ((0, viem_1.isAddressEqual)(accruedVault.performanceFeeRecipient, params.owner)
106
+ ? performanceFeeShares
107
+ : 0n));
108
+ }
109
+ /**
110
+ * Computes every Vault V2 force-withdraw amount from a vault snapshot, without any RPC.
111
+ *
112
+ * Reproduces `vaultExitBundlesV1ForceWithdrawVaultV2` arithmetic:
113
+ *
114
+ * ```solidity
115
+ * withdrawableAssets = idle + min(liquidityAdapterAssets, liquidityMarketLiquidity);
116
+ * assetsToWithdraw = min(exitAssets, withdrawableAssets);
117
+ * assetsToDeallocate = mulDivDown(exitAssets - assetsToWithdraw, WAD, WAD + penalty);
118
+ * ```
119
+ *
120
+ * `coveredAssets` sums `min(adapterPosition, marketLiquidity)` over the adapter's markets, minus
121
+ * whatever the penalty-free leg already drained from the liquidity market. The sum is deliberately
122
+ * order-independent: the contract's loop visits every market taking `min(available, remaining)`, so
123
+ * total capacity does not depend on the adapter's storage order — which matters because a drained
124
+ * market is removed from that list mid-loop.
125
+ *
126
+ * That order-independence assumes `VaultExitBundlesV1` copies `adapter.marketIds` into memory
127
+ * *before* the loop. If it instead re-read adapter storage each iteration,
128
+ * `MorphoMarketV1AdapterV2.deallocate`'s swap-and-pop removal of a drained market would make the
129
+ * loop skip markets, and this sum would overstate real capacity — letting an exit through that
130
+ * panics on-chain. The claim is load-bearing for the coverage guard and is verified only by the
131
+ * fork suite, not by any in-repo contract source.
132
+ *
133
+ * @param params - Plan inputs.
134
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
135
+ * @param params.adapter - The vault's sole MorphoMarketV1AdapterV2, from
136
+ * {@link resolveVaultV2ForceWithdrawEligibility}.
137
+ * @param params.liquidityMarketId - Market the vault routes penalty-free liquidity through, or
138
+ * `undefined` when the vault has no liquidity adapter.
139
+ * @param params.exitAssets - Penalty-inclusive amount to exit.
140
+ * @param params.timestamp - Timestamp used to accrue every Morpho Blue market before converting
141
+ * adapter shares.
142
+ * @returns The resolved plan. `coveredAssets < assetsToDeallocate` means the exit would overrun the
143
+ * contract's unbounded loop; the caller decides how to report that.
144
+ * @throws {NonPositiveInputError} when `exitAssets` is not positive.
145
+ * @example
146
+ * ```ts
147
+ * import {
148
+ * computeVaultV2ForceWithdrawPlan,
149
+ * resolveVaultV2ForceWithdrawEligibility,
150
+ * } from "@morpho-org/morpho-sdk";
151
+ *
152
+ * const eligibility = resolveVaultV2ForceWithdrawEligibility(vaultData);
153
+ * if (eligibility.type === "eligible") {
154
+ * const plan = computeVaultV2ForceWithdrawPlan({
155
+ * vaultData,
156
+ * adapter: eligibility.adapter,
157
+ * liquidityMarketId: eligibility.liquidityMarketId,
158
+ * exitAssets: 1_000_000n,
159
+ * timestamp: 1_800_000_000n,
160
+ * });
161
+ * // plan.withdrawnAssets is what the user receives before the referral fee
162
+ * }
163
+ * ```
164
+ */
165
+ function computeVaultV2ForceWithdrawPlan(params) {
166
+ const { vaultData, adapter, liquidityMarketId, exitAssets, timestamp } = params;
167
+ // Guard the exported planner: a non-positive `exitAssets` would flow a negative through
168
+ // `min(exitAssets, withdrawable)` and return a plan with negative amounts. The entity and preview
169
+ // reject it upstream; this protects direct importers of the advertised helper.
170
+ if (exitAssets <= 0n)
171
+ throw new index_js_1.NonPositiveInputError("exitAssets", exitAssets);
172
+ const penalty = vaultData.forceDeallocatePenalties[adapter.address] ?? 0n;
173
+ const idleAssets = vaultData.assetBalance;
174
+ // `min(adapterPosition, marketLiquidity)` per market, on interest-accrued market state — the
175
+ // contract reads `expectedMarketBalances`, so the un-accrued `maxWithdraw` helpers on
176
+ // `AccrualVaultV2` would understate capacity.
177
+ const availableByMarket = new Map(adapter.markets.map((market) => {
178
+ const accrued = market.accrueInterest(blue_sdk_1.MathLib.max(timestamp, market.lastUpdate));
179
+ return [
180
+ market.id,
181
+ blue_sdk_1.MathLib.min(accrued.toSupplyAssets(adapter.supplyShares[market.id] ?? 0n), accrued.liquidity),
182
+ ];
183
+ }));
184
+ const liquidityCapacity = liquidityMarketId == null
185
+ ? 0n
186
+ : (availableByMarket.get(liquidityMarketId) ?? 0n);
187
+ const withdrawableAssets = idleAssets + liquidityCapacity;
188
+ const assetsToWithdraw = blue_sdk_1.MathLib.min(exitAssets, withdrawableAssets);
189
+ const assetsToDeallocate = blue_sdk_1.MathLib.mulDivDown(exitAssets - assetsToWithdraw, blue_sdk_1.MathLib.WAD, blue_sdk_1.MathLib.WAD + penalty);
190
+ // The penalty-free leg pulls its shortfall through the liquidity adapter, draining that market
191
+ // before the force-deallocation loop reaches it.
192
+ const drainedFromLiquidityMarket = blue_sdk_1.MathLib.zeroFloorSub(assetsToWithdraw, idleAssets);
193
+ if (liquidityMarketId != null && drainedFromLiquidityMarket > 0n) {
194
+ availableByMarket.set(liquidityMarketId, blue_sdk_1.MathLib.zeroFloorSub(liquidityCapacity, drainedFromLiquidityMarket));
195
+ }
196
+ let coveredAssets = 0n;
197
+ const nonEmpty = [];
198
+ for (const available of availableByMarket.values()) {
199
+ if (available <= 0n)
200
+ continue;
201
+ coveredAssets += available;
202
+ nonEmpty.push(available);
203
+ }
204
+ // `maxExitAssets` must not depend on the requested amount. At the ceiling the penalty-free leg
205
+ // always drains the liquidity market completely, so that market contributes nothing to the
206
+ // force-deallocation loop — whereas a small request leaves part of it, which would overstate the
207
+ // ceiling for callers using it to cap an input.
208
+ let saturatedCoveredAssets = 0n;
209
+ for (const [marketId, available] of availableByMarket) {
210
+ if (marketId === liquidityMarketId)
211
+ continue;
212
+ if (available > 0n)
213
+ saturatedCoveredAssets += available;
214
+ }
215
+ // Worst-case leg count is the ascending walk: the most markets the loop can touch is the number
216
+ // of smallest positions that together reach `assetsToDeallocate`. Deliberately an upper bound, not
217
+ // a replay of the contract's prefetched `marketIds` order (where an earlier market may cover the
218
+ // whole request in one leg): this count feeds the share-burn *upper* bound behind the slippage
219
+ // floor, so it must hold for any execution order. Replaying a snapshot order that then diverges at
220
+ // inclusion (a market added or drained between `getData()` and execution) would under-count legs,
221
+ // over-state the floor, and false-revert a valid distressed exit — a worse failure than the
222
+ // bounded looseness (≤ `penaltyLegs - 1` asset-units, absorbed by `slippageTolerance`) the
223
+ // ascending walk leaves. Tightening it to the exact walk is a separate change needing fork
224
+ // coverage of the snapshot-vs-execution divergence.
225
+ let penaltyLegs = 0;
226
+ let remaining = assetsToDeallocate;
227
+ for (const available of nonEmpty.toSorted((a, b) => a === b ? 0 : a > b ? 1 : -1)) {
228
+ if (remaining <= 0n)
229
+ break;
230
+ penaltyLegs += 1;
231
+ remaining -= blue_sdk_1.MathLib.min(available, remaining);
232
+ }
233
+ return {
234
+ penalty,
235
+ exitAssets,
236
+ assetsToWithdraw,
237
+ assetsToDeallocate,
238
+ // `sum(ceil(assetsᵢ·penalty/WAD)) <= ceil(sum(assetsᵢ)·penalty/WAD) + legs - 1`. The per-leg
239
+ // slack only exists because each chunk rounds its own charge up; at a zero penalty every chunk
240
+ // charges exactly nothing, so carrying the slack would invent penalty assets the contract never
241
+ // debits — inflating the share-burn denominator and weakening the derived bound.
242
+ penaltyAssets: penaltyLegs === 0 || penalty === 0n
243
+ ? 0n
244
+ : blue_sdk_1.MathLib.wMulUp(assetsToDeallocate, penalty) + BigInt(penaltyLegs - 1),
245
+ withdrawnAssets: assetsToWithdraw + assetsToDeallocate,
246
+ coveredAssets,
247
+ // Both bounds keep the ceiling *actionable*, since callers cap an input field with it and the
248
+ // coverage error tells them to reduce to it. A vault with nothing to give reports zero: the
249
+ // inversion rounds up to `1n` at a positive penalty, and `1n` withdraws nothing, which the
250
+ // entity rejects. And the gross-up can exceed the ABI slot on an enormous snapshot, which the
251
+ // entity also rejects — so it saturates rather than advertising an unusable amount.
252
+ maxExitAssets: withdrawableAssets === 0n && saturatedCoveredAssets === 0n
253
+ ? 0n
254
+ : blue_sdk_1.MathLib.min(withdrawableAssets +
255
+ blue_sdk_1.MathLib.wMulUp(saturatedCoveredAssets + 1n, blue_sdk_1.MathLib.WAD + penalty) -
256
+ 1n, viem_1.maxUint256),
257
+ penaltyLegs,
258
+ };
259
+ }
260
+ /**
261
+ * Upper-bounds the vault shares a Vault V2 force withdrawal burns.
262
+ *
263
+ * The contract splits the burn across up to `penaltyLegs + 2` separate `VaultV2.withdraw` calls (the
264
+ * penalty-free leg, one per `forceDeallocate`, and the final deallocated leg), each rounding its own
265
+ * share burn up. Converting the aggregate already spends one ceiling, so the bound adds one share
266
+ * per *additional* leg that moves a positive amount — a zero-amount leg burns `toShares(0, "Up")`
267
+ * and rounds nothing.
268
+ *
269
+ * The result is the **denominator of {@link computeMinForceWithdrawSharePrice}** — the largest share
270
+ * burn the realized exit price is measured against. It takes the max over the two supplied snapshots
271
+ * because interest lowers the burn while management fees raise it, so neither snapshot alone bounds
272
+ * execution. The entity passes both accrued to `now` (execution time): the raw `lastUpdate` snapshot
273
+ * underestimates the burn a stale fee-bearing vault realizes — the first withdrawal accrues pending
274
+ * management fees before burning shares — which lifts the floor above the faithful price and trips
275
+ * `SlippageExceeded`. Accruing to `now`, not the caller-chosen `deadline`, tracks execution without
276
+ * letting a long deadline silently weaken the guard; `slippageTolerance` absorbs the residual drift
277
+ * until inclusion. Pass distinct snapshots to bound the burn across an accrual window.
278
+ *
279
+ * This is **not** the share allowance to authorize. The price floor's denominator is this bound
280
+ * minus `computeVaultV2ForceWithdrawFeeSharesMinted({ vaultData, owner, timestamp: now })`: the
281
+ * contract measures the *net* burn, which fee mints to `owner` shrink. The allowance is
282
+ * `min(mulDivUp(exitAssets, RAY, minSharePriceE27) + computeVaultV2ForceWithdrawFeeSharesMinted({
283
+ * vaultData, owner, timestamp: deadline }), maxUint256)`: the permit pays for the *gross* burn.
284
+ *
285
+ * @param params - Share-bound inputs.
286
+ * @param params.vaultData - Pre-fetched Vault V2 accrual snapshot.
287
+ * @param params.deadlineVaultData - The same vault accrued to a second timestamp; the max of the two
288
+ * share burns is returned. The entity passes the `now`-accrued snapshot for both.
289
+ * @param params.plan - Plan from {@link computeVaultV2ForceWithdrawPlan}.
290
+ * @returns An upper bound, in vault shares, of what the exit burns.
291
+ * @example
292
+ * ```ts
293
+ * import { MathLib } from "@morpho-org/blue-sdk";
294
+ * import {
295
+ * computeVaultV2ForceWithdrawFeeSharesMinted,
296
+ * computeVaultV2ForceWithdrawSharesBurnt,
297
+ * } from "@morpho-org/morpho-sdk";
298
+ *
299
+ * const { vault: nowVaultData } = vaultData.accrueInterest(now);
300
+ * const sharesBurnt = computeVaultV2ForceWithdrawSharesBurnt({
301
+ * vaultData: nowVaultData,
302
+ * deadlineVaultData: nowVaultData,
303
+ * plan,
304
+ * });
305
+ * const feeSharesNow = computeVaultV2ForceWithdrawFeeSharesMinted({
306
+ * vaultData,
307
+ * owner,
308
+ * timestamp: now,
309
+ * });
310
+ * const sharesBurntForFloor = sharesBurnt - feeSharesNow;
311
+ * const requiredShareAllowance = MathLib.min(
312
+ * MathLib.mulDivUp(exitAssets, MathLib.RAY, minSharePriceE27) +
313
+ * computeVaultV2ForceWithdrawFeeSharesMinted({
314
+ * vaultData,
315
+ * owner,
316
+ * timestamp: deadline,
317
+ * }),
318
+ * maxUint256,
319
+ * );
320
+ * ```
321
+ */
322
+ function computeVaultV2ForceWithdrawSharesBurnt(params) {
323
+ const { vaultData, deadlineVaultData, plan } = params;
324
+ // `penaltyAssets` already carries the per-market ceil accumulation, so this is the full
325
+ // penalty-inclusive amount debited from the user's position.
326
+ const grossDebited = plan.withdrawnAssets + plan.penaltyAssets;
327
+ // Only withdrawals that move a positive amount round anything: `toShares(0, "Up")` is `0`. So the
328
+ // penalty-free leg counts only when it pays out, the `forceDeallocate` burns count only at a
329
+ // positive penalty, and the deallocated leg counts only when the loop deallocated something.
330
+ const positiveLegs = (plan.assetsToWithdraw > 0n ? 1 : 0) +
331
+ (plan.penalty > 0n ? plan.penaltyLegs : 0) +
332
+ (plan.assetsToDeallocate > 0n ? 1 : 0);
333
+ return (blue_sdk_1.MathLib.max(vaultData.toShares(grossDebited, "Up"), deadlineVaultData.toShares(grossDebited, "Up")) +
334
+ // `sum(ceil(sharesᵢ)) <= ceil(sum(sharesᵢ)) + (positiveLegs - 1)`: the aggregate conversion above
335
+ // already spends one ceiling, so only the *additional* positive legs can each cost one more
336
+ // share. A fixed `penaltyLegs + 2` overcounts every zero-amount leg, and because this value is
337
+ // the slippage denominator an overcount silently widens the price drop the bound accepts —
338
+ // worst on a dust exit, where two phantom shares can dominate the real burn.
339
+ BigInt(positiveLegs > 0 ? positiveLegs - 1 : 0));
340
+ }
341
+ /**
342
+ * Computes a lower bound of the Vault V2 shares that a force withdrawal burns.
343
+ *
344
+ * The penalty-free/penalised split can move as liquidity accrues between planning and inclusion.
345
+ * This lower bound is used to reject fee-recipient exits whose fee mints could reach the burn
346
+ * measured by VaultExitBundlesV1, independently of that split.
347
+ *
348
+ * @param params - Lower-bound inputs.
349
+ * @param params.vaultData - Vault V2 snapshot already accrued to the execution timestamp.
350
+ * @param params.plan - Plan from {@link computeVaultV2ForceWithdrawPlan}.
351
+ * @returns A lower bound, in vault shares, of the burn measured by the contract.
352
+ * @example
353
+ * ```ts
354
+ * import { computeVaultV2ForceWithdrawMinSharesBurnt } from "@morpho-org/morpho-sdk";
355
+ *
356
+ * const minSharesBurnt = computeVaultV2ForceWithdrawMinSharesBurnt({
357
+ * vaultData,
358
+ * plan,
359
+ * });
360
+ * ```
361
+ */
362
+ function computeVaultV2ForceWithdrawMinSharesBurnt(params) {
363
+ const { vaultData, plan } = params;
364
+ // The penalty-free/penalised split moves as the liquidity market accrues, but any split debits
365
+ // within `1 + penalty` (< 2 asset units) of `exitAssets`, so `exitAssets - 1` lower-bounds every
366
+ // execution-time split.
367
+ return vaultData.toShares(blue_sdk_1.MathLib.min(plan.withdrawnAssets +
368
+ blue_sdk_1.MathLib.wMulUp(plan.assetsToDeallocate, plan.penalty), blue_sdk_1.MathLib.zeroFloorSub(plan.exitAssets, 1n)), "Down");
369
+ }
@@ -1,6 +1,17 @@
1
1
  import type { InputMarketParams } from "@morpho-org/blue-sdk";
2
- import type { Address, Hex, WalletClient } from "viem";
2
+ import type { Address, Hex, TypedDataDefinition, WalletClient } from "viem";
3
3
  import type { Deallocation } from "./deallocation.js";
4
+ /**
5
+ * Serves as the common discriminated action-metadata base shared by both
6
+ * {@link TransactionAction} (actions that carry encoded calldata) and
7
+ * {@link SignatureRequirementAction} (signature requirements whose metadata is
8
+ * exposed before any calldata exists). Each concrete action narrows
9
+ * {@link BaseAction} on its literal `type` tag and carries an
10
+ * operation-specific `args` record surfaced for tracing.
11
+ *
12
+ * @typeParam TType - Literal discriminator identifying the action.
13
+ * @typeParam TArgs - The action's argument record.
14
+ */
4
15
  export interface BaseAction<TType extends string = string, TArgs extends Record<string, unknown> = Record<string, unknown>> {
5
16
  readonly type: TType;
6
17
  readonly args: TArgs;
@@ -77,14 +88,22 @@ export interface VaultV2InKindRedeemAction extends BaseAction<"vaultV2InKindRede
77
88
  readonly deadline: bigint;
78
89
  }> {
79
90
  }
91
+ /**
92
+ * Metadata for a Vault V2 force withdrawal through VaultExitBundlesV1.
93
+ *
94
+ * `exitAssets` is penalty-inclusive: the assets actually delivered are
95
+ * `assetsToWithdraw + floor((exitAssets - assetsToWithdraw) * WAD / (WAD + penalty))`, minus the
96
+ * referral fee.
97
+ */
80
98
  export interface VaultV2ForceWithdrawAction extends BaseAction<"vaultV2ForceWithdraw", {
81
- vault: Address;
82
- deallocations: readonly Deallocation[];
83
- withdraw: {
84
- amount: bigint;
85
- recipient: Address;
86
- };
87
- onBehalf: Address;
99
+ readonly vault: Address;
100
+ readonly adapter: Address;
101
+ readonly exitAssets: bigint;
102
+ readonly minSharePriceE27: bigint;
103
+ readonly referralFeePct: bigint;
104
+ readonly referralFeeRecipient: Address;
105
+ readonly onBehalf: Address;
106
+ readonly deadline: bigint;
88
107
  }> {
89
108
  }
90
109
  export interface VaultV2ForceRedeemAction extends BaseAction<"vaultV2ForceRedeem", {
@@ -379,8 +398,19 @@ export interface MidnightCancelOfferAction extends BaseAction<"midnightCancelOff
379
398
  readonly onBehalf: Address;
380
399
  }> {
381
400
  }
382
- /** Metadata discriminators carried by transactions returned by the SDK. */
401
+ /**
402
+ * Enumerates every action a {@link Transaction} can describe across the VaultV1,
403
+ * VaultV2, Blue, and Midnight flows. The `type` tag discriminates the union so
404
+ * consumers can `switch` exhaustively on it.
405
+ */
383
406
  export type TransactionAction = ERC20ApprovalAction | VaultV2DepositAction | VaultV2WithdrawAction | VaultV2RedeemAction | VaultV2InKindRedeemAction | VaultV2ForceWithdrawAction | VaultV2ForceRedeemAction | VaultV1DepositAction | VaultV1WithdrawAction | VaultV1RedeemAction | VaultV1InKindRedeemAction | VaultV1MigrateToV2Action | BlueSupplyAction | BlueSupplyCollateralAction | BlueBorrowAction | BlueSupplyCollateralBorrowAction | BlueRepayAction | BlueWithdrawCollateralAction | BlueRepayWithdrawCollateralAction | BlueWithdrawAction | BlueRefinanceAction | BlueAuthorizationAction | MidnightAuthorizationAction | SetterRatifierRatifyRootAction | MidnightTakeLendAction | MidnightTakeBorrowAction | MidnightSupplyCollateralTakeBorrowAction | MidnightSupplyCollateralAction | MempoolSubmitOffersAction | MidnightRedeemAction | MidnightRepayWithdrawCollateralAction | MidnightCancelOfferAction;
407
+ /**
408
+ * Describes a single, immutable, deep-frozen transaction to submit on-chain:
409
+ * the target `to`, native `value`, encoded call `data`, and the originating
410
+ * {@link BaseAction} for tracing. Every action builder returns one.
411
+ *
412
+ * @typeParam TAction - The action that produced this transaction.
413
+ */
384
414
  export interface Transaction<TAction extends BaseAction = TransactionAction> {
385
415
  readonly to: Address;
386
416
  readonly value: bigint;
@@ -413,7 +443,7 @@ export type BundlesFundingArgs = {
413
443
  export interface BundlesTokenRequirementsOptions {
414
444
  /** Prefer ERC-2612 when the funded token exposes a compatible nonce. */
415
445
  readonly useSimplePermit?: boolean;
416
- /** Explicit unused Permit2 SignatureTransfer unordered nonce. */
446
+ /** Explicit unused Permit2 SignatureTransfer unordered nonce; defaults to the lowest unused nonce. */
417
447
  readonly permit2Nonce?: bigint;
418
448
  }
419
449
  /** Mutually exclusive source amount accepted by a Vault V1 to Vault V2 migration. */
@@ -424,6 +454,13 @@ export type VaultV1MigrateToV2AmountArgs = {
424
454
  readonly assets: bigint;
425
455
  readonly shares?: never;
426
456
  };
457
+ /**
458
+ * Holds the pre-resolved arguments for an ERC-2612 `permit`: the signed approval
459
+ * of `amount` of `asset` from `owner` to the permitted spender, bounded by the
460
+ * `deadline` timestamp and consuming the given `nonce`. The associated
461
+ * {@link PermitAction} identifies the permitted spender, including fixed-bundle
462
+ * contracts and the GeneralAdapter1 periphery.
463
+ */
427
464
  export interface PermitArgs {
428
465
  readonly owner: Address;
429
466
  readonly nonce: bigint;
@@ -432,6 +469,12 @@ export interface PermitArgs {
432
469
  readonly amount: bigint;
433
470
  readonly deadline: bigint;
434
471
  }
472
+ /**
473
+ * Holds the pre-resolved arguments for a Permit2 `permit` bundler call. It
474
+ * mirrors {@link PermitArgs} but adds the Permit2 allowance `expiration` (when
475
+ * the on-chain allowance lapses) alongside the signature `deadline` (by when the
476
+ * signature must be submitted).
477
+ */
435
478
  export interface Permit2Args {
436
479
  readonly owner: Address;
437
480
  readonly nonce: bigint;
@@ -467,6 +510,8 @@ export interface MidnightOfferRootSignatureArgs {
467
510
  readonly signature: Hex;
468
511
  readonly payload: Hex;
469
512
  }
513
+ /** EIP-712 payload carried by a signable requirement action. */
514
+ export type RequirementTypedData = TypedDataDefinition<Record<string, unknown>, string>;
470
515
  export interface PermitAction extends BaseAction<"permit", {
471
516
  readonly spender: Address;
472
517
  readonly amount: bigint;
@@ -474,6 +519,13 @@ export interface PermitAction extends BaseAction<"permit", {
474
519
  /** Permit nonce captured by a prepared requirement, when available. */
475
520
  readonly nonce?: bigint;
476
521
  }> {
522
+ /**
523
+ * EIP-712 payload `sign()` signs for this permit, exposed so it can be inspected or displayed
524
+ * before signing. Required on {@link Requirement.action}; optional here only so hand-built action
525
+ * metadata (e.g. test fixtures) need not supply it. The payload is deep-frozen and `sign()` signs
526
+ * this exact payload.
527
+ */
528
+ readonly typedData?: RequirementTypedData;
477
529
  }
478
530
  export interface Permit2Action extends BaseAction<"permit2", {
479
531
  spender: Address;
@@ -481,6 +533,8 @@ export interface Permit2Action extends BaseAction<"permit2", {
481
533
  deadline: bigint;
482
534
  expiration: bigint;
483
535
  }> {
536
+ /** EIP-712 payload to sign for this Permit2 AllowanceTransfer. See {@link PermitAction.typedData}. */
537
+ readonly typedData?: RequirementTypedData;
484
538
  }
485
539
  /** Signable Permit2 SignatureTransfer requirement for a fixed bundles token pull. */
486
540
  export interface Permit2SignatureTransferAction extends BaseAction<"permit2SignatureTransfer", {
@@ -489,6 +543,8 @@ export interface Permit2SignatureTransferAction extends BaseAction<"permit2Signa
489
543
  readonly nonce: bigint;
490
544
  readonly deadline: bigint;
491
545
  }> {
546
+ /** EIP-712 payload to sign for this Permit2 SignatureTransfer. See {@link PermitAction.typedData}. */
547
+ readonly typedData?: RequirementTypedData;
492
548
  }
493
549
  /**
494
550
  * Signable Morpho authorization requirement. Its `authorized` operator is route-specific:
@@ -499,6 +555,8 @@ export interface AuthorizationAction extends BaseAction<"authorization", {
499
555
  isAuthorized: boolean;
500
556
  deadline: bigint;
501
557
  }> {
558
+ /** EIP-712 payload to sign for this Morpho authorization. See {@link PermitAction.typedData}. */
559
+ readonly typedData?: RequirementTypedData;
502
560
  }
503
561
  /** Metadata for a Midnight offer-root signature request. */
504
562
  export interface MidnightOfferRootSignatureAction extends BaseAction<"midnightOfferRootSignature", {
@@ -506,6 +564,15 @@ export interface MidnightOfferRootSignatureAction extends BaseAction<"midnightOf
506
564
  readonly ratifier: Address;
507
565
  readonly offers: number;
508
566
  }> {
567
+ /**
568
+ * EIP-712 offer-tree payload `sign()` signs for this Midnight ratification, exposed so it can be
569
+ * inspected or displayed before signing. See {@link PermitAction.typedData}.
570
+ *
571
+ * A bare signature over this payload is not enough to build the submit-offers transaction:
572
+ * `sign()` also derives the ratification payload (`MidnightOfferRootSignature.args.payload`) that
573
+ * `buildTx()` submits to the mempool.
574
+ */
575
+ readonly typedData?: RequirementTypedData;
509
576
  }
510
577
  /** Action metadata supported by signature requirements. */
511
578
  export type SignatureRequirementAction = PermitAction | Permit2Action | Permit2SignatureTransferAction | AuthorizationAction | MidnightOfferRootSignatureAction;
@@ -551,16 +618,31 @@ export type RequirementSignature<TAction extends SignatureRequirementAction | un
551
618
  type RequirementResult<TSignatureOrAction extends RequirementSignature | SignatureRequirementAction, TArgs extends RequirementSignatureArgs | undefined> = TSignatureOrAction extends SignatureRequirementAction ? RequirementSignature<TSignatureOrAction, Extract<TArgs, RequirementSignatureArgs>> : Extract<TSignatureOrAction, RequirementSignature>;
552
619
  /**
553
620
  * A signable approval / authorization requirement. `sign()` returns the matching
554
- * {@link RequirementSignature}; `action` describes the requirement without signing.
621
+ * {@link RequirementSignature}; `action` describes the requirement without signing and carries the
622
+ * EIP-712 `typedData` payload so an integrator can inspect or display it before signing.
555
623
  *
556
624
  * Generic over the signature it produces so permit encoders narrow to
557
625
  * {@link PermitRequirementSignature} and the authorization encoder to
558
626
  * {@link AuthorizationRequirementSignature}; the two-parameter form is kept for
559
627
  * Midnight action requirements that are parameterized by action and args.
628
+ *
629
+ * @example
630
+ * ```ts
631
+ * const requirement = (await output.getRequirements()).find(isRequirementSignature);
632
+ * if (requirement == null) return; // nothing to sign (only on-chain approvals, or none)
633
+ *
634
+ * const typedData = requirement.action.typedData; // exact EIP-712 payload `sign()` will sign
635
+ * const signed = await requirement.sign(walletClient, owner);
636
+ * const tx = output.buildTx([signed]); // Midnight outputs take the single signature instead
637
+ * ```
560
638
  */
561
639
  export interface Requirement<TSignatureOrAction extends RequirementSignature | SignatureRequirementAction = RequirementSignature, TArgs extends RequirementSignatureArgs | undefined = undefined> {
562
- sign: (client: WalletClient, userAddress: Address) => Promise<RequirementResult<TSignatureOrAction, TArgs>>;
563
- action: RequirementResult<TSignatureOrAction, TArgs>["action"];
640
+ /** Signs `action.typedData` with `client`, verifies the signature recovers `userAddress`, and returns the signed requirement. */
641
+ readonly sign: (client: WalletClient, userAddress: Address) => Promise<RequirementResult<TSignatureOrAction, TArgs>>;
642
+ /** Requirement metadata; `typedData` is always populated on SDK-built requirements. */
643
+ readonly action: RequirementResult<TSignatureOrAction, TArgs>["action"] & {
644
+ readonly typedData: RequirementTypedData;
645
+ };
564
646
  }
565
647
  /** Bundler3 token signature requirement. */
566
648
  export type Bundler3TokenSignatureRequirement = Requirement<PermitRequirementSignature>;