@morpho-org/morpho-sdk 7.1.0-next.1 → 8.2.0-next.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 (193) hide show
  1. package/MIGRATION-v7-to-v8.md +290 -0
  2. package/README.md +11 -6
  3. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  4. package/lib/cjs/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  5. package/lib/cjs/actions/midnight/cancelAndMake.d.ts +17 -71
  6. package/lib/cjs/actions/midnight/cancelAndMake.js +41 -29
  7. package/lib/cjs/actions/midnight/redeem.d.ts +8 -1
  8. package/lib/cjs/actions/midnight/redeem.js +18 -1
  9. package/lib/cjs/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  10. package/lib/cjs/actions/midnight/repayWithdrawCollateral.js +24 -2
  11. package/lib/cjs/actions/midnight/supplyCollateral.d.ts +1 -0
  12. package/lib/cjs/actions/midnight/supplyCollateral.js +3 -0
  13. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  14. package/lib/cjs/actions/midnight/supplyCollateralTakeBorrow.js +49 -14
  15. package/lib/cjs/actions/midnight/takeBorrow.d.ts +18 -5
  16. package/lib/cjs/actions/midnight/takeBorrow.js +44 -12
  17. package/lib/cjs/actions/midnight/takeLend.d.ts +10 -5
  18. package/lib/cjs/actions/midnight/takeLend.js +27 -9
  19. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  20. package/lib/cjs/actions/midnight/takeRepayWithdrawCollateral.js +51 -27
  21. package/lib/cjs/actions/midnight/takeWithdraw.d.ts +14 -5
  22. package/lib/cjs/actions/midnight/takeWithdraw.js +40 -9
  23. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  24. package/lib/cjs/actions/requirements/blue/getBlueAuthorizationRequirement.js +11 -6
  25. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  26. package/lib/cjs/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  27. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  28. package/lib/cjs/actions/requirements/encode/encodeErc20Permit.js +17 -6
  29. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  30. package/lib/cjs/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  31. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  32. package/lib/cjs/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  33. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  34. package/lib/cjs/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  35. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  36. package/lib/cjs/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  37. package/lib/cjs/actions/requirements/validateClientChainId.d.ts +26 -0
  38. package/lib/cjs/actions/requirements/validateClientChainId.js +34 -0
  39. package/lib/cjs/blue/errors.d.ts +1 -1
  40. package/lib/cjs/blue/errors.js +3 -1
  41. package/lib/cjs/blue/types.d.ts +1 -1
  42. package/lib/cjs/blue/utils.d.ts +1 -1
  43. package/lib/cjs/blue/utils.js +5 -1
  44. package/lib/cjs/entities/blue/blue.d.ts +109 -27
  45. package/lib/cjs/entities/blue/blue.js +103 -28
  46. package/lib/cjs/entities/index.d.ts +1 -1
  47. package/lib/cjs/entities/midnight/deadline.d.ts +15 -0
  48. package/lib/cjs/entities/midnight/deadline.js +24 -0
  49. package/lib/cjs/entities/midnight/midnight.d.ts +427 -72
  50. package/lib/cjs/entities/midnight/midnight.js +864 -186
  51. package/lib/cjs/entities/midnight/publication.d.ts +134 -0
  52. package/lib/cjs/entities/midnight/publication.js +404 -0
  53. package/lib/cjs/entities/midnight/types.d.ts +26 -5
  54. package/lib/cjs/entities/requirements/assertContractCode.d.ts +49 -0
  55. package/lib/cjs/entities/requirements/assertContractCode.js +79 -0
  56. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  57. package/lib/cjs/entities/requirements/getBundlesTokenRequirements.js +45 -18
  58. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  59. package/lib/cjs/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  60. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  61. package/lib/cjs/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  62. package/lib/cjs/entities/vaultV1/vaultV1.d.ts +63 -11
  63. package/lib/cjs/entities/vaultV1/vaultV1.js +52 -15
  64. package/lib/cjs/entities/vaultV2/vaultV2.d.ts +54 -12
  65. package/lib/cjs/entities/vaultV2/vaultV2.js +52 -15
  66. package/lib/cjs/entities/vaultV2BlueReallocationData.d.ts +12 -6
  67. package/lib/cjs/entities/vaultV2BlueReallocationData.js +42 -14
  68. package/lib/cjs/errors.d.ts +1 -1
  69. package/lib/cjs/errors.js +4 -2
  70. package/lib/cjs/helpers/constant.d.ts +5 -0
  71. package/lib/cjs/helpers/constant.js +6 -1
  72. package/lib/cjs/helpers/index.d.ts +1 -1
  73. package/lib/cjs/helpers/index.js +2 -1
  74. package/lib/cjs/helpers/validate.d.ts +163 -8
  75. package/lib/cjs/helpers/validate.js +179 -8
  76. package/lib/cjs/helpers/validateMidnightBounds.d.ts +47 -0
  77. package/lib/cjs/helpers/validateMidnightBounds.js +79 -0
  78. package/lib/cjs/helpers/validateMidnightPublication.d.ts +12 -0
  79. package/lib/cjs/helpers/validateMidnightPublication.js +144 -0
  80. package/lib/cjs/helpers/validateMidnightReceiver.d.ts +29 -0
  81. package/lib/cjs/helpers/validateMidnightReceiver.js +84 -0
  82. package/lib/cjs/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  83. package/lib/cjs/helpers/validateMidnightTakeFeasibility.js +231 -0
  84. package/lib/cjs/index.d.ts +1 -0
  85. package/lib/cjs/index.js +3 -0
  86. package/lib/cjs/types/error.d.ts +197 -4
  87. package/lib/cjs/types/error.js +265 -5
  88. package/lib/cjs/types/index.d.ts +1 -0
  89. package/lib/cjs/types/index.js +1 -0
  90. package/lib/cjs/types/midnightCancelAndMake.d.ts +70 -0
  91. package/lib/cjs/types/midnightCancelAndMake.js +2 -0
  92. package/lib/cjs/types/midnightPublicationError.d.ts +332 -0
  93. package/lib/cjs/types/midnightPublicationError.js +376 -0
  94. package/lib/cjs/types/sharedLiquidity.d.ts +12 -7
  95. package/lib/cjs/types.d.ts +1 -1
  96. package/lib/cjs/utils.d.ts +2 -1
  97. package/lib/cjs/utils.js +8 -2
  98. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.d.ts +2 -0
  99. package/lib/esm/actions/bundles/resolveBundlesTokenRequirements.js +2 -0
  100. package/lib/esm/actions/midnight/cancelAndMake.d.ts +17 -71
  101. package/lib/esm/actions/midnight/cancelAndMake.js +42 -30
  102. package/lib/esm/actions/midnight/redeem.d.ts +8 -1
  103. package/lib/esm/actions/midnight/redeem.js +18 -1
  104. package/lib/esm/actions/midnight/repayWithdrawCollateral.d.ts +19 -3
  105. package/lib/esm/actions/midnight/repayWithdrawCollateral.js +24 -2
  106. package/lib/esm/actions/midnight/supplyCollateral.d.ts +1 -0
  107. package/lib/esm/actions/midnight/supplyCollateral.js +3 -0
  108. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.d.ts +21 -6
  109. package/lib/esm/actions/midnight/supplyCollateralTakeBorrow.js +52 -17
  110. package/lib/esm/actions/midnight/takeBorrow.d.ts +18 -5
  111. package/lib/esm/actions/midnight/takeBorrow.js +47 -15
  112. package/lib/esm/actions/midnight/takeLend.d.ts +10 -5
  113. package/lib/esm/actions/midnight/takeLend.js +27 -9
  114. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.d.ts +22 -7
  115. package/lib/esm/actions/midnight/takeRepayWithdrawCollateral.js +52 -28
  116. package/lib/esm/actions/midnight/takeWithdraw.d.ts +14 -5
  117. package/lib/esm/actions/midnight/takeWithdraw.js +41 -10
  118. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.d.ts +6 -2
  119. package/lib/esm/actions/requirements/blue/getBlueAuthorizationRequirement.js +13 -8
  120. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.d.ts +3 -0
  121. package/lib/esm/actions/requirements/encode/encodeBlueSignatureAuthorization.js +2 -1
  122. package/lib/esm/actions/requirements/encode/encodeErc20Permit.d.ts +13 -2
  123. package/lib/esm/actions/requirements/encode/encodeErc20Permit.js +17 -6
  124. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.d.ts +3 -0
  125. package/lib/esm/actions/requirements/encode/encodeErc20Permit2SignatureTransfer.js +2 -1
  126. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.d.ts +5 -0
  127. package/lib/esm/actions/requirements/encode/encodeVaultSharesPermit.js +4 -1
  128. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.d.ts +3 -1
  129. package/lib/esm/actions/requirements/midnight/getMidnightApprovalRequirements.js +5 -1
  130. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.d.ts +3 -1
  131. package/lib/esm/actions/requirements/midnight/getMidnightAuthorizationRequirement.js +5 -1
  132. package/lib/esm/actions/requirements/validateClientChainId.d.ts +26 -0
  133. package/lib/esm/actions/requirements/validateClientChainId.js +30 -0
  134. package/lib/esm/blue/errors.d.ts +1 -1
  135. package/lib/esm/blue/errors.js +1 -1
  136. package/lib/esm/blue/types.d.ts +1 -1
  137. package/lib/esm/blue/utils.d.ts +1 -1
  138. package/lib/esm/blue/utils.js +1 -1
  139. package/lib/esm/entities/blue/blue.d.ts +109 -27
  140. package/lib/esm/entities/blue/blue.js +104 -29
  141. package/lib/esm/entities/index.d.ts +1 -1
  142. package/lib/esm/entities/midnight/deadline.d.ts +15 -0
  143. package/lib/esm/entities/midnight/deadline.js +20 -0
  144. package/lib/esm/entities/midnight/midnight.d.ts +427 -72
  145. package/lib/esm/entities/midnight/midnight.js +865 -187
  146. package/lib/esm/entities/midnight/publication.d.ts +134 -0
  147. package/lib/esm/entities/midnight/publication.js +397 -0
  148. package/lib/esm/entities/midnight/types.d.ts +26 -5
  149. package/lib/esm/entities/requirements/assertContractCode.d.ts +49 -0
  150. package/lib/esm/entities/requirements/assertContractCode.js +74 -0
  151. package/lib/esm/entities/requirements/getBundlesTokenRequirements.d.ts +19 -4
  152. package/lib/esm/entities/requirements/getBundlesTokenRequirements.js +47 -20
  153. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.d.ts +3 -2
  154. package/lib/esm/entities/requirements/getUnusedPermit2Nonce.js +5 -2
  155. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.d.ts +5 -1
  156. package/lib/esm/entities/requirements/getVaultBundlesSharesRequirements.js +8 -2
  157. package/lib/esm/entities/vaultV1/vaultV1.d.ts +63 -11
  158. package/lib/esm/entities/vaultV1/vaultV1.js +53 -16
  159. package/lib/esm/entities/vaultV2/vaultV2.d.ts +54 -12
  160. package/lib/esm/entities/vaultV2/vaultV2.js +53 -16
  161. package/lib/esm/entities/vaultV2BlueReallocationData.d.ts +12 -6
  162. package/lib/esm/entities/vaultV2BlueReallocationData.js +42 -14
  163. package/lib/esm/errors.d.ts +1 -1
  164. package/lib/esm/errors.js +1 -1
  165. package/lib/esm/helpers/constant.d.ts +5 -0
  166. package/lib/esm/helpers/constant.js +5 -0
  167. package/lib/esm/helpers/index.d.ts +1 -1
  168. package/lib/esm/helpers/index.js +1 -1
  169. package/lib/esm/helpers/validate.d.ts +163 -8
  170. package/lib/esm/helpers/validate.js +177 -7
  171. package/lib/esm/helpers/validateMidnightBounds.d.ts +47 -0
  172. package/lib/esm/helpers/validateMidnightBounds.js +72 -0
  173. package/lib/esm/helpers/validateMidnightPublication.d.ts +12 -0
  174. package/lib/esm/helpers/validateMidnightPublication.js +139 -0
  175. package/lib/esm/helpers/validateMidnightReceiver.d.ts +29 -0
  176. package/lib/esm/helpers/validateMidnightReceiver.js +80 -0
  177. package/lib/esm/helpers/validateMidnightTakeFeasibility.d.ts +102 -0
  178. package/lib/esm/helpers/validateMidnightTakeFeasibility.js +226 -0
  179. package/lib/esm/index.d.ts +1 -0
  180. package/lib/esm/index.js +1 -0
  181. package/lib/esm/types/error.d.ts +197 -4
  182. package/lib/esm/types/error.js +253 -2
  183. package/lib/esm/types/index.d.ts +1 -0
  184. package/lib/esm/types/index.js +1 -0
  185. package/lib/esm/types/midnightCancelAndMake.d.ts +70 -0
  186. package/lib/esm/types/midnightCancelAndMake.js +1 -0
  187. package/lib/esm/types/midnightPublicationError.d.ts +332 -0
  188. package/lib/esm/types/midnightPublicationError.js +359 -0
  189. package/lib/esm/types/sharedLiquidity.d.ts +12 -7
  190. package/lib/esm/types.d.ts +1 -1
  191. package/lib/esm/utils.d.ts +2 -1
  192. package/lib/esm/utils.js +2 -1
  193. package/package.json +7 -6
@@ -2,8 +2,11 @@ import { MarketUtils, midnightBundlesV2Abi, } from "@morpho-org/midnight-sdk";
2
2
  import { deepFreeze, getChainAddress } from "@morpho-org/morpho-ts";
3
3
  import { encodeFunctionData, maxUint256, zeroAddress, } from "viem";
4
4
  import { addTransactionMetadata } from "../../helpers/index.js";
5
- import { validateDeadline, validateReferralFee, validateUint256Field, } from "../../helpers/validate.js";
5
+ import { validateDeadline, validateReferralFee, } from "../../helpers/validate.js";
6
+ import { validateMidnightReferralFeeCap, validateMidnightTakeableOfferBounds, validateMidnightUint128Field, } from "../../helpers/validateMidnightBounds.js";
6
7
  import { validateMidnightMarket } from "../../helpers/validateMidnightMarket.js";
8
+ import { validateMidnightReceiver } from "../../helpers/validateMidnightReceiver.js";
9
+ import { validateMidnightSellTargetBounds } from "../../helpers/validateMidnightTakeFeasibility.js";
7
10
  import { validateTakeableOffers } from "../../helpers/validateTakeableOffers.js";
8
11
  import { NonPositiveInputError, UnboundedMidnightTakeInputError, } from "../../types/index.js";
9
12
  const validateParams = (params) => {
@@ -14,6 +17,14 @@ const validateParams = (params) => {
14
17
  takeableOffers: params.takeableOffers,
15
18
  expectedBuy: true,
16
19
  });
20
+ validateMidnightTakeableOfferBounds(params.takeableOffers);
21
+ // Rejects receivers that would strand the withdrawn assets in a contract.
22
+ validateMidnightReceiver({
23
+ chainId: params.chainId,
24
+ market: params.market,
25
+ field: "receiver",
26
+ receiver: params.receiver,
27
+ });
17
28
  const { target } = params;
18
29
  if (target.type === "assets") {
19
30
  if (target.assets <= 0n) {
@@ -25,8 +36,8 @@ const validateParams = (params) => {
25
36
  if (target.maxUnits <= 0n) {
26
37
  throw new NonPositiveInputError("target.maxUnits", target.maxUnits);
27
38
  }
28
- validateUint256Field("target.assets", target.assets);
29
- validateUint256Field("target.maxUnits", target.maxUnits);
39
+ validateMidnightUint128Field("target.assets", target.assets);
40
+ validateMidnightUint128Field("target.maxUnits", target.maxUnits);
30
41
  }
31
42
  else {
32
43
  if (target.units === maxUint256) {
@@ -38,14 +49,25 @@ const validateParams = (params) => {
38
49
  if (target.minSellerAssets <= 0n) {
39
50
  throw new NonPositiveInputError("target.minSellerAssets", target.minSellerAssets);
40
51
  }
41
- validateUint256Field("target.units", target.units);
42
- validateUint256Field("target.minSellerAssets", target.minSellerAssets);
52
+ validateMidnightUint128Field("target.units", target.units);
53
+ validateMidnightUint128Field("target.minSellerAssets", target.minSellerAssets);
43
54
  }
44
55
  if (params.deadline === maxUint256) {
45
56
  throw new UnboundedMidnightTakeInputError("deadline");
46
57
  }
47
58
  validateDeadline(params.deadline);
48
59
  const { referralFeePct, referralFeeRecipient } = validateReferralFee(params);
60
+ validateMidnightReferralFeeCap(referralFeePct);
61
+ validateMidnightSellTargetBounds({ target, referralFeePct });
62
+ if (referralFeePct > 0n) {
63
+ // Rejects fee recipients that would strand the fee in a contract.
64
+ validateMidnightReceiver({
65
+ chainId: params.chainId,
66
+ market: params.market,
67
+ field: "referralFeeRecipient",
68
+ receiver: referralFeeRecipient,
69
+ });
70
+ }
49
71
  return { marketId, referralFeePct, referralFeeRecipient };
50
72
  };
51
73
  /**
@@ -61,9 +83,10 @@ const validateParams = (params) => {
61
83
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
62
84
  * @param params.market - Midnight market traded by every takeable offer.
63
85
  * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
64
- * @param params.receiver - Recipient of the withdrawn loan assets.
86
+ * @param params.receiver - Recipient of the withdrawn loan assets; Midnight protocol and market
87
+ * token contracts are rejected.
65
88
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
66
- * @param params.deadline - Bounded bundle execution deadline timestamp.
89
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
67
90
  * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
68
91
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
69
92
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -77,13 +100,21 @@ const validateParams = (params) => {
77
100
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
78
101
  * @throws {NonPositiveInputError} when the target amount, `maxUnits`, `minSellerAssets` or
79
102
  * `deadline` is not positive.
80
- * @throws {NegativeInputError} when `referralFeePct` is negative.
81
- * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`,
82
- * `target.minSellerAssets` or `deadline` exceeds `uint256`.
103
+ * @throws {NegativeInputError} when a takeable offer cap or `referralFeePct` is negative.
104
+ * @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, when
105
+ * `target.maxUnits` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a higher
106
+ * ceiling gives no slippage protection), or when `deadline` exceeds `uint256`.
83
107
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or `deadline`
84
108
  * is `maxUint256`.
109
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
110
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
111
+ * market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
85
112
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
113
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
86
114
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
115
+ * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
116
+ * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
117
+ * a unit sells for at most one asset.
87
118
  * @example
88
119
  * ```ts
89
120
  * import { Time } from "@morpho-org/morpho-ts";
@@ -18,12 +18,14 @@ import { type AuthorizationRequirementSignature, type BlueAuthorizationAction, t
18
18
  * @param params.authorized - Operator to authorize. Defaults to the chain's registered
19
19
  * BlueBundlesV1 deployment and must match it.
20
20
  * @param params.deadline - Optional signature deadline forwarded to the authorization encoder.
21
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
21
22
  * @param params.supportSignature - When `true`, return a signable `Requirement` instead of a
22
23
  * transaction so the destination route can consume the signed authorization.
23
24
  * @returns A deep-frozen `Transaction<BlueAuthorizationAction>`, a signable authorization
24
25
  * `Requirement` (when `supportSignature` is `true`), or `null` when authorization is already in
25
26
  * place.
26
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
27
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, a
28
+ * chain other than `params.chainId`.
27
29
  * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is not the chain's
28
30
  * BlueBundlesV1 operator.
29
31
  * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
@@ -31,7 +33,8 @@ import { type AuthorizationRequirementSignature, type BlueAuthorizationAction, t
31
33
  * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
32
34
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
33
35
  * @throws {UnknownAddressError} when BlueBundlesV1 is not registered on the target chain.
34
- * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
36
+ * @throws {viem.BaseError} when the `eth_chainId` request or an authorization or nonce RPC read
37
+ * fails.
35
38
  * @example
36
39
  * ```ts
37
40
  * import { createPublicClient, http, zeroAddress } from "viem";
@@ -60,4 +63,5 @@ export declare const getBlueAuthorizationRequirement: (params: {
60
63
  readonly supportSignature?: boolean;
61
64
  readonly authorized?: Address;
62
65
  readonly deadline?: bigint;
66
+ readonly now?: bigint;
63
67
  }) => Promise<Readonly<Transaction<BlueAuthorizationAction>> | Requirement<AuthorizationRequirementSignature> | null>;
@@ -2,9 +2,10 @@ import { getChainAddresses } from "@morpho-org/blue-sdk";
2
2
  import { blueAbi } from "@morpho-org/blue-sdk-viem";
3
3
  import { deepFreeze, getChainAddress, Time } from "@morpho-org/morpho-ts";
4
4
  import { encodeFunctionData, isAddressEqual, publicActions, } from "viem";
5
- import { validateDeadline } from "../../../helpers/validate.js";
6
- import { ChainIdMismatchError, ExpiredDeadlineError, UnsupportedAuthorizationOperatorError, } from "../../../types/index.js";
5
+ import { validateChainId, validateDeadline, } from "../../../helpers/validate.js";
6
+ import { ExpiredDeadlineError, UnsupportedAuthorizationOperatorError, } from "../../../types/index.js";
7
7
  import { encodeBlueSignatureAuthorization } from "../encode/encodeBlueSignatureAuthorization.js";
8
+ import { validateClientChainId } from "../validateClientChainId.js";
8
9
  /**
9
10
  * Resolves whether a supported operator needs Blue authorization for the given user, and returns
10
11
  * the requirement to satisfy it when it does.
@@ -22,12 +23,14 @@ import { encodeBlueSignatureAuthorization } from "../encode/encodeBlueSignatureA
22
23
  * @param params.authorized - Operator to authorize. Defaults to the chain's registered
23
24
  * BlueBundlesV1 deployment and must match it.
24
25
  * @param params.deadline - Optional signature deadline forwarded to the authorization encoder.
26
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
25
27
  * @param params.supportSignature - When `true`, return a signable `Requirement` instead of a
26
28
  * transaction so the destination route can consume the signed authorization.
27
29
  * @returns A deep-frozen `Transaction<BlueAuthorizationAction>`, a signable authorization
28
30
  * `Requirement` (when `supportSignature` is `true`), or `null` when authorization is already in
29
31
  * place.
30
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
32
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, a
33
+ * chain other than `params.chainId`.
31
34
  * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is not the chain's
32
35
  * BlueBundlesV1 operator.
33
36
  * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
@@ -35,7 +38,8 @@ import { encodeBlueSignatureAuthorization } from "../encode/encodeBlueSignatureA
35
38
  * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
36
39
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
37
40
  * @throws {UnknownAddressError} when BlueBundlesV1 is not registered on the target chain.
38
- * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
41
+ * @throws {viem.BaseError} when the `eth_chainId` request or an authorization or nonce RPC read
42
+ * fails.
39
43
  * @example
40
44
  * ```ts
41
45
  * import { createPublicClient, http, zeroAddress } from "viem";
@@ -59,9 +63,7 @@ import { encodeBlueSignatureAuthorization } from "../encode/encodeBlueSignatureA
59
63
  */
60
64
  export const getBlueAuthorizationRequirement = async (params) => {
61
65
  const { viemClient, chainId, userAddress, supportSignature } = params;
62
- if (viemClient.chain?.id !== chainId) {
63
- throw new ChainIdMismatchError(viemClient.chain?.id, chainId);
64
- }
66
+ validateChainId(viemClient.chain?.id, chainId);
65
67
  const { blue: morpho } = getChainAddresses(chainId);
66
68
  const blueBundlesV1 = getChainAddress(chainId, "bundles.blueBundlesV1");
67
69
  const authorized = params.authorized ?? blueBundlesV1;
@@ -78,11 +80,12 @@ export const getBlueAuthorizationRequirement = async (params) => {
78
80
  // or would revert on-chain. An omitted deadline defaults downstream to two hours from now.
79
81
  if (params.deadline != null) {
80
82
  validateDeadline(params.deadline);
81
- const timestamp = Time.timestamp();
83
+ const timestamp = params.now ?? Time.timestamp();
82
84
  if (params.deadline <= timestamp) {
83
85
  throw new ExpiredDeadlineError(params.deadline, timestamp);
84
86
  }
85
87
  }
88
+ await validateClientChainId(viemClient, chainId);
86
89
  // The signable path needs the user's Morpho nonce; fetch it alongside the
87
90
  // authorization status so both reads share a round-trip (batched into a
88
91
  // single multicall when the client enables batching) instead of
@@ -110,8 +113,10 @@ export const getBlueAuthorizationRequirement = async (params) => {
110
113
  chainId,
111
114
  nonce,
112
115
  deadline: params.deadline,
116
+ now: params.now,
113
117
  });
114
118
  }
119
+ await validateClientChainId(viemClient, chainId);
115
120
  const isAuthorized = await pc.readContract({
116
121
  address: morpho,
117
122
  abi: blueAbi,
@@ -15,6 +15,8 @@ interface EncodeBlueSignatureAuthorizationParams {
15
15
  isAuthorized?: boolean;
16
16
  /** Signature deadline in seconds. Defaults to two hours from now. */
17
17
  deadline?: bigint;
18
+ /** Timestamp the deadline is validated against; defaults to the current time. */
19
+ now?: bigint;
18
20
  }
19
21
  /**
20
22
  * Builds a Morpho authorization `Requirement` that, once signed, lets BlueBundlesV1 operate on
@@ -38,6 +40,7 @@ interface EncodeBlueSignatureAuthorizationParams {
38
40
  * @param params.nonce - The owner's current Morpho authorization nonce.
39
41
  * @param params.isAuthorized - Grant (`true`, default) or revoke (`false`).
40
42
  * @param params.deadline - Optional signature deadline in seconds.
43
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
41
44
  * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
42
45
  * `sign(client, userAddress)` produces the deep-frozen signature.
43
46
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
@@ -26,6 +26,7 @@ import { ChainIdMismatchError, ExpiredDeadlineError, UnsupportedAuthorizationOpe
26
26
  * @param params.nonce - The owner's current Morpho authorization nonce.
27
27
  * @param params.isAuthorized - Grant (`true`, default) or revoke (`false`).
28
28
  * @param params.deadline - Optional signature deadline in seconds.
29
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
29
30
  * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
30
31
  * `sign(client, userAddress)` produces the deep-frozen signature.
31
32
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
@@ -77,7 +78,7 @@ export const encodeBlueSignatureAuthorization = async (viemClient, params) => {
77
78
  // from now and is always valid.
78
79
  if (params.deadline != null) {
79
80
  validateDeadline(params.deadline);
80
- const timestamp = Time.timestamp();
81
+ const timestamp = params.now ?? Time.timestamp();
81
82
  if (params.deadline <= timestamp) {
82
83
  throw new ExpiredDeadlineError(params.deadline, timestamp);
83
84
  }
@@ -12,6 +12,8 @@ interface EncodeErc20PermitParams {
12
12
  nonce: bigint;
13
13
  supportDeployless?: boolean;
14
14
  deadline?: bigint;
15
+ /** Timestamp the deadline is validated against; defaults to the current time. */
16
+ now?: bigint;
15
17
  }
16
18
  /**
17
19
  * Builds an EIP-2612 permit `Requirement` that, once signed, lets a supported SDK spender pull
@@ -34,16 +36,25 @@ interface EncodeErc20PermitParams {
34
36
  * @param params.nonce - The owner's current EIP-2612 nonce on `token`.
35
37
  * @param params.supportDeployless - Whether `fetchToken` should use deployless multicall.
36
38
  * @param params.deadline - Signature expiration timestamp. Defaults to two hours from now.
39
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
37
40
  * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
38
41
  * `sign(client, userAddress)` produces the deep-frozen signature.
39
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
42
+ * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`, or when the RPC
43
+ * reports another chain via `eth_chainId` (checked after the deadline, before the metadata read).
40
44
  * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
41
45
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not VaultBundlesV1 or
42
46
  * BlueBundlesV1 for `chainId`.
43
47
  * @throws {NonPositiveInputError} when an explicit `deadline` is not positive.
44
48
  * @throws {InputExceedsMaxError} when an explicit `deadline` exceeds `uint256`.
45
49
  * @throws {ExpiredDeadlineError} when an explicit `deadline` is positive but not in the future.
46
- * @throws {viem.BaseError} when the token metadata read fails with no fallback left.
50
+ * @throws {UnknownTokenError} when `decimals()` reverts, has no code, returns undecodable data, or is out of range.
51
+ * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
52
+ * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
53
+ * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
54
+ * @throws {MissingPermitDomainNameError} when the token exposes neither `name()` nor
55
+ * `eip712Domain()`, so its permit domain is unknown.
56
+ * @throws {viem.BaseError} when the `eth_chainId` request or a token metadata read fails at the
57
+ * transport.
47
58
  * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
48
59
  * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
49
60
  * client account differs from `userAddress`.
@@ -4,6 +4,7 @@ import { signAndVerifyTypedData } from "../../../helpers/signAndVerifyTypedData.
4
4
  import { validateDeadline, validateUserAddress, } from "../../../helpers/validate.js";
5
5
  import { validateRequirementSpender } from "../../../helpers/validateRequirementSpender.js";
6
6
  import { ChainIdMismatchError, ExpiredDeadlineError, } from "../../../types/index.js";
7
+ import { validateClientChainId } from "../validateClientChainId.js";
7
8
  /**
8
9
  * Builds an EIP-2612 permit `Requirement` that, once signed, lets a supported SDK spender pull
9
10
  * `amount` of `token`.
@@ -25,16 +26,25 @@ import { ChainIdMismatchError, ExpiredDeadlineError, } from "../../../types/inde
25
26
  * @param params.nonce - The owner's current EIP-2612 nonce on `token`.
26
27
  * @param params.supportDeployless - Whether `fetchToken` should use deployless multicall.
27
28
  * @param params.deadline - Signature expiration timestamp. Defaults to two hours from now.
29
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
28
30
  * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
29
31
  * `sign(client, userAddress)` produces the deep-frozen signature.
30
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
32
+ * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`, or when the RPC
33
+ * reports another chain via `eth_chainId` (checked after the deadline, before the metadata read).
31
34
  * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
32
35
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not VaultBundlesV1 or
33
36
  * BlueBundlesV1 for `chainId`.
34
37
  * @throws {NonPositiveInputError} when an explicit `deadline` is not positive.
35
38
  * @throws {InputExceedsMaxError} when an explicit `deadline` exceeds `uint256`.
36
39
  * @throws {ExpiredDeadlineError} when an explicit `deadline` is positive but not in the future.
37
- * @throws {viem.BaseError} when the token metadata read fails with no fallback left.
40
+ * @throws {UnknownTokenError} when `decimals()` reverts, has no code, returns undecodable data, or is out of range.
41
+ * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
42
+ * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
43
+ * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
44
+ * @throws {MissingPermitDomainNameError} when the token exposes neither `name()` nor
45
+ * `eip712Domain()`, so its permit domain is unknown.
46
+ * @throws {viem.BaseError} when the `eth_chainId` request or a token metadata read fails at the
47
+ * transport.
38
48
  * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
39
49
  * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
40
50
  * client account differs from `userAddress`.
@@ -69,17 +79,18 @@ export const encodeErc20Permit = async (viemClient, params) => {
69
79
  spender,
70
80
  allowed: ["vaultBundlesV1", "blueBundlesV1"],
71
81
  });
72
- const now = Time.timestamp();
82
+ const timestamp = params.now ?? Time.timestamp();
73
83
  // Validate an explicit deadline before the token-metadata read: this exported encoder can be
74
84
  // called independently of the BlueBundlesV1 resolver, and an out-of-range or already-expired
75
85
  // deadline otherwise surfaces only as a downstream wallet typed-data error or an on-chain revert.
76
86
  if (params.deadline != null) {
77
87
  validateDeadline(params.deadline);
78
- if (params.deadline <= now) {
79
- throw new ExpiredDeadlineError(params.deadline, now);
88
+ if (params.deadline <= timestamp) {
89
+ throw new ExpiredDeadlineError(params.deadline, timestamp);
80
90
  }
81
91
  }
82
- const deadline = params.deadline ?? now + Time.s.from.h(2n);
92
+ const deadline = params.deadline ?? Time.timestamp() + Time.s.from.h(2n);
93
+ await validateClientChainId(viemClient, chainId);
83
94
  const tokenData = await fetchToken(token, viemClient, {
84
95
  deployless: supportDeployless,
85
96
  });
@@ -14,6 +14,8 @@ export interface EncodeErc20Permit2SignatureTransferParams {
14
14
  readonly nonce: bigint;
15
15
  /** Signature expiration timestamp in seconds. */
16
16
  readonly deadline: bigint;
17
+ /** Timestamp the deadline is validated against; defaults to the current time. */
18
+ readonly now?: bigint;
17
19
  }
18
20
  /**
19
21
  * Builds a Permit2 SignatureTransfer requirement for a direct fixed-bundles token pull.
@@ -29,6 +31,7 @@ export interface EncodeErc20Permit2SignatureTransferParams {
29
31
  * @param params.chainId - Target chain id.
30
32
  * @param params.nonce - Unused Permit2 unordered nonce.
31
33
  * @param params.deadline - Signature expiration timestamp in seconds.
34
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
32
35
  * @returns A requirement whose `action.typedData` is the EIP-712 payload and whose
33
36
  * `sign(client, userAddress)` returns a deep-frozen signature result.
34
37
  * @throws {NegativeInputError} when `amount` or `nonce` is negative.
@@ -19,6 +19,7 @@ import { ExpiredDeadlineError, InputExceedsMaxError, NonPositiveInputError, } fr
19
19
  * @param params.chainId - Target chain id.
20
20
  * @param params.nonce - Unused Permit2 unordered nonce.
21
21
  * @param params.deadline - Signature expiration timestamp in seconds.
22
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
22
23
  * @returns A requirement whose `action.typedData` is the EIP-712 payload and whose
23
24
  * `sign(client, userAddress)` returns a deep-frozen signature result.
24
25
  * @throws {NegativeInputError} when `amount` or `nonce` is negative.
@@ -71,7 +72,7 @@ export const encodeErc20Permit2SignatureTransfer = (params) => {
71
72
  // Reject an already-expired deadline before signing so a direct caller is never walked through a
72
73
  // wallet EIP-712 prompt for a SignatureTransfer that Permit2 would revert with `SignatureExpired`.
73
74
  // The sibling encodeErc20Permit and the token-requirement resolver enforce the same guard.
74
- const timestamp = Time.timestamp();
75
+ const timestamp = params.now ?? Time.timestamp();
75
76
  if (deadline <= timestamp) {
76
77
  throw new ExpiredDeadlineError(deadline, timestamp);
77
78
  }
@@ -18,6 +18,8 @@ export interface EncodeVaultSharesPermitParams {
18
18
  readonly amount: bigint;
19
19
  /** Shared permit and bundle deadline. */
20
20
  readonly deadline: bigint;
21
+ /** Timestamp the deadline is validated against; defaults to the current time. */
22
+ readonly now?: bigint;
21
23
  }
22
24
  /**
23
25
  * Builds the bounded ERC-2612 shares-permit requirement used by an in-kind vault exit.
@@ -34,6 +36,7 @@ export interface EncodeVaultSharesPermitParams {
34
36
  * @param params.nonce - Current vault permit nonce for the owner.
35
37
  * @param params.amount - Vault-share allowance to authorize.
36
38
  * @param params.deadline - Shared permit and bundle deadline.
39
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
37
40
  * @returns A requirement whose `action.typedData` is the EIP-712 payload and whose `sign()` result
38
41
  * can be embedded in fixed vault-bundles calldata.
39
42
  * @throws {UnsupportedChainIdError} when no address registry exists for `chainId`.
@@ -49,6 +52,8 @@ export interface EncodeVaultSharesPermitParams {
49
52
  * @throws {InvalidPermitDomainChainIdError} when a Vault V1 permit domain targets another chain or omits `chainId`.
50
53
  * @throws {InvalidPermitDomainVerifyingContractError} when a Vault V1 permit domain targets another token or omits `verifyingContract`.
51
54
  * @throws {UnsupportedPermitDomainExtensionsError} when a Vault V1 permit domain advertises unsupported extensions.
55
+ * @throws {MissingPermitDomainNameError} when a Vault V1 `vault` has neither an EIP-5267 domain
56
+ * nor a `name`, so its permit domain is unknown.
52
57
  * @example
53
58
  * ```ts
54
59
  * import { encodeVaultSharesPermit } from "@morpho-org/morpho-sdk";
@@ -21,6 +21,7 @@ import { ExpiredDeadlineError, } from "../../../types/index.js";
21
21
  * @param params.nonce - Current vault permit nonce for the owner.
22
22
  * @param params.amount - Vault-share allowance to authorize.
23
23
  * @param params.deadline - Shared permit and bundle deadline.
24
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
24
25
  * @returns A requirement whose `action.typedData` is the EIP-712 payload and whose `sign()` result
25
26
  * can be embedded in fixed vault-bundles calldata.
26
27
  * @throws {UnsupportedChainIdError} when no address registry exists for `chainId`.
@@ -36,6 +37,8 @@ import { ExpiredDeadlineError, } from "../../../types/index.js";
36
37
  * @throws {InvalidPermitDomainChainIdError} when a Vault V1 permit domain targets another chain or omits `chainId`.
37
38
  * @throws {InvalidPermitDomainVerifyingContractError} when a Vault V1 permit domain targets another token or omits `verifyingContract`.
38
39
  * @throws {UnsupportedPermitDomainExtensionsError} when a Vault V1 permit domain advertises unsupported extensions.
40
+ * @throws {MissingPermitDomainNameError} when a Vault V1 `vault` has neither an EIP-5267 domain
41
+ * nor a `name`, so its permit domain is unknown.
39
42
  * @example
40
43
  * ```ts
41
44
  * import { encodeVaultSharesPermit } from "@morpho-org/morpho-sdk";
@@ -89,7 +92,7 @@ export const encodeVaultSharesPermit = (params) => {
89
92
  spender,
90
93
  allowed: ["vaultExitBundlesV1", "vaultBundlesV1"],
91
94
  });
92
- const now = Time.timestamp();
95
+ const now = params.now ?? Time.timestamp();
93
96
  // Validate the explicit deadline: this exported encoder can be called independently of the
94
97
  // guarded resolvers, and an out-of-range or already-expired deadline otherwise surfaces only as
95
98
  // a downstream wallet typed-data error or an on-chain revert.
@@ -34,7 +34,9 @@ export interface GetMidnightApprovalRequirementsParams {
34
34
  * @param params.amount - Minimum allowance the spender needs.
35
35
  * @param params.approvalAmount - Allowance to approve when one is needed; defaults to `maxUint256` and must be at least `amount`.
36
36
  * @returns Approval transactions required for `spender` to pull `amount`.
37
- * @throws {ChainIdMismatchError} when the viem client is connected to another chain.
37
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
38
+ * another chain than `params.chainId`.
39
+ * @throws {viem.BaseError} when the `eth_chainId` request or allowance read fails.
38
40
  * @throws {NegativeInputError} when `amount` or `approvalAmount` is negative.
39
41
  * @throws {InputExceedsMaxError} when `amount` or `approvalAmount` exceeds `maxUint256`.
40
42
  * @throws {ApprovalAmountLessThanSpendAmountError} when `approvalAmount < amount`.
@@ -3,6 +3,7 @@ import { readContract } from "viem/actions";
3
3
  import { validateChainId, validateRequirementSpender, } from "../../../helpers/index.js";
4
4
  import { validateUint256Field } from "../../../helpers/validate.js";
5
5
  import { getRequirementsApproval } from "../getRequirementsApproval.js";
6
+ import { validateClientChainId } from "../validateClientChainId.js";
6
7
  /**
7
8
  * Resolves classic ERC20 approval requirements for a Midnight spender.
8
9
  *
@@ -23,7 +24,9 @@ import { getRequirementsApproval } from "../getRequirementsApproval.js";
23
24
  * @param params.amount - Minimum allowance the spender needs.
24
25
  * @param params.approvalAmount - Allowance to approve when one is needed; defaults to `maxUint256` and must be at least `amount`.
25
26
  * @returns Approval transactions required for `spender` to pull `amount`.
26
- * @throws {ChainIdMismatchError} when the viem client is connected to another chain.
27
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
28
+ * another chain than `params.chainId`.
29
+ * @throws {viem.BaseError} when the `eth_chainId` request or allowance read fails.
27
30
  * @throws {NegativeInputError} when `amount` or `approvalAmount` is negative.
28
31
  * @throws {InputExceedsMaxError} when `amount` or `approvalAmount` exceeds `maxUint256`.
29
32
  * @throws {ApprovalAmountLessThanSpendAmountError} when `approvalAmount < amount`.
@@ -64,6 +67,7 @@ export const getMidnightApprovalRequirements = async (params) => {
64
67
  });
65
68
  if (params.amount === 0n)
66
69
  return [];
70
+ await validateClientChainId(params.viemClient, params.chainId);
67
71
  const allowance = await readContract(params.viemClient, {
68
72
  address: params.token,
69
73
  abi: erc20Abi,
@@ -21,7 +21,9 @@ export interface GetMidnightAuthorizationRequirementParams {
21
21
  * @param params.owner - Account granting authorization.
22
22
  * @param params.authorized - MidnightBundlesV2.
23
23
  * @returns Authorization transaction, or `null` when already authorized.
24
- * @throws {ChainIdMismatchError} when the viem client is connected to another chain.
24
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
25
+ * another chain than `params.chainId`.
26
+ * @throws {viem.BaseError} when the `eth_chainId` request or authorization read fails.
25
27
  * @throws {UnsupportedMidnightAuthorizationTargetError} when `authorized` is not MidnightBundlesV2.
26
28
  * @example
27
29
  * ```ts
@@ -4,6 +4,7 @@ import { encodeFunctionData } from "viem";
4
4
  import { readContract } from "viem/actions";
5
5
  import { validateChainId } from "../../../helpers/index.js";
6
6
  import { validateMidnightAuthorizationTarget } from "../../../helpers/validateMidnightAuthorizationTarget.js";
7
+ import { validateClientChainId } from "../validateClientChainId.js";
7
8
  /**
8
9
  * Resolves the Midnight authorization transaction for a Midnight bundle operator.
9
10
  *
@@ -18,7 +19,9 @@ import { validateMidnightAuthorizationTarget } from "../../../helpers/validateMi
18
19
  * @param params.owner - Account granting authorization.
19
20
  * @param params.authorized - MidnightBundlesV2.
20
21
  * @returns Authorization transaction, or `null` when already authorized.
21
- * @throws {ChainIdMismatchError} when the viem client is connected to another chain.
22
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
23
+ * another chain than `params.chainId`.
24
+ * @throws {viem.BaseError} when the `eth_chainId` request or authorization read fails.
22
25
  * @throws {UnsupportedMidnightAuthorizationTargetError} when `authorized` is not MidnightBundlesV2.
23
26
  * @example
24
27
  * ```ts
@@ -49,6 +52,7 @@ export const getMidnightAuthorizationRequirement = async (params) => {
49
52
  chainId: params.chainId,
50
53
  authorized: params.authorized,
51
54
  });
55
+ await validateClientChainId(params.viemClient, params.chainId);
52
56
  const midnight = getChainAddress(params.chainId, "midnight");
53
57
  const isAuthorized = await readContract(params.viemClient, {
54
58
  address: midnight,
@@ -0,0 +1,26 @@
1
+ import type { Client } from "viem";
2
+ /**
3
+ * Validates both the chain the viem client declares and the chain its transport serves.
4
+ *
5
+ * Sends one `eth_chainId` request per call; the result is never cached, so every flow observes the
6
+ * endpoint it actually reads from. An honest RPC connected to another chain fails here, before any
7
+ * state read. A provider that lies about `eth_chainId` is not detected (see THREAT_MODEL.md, RPC).
8
+ *
9
+ * @param client - Viem client whose declared chain and transport are checked.
10
+ * @param expectedChainId - Chain ID expected by the entity or action.
11
+ * @returns Resolves only when both the declared and the observed chain IDs equal
12
+ * `expectedChainId`.
13
+ * @throws {ChainIdMismatchError} when the declared or the observed chain ID differs from
14
+ * `expectedChainId`.
15
+ * @throws {viem.BaseError} when the `eth_chainId` request fails.
16
+ * @example
17
+ * ```ts
18
+ * import { createPublicClient, http } from "viem";
19
+ * import { mainnet } from "viem/chains";
20
+ * import { validateClientChainId } from "@morpho-org/morpho-sdk";
21
+ *
22
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
23
+ * await validateClientChainId(client, mainnet.id);
24
+ * ```
25
+ */
26
+ export declare const validateClientChainId: (client: Client, expectedChainId: number) => Promise<void>;
@@ -0,0 +1,30 @@
1
+ import { getChainId } from "viem/actions";
2
+ import { validateChainId } from "../../helpers/validate.js";
3
+ /**
4
+ * Validates both the chain the viem client declares and the chain its transport serves.
5
+ *
6
+ * Sends one `eth_chainId` request per call; the result is never cached, so every flow observes the
7
+ * endpoint it actually reads from. An honest RPC connected to another chain fails here, before any
8
+ * state read. A provider that lies about `eth_chainId` is not detected (see THREAT_MODEL.md, RPC).
9
+ *
10
+ * @param client - Viem client whose declared chain and transport are checked.
11
+ * @param expectedChainId - Chain ID expected by the entity or action.
12
+ * @returns Resolves only when both the declared and the observed chain IDs equal
13
+ * `expectedChainId`.
14
+ * @throws {ChainIdMismatchError} when the declared or the observed chain ID differs from
15
+ * `expectedChainId`.
16
+ * @throws {viem.BaseError} when the `eth_chainId` request fails.
17
+ * @example
18
+ * ```ts
19
+ * import { createPublicClient, http } from "viem";
20
+ * import { mainnet } from "viem/chains";
21
+ * import { validateClientChainId } from "@morpho-org/morpho-sdk";
22
+ *
23
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
24
+ * await validateClientChainId(client, mainnet.id);
25
+ * ```
26
+ */
27
+ export const validateClientChainId = async (client, expectedChainId) => {
28
+ validateChainId(client.chain?.id, expectedChainId);
29
+ validateChainId(await getChainId(client), expectedChainId);
30
+ };
@@ -1,4 +1,4 @@
1
1
  export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidAddressError, InvalidBitLengthError, InvalidMarketParamsError, InvalidPositionAccrualStateError, InvalidPositionLossFactorError, InvalidVaultV2MidnightAdapterMarketsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MarketParamsIdMismatchError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
4
+ export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
@@ -1,4 +1,4 @@
1
1
  export { BlueErrors, DivisionByZeroError, IncompleteChainRegistryError, InvalidAddressError, InvalidBitLengthError, InvalidMarketParamsError, InvalidPositionAccrualStateError, InvalidPositionLossFactorError, InvalidVaultV2MidnightAdapterMarketsError, RegistryValueAlreadyRegisteredError, UnknownAddressError, UnknownDataError, UnknownFactory, UnknownMarketAllocationError, UnknownMarketParamsError, UnknownOfFactory, UnknownTokenError, UnknownTokenPriceError, UnknownVaultConfigError, UnsupportedChainIdError, UnsupportedMarketIrmError,
2
2
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
3
3
  UnsupportedPreLiquidationParamsError, UnsupportedVaultV2AdapterError, VaultV2Errors, } from "@morpho-org/blue-sdk";
4
- export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MarketParamsIdMismatchError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
4
+ export { getUnsupportedVaultV2Adapter, InvalidNumberError, InvalidPermitDomainChainIdError, InvalidPermitDomainVerifyingContractError, isUnknownOfFactoryError, MalformedTokenMetadataError, MarketParamsIdMismatchError, MissingPermitDomainNameError, NonTupleReturnValueError, UnknownAbiFunctionError, UnnamedAbiOutputsError, UnresolvedBlockNumberError, UnsupportedPermitDomainExtensionsError, } from "@morpho-org/blue-sdk-viem";
@@ -1,2 +1,2 @@
1
1
  export type { BigIntish, CollateralAllocation, Eip712Field, Erc20AllowanceRecipient, Failable, Fetchable, InputMarketParams, Loadable, MarketId, MaxBorrowOptions, MaxPositionCapacities, MaxWithdrawCollateralOptions, Pending, } from "@morpho-org/blue-sdk";
2
- export type { AuthorizationArgs, DeploylessFetchParameters, FetchParameters, InputAllocation, MetaMorphoCall, Permit2PermitArgs, Permit2TransferFromArgs, PermitArgs, } from "@morpho-org/blue-sdk-viem";
2
+ export type { AuthorizationArgs, DeploylessFetchParameters, FetchParameters, InputAllocation, MetaMorphoCall, Permit2PermitArgs, Permit2TransferFromArgs, PermitArgs, TokenMetadataField, } from "@morpho-org/blue-sdk-viem";
@@ -4,4 +4,4 @@ export { AdaptiveCurveIrmLib, CapacityLimitReason,
4
4
  defaultPreLiquidationParamsRegistry,
5
5
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
6
6
  getDefaultPreLiquidationParams, MarketUtils, MathLib, SharesMath, VaultUtils, VaultV2BlueMarketPublicAllocatorConfigUtils, VaultV2BluePublicAllocatorConfigUtils, VaultV2MidnightAdapterUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
7
- export { decodeBytes32String, getAuthorizationTypedData, getPermit2PermitTypedData, getPermit2TransferFromTypedData, getPermitTypedData, MetaMorphoAction, optionalBoolean, readContractRestructured, restructure, safeGetAddress, safeParseNumber, safeParseUnits, } from "@morpho-org/blue-sdk-viem";
7
+ export { catchRevertOnly, decodeBytes32String, getAuthorizationTypedData, getPermit2PermitTypedData, getPermit2TransferFromTypedData, getPermitTypedData, isContractRevertError, isTransportError, isUndecodableResultError, MetaMorphoAction, optionalBoolean, readContractRestructured, restructure, safeGetAddress, safeParseNumber, safeParseUnits, } from "@morpho-org/blue-sdk-viem";
@@ -3,4 +3,4 @@ export { AdaptiveCurveIrmLib, CapacityLimitReason,
3
3
  defaultPreLiquidationParamsRegistry,
4
4
  /** @deprecated Pre-liquidation support is deprecated and will be removed in the next major. */
5
5
  getDefaultPreLiquidationParams, MarketUtils, MathLib, SharesMath, VaultUtils, VaultV2BlueMarketPublicAllocatorConfigUtils, VaultV2BluePublicAllocatorConfigUtils, VaultV2MidnightAdapterUtils, VaultV2Utils, } from "@morpho-org/blue-sdk";
6
- export { decodeBytes32String, getAuthorizationTypedData, getPermit2PermitTypedData, getPermit2TransferFromTypedData, getPermitTypedData, MetaMorphoAction, optionalBoolean, readContractRestructured, restructure, safeGetAddress, safeParseNumber, safeParseUnits, } from "@morpho-org/blue-sdk-viem";
6
+ export { catchRevertOnly, decodeBytes32String, getAuthorizationTypedData, getPermit2PermitTypedData, getPermit2TransferFromTypedData, getPermitTypedData, isContractRevertError, isTransportError, isUndecodableResultError, MetaMorphoAction, optionalBoolean, readContractRestructured, restructure, safeGetAddress, safeParseNumber, safeParseUnits, } from "@morpho-org/blue-sdk-viem";