ox 1.8.14 → 1.8.16

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 (172) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/dist/core/AbiError.d.ts +52 -6
  3. package/dist/core/AbiError.d.ts.map +1 -1
  4. package/dist/core/AbiError.js +60 -4
  5. package/dist/core/AbiError.js.map +1 -1
  6. package/dist/core/AbiEvent.d.ts +4 -2
  7. package/dist/core/AbiEvent.d.ts.map +1 -1
  8. package/dist/core/AbiEvent.js +62 -36
  9. package/dist/core/AbiEvent.js.map +1 -1
  10. package/dist/core/AbiFunction.d.ts +48 -2
  11. package/dist/core/AbiFunction.d.ts.map +1 -1
  12. package/dist/core/AbiFunction.js +59 -3
  13. package/dist/core/AbiFunction.js.map +1 -1
  14. package/dist/core/Address.d.ts +17 -2
  15. package/dist/core/Address.d.ts.map +1 -1
  16. package/dist/core/Address.js +17 -1
  17. package/dist/core/Address.js.map +1 -1
  18. package/dist/core/Authorization.d.ts +24 -2
  19. package/dist/core/Authorization.d.ts.map +1 -1
  20. package/dist/core/Authorization.js +29 -2
  21. package/dist/core/Authorization.js.map +1 -1
  22. package/dist/core/Keystore.d.ts +31 -2
  23. package/dist/core/Keystore.d.ts.map +1 -1
  24. package/dist/core/Keystore.js +28 -2
  25. package/dist/core/Keystore.js.map +1 -1
  26. package/dist/core/Secp256k1.d.ts.map +1 -1
  27. package/dist/core/Secp256k1.js +4 -1
  28. package/dist/core/Secp256k1.js.map +1 -1
  29. package/dist/core/Signature.d.ts +1 -1
  30. package/dist/core/Signature.d.ts.map +1 -1
  31. package/dist/core/Signature.js +4 -2
  32. package/dist/core/Signature.js.map +1 -1
  33. package/dist/core/Siwe.d.ts +4 -0
  34. package/dist/core/Siwe.d.ts.map +1 -1
  35. package/dist/core/Siwe.js +29 -3
  36. package/dist/core/Siwe.js.map +1 -1
  37. package/dist/core/TxEnvelopeEip1559.d.ts.map +1 -1
  38. package/dist/core/TxEnvelopeEip1559.js +2 -1
  39. package/dist/core/TxEnvelopeEip1559.js.map +1 -1
  40. package/dist/core/TxEnvelopeEip2930.d.ts.map +1 -1
  41. package/dist/core/TxEnvelopeEip2930.js +2 -1
  42. package/dist/core/TxEnvelopeEip2930.js.map +1 -1
  43. package/dist/core/TxEnvelopeEip7702.d.ts +1 -1
  44. package/dist/core/TxEnvelopeEip7702.d.ts.map +1 -1
  45. package/dist/core/TxEnvelopeEip7702.js +6 -1
  46. package/dist/core/TxEnvelopeEip7702.js.map +1 -1
  47. package/dist/core/TxEnvelopeLegacy.d.ts.map +1 -1
  48. package/dist/core/TxEnvelopeLegacy.js +49 -7
  49. package/dist/core/TxEnvelopeLegacy.js.map +1 -1
  50. package/dist/core/TypedData.d.ts +3 -1
  51. package/dist/core/TypedData.d.ts.map +1 -1
  52. package/dist/core/TypedData.js +9 -9
  53. package/dist/core/TypedData.js.map +1 -1
  54. package/dist/core/Value.d.ts.map +1 -1
  55. package/dist/core/Value.js +14 -3
  56. package/dist/core/Value.js.map +1 -1
  57. package/dist/core/internal/abiParameters.d.ts +1 -1
  58. package/dist/core/internal/abiParameters.d.ts.map +1 -1
  59. package/dist/core/internal/abiParameters.js +7 -2
  60. package/dist/core/internal/abiParameters.js.map +1 -1
  61. package/dist/core/internal/cursor.d.ts +13 -0
  62. package/dist/core/internal/cursor.d.ts.map +1 -1
  63. package/dist/core/internal/cursor.js +27 -0
  64. package/dist/core/internal/cursor.js.map +1 -1
  65. package/dist/erc4337/UserOperation.d.ts.map +1 -1
  66. package/dist/erc4337/UserOperation.js +1 -3
  67. package/dist/erc4337/UserOperation.js.map +1 -1
  68. package/dist/erc7821/Execute.d.ts +45 -0
  69. package/dist/erc7821/Execute.d.ts.map +1 -1
  70. package/dist/erc7821/Execute.js +70 -2
  71. package/dist/erc7821/Execute.js.map +1 -1
  72. package/dist/index.d.ts +1 -1
  73. package/dist/index.js +1 -1
  74. package/dist/tempo/KeyAuthorization.d.ts +9 -3
  75. package/dist/tempo/KeyAuthorization.d.ts.map +1 -1
  76. package/dist/tempo/KeyAuthorization.js +16 -0
  77. package/dist/tempo/KeyAuthorization.js.map +1 -1
  78. package/dist/tempo/SignatureEnvelope.d.ts +1 -1
  79. package/dist/tempo/SignatureEnvelope.d.ts.map +1 -1
  80. package/dist/tempo/SignatureEnvelope.js +46 -13
  81. package/dist/tempo/SignatureEnvelope.js.map +1 -1
  82. package/dist/tempo/SignaturePreAuthorized.d.ts +192 -0
  83. package/dist/tempo/SignaturePreAuthorized.d.ts.map +1 -0
  84. package/dist/tempo/SignaturePreAuthorized.js +299 -0
  85. package/dist/tempo/SignaturePreAuthorized.js.map +1 -0
  86. package/dist/tempo/TransactionRequest.d.ts +1 -1
  87. package/dist/tempo/TransactionRequest.d.ts.map +1 -1
  88. package/dist/tempo/TransactionRequest.js +5 -2
  89. package/dist/tempo/TransactionRequest.js.map +1 -1
  90. package/dist/tempo/TxEnvelopeTempo.d.ts +30 -1
  91. package/dist/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  92. package/dist/tempo/TxEnvelopeTempo.js +51 -2
  93. package/dist/tempo/TxEnvelopeTempo.js.map +1 -1
  94. package/dist/tempo/index.d.ts +26 -0
  95. package/dist/tempo/index.d.ts.map +1 -1
  96. package/dist/tempo/index.js +26 -0
  97. package/dist/tempo/index.js.map +1 -1
  98. package/dist/webauthn/Registration.d.ts +2 -0
  99. package/dist/webauthn/Registration.d.ts.map +1 -1
  100. package/dist/webauthn/Registration.js +2 -6
  101. package/dist/webauthn/Registration.js.map +1 -1
  102. package/dist/zod/tempo/KeyAuthorization.d.ts.map +1 -1
  103. package/dist/zod/tempo/KeyAuthorization.js +4 -2
  104. package/dist/zod/tempo/KeyAuthorization.js.map +1 -1
  105. package/dist/zod/tempo/SignatureEnvelope.d.ts.map +1 -1
  106. package/dist/zod/tempo/SignatureEnvelope.js +24 -14
  107. package/dist/zod/tempo/SignatureEnvelope.js.map +1 -1
  108. package/package.json +6 -1
  109. package/src/core/AbiError.ts +82 -8
  110. package/src/core/AbiEvent.ts +90 -45
  111. package/src/core/AbiFunction.ts +76 -4
  112. package/src/core/Address.ts +18 -1
  113. package/src/core/Authorization.ts +34 -4
  114. package/src/core/Keystore.ts +40 -3
  115. package/src/core/Secp256k1.ts +4 -1
  116. package/src/core/Signature.ts +7 -3
  117. package/src/core/Siwe.ts +29 -3
  118. package/src/core/TxEnvelopeEip1559.ts +4 -1
  119. package/src/core/TxEnvelopeEip2930.ts +4 -1
  120. package/src/core/TxEnvelopeEip7702.ts +9 -2
  121. package/src/core/TxEnvelopeLegacy.ts +58 -7
  122. package/src/core/TypedData.ts +10 -9
  123. package/src/core/Value.ts +14 -3
  124. package/src/core/_test/AbiError.test.ts +105 -2
  125. package/src/core/_test/AbiEvent.fuzz.ts +1 -1
  126. package/src/core/_test/AbiEvent.test-d.ts +46 -0
  127. package/src/core/_test/AbiEvent.test.ts +563 -11
  128. package/src/core/_test/AbiFunction.test.ts +74 -2
  129. package/src/core/_test/AbiParameters.adversarial.fuzz.ts +1 -0
  130. package/src/core/_test/AbiParameters.decode.test.ts +110 -0
  131. package/src/core/_test/AbiParameters.encode.test.ts +26 -1
  132. package/src/core/_test/Address.test.ts +41 -0
  133. package/src/core/_test/Authorization.test.ts +130 -0
  134. package/src/core/_test/Keystore.test.ts +65 -1
  135. package/src/core/_test/Secp256k1.test.ts +36 -0
  136. package/src/core/_test/Signature.test.ts +102 -0
  137. package/src/core/_test/Siwe.test.ts +123 -0
  138. package/src/core/_test/TransactionEnvelopeEip1559.test.ts +28 -0
  139. package/src/core/_test/TransactionEnvelopeEip2930.test.ts +28 -0
  140. package/src/core/_test/TransactionEnvelopeEip7702.test.ts +133 -0
  141. package/src/core/_test/TransactionEnvelopeLegacy.test.ts +322 -1
  142. package/src/core/_test/TypedData.test.ts +178 -0
  143. package/src/core/_test/Value.test.ts +21 -0
  144. package/src/core/_test/internal/cursor.test.ts +35 -0
  145. package/src/core/internal/abiParameters.ts +7 -2
  146. package/src/core/internal/cursor.ts +36 -0
  147. package/src/erc4337/UserOperation.ts +3 -4
  148. package/src/erc4337/_test/UserOperation.test.ts +59 -1
  149. package/src/erc7821/Execute.ts +83 -2
  150. package/src/erc7821/_test/Execute.test.ts +217 -1
  151. package/src/index.ts +1 -1
  152. package/src/tempo/KeyAuthorization.test.ts +91 -0
  153. package/src/tempo/KeyAuthorization.ts +32 -3
  154. package/src/tempo/SignatureEnvelope.test.ts +211 -27
  155. package/src/tempo/SignatureEnvelope.ts +55 -11
  156. package/src/tempo/SignaturePreAuthorized.test-d.ts +29 -0
  157. package/src/tempo/SignaturePreAuthorized.test.ts +410 -0
  158. package/src/tempo/SignaturePreAuthorized.ts +370 -0
  159. package/src/tempo/TransactionRequest.test.ts +30 -0
  160. package/src/tempo/TransactionRequest.ts +7 -2
  161. package/src/tempo/TxEnvelopeTempo.test.ts +310 -0
  162. package/src/tempo/TxEnvelopeTempo.ts +64 -1
  163. package/src/tempo/configurableAccounts.e2e.test.ts +1 -1
  164. package/src/tempo/index.ts +26 -0
  165. package/src/version.ts +1 -1
  166. package/src/webauthn/Registration.ts +4 -6
  167. package/src/webauthn/_test/Registration.browser.test.ts +14 -0
  168. package/src/webauthn/_test/Registration.test.ts +60 -0
  169. package/src/zod/tempo/KeyAuthorization.ts +12 -5
  170. package/src/zod/tempo/SignatureEnvelope.ts +31 -16
  171. package/src/zod/tempo/_test/KeyAuthorization.test.ts +36 -0
  172. package/src/zod/tempo/_test/SignatureEnvelope.test.ts +101 -3
@@ -1,5 +1,5 @@
1
1
  import type * as Address from './Address.js'
2
- import type * as Errors from './Errors.js'
2
+ import * as Errors from './Errors.js'
3
3
  import * as Hash from './Hash.js'
4
4
  import * as Hex from './Hex.js'
5
5
  import * as Quantity from './internal/quantity.js'
@@ -187,7 +187,7 @@ export function fromRpc(authorization: Rpc): Signed {
187
187
 
188
188
  return {
189
189
  address,
190
- chainId: Number(chainId),
190
+ chainId: Hex.toNumber(chainId),
191
191
  nonce: BigInt(nonce),
192
192
  ...signature,
193
193
  }
@@ -276,10 +276,14 @@ export declare namespace fromRpcList {
276
276
  export function fromTuple<const tuple extends Tuple>(
277
277
  tuple: tuple,
278
278
  ): fromTuple.ReturnType<tuple> {
279
+ if (tuple.length !== 3 && tuple.length !== 6)
280
+ throw new InvalidError(
281
+ 'Expected [chainId, address, nonce] or [chainId, address, nonce, yParity, r, s].',
282
+ )
279
283
  const [chainId, address, nonce, yParity, r, s] = tuple
280
284
  let args = {
281
285
  address,
282
- chainId: chainId === '0x' ? 0 : Number(chainId),
286
+ chainId: chainId === '0x' ? 0 : Hex.toNumber(chainId),
283
287
  nonce: nonce === '0x' ? 0n : BigInt(nonce),
284
288
  }
285
289
  if (yParity && r && s) {
@@ -302,7 +306,7 @@ export declare namespace fromTuple {
302
306
  Authorization<authorization extends Tuple<true> ? true : false>
303
307
  >
304
308
 
305
- type ErrorType = Errors.GlobalErrorType
309
+ type ErrorType = InvalidError | Errors.GlobalErrorType
306
310
  }
307
311
 
308
312
  /**
@@ -693,3 +697,29 @@ function assertYParity(yParity: number) {
693
697
  value: `${yParity}`,
694
698
  })
695
699
  }
700
+
701
+ /**
702
+ * Thrown when an EIP-7702 Authorization tuple is structurally invalid.
703
+ *
704
+ * @example
705
+ * ```ts twoslash
706
+ * // @noErrors
707
+ * import { Authorization } from 'ox'
708
+ *
709
+ * Authorization.fromTuple([
710
+ * '0x1',
711
+ * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',
712
+ * '0x3',
713
+ * '0x1'
714
+ * ])
715
+ * // @error: Authorization.InvalidError: Invalid authorization.
716
+ * // @error: Details: Expected [chainId, address, nonce] or [chainId, address, nonce, yParity, r, s].
717
+ * ```
718
+ */
719
+ export class InvalidError extends Errors.BaseError {
720
+ override readonly name = 'Authorization.InvalidError'
721
+
722
+ constructor(details: string) {
723
+ super('Invalid authorization.', { details })
724
+ }
725
+ }
@@ -1,5 +1,5 @@
1
1
  import * as Bytes from './Bytes.js'
2
- import type * as Errors from './Errors.js'
2
+ import * as Errors from './Errors.js'
3
3
  import * as engine from './internal/keystore.js'
4
4
  import * as Hash from './Hash.js'
5
5
  import type * as Hex from './Hex.js'
@@ -83,7 +83,7 @@ export type ScryptDeriveOpts = BaseDeriveOpts<
83
83
  * ```
84
84
  *
85
85
  * @param keystore - JSON keystore.
86
- * @param key - Key to use for decryption.
86
+ * @param key - Key to use for decryption. Must contain at least 32 bytes; the first 32 bytes are used.
87
87
  * @param options - Decryption options.
88
88
  * @returns Decrypted private key.
89
89
  */
@@ -94,6 +94,7 @@ export function decrypt<as extends 'Hex' | 'Bytes' = 'Hex'>(
94
94
  ): decrypt.ReturnType<as> {
95
95
  const { as = 'Hex' } = options
96
96
  const key_ = Bytes.from(typeof key === 'function' ? key() : key)
97
+ if (key_.length < 32) throw new InvalidKeySizeError({ size: key_.length })
97
98
 
98
99
  const encKey = Bytes.slice(key_, 0, 16)
99
100
  const macKey = Bytes.slice(key_, 16, 32)
@@ -123,6 +124,8 @@ export declare namespace decrypt {
123
124
  type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =
124
125
  | (as extends 'Hex' ? Hex.Hex : never)
125
126
  | (as extends 'Bytes' ? Bytes.Bytes : never)
127
+
128
+ type ErrorType = InvalidKeySizeError | Errors.GlobalErrorType
126
129
  }
127
130
 
128
131
  /**
@@ -169,7 +172,7 @@ export declare namespace decrypt {
169
172
  * ```
170
173
  *
171
174
  * @param privateKey - Private key to encrypt.
172
- * @param key - Key to use for encryption.
175
+ * @param key - Key to use for encryption. Must contain at least 32 bytes; the first 32 bytes are used.
173
176
  * @param options - Encryption options.
174
177
  * @returns Encrypted keystore.
175
178
  */
@@ -181,6 +184,7 @@ export function encrypt(
181
184
  const { id = crypto.randomUUID(), kdf, kdfparams, iv } = options
182
185
 
183
186
  const key_ = Bytes.from(typeof key === 'function' ? key() : key)
187
+ if (key_.length < 32) throw new InvalidKeySizeError({ size: key_.length })
184
188
  const value_ = Bytes.from(privateKey)
185
189
 
186
190
  const encKey = Bytes.slice(key_, 0, 16)
@@ -208,6 +212,8 @@ export declare namespace encrypt {
208
212
  /** UUID. */
209
213
  id?: string | undefined
210
214
  }
215
+
216
+ type ErrorType = InvalidKeySizeError | Errors.GlobalErrorType
211
217
  }
212
218
 
213
219
  /**
@@ -532,6 +538,37 @@ export declare namespace toKeyAsync {
532
538
  }
533
539
  }
534
540
 
541
+ /**
542
+ * Thrown when a key contains fewer than 32 bytes.
543
+ *
544
+ * @example
545
+ * ```ts twoslash
546
+ * import { Keystore } from 'ox'
547
+ *
548
+ * const [, opts] = Keystore.pbkdf2({
549
+ * password: 'testpassword'
550
+ * })
551
+ *
552
+ * Keystore.encrypt('0x01', '0x0123456789abcdef', opts)
553
+ * // @error: Keystore.InvalidKeySizeError: Key must contain at least 32 bytes. Received 8 bytes.
554
+ * ```
555
+ */
556
+ export class InvalidKeySizeError extends Errors.BaseError {
557
+ override readonly name = 'Keystore.InvalidKeySizeError'
558
+
559
+ constructor(options: InvalidKeySizeError.Options) {
560
+ super(`Key must contain at least 32 bytes. Received ${options.size} bytes.`)
561
+ }
562
+ }
563
+
564
+ export declare namespace InvalidKeySizeError {
565
+ /** Options for {@link ox#Keystore.InvalidKeySizeError}. */
566
+ type Options = {
567
+ /** Received key size. */
568
+ size: number
569
+ }
570
+ }
571
+
535
572
  ///////////////////////////////////////////////////////////////////////////
536
573
 
537
574
  /** @internal */
@@ -635,7 +635,10 @@ export function verify(options: verify.Options): boolean {
635
635
  if (options.address)
636
636
  return Address.isEqual(
637
637
  options.address,
638
- recoverAddress({ payload, signature: options.signature }),
638
+ recoverAddress({
639
+ payload: hash === true ? Hash.sha256(payload) : payload,
640
+ signature: options.signature,
641
+ }),
639
642
  )
640
643
  const sig = normalizeSignature(options.signature)
641
644
  return engine.verify(
@@ -72,7 +72,10 @@ export function assert(
72
72
  throw new MissingPropertiesError({ signature })
73
73
  if (typeof signature.s === 'undefined')
74
74
  throw new MissingPropertiesError({ signature })
75
- if (recovered && typeof signature.yParity === 'undefined')
75
+ if (
76
+ recovered &&
77
+ (signature.yParity === undefined || signature.yParity === null)
78
+ )
76
79
  throw new MissingPropertiesError({ signature })
77
80
  try {
78
81
  const r = BigInt(signature.r)
@@ -89,7 +92,7 @@ export function assert(
89
92
  throw new InvalidSError({ value: signature.s })
90
93
  }
91
94
  if (
92
- typeof signature.yParity === 'number' &&
95
+ signature.yParity !== undefined &&
93
96
  signature.yParity !== 0 &&
94
97
  signature.yParity !== 1
95
98
  )
@@ -867,6 +870,7 @@ export declare namespace toRpc {
867
870
  * @returns The {@link ox#Signature.Tuple}.
868
871
  */
869
872
  export function toTuple(signature: Signature): Tuple {
873
+ assert(signature, { recovered: true })
870
874
  const { r, s, yParity } = signature
871
875
 
872
876
  // RLP wants minimal-length big-endian; strip leading zero nibbles from the
@@ -875,7 +879,7 @@ export function toTuple(signature: Signature): Tuple {
875
879
  }
876
880
 
877
881
  export declare namespace toTuple {
878
- type ErrorType = Errors.GlobalErrorType
882
+ type ErrorType = assert.ErrorType | Errors.GlobalErrorType
879
883
  }
880
884
 
881
885
  /**
package/src/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
  const siweDateTimeRegex =
27
30
  /^(\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])[Tt]([01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d+)?(?:[Zz]|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/
28
31
 
@@ -245,6 +248,15 @@ export function createMessage(value: Message): string {
245
248
  `Provided value: ${statement}`,
246
249
  ],
247
250
  })
251
+ if (requestId && /[\n\r]/.test(requestId))
252
+ throw new InvalidMessageFieldError({
253
+ field: 'requestId',
254
+ metaMessages: [
255
+ "- Request ID must not include '\\n' or '\\r'.",
256
+ '',
257
+ `Provided value: ${requestId}`,
258
+ ],
259
+ })
248
260
  }
249
261
 
250
262
  // Construct message
@@ -394,6 +406,10 @@ function splitUri(value: string) {
394
406
  /**
395
407
  * [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message into message fields object.
396
408
  *
409
+ * The message can be the prefix (up to the statement), the suffix (from `URI`), or both.
410
+ * Returns an empty object when the message has any other text, such as fields that are
411
+ * out of order or text after the last field.
412
+ *
397
413
  * @example
398
414
  * ```ts twoslash
399
415
  * import { Siwe } from 'ox'
@@ -424,13 +440,23 @@ function splitUri(value: string) {
424
440
  * @returns Message fields object.
425
441
  */
426
442
  export function parseMessage(message: string): ExactPartial<Message> {
427
- const { scheme, statement, ...prefix } = (message.match(prefixRegex)
428
- ?.groups ?? {}) as {
443
+ const prefixMatch = message.match(prefixRegex)
444
+ const { scheme, statement, ...prefix } = (prefixMatch?.groups ?? {}) as {
429
445
  address: Address.Address
430
446
  domain: string
431
447
  scheme?: string
432
448
  statement?: string
433
449
  }
450
+ // The suffix starts where the prefix ends. Without a statement, the prefix
451
+ // is followed by one more line feed (as `createMessage` emits) or by none.
452
+ const rest = (() => {
453
+ const rest = message.slice(prefixMatch?.[0].length ?? 0)
454
+ if (prefixMatch && statement === undefined && rest.startsWith('\n'))
455
+ return rest.slice(1)
456
+ return rest
457
+ })()
458
+ const suffixMatch = rest.match(anchoredSuffixRegex)
459
+ if (rest && !suffixMatch) return {}
434
460
  const {
435
461
  chainId,
436
462
  expirationTime,
@@ -439,7 +465,7 @@ export function parseMessage(message: string): ExactPartial<Message> {
439
465
  requestId,
440
466
  resources: resources_,
441
467
  ...suffix
442
- } = (message.match(suffixRegex)?.groups ?? {}) as {
468
+ } = (suffixMatch?.groups ?? {}) as {
443
469
  chainId: string
444
470
  expirationTime?: string
445
471
  issuedAt?: string
@@ -71,7 +71,10 @@ export type Type = typeof type
71
71
  */
72
72
  export function assert(envelope: PartialBy<TxEnvelopeEip1559, 'type'>) {
73
73
  const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = envelope
74
- if (chainId <= 0)
74
+ if (
75
+ typeof chainId !== 'undefined' &&
76
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
77
+ )
75
78
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
76
79
  if (to) Address.assert(to, { strict: false })
77
80
  if (maxFeePerGas && BigInt(maxFeePerGas) > 2n ** 256n - 1n)
@@ -69,7 +69,10 @@ export type Type = typeof type
69
69
  */
70
70
  export function assert(envelope: PartialBy<TxEnvelopeEip2930, 'type'>) {
71
71
  const { chainId, gasPrice, to } = envelope
72
- if (chainId <= 0)
72
+ if (
73
+ typeof chainId !== 'undefined' &&
74
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
75
+ )
73
76
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
74
77
  if (to) Address.assert(to, { strict: false })
75
78
  if (gasPrice && BigInt(gasPrice) > 2n ** 256n - 1n)
@@ -197,10 +197,17 @@ export function deserialize(
197
197
  )
198
198
  // Authorization list is preserved even when empty for round-trip parity
199
199
  // with the legacy `authorizationList !== '0x'` hex check.
200
- if (Array.isArray(authorizationList))
200
+ if (Array.isArray(authorizationList)) {
201
+ // A transaction holds signed authorizations only.
202
+ for (const tuple of authorizationList)
203
+ if (!Array.isArray(tuple) || tuple.length !== 6)
204
+ throw new Authorization.InvalidError(
205
+ 'Expected [chainId, address, nonce, yParity, r, s].',
206
+ )
201
207
  transaction.authorizationList = Authorization.fromTupleList(
202
208
  Tx.bytesTreeToHex(authorizationList as never) as never,
203
209
  )
210
+ }
204
211
 
205
212
  const signature =
206
213
  r && s && yParity
@@ -222,7 +229,7 @@ export function deserialize(
222
229
  }
223
230
 
224
231
  export declare namespace deserialize {
225
- type ErrorType = Errors.GlobalErrorType
232
+ type ErrorType = Authorization.InvalidError | Errors.GlobalErrorType
226
233
  }
227
234
 
228
235
  /**
@@ -68,7 +68,10 @@ export type Type = typeof type
68
68
  export function assert(envelope: PartialBy<TxEnvelopeLegacy, 'type'>) {
69
69
  const { chainId, gasPrice, to } = envelope
70
70
  if (to) Address.assert(to, { strict: false })
71
- if (typeof chainId !== 'undefined' && 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 (gasPrice && BigInt(gasPrice) > 2n ** 256n - 1n)
74
77
  throw new TransactionEnvelope.GasPriceTooHighError({ gasPrice })
@@ -111,7 +114,12 @@ export function deserialize(serialized: Hex.Hex): Compute<TxEnvelopeLegacy> {
111
114
  const [nonce, gasPrice, gas, to, value, data, chainIdOrV_, r, s] =
112
115
  tuple as readonly Bytes.Bytes[]
113
116
 
114
- if (!(tuple.length === 6 || tuple.length === 9))
117
+ if (
118
+ !Array.isArray(tuple) ||
119
+ !(tuple.length === 6 || tuple.length === 9) ||
120
+ // Every field is a byte string, never a nested list.
121
+ tuple.some((item) => !(item instanceof Uint8Array))
122
+ )
115
123
  throw new TransactionEnvelope.InvalidSerializedError({
116
124
  attributes: {
117
125
  nonce,
@@ -144,18 +152,46 @@ export function deserialize(serialized: Hex.Hex): Compute<TxEnvelopeLegacy> {
144
152
  if (nonce !== undefined) transaction.nonce = Tx.bytesToBigIntOrZero(nonce)
145
153
  const value_ = Tx.bytesToBigIntOrUndefined(value)
146
154
  if (value_ !== undefined) transaction.value = value_
155
+ // `gasPrice`, `r` and `s` are bounded by byte length, so that an oversized
156
+ // value is rejected before it is converted.
157
+ if ((gasPrice as Bytes.Bytes).length > 32)
158
+ throw new TransactionEnvelope.GasPriceTooHighError()
147
159
  const gasPrice_ = Tx.bytesToBigIntOrUndefined(gasPrice)
148
160
  if (gasPrice_ !== undefined) transaction.gasPrice = gasPrice_
149
161
 
150
- if (tuple.length === 6) return transaction
162
+ if (tuple.length === 6) {
163
+ assert(transaction)
164
+ return transaction
165
+ }
151
166
 
152
- const chainIdOrV = Tx.bytesToNumberOrUndefined(chainIdOrV_) ?? 0
167
+ // `chainId` and `yParity` are derived from `v` as a number, so `v` must be a
168
+ // safe integer (which fits in 7 bytes).
169
+ const chainIdOrV =
170
+ (chainIdOrV_ as Bytes.Bytes).length > 7
171
+ ? Number.NaN
172
+ : (Tx.bytesToNumberOrUndefined(chainIdOrV_) ?? 0)
173
+ if (!Number.isSafeInteger(chainIdOrV))
174
+ throw new TransactionEnvelope.InvalidSerializedError({
175
+ attributes: {},
176
+ serialized,
177
+ type,
178
+ })
153
179
 
154
180
  if ((s as Bytes.Bytes).length === 0 && (r as Bytes.Bytes).length === 0) {
155
181
  if (chainIdOrV > 0) transaction.chainId = Number(chainIdOrV)
182
+ assert(transaction)
156
183
  return transaction
157
184
  }
158
185
 
186
+ if ((r as Bytes.Bytes).length > 32)
187
+ throw new Signature.InvalidRError({
188
+ value: Tx.bytesToHex(r as Bytes.Bytes),
189
+ })
190
+ if ((s as Bytes.Bytes).length > 32)
191
+ throw new Signature.InvalidSError({
192
+ value: Tx.bytesToHex(s as Bytes.Bytes),
193
+ })
194
+
159
195
  const v = chainIdOrV
160
196
  const chainId: number | undefined = Math.floor((v - 35) / 2)
161
197
  if (chainId > 0) transaction.chainId = chainId
@@ -393,11 +429,18 @@ export function hash<presign extends boolean = false>(
393
429
  options: hash.Options<presign> = {},
394
430
  ): hash.ReturnType {
395
431
  const { presign } = options
432
+ const { chainId, v } = envelope
396
433
  return Hash.keccak256(
397
434
  serialize({
398
435
  ...envelope,
399
436
  ...(presign
400
437
  ? {
438
+ // An EIP-155 `v` carries the chain ID when `chainId` is absent.
439
+ chainId:
440
+ chainId ??
441
+ (typeof v === 'number' && v >= 37
442
+ ? Math.floor((v - 35) / 2)
443
+ : undefined),
401
444
  r: undefined,
402
445
  s: undefined,
403
446
  yParity: undefined,
@@ -509,6 +552,17 @@ export function serialize(
509
552
 
510
553
  if (signature) {
511
554
  const v = (() => {
555
+ // EIP-155 (explicit chainId)
556
+ if (chainId > 0) {
557
+ if (signature.v >= 35) {
558
+ // `v` must encode the same chain as `chainId`.
559
+ if (Math.floor((signature.v - 35) / 2) !== chainId)
560
+ throw new TransactionEnvelope.InvalidChainIdError({ chainId })
561
+ return signature.v
562
+ }
563
+ return chainId * 2 + 35 + Signature.vToYParity(signature.v)
564
+ }
565
+
512
566
  // EIP-155 (inferred chainId)
513
567
  if (signature.v >= 35) {
514
568
  const inferredChainId = Math.floor((signature.v - 35) / 2)
@@ -516,9 +570,6 @@ export function serialize(
516
570
  return 27 + (signature.v === 35 ? 0 : 1)
517
571
  }
518
572
 
519
- // EIP-155 (explicit chainId)
520
- if (chainId > 0) return chainId * 2 + 35 + signature.v - 27
521
-
522
573
  // Pre-EIP-155 (no chainId)
523
574
  const v = 27 + (signature.v === 27 ? 0 : 1)
524
575
  if (signature.v !== v)
@@ -160,6 +160,8 @@ export function assert<
160
160
  expectedSize: Number.parseInt(size, 10),
161
161
  givenSize: Hex.size(value as Hex.Hex),
162
162
  })
163
+ if (size && (value as Hex.Hex).length % 2 !== 0)
164
+ throw new Hex.InvalidLengthError(value as Hex.Hex)
163
165
  }
164
166
 
165
167
  if (Object.hasOwn(types, type))
@@ -209,6 +211,7 @@ export declare namespace assert {
209
211
  | InvalidPrimaryTypeError
210
212
  | InvalidStructTypeError
211
213
  | InvalidTypeError
214
+ | Hex.InvalidLengthError
212
215
  | Hex.fromNumber.ErrorType
213
216
  | Hex.size.ErrorType
214
217
  | Errors.GlobalErrorType
@@ -407,6 +410,8 @@ export declare namespace encodeType {
407
410
  /**
408
411
  * Gets [EIP-712 Typed Data](https://eips.ethereum.org/EIPS/eip-712) schema for EIP-721 domain.
409
412
  *
413
+ * A field is part of the schema when it is present on the domain (not `undefined` or `null`).
414
+ *
410
415
  * @example
411
416
  * ```ts twoslash
412
417
  * import { TypedData } from 'ox'
@@ -433,18 +438,14 @@ export function extractEip712DomainTypes(
433
438
  domain: Domain | undefined,
434
439
  ): Parameter[] {
435
440
  return [
436
- typeof domain?.name === 'string' && { name: 'name', type: 'string' },
437
- typeof domain?.version === 'string' && { name: 'version', type: 'string' },
438
- (typeof domain?.chainId === 'number' ||
439
- typeof domain?.chainId === 'bigint') && {
440
- name: 'chainId',
441
- type: 'uint256',
442
- },
443
- domain?.verifyingContract && {
441
+ domain?.name != null && { name: 'name', type: 'string' },
442
+ domain?.version != null && { name: 'version', type: 'string' },
443
+ domain?.chainId != null && { name: 'chainId', type: 'uint256' },
444
+ domain?.verifyingContract != null && {
444
445
  name: 'verifyingContract',
445
446
  type: 'address',
446
447
  },
447
- domain?.salt && { name: 'salt', type: 'bytes32' },
448
+ domain?.salt != null && { name: 'salt', type: 'bytes32' },
448
449
  ].filter(Boolean) as Parameter[]
449
450
  }
450
451
 
package/src/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]*)?|\.[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).
@@ -42,7 +41,7 @@ export function format(value: bigint, decimals = 0) {
42
41
  display.slice(0, display.length - decimals),
43
42
  display.slice(display.length - decimals),
44
43
  ]
45
- fraction = fraction.replace(trailingZerosRegex, '')
44
+ fraction = trimTrailingZeros(fraction)
46
45
  return `${negative ? '-' : ''}${integer || '0'}${
47
46
  fraction ? `.${fraction}` : ''
48
47
  }`
@@ -133,7 +132,7 @@ export function from(value: string, decimals = 0) {
133
132
  if (integer === '') integer = '0'
134
133
 
135
134
  // trim trailing zeros.
136
- fraction = fraction.replace(trailingZerosRegex, '')
135
+ fraction = trimTrailingZeros(fraction)
137
136
 
138
137
  // round off if the fraction is larger than the number of decimals.
139
138
  if (decimals === 0) {
@@ -195,6 +194,18 @@ export declare namespace from {
195
194
  type ErrorType = Errors.GlobalErrorType
196
195
  }
197
196
 
197
+ /**
198
+ * Removes trailing zeros with a backward scan, which stays linear in the
199
+ * length of the value.
200
+ *
201
+ * @internal
202
+ */
203
+ function trimTrailingZeros(value: string): string {
204
+ let end = value.length
205
+ while (end > 0 && value.charCodeAt(end - 1) === 48) end--
206
+ return value.slice(0, end)
207
+ }
208
+
198
209
  /**
199
210
  * Parses a string representation of Ether to a `bigint` Value (default: wei).
200
211
  *