ox 0.14.64 → 0.14.66

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 (184) hide show
  1. package/CHANGELOG.md +68 -0
  2. package/_cjs/core/AbiError.js +25 -4
  3. package/_cjs/core/AbiError.js.map +1 -1
  4. package/_cjs/core/AbiEvent.js +18 -3
  5. package/_cjs/core/AbiEvent.js.map +1 -1
  6. package/_cjs/core/AbiFunction.js +27 -3
  7. package/_cjs/core/AbiFunction.js.map +1 -1
  8. package/_cjs/core/Address.js +1 -0
  9. package/_cjs/core/Address.js.map +1 -1
  10. package/_cjs/core/Authorization.js +29 -2
  11. package/_cjs/core/Authorization.js.map +1 -1
  12. package/_cjs/core/Keystore.js +18 -0
  13. package/_cjs/core/Keystore.js.map +1 -1
  14. package/_cjs/core/Secp256k1.js +5 -1
  15. package/_cjs/core/Secp256k1.js.map +1 -1
  16. package/_cjs/core/Signature.js +4 -2
  17. package/_cjs/core/Signature.js.map +1 -1
  18. package/_cjs/core/Siwe.js +22 -3
  19. package/_cjs/core/Siwe.js.map +1 -1
  20. package/_cjs/core/TxEnvelopeEip1559.js +2 -1
  21. package/_cjs/core/TxEnvelopeEip1559.js.map +1 -1
  22. package/_cjs/core/TxEnvelopeEip2930.js +2 -1
  23. package/_cjs/core/TxEnvelopeEip2930.js.map +1 -1
  24. package/_cjs/core/TxEnvelopeEip7702.js +5 -1
  25. package/_cjs/core/TxEnvelopeEip7702.js.map +1 -1
  26. package/_cjs/core/TxEnvelopeLegacy.js +41 -8
  27. package/_cjs/core/TxEnvelopeLegacy.js.map +1 -1
  28. package/_cjs/core/TypedData.js +7 -9
  29. package/_cjs/core/TypedData.js.map +1 -1
  30. package/_cjs/core/Value.js +8 -3
  31. package/_cjs/core/Value.js.map +1 -1
  32. package/_cjs/core/internal/abiParameters.js +6 -2
  33. package/_cjs/core/internal/abiParameters.js.map +1 -1
  34. package/_cjs/core/internal/cursor.js +30 -1
  35. package/_cjs/core/internal/cursor.js.map +1 -1
  36. package/_cjs/erc4337/UserOperation.js +1 -1
  37. package/_cjs/erc4337/UserOperation.js.map +1 -1
  38. package/_cjs/erc7821/Execute.js +41 -3
  39. package/_cjs/erc7821/Execute.js.map +1 -1
  40. package/_cjs/tempo/KeyAuthorization.js +22 -1
  41. package/_cjs/tempo/KeyAuthorization.js.map +1 -1
  42. package/_cjs/tempo/SignatureEnvelope.js +37 -12
  43. package/_cjs/tempo/SignatureEnvelope.js.map +1 -1
  44. package/_cjs/tempo/SignaturePreAuthorized.js +177 -0
  45. package/_cjs/tempo/SignaturePreAuthorized.js.map +1 -0
  46. package/_cjs/tempo/TxEnvelopeTempo.js +34 -3
  47. package/_cjs/tempo/TxEnvelopeTempo.js.map +1 -1
  48. package/_cjs/tempo/index.js +2 -1
  49. package/_cjs/tempo/index.js.map +1 -1
  50. package/_cjs/version.js +1 -1
  51. package/_cjs/webauthn/Registration.js +2 -6
  52. package/_cjs/webauthn/Registration.js.map +1 -1
  53. package/_esm/core/AbiError.js +64 -3
  54. package/_esm/core/AbiError.js.map +1 -1
  55. package/_esm/core/AbiEvent.js +24 -3
  56. package/_esm/core/AbiEvent.js.map +1 -1
  57. package/_esm/core/AbiFunction.js +64 -3
  58. package/_esm/core/AbiFunction.js.map +1 -1
  59. package/_esm/core/Address.js +17 -1
  60. package/_esm/core/Address.js.map +1 -1
  61. package/_esm/core/Authorization.js +47 -2
  62. package/_esm/core/Authorization.js.map +1 -1
  63. package/_esm/core/Keystore.js +33 -2
  64. package/_esm/core/Keystore.js.map +1 -1
  65. package/_esm/core/Secp256k1.js +5 -1
  66. package/_esm/core/Secp256k1.js.map +1 -1
  67. package/_esm/core/Signature.js +4 -2
  68. package/_esm/core/Signature.js.map +1 -1
  69. package/_esm/core/Siwe.js +29 -3
  70. package/_esm/core/Siwe.js.map +1 -1
  71. package/_esm/core/TxEnvelopeEip1559.js +2 -1
  72. package/_esm/core/TxEnvelopeEip1559.js.map +1 -1
  73. package/_esm/core/TxEnvelopeEip2930.js +2 -1
  74. package/_esm/core/TxEnvelopeEip2930.js.map +1 -1
  75. package/_esm/core/TxEnvelopeEip7702.js +6 -1
  76. package/_esm/core/TxEnvelopeEip7702.js.map +1 -1
  77. package/_esm/core/TxEnvelopeLegacy.js +49 -9
  78. package/_esm/core/TxEnvelopeLegacy.js.map +1 -1
  79. package/_esm/core/TypedData.js +9 -9
  80. package/_esm/core/TypedData.js.map +1 -1
  81. package/_esm/core/Value.js +14 -3
  82. package/_esm/core/Value.js.map +1 -1
  83. package/_esm/core/internal/abiParameters.js +9 -2
  84. package/_esm/core/internal/abiParameters.js.map +1 -1
  85. package/_esm/core/internal/cursor.js +32 -0
  86. package/_esm/core/internal/cursor.js.map +1 -1
  87. package/_esm/erc4337/UserOperation.js +1 -1
  88. package/_esm/erc4337/UserOperation.js.map +1 -1
  89. package/_esm/erc7821/Execute.js +76 -2
  90. package/_esm/erc7821/Execute.js.map +1 -1
  91. package/_esm/index.js +1 -1
  92. package/_esm/tempo/KeyAuthorization.js +21 -0
  93. package/_esm/tempo/KeyAuthorization.js.map +1 -1
  94. package/_esm/tempo/SignatureEnvelope.js +46 -13
  95. package/_esm/tempo/SignatureEnvelope.js.map +1 -1
  96. package/_esm/tempo/SignaturePreAuthorized.js +314 -0
  97. package/_esm/tempo/SignaturePreAuthorized.js.map +1 -0
  98. package/_esm/tempo/TxEnvelopeTempo.js +56 -2
  99. package/_esm/tempo/TxEnvelopeTempo.js.map +1 -1
  100. package/_esm/tempo/index.js +8 -0
  101. package/_esm/tempo/index.js.map +1 -1
  102. package/_esm/version.js +1 -1
  103. package/_esm/webauthn/Registration.js +2 -6
  104. package/_esm/webauthn/Registration.js.map +1 -1
  105. package/_types/core/AbiError.d.ts +51 -5
  106. package/_types/core/AbiError.d.ts.map +1 -1
  107. package/_types/core/AbiEvent.d.ts +4 -2
  108. package/_types/core/AbiEvent.d.ts.map +1 -1
  109. package/_types/core/AbiFunction.d.ts +48 -2
  110. package/_types/core/AbiFunction.d.ts.map +1 -1
  111. package/_types/core/Address.d.ts +17 -2
  112. package/_types/core/Address.d.ts.map +1 -1
  113. package/_types/core/Authorization.d.ts +24 -2
  114. package/_types/core/Authorization.d.ts.map +1 -1
  115. package/_types/core/Keystore.d.ts +31 -2
  116. package/_types/core/Keystore.d.ts.map +1 -1
  117. package/_types/core/Secp256k1.d.ts.map +1 -1
  118. package/_types/core/Signature.d.ts +1 -1
  119. package/_types/core/Signature.d.ts.map +1 -1
  120. package/_types/core/Siwe.d.ts +4 -0
  121. package/_types/core/Siwe.d.ts.map +1 -1
  122. package/_types/core/TxEnvelopeEip1559.d.ts.map +1 -1
  123. package/_types/core/TxEnvelopeEip2930.d.ts.map +1 -1
  124. package/_types/core/TxEnvelopeEip7702.d.ts +1 -1
  125. package/_types/core/TxEnvelopeEip7702.d.ts.map +1 -1
  126. package/_types/core/TxEnvelopeLegacy.d.ts.map +1 -1
  127. package/_types/core/TypedData.d.ts +3 -1
  128. package/_types/core/TypedData.d.ts.map +1 -1
  129. package/_types/core/Value.d.ts.map +1 -1
  130. package/_types/core/internal/abiParameters.d.ts +1 -1
  131. package/_types/core/internal/abiParameters.d.ts.map +1 -1
  132. package/_types/core/internal/cursor.d.ts +13 -0
  133. package/_types/core/internal/cursor.d.ts.map +1 -1
  134. package/_types/erc7821/Execute.d.ts +46 -1
  135. package/_types/erc7821/Execute.d.ts.map +1 -1
  136. package/_types/index.d.ts +1 -1
  137. package/_types/tempo/KeyAuthorization.d.ts +9 -3
  138. package/_types/tempo/KeyAuthorization.d.ts.map +1 -1
  139. package/_types/tempo/SignatureEnvelope.d.ts +1 -1
  140. package/_types/tempo/SignatureEnvelope.d.ts.map +1 -1
  141. package/_types/tempo/SignaturePreAuthorized.d.ts +192 -0
  142. package/_types/tempo/SignaturePreAuthorized.d.ts.map +1 -0
  143. package/_types/tempo/TxEnvelopeTempo.d.ts +30 -1
  144. package/_types/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  145. package/_types/tempo/index.d.ts +8 -0
  146. package/_types/tempo/index.d.ts.map +1 -1
  147. package/_types/version.d.ts +1 -1
  148. package/_types/webauthn/Registration.d.ts +2 -0
  149. package/_types/webauthn/Registration.d.ts.map +1 -1
  150. package/core/AbiError.ts +81 -7
  151. package/core/AbiEvent.ts +50 -11
  152. package/core/AbiFunction.ts +76 -4
  153. package/core/Address.ts +18 -1
  154. package/core/Authorization.ts +47 -4
  155. package/core/Keystore.ts +40 -3
  156. package/core/Secp256k1.ts +5 -1
  157. package/core/Signature.ts +7 -2
  158. package/core/Siwe.ts +29 -3
  159. package/core/TxEnvelopeEip1559.ts +4 -1
  160. package/core/TxEnvelopeEip2930.ts +4 -1
  161. package/core/TxEnvelopeEip7702.ts +9 -2
  162. package/core/TxEnvelopeLegacy.ts +56 -10
  163. package/core/TypedData.ts +10 -9
  164. package/core/Value.ts +14 -3
  165. package/core/internal/abiParameters.ts +8 -2
  166. package/core/internal/cursor.ts +36 -0
  167. package/erc4337/UserOperation.ts +1 -1
  168. package/erc7821/Execute.ts +84 -3
  169. package/index.ts +1 -1
  170. package/package.json +11 -1
  171. package/tempo/KeyAuthorization.test.ts +91 -0
  172. package/tempo/KeyAuthorization.ts +32 -3
  173. package/tempo/SignatureEnvelope.test.ts +211 -27
  174. package/tempo/SignatureEnvelope.ts +55 -11
  175. package/tempo/SignaturePreAuthorized/package.json +6 -0
  176. package/tempo/SignaturePreAuthorized.test-d/package.json +6 -0
  177. package/tempo/SignaturePreAuthorized.test-d.ts +29 -0
  178. package/tempo/SignaturePreAuthorized.test.ts +410 -0
  179. package/tempo/SignaturePreAuthorized.ts +370 -0
  180. package/tempo/TxEnvelopeTempo.test.ts +310 -0
  181. package/tempo/TxEnvelopeTempo.ts +64 -1
  182. package/tempo/index.ts +9 -0
  183. package/version.ts +1 -1
  184. package/webauthn/Registration.ts +4 -6
package/core/Siwe.ts CHANGED
@@ -23,6 +23,9 @@ export const prefixRegex =
23
23
  export const suffixRegex =
24
24
  /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.*))?(?:\nResources:(?<resources>(?:\n- .+)*))?/
25
25
 
26
+ // Matches `suffixRegex` from the start of the input to its end.
27
+ const anchoredSuffixRegex = new RegExp(`^(?:${suffixRegex.source})$`)
28
+
26
29
  // URI validation (see `isUri`).
27
30
  const uriIllegalCharacterRegex = /[^a-z0-9:/?#[\]@!$&'()*+,;=.\-_~%]/i
28
31
  const uriInvalidEscapeRegex = /%[^0-9a-f]/i
@@ -211,6 +214,15 @@ export function createMessage(value: Message): string {
211
214
  `Provided value: ${statement}`,
212
215
  ],
213
216
  })
217
+ if (requestId && /[\n\r]/.test(requestId))
218
+ throw new InvalidMessageFieldError({
219
+ field: 'requestId',
220
+ metaMessages: [
221
+ "- Request ID must not include '\\n' or '\\r'.",
222
+ '',
223
+ `Provided value: ${requestId}`,
224
+ ],
225
+ })
214
226
  }
215
227
 
216
228
  // Construct message
@@ -341,6 +353,10 @@ function splitUri(value: string) {
341
353
  /**
342
354
  * [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message into message fields object.
343
355
  *
356
+ * The message can be the prefix (up to the statement), the suffix (from `URI`), or both.
357
+ * Returns an empty object when the message has any other text, such as fields that are
358
+ * out of order or text after the last field.
359
+ *
344
360
  * @example
345
361
  * ```ts twoslash
346
362
  * import { Siwe } from 'ox'
@@ -371,13 +387,23 @@ function splitUri(value: string) {
371
387
  * @returns Message fields object.
372
388
  */
373
389
  export function parseMessage(message: string): ExactPartial<Message> {
374
- const { scheme, statement, ...prefix } = (message.match(prefixRegex)
375
- ?.groups ?? {}) as {
390
+ const prefixMatch = message.match(prefixRegex)
391
+ const { scheme, statement, ...prefix } = (prefixMatch?.groups ?? {}) as {
376
392
  address: Address.Address
377
393
  domain: string
378
394
  scheme?: string
379
395
  statement?: string
380
396
  }
397
+ // The suffix starts where the prefix ends. Without a statement, the prefix
398
+ // is followed by one more line feed (as `createMessage` emits) or by none.
399
+ const rest = (() => {
400
+ const rest = message.slice(prefixMatch?.[0].length ?? 0)
401
+ if (prefixMatch && statement === undefined && rest.startsWith('\n'))
402
+ return rest.slice(1)
403
+ return rest
404
+ })()
405
+ const suffixMatch = rest.match(anchoredSuffixRegex)
406
+ if (rest && !suffixMatch) return {}
381
407
  const {
382
408
  chainId,
383
409
  expirationTime,
@@ -386,7 +412,7 @@ export function parseMessage(message: string): ExactPartial<Message> {
386
412
  requestId,
387
413
  resources: resources_,
388
414
  ...suffix
389
- } = (message.match(suffixRegex)?.groups ?? {}) as {
415
+ } = (suffixMatch?.groups ?? {}) as {
390
416
  chainId: string
391
417
  expirationTime?: string
392
418
  issuedAt?: string
@@ -68,7 +68,10 @@ export type Type = typeof type
68
68
  */
69
69
  export function assert(envelope: PartialBy<TxEnvelopeEip1559, 'type'>) {
70
70
  const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = envelope
71
- if (chainId <= 0)
71
+ if (
72
+ typeof chainId !== 'undefined' &&
73
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
74
+ )
72
75
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
73
76
  if (to) Address.assert(to, { strict: false })
74
77
  if (maxFeePerGas && BigInt(maxFeePerGas) > 2n ** 256n - 1n)
@@ -66,7 +66,10 @@ export type Type = typeof type
66
66
  */
67
67
  export function assert(envelope: PartialBy<TxEnvelopeEip2930, 'type'>) {
68
68
  const { chainId, gasPrice, to } = envelope
69
- if (chainId <= 0)
69
+ if (
70
+ typeof chainId !== 'undefined' &&
71
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
72
+ )
70
73
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
71
74
  if (to) Address.assert(to, { strict: false })
72
75
  if (gasPrice && BigInt(gasPrice) > 2n ** 256n - 1n)
@@ -183,10 +183,17 @@ export function deserialize(
183
183
  transaction.maxFeePerGas = 0n
184
184
  if (accessList!.length !== 0 && accessList !== '0x')
185
185
  transaction.accessList = AccessList.fromTupleList(accessList as never)
186
- if (authorizationList !== '0x')
186
+ if (authorizationList !== '0x') {
187
+ // A transaction holds signed authorizations only.
188
+ for (const tuple of authorizationList as never as readonly unknown[])
189
+ if (!Array.isArray(tuple) || tuple.length !== 6)
190
+ throw new Authorization.InvalidError(
191
+ 'Expected [chainId, address, nonce, yParity, r, s].',
192
+ )
187
193
  transaction.authorizationList = Authorization.fromTupleList(
188
194
  authorizationList as never,
189
195
  )
196
+ }
190
197
 
191
198
  const signature =
192
199
  r && s && yParity ? Signature.fromTuple([yParity, r, s]) : undefined
@@ -202,7 +209,7 @@ export function deserialize(
202
209
  }
203
210
 
204
211
  export declare namespace deserialize {
205
- type ErrorType = Errors.GlobalErrorType
212
+ type ErrorType = Authorization.InvalidError | Errors.GlobalErrorType
206
213
  }
207
214
 
208
215
  /**
@@ -65,7 +65,10 @@ export type Type = typeof type
65
65
  export function assert(envelope: PartialBy<TxEnvelopeLegacy, 'type'>) {
66
66
  const { chainId, gasPrice, to } = envelope
67
67
  if (to) Address.assert(to, { strict: false })
68
- if (typeof chainId !== 'undefined' && chainId <= 0)
68
+ if (
69
+ typeof chainId !== 'undefined' &&
70
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
71
+ )
69
72
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
70
73
  if (gasPrice && BigInt(gasPrice) > 2n ** 256n - 1n)
71
74
  throw new TransactionEnvelope.GasPriceTooHighError({ gasPrice })
@@ -106,7 +109,12 @@ export function deserialize(serialized: Hex.Hex): Compute<TxEnvelopeLegacy> {
106
109
  const [nonce, gasPrice, gas, to, value, data, chainIdOrV_, r, s] =
107
110
  tuple as readonly Hex.Hex[]
108
111
 
109
- if (!(tuple.length === 6 || tuple.length === 9))
112
+ if (
113
+ !Array.isArray(tuple) ||
114
+ !(tuple.length === 6 || tuple.length === 9) ||
115
+ // Every field is a byte string, never a nested list.
116
+ tuple.some((item) => typeof item !== 'string')
117
+ )
110
118
  throw new TransactionEnvelope.InvalidSerializedError({
111
119
  attributes: {
112
120
  nonce,
@@ -136,21 +144,44 @@ export function deserialize(serialized: Hex.Hex): Compute<TxEnvelopeLegacy> {
136
144
  if (Hex.validate(nonce))
137
145
  transaction.nonce = nonce === '0x' ? 0n : BigInt(nonce)
138
146
  if (Hex.validate(value) && value !== '0x') transaction.value = BigInt(value)
147
+ // `gasPrice`, `r` and `s` are bounded by byte length, so that an oversized
148
+ // value is rejected before it is converted.
149
+ if (Hex.size(gasPrice as Hex.Hex) > 32)
150
+ throw new TransactionEnvelope.GasPriceTooHighError()
139
151
  if (Hex.validate(gasPrice) && gasPrice !== '0x')
140
152
  transaction.gasPrice = BigInt(gasPrice)
141
153
 
142
- if (tuple.length === 6) return transaction
154
+ if (tuple.length === 6) {
155
+ assert(transaction)
156
+ return transaction
157
+ }
143
158
 
144
- const chainIdOrV =
145
- Hex.validate(chainIdOrV_) && chainIdOrV_ !== '0x'
146
- ? Number(chainIdOrV_ as Hex.Hex)
147
- : 0
159
+ // `chainId` and `yParity` are derived from `v` as a number, so `v` must be a
160
+ // safe integer (which fits in 7 bytes).
161
+ const chainIdOrV = (() => {
162
+ if (Hex.size(chainIdOrV_ as Hex.Hex) > 7) return Number.NaN
163
+ if (Hex.validate(chainIdOrV_) && chainIdOrV_ !== '0x')
164
+ return Number(chainIdOrV_ as Hex.Hex)
165
+ return 0
166
+ })()
167
+ if (!Number.isSafeInteger(chainIdOrV))
168
+ throw new TransactionEnvelope.InvalidSerializedError({
169
+ attributes: {},
170
+ serialized,
171
+ type,
172
+ })
148
173
 
149
174
  if (s === '0x' && r === '0x') {
150
175
  if (chainIdOrV > 0) transaction.chainId = Number(chainIdOrV)
176
+ assert(transaction)
151
177
  return transaction
152
178
  }
153
179
 
180
+ if (Hex.size(r as Hex.Hex) > 32)
181
+ throw new Signature.InvalidRError({ value: r })
182
+ if (Hex.size(s as Hex.Hex) > 32)
183
+ throw new Signature.InvalidSError({ value: s })
184
+
154
185
  const v = chainIdOrV
155
186
  const chainId: number | undefined = Math.floor((v - 35) / 2)
156
187
  if (chainId > 0) transaction.chainId = chainId
@@ -380,11 +411,18 @@ export function hash<presign extends boolean = false>(
380
411
  options: hash.Options<presign> = {},
381
412
  ): hash.ReturnType {
382
413
  const { presign } = options
414
+ const { chainId, v } = envelope
383
415
  return Hash.keccak256(
384
416
  serialize({
385
417
  ...envelope,
386
418
  ...(presign
387
419
  ? {
420
+ // An EIP-155 `v` carries the chain ID when `chainId` is absent.
421
+ chainId:
422
+ chainId ??
423
+ (typeof v === 'number' && v >= 37
424
+ ? Math.floor((v - 35) / 2)
425
+ : undefined),
388
426
  r: undefined,
389
427
  s: undefined,
390
428
  yParity: undefined,
@@ -495,6 +533,17 @@ export function serialize(
495
533
 
496
534
  if (signature) {
497
535
  const v = (() => {
536
+ // EIP-155 (explicit chainId)
537
+ if (chainId > 0) {
538
+ if (signature.v >= 35) {
539
+ // `v` must encode the same chain as `chainId`.
540
+ if (Math.floor((signature.v - 35) / 2) !== chainId)
541
+ throw new TransactionEnvelope.InvalidChainIdError({ chainId })
542
+ return signature.v
543
+ }
544
+ return chainId * 2 + 35 + Signature.vToYParity(signature.v)
545
+ }
546
+
498
547
  // EIP-155 (inferred chainId)
499
548
  if (signature.v >= 35) {
500
549
  const inferredChainId = Math.floor((signature.v - 35) / 2)
@@ -502,9 +551,6 @@ export function serialize(
502
551
  return 27 + (signature.v === 35 ? 0 : 1)
503
552
  }
504
553
 
505
- // EIP-155 (explicit chainId)
506
- if (chainId > 0) return chainId * 2 + 35 + signature.v - 27
507
-
508
554
  // Pre-EIP-155 (no chainId)
509
555
  const v = 27 + (signature.v === 27 ? 0 : 1)
510
556
  if (signature.v !== v)
package/core/TypedData.ts CHANGED
@@ -146,6 +146,8 @@ export function assert<
146
146
  expectedSize: Number.parseInt(size, 10),
147
147
  givenSize: Hex.size(value as Hex.Hex),
148
148
  })
149
+ if (size && (value as Hex.Hex).length % 2 !== 0)
150
+ throw new Hex.InvalidLengthError(value as Hex.Hex)
149
151
  }
150
152
 
151
153
  if (Object.hasOwn(types, type))
@@ -184,6 +186,7 @@ export declare namespace assert {
184
186
  | InvalidPrimaryTypeError
185
187
  | InvalidStructTypeError
186
188
  | InvalidTypeError
189
+ | Hex.InvalidLengthError
187
190
  | Hex.fromNumber.ErrorType
188
191
  | Hex.size.ErrorType
189
192
  | Errors.GlobalErrorType
@@ -372,6 +375,8 @@ export declare namespace encodeType {
372
375
  /**
373
376
  * Gets [EIP-712 Typed Data](https://eips.ethereum.org/EIPS/eip-712) schema for EIP-721 domain.
374
377
  *
378
+ * A field is part of the schema when it is present on the domain (not `undefined` or `null`).
379
+ *
375
380
  * @example
376
381
  * ```ts twoslash
377
382
  * import { TypedData } from 'ox'
@@ -397,18 +402,14 @@ export function extractEip712DomainTypes(
397
402
  domain: Domain | undefined,
398
403
  ): Parameter[] {
399
404
  return [
400
- typeof domain?.name === 'string' && { name: 'name', type: 'string' },
401
- typeof domain?.version === 'string' && { name: 'version', type: 'string' },
402
- (typeof domain?.chainId === 'number' ||
403
- typeof domain?.chainId === 'bigint') && {
404
- name: 'chainId',
405
- type: 'uint256',
406
- },
407
- domain?.verifyingContract && {
405
+ domain?.name != null && { name: 'name', type: 'string' },
406
+ domain?.version != null && { name: 'version', type: 'string' },
407
+ domain?.chainId != null && { name: 'chainId', type: 'uint256' },
408
+ domain?.verifyingContract != null && {
408
409
  name: 'verifyingContract',
409
410
  type: 'address',
410
411
  },
411
- domain?.salt && { name: 'salt', type: 'bytes32' },
412
+ domain?.salt != null && { name: 'salt', type: 'bytes32' },
412
413
  ].filter(Boolean) as Parameter[]
413
414
  }
414
415
 
package/core/Value.ts CHANGED
@@ -10,7 +10,6 @@ export const exponents = {
10
10
  } as const
11
11
 
12
12
  const decimalNumberRegex = /^(-?)([0-9]*)\.?([0-9]*)$/
13
- const trailingZerosRegex = /(0+)$/
14
13
 
15
14
  /**
16
15
  * Formats a `bigint` Value to its string representation (divided by the given exponent).
@@ -39,7 +38,7 @@ export function format(value: bigint, decimals = 0) {
39
38
  display.slice(0, display.length - decimals),
40
39
  display.slice(display.length - decimals),
41
40
  ]
42
- fraction = fraction.replace(trailingZerosRegex, '')
41
+ fraction = trimTrailingZeros(fraction)
43
42
  return `${negative ? '-' : ''}${integer || '0'}${
44
43
  fraction ? `.${fraction}` : ''
45
44
  }`
@@ -123,7 +122,7 @@ export function from(value: string, decimals = 0) {
123
122
  if (negative) integer = integer.slice(1)
124
123
 
125
124
  // trim trailing zeros.
126
- fraction = fraction.replace(trailingZerosRegex, '')
125
+ fraction = trimTrailingZeros(fraction)
127
126
 
128
127
  // round off if the fraction is larger than the number of decimals.
129
128
  if (decimals === 0) {
@@ -159,6 +158,18 @@ export declare namespace from {
159
158
  type ErrorType = Errors.GlobalErrorType
160
159
  }
161
160
 
161
+ /**
162
+ * Removes trailing zeros with a backward scan, which stays linear in the
163
+ * length of the value.
164
+ *
165
+ * @internal
166
+ */
167
+ function trimTrailingZeros(value: string): string {
168
+ let end = value.length
169
+ while (end > 0 && value.charCodeAt(end - 1) === 48) end--
170
+ return value.slice(0, end)
171
+ }
172
+
162
173
  /**
163
174
  * Parses a string representation of Ether to a `bigint` Value (default: wei).
164
175
  *
@@ -280,8 +280,9 @@ export function decodeBytes(
280
280
  return [Hex.fromBytes(data), 32]
281
281
  }
282
282
 
283
- const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size, 10), 32))
284
- return [value, 32]
283
+ // Read the whole slot so that a slot cut short of its padding is out of bounds.
284
+ const word = cursor.readBytes(32)
285
+ return [Hex.fromBytes(word.subarray(0, Number.parseInt(size, 10))), 32]
285
286
  }
286
287
 
287
288
  export declare namespace decodeBytes {
@@ -664,6 +665,9 @@ export function encodeBytes(
664
665
  const [, parametersize] = type.split('bytes')
665
666
  const bytesSize = Hex.size(value)
666
667
  if (!parametersize) {
668
+ // An unpaired nibble has no byte to belong to, so reject it instead of
669
+ // guessing which half of a byte it is.
670
+ if (value.length % 2 !== 0) throw new Hex.InvalidLengthError(value)
667
671
  let value_ = value
668
672
  // If the size is not divisible by 32 bytes, pad the end
669
673
  // with empty bytes to the ceiling 32 bytes.
@@ -682,12 +686,14 @@ export function encodeBytes(
682
686
  expectedSize: Number.parseInt(parametersize, 10),
683
687
  value,
684
688
  })
689
+ if (value.length % 2 !== 0) throw new Hex.InvalidLengthError(value)
685
690
  return { dynamic: false, encoded: Hex.padRight(value) }
686
691
  }
687
692
 
688
693
  /** @internal */
689
694
  export declare namespace encodeBytes {
690
695
  type ErrorType =
696
+ | Hex.InvalidLengthError
691
697
  | Hex.padLeft.ErrorType
692
698
  | Hex.padRight.ErrorType
693
699
  | Hex.fromNumber.ErrorType
@@ -7,10 +7,15 @@ export type Cursor = {
7
7
  dataView: DataView
8
8
  position: number
9
9
  positionReadCount: Map<number, number>
10
+ /** Total number of bytes read. */
11
+ readSize: number
12
+ /** Maximum total number of bytes that can be read. */
13
+ readSizeLimit: number
10
14
  recursiveReadCount: number
11
15
  recursiveReadLimit: number
12
16
  remaining: number
13
17
  assertReadLimit(position?: number): void
18
+ assertReadSize(length: number): void
14
19
  assertPosition(position: number): void
15
20
  decrementPosition(offset: number): void
16
21
  getReadCount(position?: number): number
@@ -42,6 +47,8 @@ const staticCursor: Cursor = {
42
47
  dataView: new DataView(new ArrayBuffer(0)),
43
48
  position: 0,
44
49
  positionReadCount: new Map(),
50
+ readSize: 0,
51
+ readSizeLimit: Number.POSITIVE_INFINITY,
45
52
  recursiveReadCount: 0,
46
53
  recursiveReadLimit: Number.POSITIVE_INFINITY,
47
54
  assertReadLimit() {
@@ -51,6 +58,14 @@ const staticCursor: Cursor = {
51
58
  limit: this.recursiveReadLimit,
52
59
  })
53
60
  },
61
+ assertReadSize(length) {
62
+ this.readSize += length
63
+ if (this.readSize > this.readSizeLimit)
64
+ throw new ReadSizeLimitExceededError({
65
+ limit: this.readSizeLimit,
66
+ size: this.readSize,
67
+ })
68
+ },
54
69
  assertPosition(position) {
55
70
  if (position < 0 || position > this.bytes.length - 1)
56
71
  throw new PositionOutOfBoundsError({
@@ -141,6 +156,7 @@ const staticCursor: Cursor = {
141
156
  this.assertReadLimit()
142
157
  this._touch()
143
158
  const value = this.inspectByte()
159
+ this.assertReadSize(1)
144
160
  this.position++
145
161
  return value
146
162
  },
@@ -148,6 +164,7 @@ const staticCursor: Cursor = {
148
164
  this.assertReadLimit()
149
165
  this._touch()
150
166
  const value = this.inspectBytes(length)
167
+ this.assertReadSize(length)
151
168
  this.position += size ?? length
152
169
  return value
153
170
  },
@@ -155,6 +172,7 @@ const staticCursor: Cursor = {
155
172
  this.assertReadLimit()
156
173
  this._touch()
157
174
  const value = this.inspectUint8()
175
+ this.assertReadSize(1)
158
176
  this.position += 1
159
177
  return value
160
178
  },
@@ -162,6 +180,7 @@ const staticCursor: Cursor = {
162
180
  this.assertReadLimit()
163
181
  this._touch()
164
182
  const value = this.inspectUint16()
183
+ this.assertReadSize(2)
165
184
  this.position += 2
166
185
  return value
167
186
  },
@@ -169,6 +188,7 @@ const staticCursor: Cursor = {
169
188
  this.assertReadLimit()
170
189
  this._touch()
171
190
  const value = this.inspectUint24()
191
+ this.assertReadSize(3)
172
192
  this.position += 3
173
193
  return value
174
194
  },
@@ -176,6 +196,7 @@ const staticCursor: Cursor = {
176
196
  this.assertReadLimit()
177
197
  this._touch()
178
198
  const value = this.inspectUint32()
199
+ this.assertReadSize(4)
179
200
  this.position += 4
180
201
  return value
181
202
  },
@@ -210,6 +231,10 @@ export function create(
210
231
  )
211
232
  cursor.positionReadCount = new Map()
212
233
  cursor.recursiveReadLimit = recursiveReadLimit
234
+ // `recursiveReadLimit` allows one read per position plus that many repeated
235
+ // reads. Allow as many bytes as that number of 32-byte reads, so that reads
236
+ // of any length are bounded by the size of the data as well.
237
+ cursor.readSizeLimit = 32 * (bytes.length + recursiveReadLimit)
213
238
  return cursor
214
239
  }
215
240
 
@@ -240,6 +265,17 @@ export class PositionOutOfBoundsError extends Errors.BaseError {
240
265
  }
241
266
  }
242
267
 
268
+ /** @internal */
269
+ export class ReadSizeLimitExceededError extends Errors.BaseError {
270
+ override readonly name = 'Cursor.ReadSizeLimitExceededError'
271
+
272
+ constructor({ limit, size }: { limit: number; size: number }) {
273
+ super(
274
+ `Read size limit of \`${limit}\` bytes exceeded (read size: \`${size}\` bytes).`,
275
+ )
276
+ }
277
+ }
278
+
243
279
  /** @internal */
244
280
  export class RecursiveReadLimitExceededError extends Errors.BaseError {
245
281
  override readonly name = 'Cursor.RecursiveReadLimitExceededError'
@@ -500,7 +500,7 @@ export function hash<
500
500
  Hex.padLeft(Hex.fromNumber(maxFeePerGas), 16),
501
501
  )
502
502
  const initCode_hashed = Hash.keccak256(
503
- factory && factoryData ? Hex.concat(factory, factoryData) : '0x',
503
+ toInitCode({ factory, factoryData }),
504
504
  )
505
505
  const paymasterAndData_hashed = Hash.keccak256(
506
506
  paymaster
@@ -1,5 +1,6 @@
1
1
  import * as AbiFunction from '../core/AbiFunction.js'
2
- import type * as Hex from '../core/Hex.js'
2
+ import * as Errors from '../core/Errors.js'
3
+ import * as Hex from '../core/Hex.js'
3
4
  import { AbiParameters } from '../index.js'
4
5
  import * as Calls from './Calls.js'
5
6
 
@@ -39,6 +40,10 @@ export const mode = {
39
40
  /**
40
41
  * Decodes calls from ERC-7821 `execute` function data.
41
42
  *
43
+ * Decodes the single batch modes only (`mode.default` and `mode.opData`). Throws
44
+ * `Execute.UnsupportedModeError` for the "batch of batches" mode (use
45
+ * `Execute.decodeBatchOfBatchesData` instead) and for unknown modes.
46
+ *
42
47
  * @example
43
48
  * ```ts twoslash
44
49
  * import { Execute } from 'ox/erc7821'
@@ -54,7 +59,13 @@ export function decodeData(data: Hex.Hex): decodeData.ReturnType {
54
59
  Hex.Hex,
55
60
  Hex.Hex,
56
61
  ]
57
- return Calls.decode(executionData, { opData: m !== mode.default })
62
+ const name = getModeName(m)
63
+ if (name !== 'default' && name !== 'opData')
64
+ throw new UnsupportedModeError({
65
+ mode: m,
66
+ supported: ['default', 'opData'],
67
+ })
68
+ return Calls.decode(executionData, { opData: name === 'opData' })
58
69
  }
59
70
 
60
71
  export declare namespace decodeData {
@@ -62,11 +73,15 @@ export declare namespace decodeData {
62
73
  calls: Call[]
63
74
  opData?: Hex.Hex | undefined
64
75
  }
76
+
77
+ type ErrorType = UnsupportedModeError | Errors.GlobalErrorType
65
78
  }
66
79
 
67
80
  /**
68
81
  * Decodes batches from ERC-7821 `execute` function data in "batch of batches" mode.
69
82
  *
83
+ * Throws `Execute.UnsupportedModeError` for any other mode.
84
+ *
70
85
  * @example
71
86
  * ```ts twoslash
72
87
  * import { Execute } from 'ox/erc7821'
@@ -80,10 +95,12 @@ export declare namespace decodeData {
80
95
  export function decodeBatchOfBatchesData(
81
96
  data: Hex.Hex,
82
97
  ): decodeBatchOfBatchesData.ReturnType {
83
- const [, executionData] = AbiFunction.decodeData(abiFunction, data) as [
98
+ const [m, executionData] = AbiFunction.decodeData(abiFunction, data) as [
84
99
  Hex.Hex,
85
100
  Hex.Hex,
86
101
  ]
102
+ if (getModeName(m) !== 'batchOfBatches')
103
+ throw new UnsupportedModeError({ mode: m, supported: ['batchOfBatches'] })
87
104
 
88
105
  const [encodedBatches] = AbiParameters.decode(
89
106
  AbiParameters.from('bytes[]'),
@@ -112,6 +129,8 @@ export function decodeBatchOfBatchesData(
112
129
 
113
130
  export declare namespace decodeBatchOfBatchesData {
114
131
  type ReturnType = Batch[]
132
+
133
+ type ErrorType = UnsupportedModeError | Errors.GlobalErrorType
115
134
  }
116
135
 
117
136
  /**
@@ -195,3 +214,65 @@ export declare namespace encodeData {
195
214
  opData?: Hex.Hex | undefined
196
215
  }
197
216
  }
217
+
218
+ /**
219
+ * Thrown when the mode of ERC-7821 `execute` function data is not supported by the decoder.
220
+ *
221
+ * @example
222
+ * ```ts twoslash
223
+ * import { Execute } from 'ox/erc7821'
224
+ *
225
+ * const data = Execute.encodeBatchOfBatchesData([
226
+ * {
227
+ * calls: [
228
+ * {
229
+ * data: '0xcafebabe',
230
+ * to: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',
231
+ * value: 1n
232
+ * }
233
+ * ]
234
+ * }
235
+ * ])
236
+ *
237
+ * Execute.decodeData(data)
238
+ * // @error: Execute.UnsupportedModeError: Execution mode `0x0100000000007821000200000000000000000000000000000000000000000000` is not supported.
239
+ * ```
240
+ */
241
+ export class UnsupportedModeError extends Errors.BaseError {
242
+ override readonly name = 'Execute.UnsupportedModeError'
243
+
244
+ constructor({ mode, supported }: UnsupportedModeError.Options) {
245
+ super(`Execution mode \`${mode}\` is not supported.`, {
246
+ metaMessages: [
247
+ `Supported modes: ${supported.map((name) => `\`${name}\``).join(', ')}.`,
248
+ ],
249
+ })
250
+ }
251
+ }
252
+
253
+ export declare namespace UnsupportedModeError {
254
+ /** Options for `Execute.UnsupportedModeError`. */
255
+ type Options = {
256
+ /** Mode of the `execute` function data. */
257
+ mode: Hex.Hex
258
+ /** Names of the modes (keys of `Execute.mode`) the decoder supports. */
259
+ supported: readonly (keyof typeof mode)[]
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Identifies an ERC-7821 execution mode the way the reference implementation
265
+ * (`_executionModeId`) does. Bytes `[0..1]` (call type and execution type) and
266
+ * bytes `[6..9]` (mode selector) identify the mode. Bytes `[2..5]` (reserved by
267
+ * ERC-7579) and bytes `[10..31]` (unused) are ignored.
268
+ *
269
+ * @internal
270
+ */
271
+ function getModeName(m: Hex.Hex): keyof typeof mode | undefined {
272
+ if (Hex.slice(m, 0, 2) !== '0x0100') return undefined
273
+ const selector = Hex.slice(m, 6, 10)
274
+ if (selector === '0x00000000') return 'default'
275
+ if (selector === '0x78210001') return 'opData'
276
+ if (selector === '0x78210002') return 'batchOfBatches'
277
+ return undefined
278
+ }
package/index.ts CHANGED
@@ -259,7 +259,7 @@ export * as AbiConstructor from './core/AbiConstructor.js'
259
259
  * const abi = Abi.from([...])
260
260
  * const error = AbiError.fromAbi(abi, 'InvalidSignature')
261
261
  *
262
- * const value = AbiError.decode(error, '0xecde634900000000000000000000000000000000000000000000000000000000000001a400000000000000000000000000000000000000000000000000000000000000450000000000000000000000000000000000000000000000000000000000000001') // [!code focus]
262
+ * const value = AbiError.decode(error, '0xe466f0a500000000000000000000000000000000000000000000000000000000000001a400000000000000000000000000000000000000000000000000000000000000450000000000000000000000000000000000000000000000000000000000000001') // [!code focus]
263
263
  * // @log: [420n, 69n, 1]
264
264
  * ```
265
265
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ox",
3
3
  "description": "Ethereum Standard Library",
4
- "version": "0.14.64",
4
+ "version": "0.14.66",
5
5
  "main": "./_cjs/index.js",
6
6
  "module": "./_esm/index.js",
7
7
  "types": "./_types/index.d.ts",
@@ -613,6 +613,16 @@
613
613
  "import": "./_esm/tempo/SignatureEnvelope.js",
614
614
  "default": "./_cjs/tempo/SignatureEnvelope.js"
615
615
  },
616
+ "./tempo/SignaturePreAuthorized.test-d": {
617
+ "types": "./_types/tempo/SignaturePreAuthorized.test-d.d.ts",
618
+ "import": "./_esm/tempo/SignaturePreAuthorized.test-d.js",
619
+ "default": "./_cjs/tempo/SignaturePreAuthorized.test-d.js"
620
+ },
621
+ "./tempo/SignaturePreAuthorized": {
622
+ "types": "./_types/tempo/SignaturePreAuthorized.d.ts",
623
+ "import": "./_esm/tempo/SignaturePreAuthorized.js",
624
+ "default": "./_cjs/tempo/SignaturePreAuthorized.js"
625
+ },
616
626
  "./tempo/TempoAddress": {
617
627
  "types": "./_types/tempo/TempoAddress.d.ts",
618
628
  "import": "./_esm/tempo/TempoAddress.js",