@morpho-org/morpho-sdk 8.3.0 → 9.0.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 (155) hide show
  1. package/MIGRATION-v8-to-v9.md +54 -0
  2. package/README.md +13 -7
  3. package/lib/cjs/actions/bundles/common.d.ts +4 -7
  4. package/lib/cjs/actions/bundles/common.js +8 -14
  5. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  6. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +1 -8
  7. package/lib/cjs/actions/midnight/authorization.d.ts +3 -1
  8. package/lib/cjs/actions/midnight/authorization.js +11 -1
  9. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +2 -0
  10. package/lib/cjs/actions/midnight/cancelAndMake.js +10 -2
  11. package/lib/cjs/actions/midnight/redeem.d.ts +3 -1
  12. package/lib/cjs/actions/midnight/redeem.js +9 -3
  13. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  14. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +7 -3
  15. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +4 -1
  16. package/lib/cjs/actions/midnight/supplyCollateral.js +10 -3
  17. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  18. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +9 -3
  19. package/lib/cjs/actions/midnight/takeBorrow.d.ts +3 -1
  20. package/lib/cjs/actions/midnight/takeBorrow.js +9 -3
  21. package/lib/cjs/actions/midnight/takeLend.d.ts +1 -0
  22. package/lib/cjs/actions/midnight/takeLend.js +7 -2
  23. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  24. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +8 -2
  25. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +3 -1
  26. package/lib/cjs/actions/midnight/takeWithdraw.js +10 -3
  27. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  28. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +5 -7
  29. package/lib/cjs/actions/requirements/getRequirementsApproval.d.ts +7 -11
  30. package/lib/cjs/actions/requirements/getRequirementsApproval.js +8 -15
  31. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  32. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +11 -8
  33. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  34. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  35. package/lib/cjs/actions/vaultV1/inKindRedeem.d.ts +1 -1
  36. package/lib/cjs/actions/vaultV1/inKindRedeem.js +1 -1
  37. package/lib/cjs/actions/vaultV1/withdraw.d.ts +4 -4
  38. package/lib/cjs/actions/vaultV1/withdraw.js +4 -4
  39. package/lib/cjs/actions/vaultV2/forceWithdraw.d.ts +1 -1
  40. package/lib/cjs/actions/vaultV2/forceWithdraw.js +1 -1
  41. package/lib/cjs/actions/vaultV2/inKindRedeem.d.ts +1 -1
  42. package/lib/cjs/actions/vaultV2/inKindRedeem.js +1 -1
  43. package/lib/cjs/actions/vaultV2/withdraw.d.ts +4 -4
  44. package/lib/cjs/actions/vaultV2/withdraw.js +4 -4
  45. package/lib/cjs/entities/blue/blue.d.ts +2 -12
  46. package/lib/cjs/entities/blue/blue.js +0 -4
  47. package/lib/cjs/entities/midnight/midnight.d.ts +56 -17
  48. package/lib/cjs/entities/midnight/midnight.js +131 -52
  49. package/lib/cjs/entities/midnight/types.d.ts +2 -9
  50. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  51. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +0 -7
  52. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  53. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -20
  54. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +40 -37
  55. package/lib/cjs/entities/vaultV1/vaultV1.js +5 -34
  56. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +36 -34
  57. package/lib/cjs/entities/vaultV2/vaultV2.js +8 -34
  58. package/lib/cjs/helpers/encodeMidnightCalldata.d.ts +48 -0
  59. package/lib/cjs/helpers/encodeMidnightCalldata.js +74 -0
  60. package/lib/cjs/helpers/slippage.d.ts +9 -25
  61. package/lib/cjs/helpers/slippage.js +10 -27
  62. package/lib/cjs/helpers/validate.d.ts +1 -0
  63. package/lib/cjs/helpers/validate.js +5 -0
  64. package/lib/cjs/helpers/validateMidnightAccount.d.ts +34 -0
  65. package/lib/cjs/helpers/validateMidnightAccount.js +47 -0
  66. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  67. package/lib/cjs/helpers/validateMidnightAuthorizationTarget.js +4 -0
  68. package/lib/cjs/helpers/validateMidnightMarket.d.ts +2 -0
  69. package/lib/cjs/helpers/validateMidnightMarket.js +5 -0
  70. package/lib/cjs/helpers/validateMidnightPublication.d.ts +11 -0
  71. package/lib/cjs/helpers/validateMidnightPublication.js +12 -1
  72. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +1 -0
  73. package/lib/cjs/helpers/validateMidnightReceiver.js +8 -0
  74. package/lib/cjs/helpers/validateTakeableOffers.d.ts +2 -1
  75. package/lib/cjs/helpers/validateTakeableOffers.js +4 -3
  76. package/lib/cjs/types/action.d.ts +3 -1
  77. package/lib/cjs/types/error.d.ts +56 -5
  78. package/lib/cjs/types/error.js +139 -10
  79. package/lib/esm/actions/bundles/common.d.ts +4 -7
  80. package/lib/esm/actions/bundles/common.js +8 -14
  81. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +1 -5
  82. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -9
  83. package/lib/esm/actions/midnight/authorization.d.ts +3 -1
  84. package/lib/esm/actions/midnight/authorization.js +12 -2
  85. package/lib/esm/actions/midnight/cancelAndMake.d.ts +2 -0
  86. package/lib/esm/actions/midnight/cancelAndMake.js +11 -3
  87. package/lib/esm/actions/midnight/redeem.d.ts +3 -1
  88. package/lib/esm/actions/midnight/redeem.js +10 -4
  89. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +1 -0
  90. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +8 -4
  91. package/lib/esm/actions/midnight/supplyCollateral.d.ts +4 -1
  92. package/lib/esm/actions/midnight/supplyCollateral.js +11 -4
  93. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +3 -1
  94. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +10 -4
  95. package/lib/esm/actions/midnight/takeBorrow.d.ts +3 -1
  96. package/lib/esm/actions/midnight/takeBorrow.js +10 -4
  97. package/lib/esm/actions/midnight/takeLend.d.ts +1 -0
  98. package/lib/esm/actions/midnight/takeLend.js +8 -3
  99. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +1 -0
  100. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +9 -3
  101. package/lib/esm/actions/midnight/takeWithdraw.d.ts +3 -1
  102. package/lib/esm/actions/midnight/takeWithdraw.js +11 -4
  103. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +1 -5
  104. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +6 -8
  105. package/lib/esm/actions/requirements/getRequirementsApproval.d.ts +7 -11
  106. package/lib/esm/actions/requirements/getRequirementsApproval.js +9 -16
  107. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +5 -10
  108. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +12 -9
  109. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +2 -0
  110. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -0
  111. package/lib/esm/actions/vaultV1/inKindRedeem.d.ts +1 -1
  112. package/lib/esm/actions/vaultV1/inKindRedeem.js +1 -1
  113. package/lib/esm/actions/vaultV1/withdraw.d.ts +4 -4
  114. package/lib/esm/actions/vaultV1/withdraw.js +4 -4
  115. package/lib/esm/actions/vaultV2/forceWithdraw.d.ts +1 -1
  116. package/lib/esm/actions/vaultV2/forceWithdraw.js +1 -1
  117. package/lib/esm/actions/vaultV2/inKindRedeem.d.ts +1 -1
  118. package/lib/esm/actions/vaultV2/inKindRedeem.js +1 -1
  119. package/lib/esm/actions/vaultV2/withdraw.d.ts +4 -4
  120. package/lib/esm/actions/vaultV2/withdraw.js +4 -4
  121. package/lib/esm/entities/blue/blue.d.ts +2 -12
  122. package/lib/esm/entities/blue/blue.js +0 -4
  123. package/lib/esm/entities/midnight/midnight.d.ts +56 -17
  124. package/lib/esm/entities/midnight/midnight.js +132 -53
  125. package/lib/esm/entities/midnight/types.d.ts +2 -9
  126. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +0 -4
  127. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +1 -8
  128. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -14
  129. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +9 -21
  130. package/lib/esm/entities/vaultV1/vaultV1.d.ts +40 -37
  131. package/lib/esm/entities/vaultV1/vaultV1.js +6 -35
  132. package/lib/esm/entities/vaultV2/vaultV2.d.ts +36 -34
  133. package/lib/esm/entities/vaultV2/vaultV2.js +8 -34
  134. package/lib/esm/helpers/encodeMidnightCalldata.d.ts +48 -0
  135. package/lib/esm/helpers/encodeMidnightCalldata.js +69 -0
  136. package/lib/esm/helpers/slippage.d.ts +9 -25
  137. package/lib/esm/helpers/slippage.js +9 -25
  138. package/lib/esm/helpers/validate.d.ts +1 -0
  139. package/lib/esm/helpers/validate.js +5 -0
  140. package/lib/esm/helpers/validateMidnightAccount.d.ts +34 -0
  141. package/lib/esm/helpers/validateMidnightAccount.js +43 -0
  142. package/lib/esm/helpers/validateMidnightAuthorizationTarget.d.ts +1 -0
  143. package/lib/esm/helpers/validateMidnightAuthorizationTarget.js +4 -0
  144. package/lib/esm/helpers/validateMidnightMarket.d.ts +2 -0
  145. package/lib/esm/helpers/validateMidnightMarket.js +5 -0
  146. package/lib/esm/helpers/validateMidnightPublication.d.ts +11 -0
  147. package/lib/esm/helpers/validateMidnightPublication.js +10 -0
  148. package/lib/esm/helpers/validateMidnightReceiver.d.ts +1 -0
  149. package/lib/esm/helpers/validateMidnightReceiver.js +8 -0
  150. package/lib/esm/helpers/validateTakeableOffers.d.ts +2 -1
  151. package/lib/esm/helpers/validateTakeableOffers.js +4 -3
  152. package/lib/esm/types/action.d.ts +3 -1
  153. package/lib/esm/types/error.d.ts +56 -5
  154. package/lib/esm/types/error.js +134 -6
  155. package/package.json +4 -3
@@ -122,16 +122,16 @@ export interface VaultV2Actions {
122
122
  /**
123
123
  * Prepares an exact-assets Vault V2 withdrawal through VaultBundlesV1.
124
124
  *
125
- * Derives the share-burn cap from the supplied `vaultData` snapshot at handle creation, then
126
- * reads the live vault-share allowance and, when a signature is needed, the permit nonce on
127
- * each `getRequirements()` call. Captures the requested amount and owner at creation, so later
128
- * changes to `params` do not change this handle's requirements or transaction.
125
+ * Derives the minimum required share allowance from the supplied `vaultData` snapshot at handle
126
+ * creation, then reads the live vault-share allowance and, when a signature is needed, the permit
127
+ * nonce on each `getRequirements()` call. Captures the requested amount and owner at creation, so
128
+ * later changes to `params` do not change this handle's requirements or transaction.
129
129
  *
130
130
  * @param params.amount - Positive gross withdrawal in underlying asset base units, before fees.
131
131
  * @param params.userAddress - Share owner that must sign and submit; receives the net assets.
132
- * @param params.vaultData - Pre-fetched Vault V2 snapshot used to derive the share cap.
133
- * @param params.slippageTolerance - Optional WAD-scaled share-price loss tolerance applied to
134
- * the share cap.
132
+ * @param params.vaultData - Pre-fetched Vault V2 snapshot used to derive the minimum share allowance.
133
+ * @param params.slippageTolerance - Optional WAD-scaled tolerance used only to size the minimum
134
+ * share allowance. It does not impose an on-chain share-burn bound.
135
135
  * Defaults to 0.03% and cannot exceed 10%.
136
136
  * @param params.referralFeePct - Optional WAD-scaled fee in [0, 1e18), defaulting to zero;
137
137
  * rounded down and deducted from the gross withdrawn assets.
@@ -140,17 +140,16 @@ export interface VaultV2Actions {
140
140
  * defaults to two hours from handle creation.
141
141
  * @returns A frozen handle with lazy `getRequirements()` and synchronous `buildTx(signatures?)`,
142
142
  * which returns a deep-frozen `Transaction<VaultV2WithdrawAction>`. Requirements are empty
143
- * when the allowance is between the cap and the cap divided by `1 - slippageTolerance`; a
144
- * larger allowance is always reset with an exact onchain approval, and an insufficient one is
145
- * raised by an approval or, with signature
146
- * support, an ERC-2612 request. The cap is fixed at handle creation while each call re-reads
147
- * the allowance. Confirm the approval or pass its signed permit to `buildTx`.
143
+ * when the allowance meets or exceeds the required share amount. An insufficient allowance is
144
+ * raised by an unlimited approval or, with signature support, an ERC-2612 request. The minimum
145
+ * is fixed at handle creation while each call re-reads the allowance. Confirm the approval or
146
+ * pass its signed permit to `buildTx`.
148
147
  * @remarks VaultBundlesV1 skips a share permit whose nonce was already consumed and proceeds
149
148
  * under the live allowance, so execute every requirement returned by the latest
150
- * `getRequirements()` — including the oversized-allowance reset — before submitting.
149
+ * `getRequirements()` before submitting.
151
150
  * @throws {ChainIdMismatchError} when the connected client targets another chain, or from
152
151
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
153
- * @throws {NonPositiveInputError} when `amount` or the computed share cap is not positive.
152
+ * @throws {NonPositiveInputError} when `amount` or the computed required share amount is not positive.
154
153
  * @throws {ExpiredDeadlineError} when `deadline` is not in the future at handle creation or
155
154
  * at any `getRequirements()` call.
156
155
  * @throws {InputExceedsMaxError} when `amount` or `deadline` exceeds uint256 at handle creation.
@@ -164,8 +163,8 @@ export interface VaultV2Actions {
164
163
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when an unsupported signature is supplied.
165
164
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when multiple permits are supplied.
166
165
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the share permit is malformed or
167
- * its spender or deadline differ from this operation's, or its amount is outside
168
- * `[cap, cap / (1 - slippageTolerance)]`.
166
+ * its spender or deadline differ from this operation's, or its amount is below the required
167
+ * share allowance.
169
168
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol
170
169
  * contract has no code at its registered address.
171
170
  * @throws {viem.BaseError} from `getRequirements()` when an allowance, nonce, or `eth_chainId`
@@ -203,8 +202,9 @@ export interface VaultV2Actions {
203
202
  * Prepares an exact-shares Vault V2 redemption through VaultBundlesV1.
204
203
  *
205
204
  * Captures `shares` and `userAddress` at handle creation for both requirements and `buildTx()`.
206
- * The caller must satisfy the exact vault-share allowance returned by `getRequirements()` before
207
- * `buildTx()`; every requirement resolution re-reads the live allowance and checks the deadline.
205
+ * The caller must satisfy the minimum share allowance returned by `getRequirements()` before
206
+ * `buildTx()`; larger allowances also suffice, and each requirement resolution re-reads the live
207
+ * allowance and checks the deadline.
208
208
  *
209
209
  * @param params - The redeem parameters.
210
210
  * @param params.shares - Exact vault shares to burn.
@@ -212,7 +212,7 @@ export interface VaultV2Actions {
212
212
  * @param [params.referralFeePct=0n] - WAD-scaled referral fee deducted from the redeemed assets; must be below WAD.
213
213
  * @param [params.referralFeeRecipient] - Non-zero recipient required when `referralFeePct` is positive.
214
214
  * @param [params.deadline] - VaultBundlesV1 execution deadline; defaults to two hours from now.
215
- * @returns Lazy exact share-allowance requirements and a synchronous transaction builder.
215
+ * @returns Lazy share-allowance requirements and a synchronous transaction builder.
216
216
  * @throws {ChainIdMismatchError} when the client and entity target different chains, or from
217
217
  * `getRequirements()` when the RPC reports another chain via `eth_chainId`.
218
218
  * @throws {NonPositiveInputError} when `shares` is not positive.
@@ -235,8 +235,8 @@ export interface VaultV2Actions {
235
235
  * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
236
236
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
237
237
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
238
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender, amount or
239
- * deadline differ from this operation's.
238
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the signature's spender or
239
+ * deadline differs from this operation's, or its amount is below the required share allowance.
240
240
  * @example
241
241
  * ```ts
242
242
  * import { isRequirementSignature } from "@morpho-org/morpho-sdk";
@@ -279,9 +279,10 @@ export interface VaultV2Actions {
279
279
  * Idle balance, penalty, and adapter positions can drift after the snapshot, so an on-chain
280
280
  * under-coverage panic remains possible if vault state changes between preparation and inclusion.
281
281
  *
282
- * In-kind exits require an exact vault-share allowance for the computed cap. An ERC-2612 permit
283
- * is emitted only to raise an insufficient allowance; an oversized allowance is always reset
284
- * with an onchain approval before the exit.
282
+ * In-kind exits have no on-chain share-price or max-shares bound. A share-price drop before
283
+ * inclusion can burn more shares than quoted when the allowance is unlimited. The SDK requires
284
+ * the computed minimum allowance, and an insufficient allowance is raised by an unlimited
285
+ * approval or ERC-2612 permit.
285
286
  *
286
287
  * @param params - In-kind redemption parameters.
287
288
  * @param params.amount - Penalty-inclusive, asset-denominated amount to exit.
@@ -316,8 +317,8 @@ export interface VaultV2Actions {
316
317
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
317
318
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
318
319
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the supplied permit is not ERC-2612, has
319
- * the wrong asset, owner, or signature encoding, or names another spender, amount, or deadline
320
- * than the prepared cap.
320
+ * the wrong asset, owner, or signature encoding, names another spender or deadline, or
321
+ * signs an amount below the required share allowance.
321
322
  * @example
322
323
  * ```ts
323
324
  * import { isRequirementSignature } from "@morpho-org/morpho-sdk";
@@ -384,12 +385,13 @@ export interface VaultV2Actions {
384
385
  * validate the user's share balance. Per-market penalties and each vault withdrawal round the
385
386
  * share burn up independently, so the exit can burn marginally more shares than `exitAssets` alone
386
387
  * implies; size `exitAssets` a small buffer below `vault.previewRedeem(sharesHeld)` so a
387
- * full-balance exit does not revert for insufficient shares. The approved share allowance this
388
- * handle returns covers a burn at least one `slippageTolerance` step below the price floor
389
- * whenever the floor exceeds one RAY unit and, in any case, at least one share above the burn
390
- * at the floor, so a price within that headroom below the floor reverts on the contract's
391
- * `minSharePriceE27` check rather than on the allowance; a deeper drop can still surface as an
392
- * ERC-20 allowance underflow.
388
+ * full-balance exit does not revert for insufficient shares. Any approval or permit this handle
389
+ * returns is unlimited. The computed share amount is only the smallest existing allowance the
390
+ * SDK accepts without a new requirement: it covers a burn at least one `slippageTolerance` step
391
+ * below the price floor whenever the floor exceeds one RAY unit and, in any case, at least one
392
+ * share above the burn at the floor. A reused allowance just above that minimum can still
393
+ * surface a deeper price drop as an ERC-20 allowance underflow rather than the contract's
394
+ * `minSharePriceE27` check.
393
395
  *
394
396
  * Idle balance, penalty, adapter positions, and market liquidity can drift after the snapshot, so
395
397
  * an on-chain revert remains possible if vault state changes between preparation and inclusion.
@@ -453,8 +455,8 @@ export interface VaultV2Actions {
453
455
  * @throws {MissingContractCodeError} from `getRequirements()` when a fixed bundles or protocol contract has no code at its registered address.
454
456
  * @throws {AmbiguousRequirementSignaturesError} from `buildTx()` when more than one permit signature is supplied.
455
457
  * @throws {UnexpectedRequirementSignatureError} from `buildTx()` when a non-permit signature is supplied.
456
- * @throws {BundlesPermitMismatchError} from `buildTx()` when the permit's spender, amount, or
457
- * deadline differs from this operation. Any handle built from the same inputs accepts the
458
+ * @throws {BundlesPermitMismatchError} from `buildTx()` when the permit's spender or deadline
459
+ * differs from this operation, or its amount is below the required share allowance. Any handle built from the same inputs accepts the
458
460
  * permit; a permit whose nonce was consumed is skipped onchain and the live allowance applies.
459
461
  * @throws {BundlesPermitMismatchError} from `buildTx()` when the requirement has the wrong permit kind, asset, or signature encoding.
460
462
  * @example
@@ -7,7 +7,6 @@ import { getBundlesReferralFeeAssets, normalizeBundlesCommonParams, resolveBundl
7
7
  import { encodeErc20Approval, encodeVaultSharesPermit, vaultV2Deposit, vaultV2ForceRedeem, vaultV2ForceWithdraw, vaultV2InKindRedeem, vaultV2Redeem, vaultV2Withdraw, } from "../../actions/index.js";
8
8
  import { validateClientChainId } from "../../actions/requirements/validateClientChainId.js";
9
9
  import { computeMinForceWithdrawSharePrice, computeVaultMaxShareAllowance, computeVaultMaxSharePrice, computeVaultV2ForceWithdrawFeeSharesMinted, computeVaultV2ForceWithdrawMinSharesBurnt, computeVaultV2ForceWithdrawPlan, computeVaultV2ForceWithdrawSharesBurnt, MAX_SLIPPAGE_TOLERANCE, resolveVaultV2ForceWithdrawEligibility, validateChainId, validateSlippageTolerance, } from "../../helpers/index.js";
10
- import { computeVaultShareAllowanceCeiling } from "../../helpers/slippage.js";
11
10
  import { validateDeadline, validateNativeVaultAsset, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
12
11
  import { AdapterNotPartOfVaultError, EmptyMarketParamsListError, ExpiredDeadlineError, InKindRedeemCoverageError, InKindRedeemZeroDeallocationError, InputExceedsMaxError, InsufficientBlueBalanceForInKindRedeemError, NonPositiveInputError, VaultAddressMismatchError, VaultV2ForceWithdrawCoverageError, VaultV2ForceWithdrawFeeSharesExceedBurnError, VaultV2ForceWithdrawSharePriceBelowFloorError, VaultV2ForceWithdrawZeroSharePriceError, VaultV2ForceWithdrawZeroWithdrawalError, VaultV2SingleAdapterRequiredError, VaultV2UndecodableLiquidityDataError, VaultV2UnsupportedExitAdapterError, VaultV2UnsupportedLiquidityAdapterError, } from "../../types/index.js";
13
12
  import { assertRegistryTargetsHaveCode } from "../requirements/assertContractCode.js";
@@ -181,28 +180,19 @@ export class MorphoVaultV2 {
181
180
  assets: amount,
182
181
  slippageTolerance,
183
182
  });
184
- const maxShareAllowance = computeVaultShareAllowanceCeiling({
185
- requiredShareAllowance,
186
- slippageTolerance,
187
- });
188
183
  return Object.freeze({
189
184
  getRequirements: async () => {
190
185
  const now = Time.timestamp();
191
186
  if (deadline <= now)
192
187
  throw new ExpiredDeadlineError(deadline, now);
193
188
  await this.assertWriteTargets(["bundles.vaultBundlesV1"]);
194
- // Re-read the live share allowance on every call instead of caching the resolved
195
- // requirements: the allowance is the sole cap on the burn, so a caller that executed the
196
- // returned approval must see it satisfied on the next call, and an allowance revoked or
197
- // raised afterwards must resurface as an outstanding requirement. The cap derived from
198
- // `vaultData` is pinned at handle creation, so re-reading cannot move it.
189
+ // Re-read the live share allowance on every call instead of caching the resolved requirements.
199
190
  return getVaultBundlesSharesRequirements(this.client.viemClient, {
200
191
  vaultData,
201
192
  version: "vaultV2",
202
193
  owner: userAddress,
203
194
  chainId: this.chainId,
204
195
  requiredShareAllowance,
205
- maxShareAllowance,
206
196
  deadline,
207
197
  supportSignature: this.client.options.supportSignature,
208
198
  now,
@@ -212,7 +202,6 @@ export class MorphoVaultV2 {
212
202
  const permit = selectBundlesSharesPermitSignature(signatures, {
213
203
  spender,
214
204
  amount: requiredShareAllowance,
215
- maxAmount: maxShareAllowance,
216
205
  deadline,
217
206
  });
218
207
  return vaultV2Withdraw({
@@ -421,14 +410,9 @@ export class MorphoVaultV2 {
421
410
  required: peak,
422
411
  });
423
412
  }
424
- // In-kind withdrawals carry no onchain share cap, so the allowance itself is the cap. A
425
- // larger leftover allowance would let a share-price loss burn past `requiredShareAllowance`.
426
- if (allowance === requiredShareAllowance)
413
+ if (allowance >= requiredShareAllowance)
427
414
  return [];
428
- // A lowering permit can be skipped after its nonce is consumed, so oversized allowances
429
- // must be reset with an onchain approval.
430
- if (allowance < requiredShareAllowance &&
431
- this.client.options.supportSignature) {
415
+ if (this.client.options.supportSignature) {
432
416
  return [
433
417
  encodeVaultSharesPermit({
434
418
  vault: vaultData,
@@ -437,7 +421,6 @@ export class MorphoVaultV2 {
437
421
  owner: userAddress,
438
422
  chainId: this.chainId,
439
423
  nonce,
440
- amount: requiredShareAllowance,
441
424
  deadline,
442
425
  }),
443
426
  ];
@@ -446,7 +429,7 @@ export class MorphoVaultV2 {
446
429
  encodeErc20Approval({
447
430
  token: this.vault,
448
431
  spender: vaultExitBundlesV1,
449
- amount: requiredShareAllowance,
432
+ amount: maxUint256,
450
433
  chainId: this.chainId,
451
434
  }),
452
435
  ];
@@ -630,17 +613,9 @@ export class MorphoVaultV2 {
630
613
  // with no real protection. Its two sibling `computeMin*SharePrice` helpers cap nothing either —
631
614
  // only the `computeMax*` ones do, where capping relaxes an upper bound and is safe.
632
615
  validateUint256Field("minSharePriceE27", minSharePriceE27);
633
- // The allowance is only a spend cap, never the price protection: the bundle checks
634
- // `minSharePriceE27` after its last withdrawal, so an allowance sized exactly to the floor
635
- // underflows `_spendAllowance` (panic 0x11) on a below-floor price before that check runs. Size
636
- // it for a price at least one tolerance step below the floor so the miss surfaces as the
637
- // bundle's own revert instead, and, in any case, for at least one share above the at-floor
638
- // burn — a burn of `atFloor + 1` shares prices strictly below the floor since
639
- // `atFloor >= exitAssets * RAY / floor`. The `minSharePriceE27 - 1` branch keeps the
640
- // denominator strictly below the floor whenever the floor exceeds 1, so even
641
- // `slippageTolerance: 0n` leaves price-space headroom; a deeper drop still exhausts the
642
- // allowance first. Add the fee shares the first withdrawal mints since the burn measured
643
- // on-chain includes them. Saturated at `maxUint256` as an ABI-slot guard.
616
+ // This is the minimum allowance needed for successful execution, not an exit cap: the bundle
617
+ // independently rejects a realized share price below `minSharePriceE27`. Include the fee
618
+ // shares minted by the first withdrawal and enough headroom for the configured tolerance.
644
619
  const allowanceSharePriceE27 = MathLib.max(MathLib.min(MathLib.mulDivDown(minSharePriceE27, MathLib.WAD - slippageTolerance, MathLib.WAD), minSharePriceE27 - 1n), 1n);
645
620
  const requiredShareAllowance = MathLib.min(MathLib.max(MathLib.mulDivUp(exitAssets, MathLib.RAY, allowanceSharePriceE27), MathLib.mulDivUp(exitAssets, MathLib.RAY, minSharePriceE27) + 1n) + feeSharesProjected, maxUint256);
646
621
  const vaultExitBundlesV1 = getChainAddress(this.chainId, "bundles.vaultExitBundlesV1");
@@ -681,7 +656,6 @@ export class MorphoVaultV2 {
681
656
  owner: userAddress,
682
657
  chainId: this.chainId,
683
658
  nonce,
684
- amount: requiredShareAllowance,
685
659
  deadline,
686
660
  });
687
661
  return [requirement];
@@ -690,7 +664,7 @@ export class MorphoVaultV2 {
690
664
  encodeErc20Approval({
691
665
  token: this.vault,
692
666
  spender: vaultExitBundlesV1,
693
- amount: requiredShareAllowance,
667
+ amount: maxUint256,
694
668
  chainId: this.chainId,
695
669
  }),
696
670
  ];
@@ -0,0 +1,48 @@
1
+ import { type MarketInput } from "@morpho-org/midnight-sdk";
2
+ import { type Abi, type ContractFunctionName, type EncodeFunctionDataParameters, type EncodeFunctionDataReturnType } from "viem";
3
+ /**
4
+ * `encodeFunctionData` for Midnight builders that reports invalid inputs as a typed SDK error.
5
+ *
6
+ * @internal
7
+ * @param parameters - viem `encodeFunctionData` parameters.
8
+ * @returns The encoded calldata.
9
+ * @throws {MidnightCalldataEncodingError} when viem cannot encode an argument.
10
+ * @example
11
+ * ```ts
12
+ * import { midnightAbi } from "@morpho-org/midnight-sdk";
13
+ *
14
+ * const data = encodeMidnightCalldata({
15
+ * abi: midnightAbi,
16
+ * functionName: "setIsAuthorized",
17
+ * args: [operator, true, owner],
18
+ * });
19
+ * ```
20
+ */
21
+ export declare function encodeMidnightCalldata<const abi extends Abi | readonly unknown[], functionName extends ContractFunctionName<abi> | undefined = undefined>(parameters: EncodeFunctionDataParameters<abi, functionName>): EncodeFunctionDataReturnType;
22
+ /**
23
+ * Runs a Midnight ABI encoding step and reports a viem encoding failure as a typed SDK error.
24
+ *
25
+ * @internal
26
+ * @param name - Name of the encoded value, reported as the error's `input`.
27
+ * @param encode - Encoding step, such as hashing a market or an offer tree.
28
+ * @returns The encoding step's result.
29
+ * @throws {MidnightCalldataEncodingError} when `encode` throws a viem error.
30
+ * @example
31
+ * ```ts
32
+ * const tree = wrapMidnightEncoding("offers", () => Tree.from(offers));
33
+ * ```
34
+ */
35
+ export declare function wrapMidnightEncoding<T>(name: string, encode: () => T): T;
36
+ /**
37
+ * `MarketUtils.toId` for Midnight builders that reports an unencodable market as a typed SDK error.
38
+ *
39
+ * @internal
40
+ * @param market - Midnight market whose struct is ABI-encoded and hashed.
41
+ * @returns The market id.
42
+ * @throws {MidnightCalldataEncodingError} when viem cannot encode a market field.
43
+ * @example
44
+ * ```ts
45
+ * const marketId = encodeMidnightMarketId(market);
46
+ * ```
47
+ */
48
+ export declare function encodeMidnightMarketId(market: MarketInput): `0x${string}`;
@@ -0,0 +1,69 @@
1
+ import { MarketUtils } from "@morpho-org/midnight-sdk";
2
+ import { BaseError, encodeFunctionData, } from "viem";
3
+ import { MidnightCalldataEncodingError } from "../types/index.js";
4
+ /**
5
+ * `encodeFunctionData` for Midnight builders that reports invalid inputs as a typed SDK error.
6
+ *
7
+ * @internal
8
+ * @param parameters - viem `encodeFunctionData` parameters.
9
+ * @returns The encoded calldata.
10
+ * @throws {MidnightCalldataEncodingError} when viem cannot encode an argument.
11
+ * @example
12
+ * ```ts
13
+ * import { midnightAbi } from "@morpho-org/midnight-sdk";
14
+ *
15
+ * const data = encodeMidnightCalldata({
16
+ * abi: midnightAbi,
17
+ * functionName: "setIsAuthorized",
18
+ * args: [operator, true, owner],
19
+ * });
20
+ * ```
21
+ */
22
+ export function encodeMidnightCalldata(parameters) {
23
+ try {
24
+ return encodeFunctionData(parameters);
25
+ }
26
+ catch (error) {
27
+ if (!(error instanceof BaseError))
28
+ throw error;
29
+ throw new MidnightCalldataEncodingError(String(parameters.functionName), error);
30
+ }
31
+ }
32
+ /**
33
+ * Runs a Midnight ABI encoding step and reports a viem encoding failure as a typed SDK error.
34
+ *
35
+ * @internal
36
+ * @param name - Name of the encoded value, reported as the error's `input`.
37
+ * @param encode - Encoding step, such as hashing a market or an offer tree.
38
+ * @returns The encoding step's result.
39
+ * @throws {MidnightCalldataEncodingError} when `encode` throws a viem error.
40
+ * @example
41
+ * ```ts
42
+ * const tree = wrapMidnightEncoding("offers", () => Tree.from(offers));
43
+ * ```
44
+ */
45
+ export function wrapMidnightEncoding(name, encode) {
46
+ try {
47
+ return encode();
48
+ }
49
+ catch (error) {
50
+ if (!(error instanceof BaseError))
51
+ throw error;
52
+ throw new MidnightCalldataEncodingError(name, error);
53
+ }
54
+ }
55
+ /**
56
+ * `MarketUtils.toId` for Midnight builders that reports an unencodable market as a typed SDK error.
57
+ *
58
+ * @internal
59
+ * @param market - Midnight market whose struct is ABI-encoded and hashed.
60
+ * @returns The market id.
61
+ * @throws {MidnightCalldataEncodingError} when viem cannot encode a market field.
62
+ * @example
63
+ * ```ts
64
+ * const marketId = encodeMidnightMarketId(market);
65
+ * ```
66
+ */
67
+ export function encodeMidnightMarketId(market) {
68
+ return wrapMidnightEncoding("marketId", () => MarketUtils.toId(market));
69
+ }
@@ -92,19 +92,22 @@ export declare const computeVaultMaxSharePrice: (params: {
92
92
  readonly slippageTolerance: bigint;
93
93
  }) => bigint;
94
94
  /**
95
- * Computes the exact vault-share authorization cap for an asset-denominated exit.
95
+ * Computes the minimum vault-share allowance required for an asset-denominated exit.
96
96
  *
97
- * The cap covers both the current and deadline-accrued preview. Vault V2 and MetaMorpho 1.0 divide
98
- * by `1 - slippageTolerance`, rounding up, to cover a share-price decline before inclusion;
97
+ * The requirement covers both the current and deadline-accrued preview. Vault V2 and MetaMorpho 1.0
98
+ * divide by `1 - slippageTolerance`, rounding up, to cover a share-price decline before inclusion;
99
99
  * MetaMorpho 1.1's `lostAssets` clamp keeps that preview upper-bounded without widening it.
100
100
  *
101
+ * "Max" refers to the most shares the exit is expected to burn at the tolerated price, which is
102
+ * the minimum allowance the SDK requires.
103
+ *
101
104
  * @param params - Vault snapshot, execution deadline, asset amount, and WAD-scaled slippage.
102
105
  * @param params.vaultData - Hydrated Vault V1 `AccrualVault` or Vault V2 `AccrualVaultV2` snapshot.
103
106
  * @param params.deadline - Bundle execution deadline as a Unix timestamp in seconds, used for accrual.
104
107
  * @param params.assets - Assets withdrawn from the vault, in the underlying token's smallest unit.
105
108
  * @param params.slippageTolerance - Accepted share-price decline as a WAD-scaled fraction (`1e18` = 100%).
106
- * @returns The maximum shares the prepared operation may burn.
107
- * @throws {NonPositiveInputError} when `assets` or the computed share cap is not positive.
109
+ * @returns The minimum share allowance required by the prepared exit.
110
+ * @throws {NonPositiveInputError} when `assets` or the computed required share amount is not positive.
108
111
  * @throws {NegativeInputError} when `slippageTolerance` is negative.
109
112
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
110
113
  * @example
@@ -126,7 +129,7 @@ export declare const computeVaultMaxSharePrice: (params: {
126
129
  * assets: 1_000_000n,
127
130
  * slippageTolerance: 500_000_000_000_000n,
128
131
  * });
129
- * // shares is the exact allowance or permit value for the prepared exit.
132
+ * // shares is the minimum required allowance for the prepared exit.
130
133
  * ```
131
134
  */
132
135
  export declare const computeVaultMaxShareAllowance: (params: {
@@ -135,22 +138,3 @@ export declare const computeVaultMaxShareAllowance: (params: {
135
138
  readonly assets: bigint;
136
139
  readonly slippageTolerance: bigint;
137
140
  }) => bigint;
138
- /**
139
- * Computes the largest live share allowance a re-prepared asset-mode exit accepts without a reset.
140
- *
141
- * A Safe approval can execute after the caller re-prepared the exit from a fresher snapshot, whose
142
- * cap is slightly lower. Allowances in `[requiredShareAllowance, ceiling]` are kept, so the burn may
143
- * exceed the current cap by at most one more slippage tolerance.
144
- *
145
- * @internal
146
- *
147
- * @param params.requiredShareAllowance - Cap from {@link computeVaultMaxShareAllowance}.
148
- * @param params.slippageTolerance - WAD-scaled slippage used to derive that cap.
149
- * @returns `requiredShareAllowance / (1 - slippageTolerance)`, rounded down.
150
- * @throws {NegativeInputError} when `slippageTolerance` is negative.
151
- * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
152
- */
153
- export declare const computeVaultShareAllowanceCeiling: (params: {
154
- readonly requiredShareAllowance: bigint;
155
- readonly slippageTolerance: bigint;
156
- }) => bigint;
@@ -129,19 +129,22 @@ export const computeVaultMaxSharePrice = (params) => {
129
129
  return MathLib.min(MathLib.mulDivUp(params.assets, MathLib.wToRay(MathLib.WAD + params.slippageTolerance), shares), MAX_ABSOLUTE_SHARE_PRICE);
130
130
  };
131
131
  /**
132
- * Computes the exact vault-share authorization cap for an asset-denominated exit.
132
+ * Computes the minimum vault-share allowance required for an asset-denominated exit.
133
133
  *
134
- * The cap covers both the current and deadline-accrued preview. Vault V2 and MetaMorpho 1.0 divide
135
- * by `1 - slippageTolerance`, rounding up, to cover a share-price decline before inclusion;
134
+ * The requirement covers both the current and deadline-accrued preview. Vault V2 and MetaMorpho 1.0
135
+ * divide by `1 - slippageTolerance`, rounding up, to cover a share-price decline before inclusion;
136
136
  * MetaMorpho 1.1's `lostAssets` clamp keeps that preview upper-bounded without widening it.
137
137
  *
138
+ * "Max" refers to the most shares the exit is expected to burn at the tolerated price, which is
139
+ * the minimum allowance the SDK requires.
140
+ *
138
141
  * @param params - Vault snapshot, execution deadline, asset amount, and WAD-scaled slippage.
139
142
  * @param params.vaultData - Hydrated Vault V1 `AccrualVault` or Vault V2 `AccrualVaultV2` snapshot.
140
143
  * @param params.deadline - Bundle execution deadline as a Unix timestamp in seconds, used for accrual.
141
144
  * @param params.assets - Assets withdrawn from the vault, in the underlying token's smallest unit.
142
145
  * @param params.slippageTolerance - Accepted share-price decline as a WAD-scaled fraction (`1e18` = 100%).
143
- * @returns The maximum shares the prepared operation may burn.
144
- * @throws {NonPositiveInputError} when `assets` or the computed share cap is not positive.
146
+ * @returns The minimum share allowance required by the prepared exit.
147
+ * @throws {NonPositiveInputError} when `assets` or the computed required share amount is not positive.
145
148
  * @throws {NegativeInputError} when `slippageTolerance` is negative.
146
149
  * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
147
150
  * @example
@@ -163,7 +166,7 @@ export const computeVaultMaxSharePrice = (params) => {
163
166
  * assets: 1_000_000n,
164
167
  * slippageTolerance: 500_000_000_000_000n,
165
168
  * });
166
- * // shares is the exact allowance or permit value for the prepared exit.
169
+ * // shares is the minimum required allowance for the prepared exit.
167
170
  * ```
168
171
  */
169
172
  export const computeVaultMaxShareAllowance = (params) => {
@@ -186,22 +189,3 @@ export const computeVaultMaxShareAllowance = (params) => {
186
189
  ? MathLib.wDivUp(previewedShares, MathLib.WAD - params.slippageTolerance)
187
190
  : previewedShares;
188
191
  };
189
- /**
190
- * Computes the largest live share allowance a re-prepared asset-mode exit accepts without a reset.
191
- *
192
- * A Safe approval can execute after the caller re-prepared the exit from a fresher snapshot, whose
193
- * cap is slightly lower. Allowances in `[requiredShareAllowance, ceiling]` are kept, so the burn may
194
- * exceed the current cap by at most one more slippage tolerance.
195
- *
196
- * @internal
197
- *
198
- * @param params.requiredShareAllowance - Cap from {@link computeVaultMaxShareAllowance}.
199
- * @param params.slippageTolerance - WAD-scaled slippage used to derive that cap.
200
- * @returns `requiredShareAllowance / (1 - slippageTolerance)`, rounded down.
201
- * @throws {NegativeInputError} when `slippageTolerance` is negative.
202
- * @throws {ExcessiveSlippageToleranceError} when `slippageTolerance` exceeds the SDK maximum.
203
- */
204
- export const computeVaultShareAllowanceCeiling = (params) => {
205
- validateSlippageTolerance(params.slippageTolerance);
206
- return MathLib.wDivDown(params.requiredShareAllowance, MathLib.WAD - params.slippageTolerance);
207
- };
@@ -284,6 +284,7 @@ export declare const validateNativeAsset: (chainId: number, asset: Address) => v
284
284
  * @returns The transaction `value` and the `wrappedNative` contract argument.
285
285
  * @throws {NegativeInputError} when `nativeAmount` is negative.
286
286
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
287
+ * @throws {MidnightCalldataEncodingError} when a pulled `token` is not a 20-byte hex address.
287
288
  * @throws {NativeAmountOnNonWNativeAssetError} when pulls are non-empty and none use wNative.
288
289
  * @throws {InputExceedsMaxError} when `nativeAmount` exceeds the maximum wNative pull, including
289
290
  * when the call pulls none.
@@ -4,6 +4,7 @@ import { isDefined } from "@morpho-org/morpho-ts";
4
4
  import { isAddress, isAddressEqual, maxUint128, maxUint256, zeroAddress, } from "viem";
5
5
  import { AccrualPositionUserMismatchError, AddressMismatchError, BorrowExceedsSafeLtvError, ChainIdMismatchError, ChainWNativeMissingError, ExcessiveSlippageToleranceError, InconsistentReallocationPenaltyError, InputExceedsMaxError, InvalidReallocationAddressError, InvalidReallocationSourceTypeError, InvalidVaultV2BlueReallocationShapeError, MarketIdMismatchError, MissingClientPropertyError, MissingMarketPriceError, NativeAmountOnNonWNativeAssetError, NativeAmountOnNonWNativeVaultError, NegativeInputError, NonPositiveInputError, ReallocationWithdrawalOnTargetMarketError, ReferralFeePctExceededError, ReferralFeeRecipientMissingError, RepayExceedsDebtError, RepaySharesExceedDebtError, WithdrawExceedsCollateralError, WithdrawExceedsSupplyError, WithdrawMakesPositionUnhealthyError, WithdrawSharesExceedSupplyError, } from "../types/index.js";
6
6
  import { DEFAULT_LLTV_BUFFER, MAX_REALLOCATION_PENALTY, MAX_SLIPPAGE_TOLERANCE, } from "./constant.js";
7
+ import { validateMidnightAddress } from "./validateMidnightAccount.js";
7
8
  /** @internal */
8
9
  const compareMarketIds = (idA, idB) => {
9
10
  const normalizedIdA = idA.toLowerCase();
@@ -366,6 +367,7 @@ export const validateNativeAsset = (chainId, asset) => {
366
367
  * @returns The transaction `value` and the `wrappedNative` contract argument.
367
368
  * @throws {NegativeInputError} when `nativeAmount` is negative.
368
369
  * @throws {ChainWNativeMissingError} when wNative is not configured for the chain.
370
+ * @throws {MidnightCalldataEncodingError} when a pulled `token` is not a 20-byte hex address.
369
371
  * @throws {NativeAmountOnNonWNativeAssetError} when pulls are non-empty and none use wNative.
370
372
  * @throws {InputExceedsMaxError} when `nativeAmount` exceeds the maximum wNative pull, including
371
373
  * when the call pulls none.
@@ -396,6 +398,9 @@ export const validateMidnightNativeAmount = (params) => {
396
398
  if (!isDefined(wNative)) {
397
399
  throw new ChainWNativeMissingError(chainId);
398
400
  }
401
+ // Reject a malformed address before viem compares it with wNative.
402
+ for (const pull of pulls)
403
+ validateMidnightAddress("token", pull.token);
399
404
  const wNativePulled = pulls.reduce((total, pull) => isAddressEqual(pull.token, wNative) ? total + pull.assets : total, 0n);
400
405
  const firstPull = pulls[0];
401
406
  if (firstPull && !pulls.some((pull) => isAddressEqual(pull.token, wNative))) {
@@ -0,0 +1,34 @@
1
+ import { type Address } from "viem";
2
+ import { MidnightZeroAccountError } from "../types/index.js";
3
+ /**
4
+ * Rejects the zero address as the account a Midnight flow prepares or encodes for.
5
+ *
6
+ * @internal
7
+ * @param field - Account field name reported by the error.
8
+ * @param account - Account to validate.
9
+ * @returns Nothing; returns normally when `account` is a well-formed non-zero address.
10
+ * @throws {MidnightCalldataEncodingError} when `account` is not a 20-byte hex address with a valid
11
+ * checksum when mixed-case.
12
+ * @throws {MidnightZeroAccountError} when `account` is the zero address.
13
+ * @example
14
+ * ```ts
15
+ * validateMidnightAccount("accountAddress", "0x0000000000000000000000000000000000000001");
16
+ * ```
17
+ */
18
+ export declare function validateMidnightAccount(field: MidnightZeroAccountError["field"], account: Address): void;
19
+ /**
20
+ * Rejects a malformed address before a Midnight builder compares or encodes it, so callers get the
21
+ * typed encoding error instead of viem's `InvalidAddressError`.
22
+ *
23
+ * @internal
24
+ * @param field - Input name reported as the error's `input`, such as `"receiver"`.
25
+ * @param address - Address to validate.
26
+ * @returns Nothing; returns normally for a 20-byte hex address with a valid checksum when mixed-case.
27
+ * @throws {MidnightCalldataEncodingError} when `address` is not a 20-byte hex address with a valid
28
+ * checksum when mixed-case.
29
+ * @example
30
+ * ```ts
31
+ * validateMidnightAddress("receiver", "0x0000000000000000000000000000000000000001");
32
+ * ```
33
+ */
34
+ export declare function validateMidnightAddress(field: string, address: Address): void;
@@ -0,0 +1,43 @@
1
+ import { InvalidAddressError, isAddress, isAddressEqual, zeroAddress, } from "viem";
2
+ import { MidnightCalldataEncodingError, MidnightZeroAccountError, } from "../types/index.js";
3
+ /**
4
+ * Rejects the zero address as the account a Midnight flow prepares or encodes for.
5
+ *
6
+ * @internal
7
+ * @param field - Account field name reported by the error.
8
+ * @param account - Account to validate.
9
+ * @returns Nothing; returns normally when `account` is a well-formed non-zero address.
10
+ * @throws {MidnightCalldataEncodingError} when `account` is not a 20-byte hex address with a valid
11
+ * checksum when mixed-case.
12
+ * @throws {MidnightZeroAccountError} when `account` is the zero address.
13
+ * @example
14
+ * ```ts
15
+ * validateMidnightAccount("accountAddress", "0x0000000000000000000000000000000000000001");
16
+ * ```
17
+ */
18
+ export function validateMidnightAccount(field, account) {
19
+ validateMidnightAddress(field, account);
20
+ if (isAddressEqual(account, zeroAddress)) {
21
+ throw new MidnightZeroAccountError(field);
22
+ }
23
+ }
24
+ /**
25
+ * Rejects a malformed address before a Midnight builder compares or encodes it, so callers get the
26
+ * typed encoding error instead of viem's `InvalidAddressError`.
27
+ *
28
+ * @internal
29
+ * @param field - Input name reported as the error's `input`, such as `"receiver"`.
30
+ * @param address - Address to validate.
31
+ * @returns Nothing; returns normally for a 20-byte hex address with a valid checksum when mixed-case.
32
+ * @throws {MidnightCalldataEncodingError} when `address` is not a 20-byte hex address with a valid
33
+ * checksum when mixed-case.
34
+ * @example
35
+ * ```ts
36
+ * validateMidnightAddress("receiver", "0x0000000000000000000000000000000000000001");
37
+ * ```
38
+ */
39
+ export function validateMidnightAddress(field, address) {
40
+ if (!isAddress(address)) {
41
+ throw new MidnightCalldataEncodingError(field, new InvalidAddressError({ address }));
42
+ }
43
+ }
@@ -6,6 +6,7 @@ import { type Address } from "viem";
6
6
  * @param params.chainId - Chain id used to resolve supported Midnight operators.
7
7
  * @param params.authorized - Operator address receiving authorization.
8
8
  * @returns Nothing after the operator matches MidnightBundlesV2.
9
+ * @throws {MidnightCalldataEncodingError} when `authorized` is not a 20-byte hex address.
9
10
  * @throws {UnsupportedMidnightAuthorizationTargetError} when `authorized` is not a supported operator.
10
11
  * @internal
11
12
  */