@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
@@ -6,7 +6,10 @@ const morpho_ts_1 = require("@morpho-org/morpho-ts");
6
6
  const viem_1 = require("viem");
7
7
  const index_js_1 = require("../../helpers/index.js");
8
8
  const validate_js_1 = require("../../helpers/validate.js");
9
+ const validateMidnightBounds_js_1 = require("../../helpers/validateMidnightBounds.js");
9
10
  const validateMidnightMarket_js_1 = require("../../helpers/validateMidnightMarket.js");
11
+ const validateMidnightReceiver_js_1 = require("../../helpers/validateMidnightReceiver.js");
12
+ const validateMidnightTakeFeasibility_js_1 = require("../../helpers/validateMidnightTakeFeasibility.js");
10
13
  const validateTakeableOffers_js_1 = require("../../helpers/validateTakeableOffers.js");
11
14
  const index_js_2 = require("../../types/index.js");
12
15
  const validateParams = (params) => {
@@ -17,6 +20,14 @@ const validateParams = (params) => {
17
20
  takeableOffers: params.takeableOffers,
18
21
  expectedBuy: true,
19
22
  });
23
+ (0, validateMidnightBounds_js_1.validateMidnightTakeableOfferBounds)(params.takeableOffers);
24
+ // Rejects receivers that would strand the withdrawn assets in a contract.
25
+ (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
26
+ chainId: params.chainId,
27
+ market: params.market,
28
+ field: "receiver",
29
+ receiver: params.receiver,
30
+ });
20
31
  const { target } = params;
21
32
  if (target.type === "assets") {
22
33
  if (target.assets <= 0n) {
@@ -28,8 +39,8 @@ const validateParams = (params) => {
28
39
  if (target.maxUnits <= 0n) {
29
40
  throw new index_js_2.NonPositiveInputError("target.maxUnits", target.maxUnits);
30
41
  }
31
- (0, validate_js_1.validateUint256Field)("target.assets", target.assets);
32
- (0, validate_js_1.validateUint256Field)("target.maxUnits", target.maxUnits);
42
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.assets", target.assets);
43
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.maxUnits", target.maxUnits);
33
44
  }
34
45
  else {
35
46
  if (target.units === viem_1.maxUint256) {
@@ -41,14 +52,25 @@ const validateParams = (params) => {
41
52
  if (target.minSellerAssets <= 0n) {
42
53
  throw new index_js_2.NonPositiveInputError("target.minSellerAssets", target.minSellerAssets);
43
54
  }
44
- (0, validate_js_1.validateUint256Field)("target.units", target.units);
45
- (0, validate_js_1.validateUint256Field)("target.minSellerAssets", target.minSellerAssets);
55
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.units", target.units);
56
+ (0, validateMidnightBounds_js_1.validateMidnightUint128Field)("target.minSellerAssets", target.minSellerAssets);
46
57
  }
47
58
  if (params.deadline === viem_1.maxUint256) {
48
59
  throw new index_js_2.UnboundedMidnightTakeInputError("deadline");
49
60
  }
50
61
  (0, validate_js_1.validateDeadline)(params.deadline);
51
62
  const { referralFeePct, referralFeeRecipient } = (0, validate_js_1.validateReferralFee)(params);
63
+ (0, validateMidnightBounds_js_1.validateMidnightReferralFeeCap)(referralFeePct);
64
+ (0, validateMidnightTakeFeasibility_js_1.validateMidnightSellTargetBounds)({ target, referralFeePct });
65
+ if (referralFeePct > 0n) {
66
+ // Rejects fee recipients that would strand the fee in a contract.
67
+ (0, validateMidnightReceiver_js_1.validateMidnightReceiver)({
68
+ chainId: params.chainId,
69
+ market: params.market,
70
+ field: "referralFeeRecipient",
71
+ receiver: referralFeeRecipient,
72
+ });
73
+ }
52
74
  return { marketId, referralFeePct, referralFeeRecipient };
53
75
  };
54
76
  /**
@@ -64,9 +86,10 @@ const validateParams = (params) => {
64
86
  * @param params.chainId - Chain id used to resolve `MidnightBundlesV2`.
65
87
  * @param params.market - Midnight market traded by every takeable offer.
66
88
  * @param params.target - `{ type: "assets", assets, maxUnits }` or `{ type: "units", units, minSellerAssets }`.
67
- * @param params.receiver - Recipient of the withdrawn loan assets.
89
+ * @param params.receiver - Recipient of the withdrawn loan assets; Midnight protocol and market
90
+ * token contracts are rejected.
68
91
  * @param params.takeableOffers - ABI-ready lend-side offers returned by the Midnight API.
69
- * @param params.deadline - Bounded bundle execution deadline timestamp.
92
+ * @param params.deadline - Bounded bundle execution deadline timestamp. Not checked against the clock; validate freshness before building.
70
93
  * @param params.referralFeePct - Optional WAD-scaled referral fee taken from the received assets.
71
94
  * @param params.referralFeeRecipient - Referral fee recipient; required with a positive fee.
72
95
  * @param params.metadata - Optional analytics metadata appended to calldata.
@@ -80,13 +103,21 @@ const validateParams = (params) => {
80
103
  * @throws {MidnightTakeableOfferMarketMismatchError} when any offer belongs to another market.
81
104
  * @throws {NonPositiveInputError} when the target amount, `maxUnits`, `minSellerAssets` or
82
105
  * `deadline` is not positive.
83
- * @throws {NegativeInputError} when `referralFeePct` is negative.
84
- * @throws {InputExceedsMaxError} when `target.assets`, `target.maxUnits`, `target.units`,
85
- * `target.minSellerAssets` or `deadline` exceeds `uint256`.
106
+ * @throws {NegativeInputError} when a takeable offer cap or `referralFeePct` is negative.
107
+ * @throws {InputExceedsMaxError} when a target amount or offer cap exceeds `uint128`, when
108
+ * `target.maxUnits` exceeds `uint128` (an SDK cap: the bundle accepts `uint256`, but a higher
109
+ * ceiling gives no slippage protection), or when `deadline` exceeds `uint256`.
86
110
  * @throws {UnboundedMidnightTakeInputError} when `target.units`, `target.maxUnits` or `deadline`
87
111
  * is `maxUint256`.
112
+ * @throws {MidnightZeroReceiverError} when `receiver` is the zero address.
113
+ * @throws {MidnightContractReceiverError} when `receiver` is a Midnight protocol contract or a
114
+ * market token contract, or when `referralFeeRecipient` is either with a positive referral fee.
88
115
  * @throws {ReferralFeePctExceededError} when `referralFeePct` is not below WAD.
116
+ * @throws {MidnightReferralFeePctExceededError} when `referralFeePct` exceeds 10% (`WAD / 10n`).
89
117
  * @throws {ReferralFeeRecipientMissingError} when a positive referral fee has no recipient.
118
+ * @throws {MidnightTakeTargetUnreachableError} when `target.minSellerAssets` exceeds `target.units`
119
+ * minus the referral fee, or `target.maxUnits` is below `target.assets` plus the referral fee, since
120
+ * a unit sells for at most one asset.
90
121
  * @example
91
122
  * ```ts
92
123
  * 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>;
@@ -8,6 +8,7 @@ const viem_1 = require("viem");
8
8
  const validate_js_1 = require("../../../helpers/validate.js");
9
9
  const index_js_1 = require("../../../types/index.js");
10
10
  const encodeBlueSignatureAuthorization_js_1 = require("../encode/encodeBlueSignatureAuthorization.js");
11
+ const validateClientChainId_js_1 = require("../validateClientChainId.js");
11
12
  /**
12
13
  * Resolves whether a supported operator needs Blue authorization for the given user, and returns
13
14
  * the requirement to satisfy it when it does.
@@ -25,12 +26,14 @@ const encodeBlueSignatureAuthorization_js_1 = require("../encode/encodeBlueSigna
25
26
  * @param params.authorized - Operator to authorize. Defaults to the chain's registered
26
27
  * BlueBundlesV1 deployment and must match it.
27
28
  * @param params.deadline - Optional signature deadline forwarded to the authorization encoder.
29
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
28
30
  * @param params.supportSignature - When `true`, return a signable `Requirement` instead of a
29
31
  * transaction so the destination route can consume the signed authorization.
30
32
  * @returns A deep-frozen `Transaction<BlueAuthorizationAction>`, a signable authorization
31
33
  * `Requirement` (when `supportSignature` is `true`), or `null` when authorization is already in
32
34
  * place.
33
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
35
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`, a
36
+ * chain other than `params.chainId`.
34
37
  * @throws {UnsupportedAuthorizationOperatorError} when `authorized` is not the chain's
35
38
  * BlueBundlesV1 operator.
36
39
  * @throws {NonPositiveInputError} when a provided `deadline` is not positive.
@@ -38,7 +41,8 @@ const encodeBlueSignatureAuthorization_js_1 = require("../encode/encodeBlueSigna
38
41
  * @throws {ExpiredDeadlineError} when a provided `deadline` is positive but not in the future.
39
42
  * @throws {UnsupportedChainIdError} when the chain is absent from the address registry.
40
43
  * @throws {UnknownAddressError} when BlueBundlesV1 is not registered on the target chain.
41
- * @throws {viem.BaseError} when an authorization or nonce RPC read fails.
44
+ * @throws {viem.BaseError} when the `eth_chainId` request or an authorization or nonce RPC read
45
+ * fails.
42
46
  * @example
43
47
  * ```ts
44
48
  * import { createPublicClient, http, zeroAddress } from "viem";
@@ -62,9 +66,7 @@ const encodeBlueSignatureAuthorization_js_1 = require("../encode/encodeBlueSigna
62
66
  */
63
67
  const getBlueAuthorizationRequirement = async (params) => {
64
68
  const { viemClient, chainId, userAddress, supportSignature } = params;
65
- if (viemClient.chain?.id !== chainId) {
66
- throw new index_js_1.ChainIdMismatchError(viemClient.chain?.id, chainId);
67
- }
69
+ (0, validate_js_1.validateChainId)(viemClient.chain?.id, chainId);
68
70
  const { blue: morpho } = (0, blue_sdk_1.getChainAddresses)(chainId);
69
71
  const blueBundlesV1 = (0, morpho_ts_1.getChainAddress)(chainId, "bundles.blueBundlesV1");
70
72
  const authorized = params.authorized ?? blueBundlesV1;
@@ -81,11 +83,12 @@ const getBlueAuthorizationRequirement = async (params) => {
81
83
  // or would revert on-chain. An omitted deadline defaults downstream to two hours from now.
82
84
  if (params.deadline != null) {
83
85
  (0, validate_js_1.validateDeadline)(params.deadline);
84
- const timestamp = morpho_ts_1.Time.timestamp();
86
+ const timestamp = params.now ?? morpho_ts_1.Time.timestamp();
85
87
  if (params.deadline <= timestamp) {
86
88
  throw new index_js_1.ExpiredDeadlineError(params.deadline, timestamp);
87
89
  }
88
90
  }
91
+ await (0, validateClientChainId_js_1.validateClientChainId)(viemClient, chainId);
89
92
  // The signable path needs the user's Morpho nonce; fetch it alongside the
90
93
  // authorization status so both reads share a round-trip (batched into a
91
94
  // single multicall when the client enables batching) instead of
@@ -113,8 +116,10 @@ const getBlueAuthorizationRequirement = async (params) => {
113
116
  chainId,
114
117
  nonce,
115
118
  deadline: params.deadline,
119
+ now: params.now,
116
120
  });
117
121
  }
122
+ await (0, validateClientChainId_js_1.validateClientChainId)(viemClient, chainId);
118
123
  const isAuthorized = await pc.readContract({
119
124
  address: morpho,
120
125
  abi: blue_sdk_viem_1.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`.
@@ -29,6 +29,7 @@ const index_js_1 = require("../../../types/index.js");
29
29
  * @param params.nonce - The owner's current Morpho authorization nonce.
30
30
  * @param params.isAuthorized - Grant (`true`, default) or revoke (`false`).
31
31
  * @param params.deadline - Optional signature deadline in seconds.
32
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
32
33
  * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
33
34
  * `sign(client, userAddress)` produces the deep-frozen signature.
34
35
  * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
@@ -80,7 +81,7 @@ const encodeBlueSignatureAuthorization = async (viemClient, params) => {
80
81
  // from now and is always valid.
81
82
  if (params.deadline != null) {
82
83
  (0, validate_js_1.validateDeadline)(params.deadline);
83
- const timestamp = morpho_ts_1.Time.timestamp();
84
+ const timestamp = params.now ?? morpho_ts_1.Time.timestamp();
84
85
  if (params.deadline <= timestamp) {
85
86
  throw new index_js_1.ExpiredDeadlineError(params.deadline, timestamp);
86
87
  }
@@ -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`.
@@ -7,6 +7,7 @@ const signAndVerifyTypedData_js_1 = require("../../../helpers/signAndVerifyTyped
7
7
  const validate_js_1 = require("../../../helpers/validate.js");
8
8
  const validateRequirementSpender_js_1 = require("../../../helpers/validateRequirementSpender.js");
9
9
  const index_js_1 = require("../../../types/index.js");
10
+ const validateClientChainId_js_1 = require("../validateClientChainId.js");
10
11
  /**
11
12
  * Builds an EIP-2612 permit `Requirement` that, once signed, lets a supported SDK spender pull
12
13
  * `amount` of `token`.
@@ -28,16 +29,25 @@ const index_js_1 = require("../../../types/index.js");
28
29
  * @param params.nonce - The owner's current EIP-2612 nonce on `token`.
29
30
  * @param params.supportDeployless - Whether `fetchToken` should use deployless multicall.
30
31
  * @param params.deadline - Signature expiration timestamp. Defaults to two hours from now.
32
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
31
33
  * @returns A `Requirement` whose `action.typedData` is the EIP-712 payload and whose
32
34
  * `sign(client, userAddress)` produces the deep-frozen signature.
33
- * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`.
35
+ * @throws {ChainIdMismatchError} when `viemClient.chain?.id !== params.chainId`, or when the RPC
36
+ * reports another chain via `eth_chainId` (checked after the deadline, before the metadata read).
34
37
  * @throws {UnsupportedChainIdError} when `chainId` is absent from the address registry.
35
38
  * @throws {UnsupportedErc20ApprovalSpenderError} when `spender` is not VaultBundlesV1 or
36
39
  * BlueBundlesV1 for `chainId`.
37
40
  * @throws {NonPositiveInputError} when an explicit `deadline` is not positive.
38
41
  * @throws {InputExceedsMaxError} when an explicit `deadline` exceeds `uint256`.
39
42
  * @throws {ExpiredDeadlineError} when an explicit `deadline` is positive but not in the future.
40
- * @throws {viem.BaseError} when the token metadata read fails with no fallback left.
43
+ * @throws {UnknownTokenError} when `decimals()` reverts, has no code, returns undecodable data, or is out of range.
44
+ * @throws {MalformedTokenMetadataError} when the token's `eip712Domain()` or
45
+ * `bytes32` `name`/`symbol` retry returns non-empty data that does not decode, or when the
46
+ * deployless query reports malformed `name()`/`symbol()`/`eip712Domain()` returndata (no fallback).
47
+ * @throws {MissingPermitDomainNameError} when the token exposes neither `name()` nor
48
+ * `eip712Domain()`, so its permit domain is unknown.
49
+ * @throws {viem.BaseError} when the `eth_chainId` request or a token metadata read fails at the
50
+ * transport.
41
51
  * @throws {MissingClientPropertyError} from `sign()` when the client has no `account.address`.
42
52
  * @throws {AddressMismatchError} from `sign()` when `userAddress` differs from `owner`, or when the
43
53
  * client account differs from `userAddress`.
@@ -72,17 +82,18 @@ const encodeErc20Permit = async (viemClient, params) => {
72
82
  spender,
73
83
  allowed: ["vaultBundlesV1", "blueBundlesV1"],
74
84
  });
75
- const now = morpho_ts_1.Time.timestamp();
85
+ const timestamp = params.now ?? morpho_ts_1.Time.timestamp();
76
86
  // Validate an explicit deadline before the token-metadata read: this exported encoder can be
77
87
  // called independently of the BlueBundlesV1 resolver, and an out-of-range or already-expired
78
88
  // deadline otherwise surfaces only as a downstream wallet typed-data error or an on-chain revert.
79
89
  if (params.deadline != null) {
80
90
  (0, validate_js_1.validateDeadline)(params.deadline);
81
- if (params.deadline <= now) {
82
- throw new index_js_1.ExpiredDeadlineError(params.deadline, now);
91
+ if (params.deadline <= timestamp) {
92
+ throw new index_js_1.ExpiredDeadlineError(params.deadline, timestamp);
83
93
  }
84
94
  }
85
- const deadline = params.deadline ?? now + morpho_ts_1.Time.s.from.h(2n);
95
+ const deadline = params.deadline ?? morpho_ts_1.Time.timestamp() + morpho_ts_1.Time.s.from.h(2n);
96
+ await (0, validateClientChainId_js_1.validateClientChainId)(viemClient, chainId);
86
97
  const tokenData = await (0, blue_sdk_viem_1.fetchToken)(token, viemClient, {
87
98
  deployless: supportDeployless,
88
99
  });
@@ -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.
@@ -22,6 +22,7 @@ const index_js_1 = require("../../../types/index.js");
22
22
  * @param params.chainId - Target chain id.
23
23
  * @param params.nonce - Unused Permit2 unordered nonce.
24
24
  * @param params.deadline - Signature expiration timestamp in seconds.
25
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
25
26
  * @returns A requirement whose `action.typedData` is the EIP-712 payload and whose
26
27
  * `sign(client, userAddress)` returns a deep-frozen signature result.
27
28
  * @throws {NegativeInputError} when `amount` or `nonce` is negative.
@@ -74,7 +75,7 @@ const encodeErc20Permit2SignatureTransfer = (params) => {
74
75
  // Reject an already-expired deadline before signing so a direct caller is never walked through a
75
76
  // wallet EIP-712 prompt for a SignatureTransfer that Permit2 would revert with `SignatureExpired`.
76
77
  // The sibling encodeErc20Permit and the token-requirement resolver enforce the same guard.
77
- const timestamp = morpho_ts_1.Time.timestamp();
78
+ const timestamp = params.now ?? morpho_ts_1.Time.timestamp();
78
79
  if (deadline <= timestamp) {
79
80
  throw new index_js_1.ExpiredDeadlineError(deadline, timestamp);
80
81
  }
@@ -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";
@@ -24,6 +24,7 @@ const index_js_1 = require("../../../types/index.js");
24
24
  * @param params.nonce - Current vault permit nonce for the owner.
25
25
  * @param params.amount - Vault-share allowance to authorize.
26
26
  * @param params.deadline - Shared permit and bundle deadline.
27
+ * @param params.now - Timestamp the deadline is validated against; defaults to the current time.
27
28
  * @returns A requirement whose `action.typedData` is the EIP-712 payload and whose `sign()` result
28
29
  * can be embedded in fixed vault-bundles calldata.
29
30
  * @throws {UnsupportedChainIdError} when no address registry exists for `chainId`.
@@ -39,6 +40,8 @@ const index_js_1 = require("../../../types/index.js");
39
40
  * @throws {InvalidPermitDomainChainIdError} when a Vault V1 permit domain targets another chain or omits `chainId`.
40
41
  * @throws {InvalidPermitDomainVerifyingContractError} when a Vault V1 permit domain targets another token or omits `verifyingContract`.
41
42
  * @throws {UnsupportedPermitDomainExtensionsError} when a Vault V1 permit domain advertises unsupported extensions.
43
+ * @throws {MissingPermitDomainNameError} when a Vault V1 `vault` has neither an EIP-5267 domain
44
+ * nor a `name`, so its permit domain is unknown.
42
45
  * @example
43
46
  * ```ts
44
47
  * import { encodeVaultSharesPermit } from "@morpho-org/morpho-sdk";
@@ -92,7 +95,7 @@ const encodeVaultSharesPermit = (params) => {
92
95
  spender,
93
96
  allowed: ["vaultExitBundlesV1", "vaultBundlesV1"],
94
97
  });
95
- const now = morpho_ts_1.Time.timestamp();
98
+ const now = params.now ?? morpho_ts_1.Time.timestamp();
96
99
  // Validate the explicit deadline: this exported encoder can be called independently of the
97
100
  // guarded resolvers, and an out-of-range or already-expired deadline otherwise surfaces only as
98
101
  // 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`.
@@ -6,6 +6,7 @@ const actions_1 = require("viem/actions");
6
6
  const index_js_1 = require("../../../helpers/index.js");
7
7
  const validate_js_1 = require("../../../helpers/validate.js");
8
8
  const getRequirementsApproval_js_1 = require("../getRequirementsApproval.js");
9
+ const validateClientChainId_js_1 = require("../validateClientChainId.js");
9
10
  /**
10
11
  * Resolves classic ERC20 approval requirements for a Midnight spender.
11
12
  *
@@ -26,7 +27,9 @@ const getRequirementsApproval_js_1 = require("../getRequirementsApproval.js");
26
27
  * @param params.amount - Minimum allowance the spender needs.
27
28
  * @param params.approvalAmount - Allowance to approve when one is needed; defaults to `maxUint256` and must be at least `amount`.
28
29
  * @returns Approval transactions required for `spender` to pull `amount`.
29
- * @throws {ChainIdMismatchError} when the viem client is connected to another chain.
30
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
31
+ * another chain than `params.chainId`.
32
+ * @throws {viem.BaseError} when the `eth_chainId` request or allowance read fails.
30
33
  * @throws {NegativeInputError} when `amount` or `approvalAmount` is negative.
31
34
  * @throws {InputExceedsMaxError} when `amount` or `approvalAmount` exceeds `maxUint256`.
32
35
  * @throws {ApprovalAmountLessThanSpendAmountError} when `approvalAmount < amount`.
@@ -67,6 +70,7 @@ const getMidnightApprovalRequirements = async (params) => {
67
70
  });
68
71
  if (params.amount === 0n)
69
72
  return [];
73
+ await (0, validateClientChainId_js_1.validateClientChainId)(params.viemClient, params.chainId);
70
74
  const allowance = await (0, actions_1.readContract)(params.viemClient, {
71
75
  address: params.token,
72
76
  abi: viem_1.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
@@ -7,6 +7,7 @@ const viem_1 = require("viem");
7
7
  const actions_1 = require("viem/actions");
8
8
  const index_js_1 = require("../../../helpers/index.js");
9
9
  const validateMidnightAuthorizationTarget_js_1 = require("../../../helpers/validateMidnightAuthorizationTarget.js");
10
+ const validateClientChainId_js_1 = require("../validateClientChainId.js");
10
11
  /**
11
12
  * Resolves the Midnight authorization transaction for a Midnight bundle operator.
12
13
  *
@@ -21,7 +22,9 @@ const validateMidnightAuthorizationTarget_js_1 = require("../../../helpers/valid
21
22
  * @param params.owner - Account granting authorization.
22
23
  * @param params.authorized - MidnightBundlesV2.
23
24
  * @returns Authorization transaction, or `null` when already authorized.
24
- * @throws {ChainIdMismatchError} when the viem client is connected to another chain.
25
+ * @throws {ChainIdMismatchError} when the client declares, or its RPC reports via `eth_chainId`,
26
+ * another chain than `params.chainId`.
27
+ * @throws {viem.BaseError} when the `eth_chainId` request or authorization read fails.
25
28
  * @throws {UnsupportedMidnightAuthorizationTargetError} when `authorized` is not MidnightBundlesV2.
26
29
  * @example
27
30
  * ```ts
@@ -52,6 +55,7 @@ const getMidnightAuthorizationRequirement = async (params) => {
52
55
  chainId: params.chainId,
53
56
  authorized: params.authorized,
54
57
  });
58
+ await (0, validateClientChainId_js_1.validateClientChainId)(params.viemClient, params.chainId);
55
59
  const midnight = (0, morpho_ts_1.getChainAddress)(params.chainId, "midnight");
56
60
  const isAuthorized = await (0, actions_1.readContract)(params.viemClient, {
57
61
  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,34 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateClientChainId = void 0;
4
+ const actions_1 = require("viem/actions");
5
+ const validate_js_1 = require("../../helpers/validate.js");
6
+ /**
7
+ * Validates both the chain the viem client declares and the chain its transport serves.
8
+ *
9
+ * Sends one `eth_chainId` request per call; the result is never cached, so every flow observes the
10
+ * endpoint it actually reads from. An honest RPC connected to another chain fails here, before any
11
+ * state read. A provider that lies about `eth_chainId` is not detected (see THREAT_MODEL.md, RPC).
12
+ *
13
+ * @param client - Viem client whose declared chain and transport are checked.
14
+ * @param expectedChainId - Chain ID expected by the entity or action.
15
+ * @returns Resolves only when both the declared and the observed chain IDs equal
16
+ * `expectedChainId`.
17
+ * @throws {ChainIdMismatchError} when the declared or the observed chain ID differs from
18
+ * `expectedChainId`.
19
+ * @throws {viem.BaseError} when the `eth_chainId` request fails.
20
+ * @example
21
+ * ```ts
22
+ * import { createPublicClient, http } from "viem";
23
+ * import { mainnet } from "viem/chains";
24
+ * import { validateClientChainId } from "@morpho-org/morpho-sdk";
25
+ *
26
+ * const client = createPublicClient({ chain: mainnet, transport: http() });
27
+ * await validateClientChainId(client, mainnet.id);
28
+ * ```
29
+ */
30
+ const validateClientChainId = async (client, expectedChainId) => {
31
+ (0, validate_js_1.validateChainId)(client.chain?.id, expectedChainId);
32
+ (0, validate_js_1.validateChainId)(await (0, actions_1.getChainId)(client), expectedChainId);
33
+ };
34
+ exports.validateClientChainId = validateClientChainId;
@@ -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,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.UnsupportedPermitDomainExtensionsError = exports.UnresolvedBlockNumberError = exports.UnnamedAbiOutputsError = exports.UnknownAbiFunctionError = exports.NonTupleReturnValueError = exports.MarketParamsIdMismatchError = exports.isUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedVaultV2AdapterError = exports.UnsupportedPreLiquidationParamsError = exports.UnsupportedMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownVaultConfigError = exports.UnknownTokenPriceError = exports.UnknownTokenError = exports.UnknownOfFactory = exports.UnknownMarketParamsError = exports.UnknownMarketAllocationError = exports.UnknownFactory = exports.UnknownDataError = exports.UnknownAddressError = exports.RegistryValueAlreadyRegisteredError = exports.InvalidVaultV2MidnightAdapterMarketsError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualStateError = exports.InvalidMarketParamsError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.IncompleteChainRegistryError = exports.DivisionByZeroError = exports.BlueErrors = void 0;
3
+ exports.UnsupportedPermitDomainExtensionsError = exports.UnresolvedBlockNumberError = exports.UnnamedAbiOutputsError = exports.UnknownAbiFunctionError = exports.NonTupleReturnValueError = exports.MissingPermitDomainNameError = exports.MarketParamsIdMismatchError = exports.MalformedTokenMetadataError = exports.isUnknownOfFactoryError = exports.InvalidPermitDomainVerifyingContractError = exports.InvalidPermitDomainChainIdError = exports.InvalidNumberError = exports.getUnsupportedVaultV2Adapter = exports.VaultV2Errors = exports.UnsupportedVaultV2AdapterError = exports.UnsupportedPreLiquidationParamsError = exports.UnsupportedMarketIrmError = exports.UnsupportedChainIdError = exports.UnknownVaultConfigError = exports.UnknownTokenPriceError = exports.UnknownTokenError = exports.UnknownOfFactory = exports.UnknownMarketParamsError = exports.UnknownMarketAllocationError = exports.UnknownFactory = exports.UnknownDataError = exports.UnknownAddressError = exports.RegistryValueAlreadyRegisteredError = exports.InvalidVaultV2MidnightAdapterMarketsError = exports.InvalidPositionLossFactorError = exports.InvalidPositionAccrualStateError = exports.InvalidMarketParamsError = exports.InvalidBitLengthError = exports.InvalidAddressError = exports.IncompleteChainRegistryError = exports.DivisionByZeroError = exports.BlueErrors = void 0;
4
4
  var blue_sdk_1 = require("@morpho-org/blue-sdk");
5
5
  Object.defineProperty(exports, "BlueErrors", { enumerable: true, get: function () { return blue_sdk_1.BlueErrors; } });
6
6
  Object.defineProperty(exports, "DivisionByZeroError", { enumerable: true, get: function () { return blue_sdk_1.DivisionByZeroError; } });
@@ -33,7 +33,9 @@ Object.defineProperty(exports, "InvalidNumberError", { enumerable: true, get: fu
33
33
  Object.defineProperty(exports, "InvalidPermitDomainChainIdError", { enumerable: true, get: function () { return blue_sdk_viem_1.InvalidPermitDomainChainIdError; } });
34
34
  Object.defineProperty(exports, "InvalidPermitDomainVerifyingContractError", { enumerable: true, get: function () { return blue_sdk_viem_1.InvalidPermitDomainVerifyingContractError; } });
35
35
  Object.defineProperty(exports, "isUnknownOfFactoryError", { enumerable: true, get: function () { return blue_sdk_viem_1.isUnknownOfFactoryError; } });
36
+ Object.defineProperty(exports, "MalformedTokenMetadataError", { enumerable: true, get: function () { return blue_sdk_viem_1.MalformedTokenMetadataError; } });
36
37
  Object.defineProperty(exports, "MarketParamsIdMismatchError", { enumerable: true, get: function () { return blue_sdk_viem_1.MarketParamsIdMismatchError; } });
38
+ Object.defineProperty(exports, "MissingPermitDomainNameError", { enumerable: true, get: function () { return blue_sdk_viem_1.MissingPermitDomainNameError; } });
37
39
  Object.defineProperty(exports, "NonTupleReturnValueError", { enumerable: true, get: function () { return blue_sdk_viem_1.NonTupleReturnValueError; } });
38
40
  Object.defineProperty(exports, "UnknownAbiFunctionError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnknownAbiFunctionError; } });
39
41
  Object.defineProperty(exports, "UnnamedAbiOutputsError", { enumerable: true, get: function () { return blue_sdk_viem_1.UnnamedAbiOutputsError; } });
@@ -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";