ox 1.8.12 → 1.8.14

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 (188) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/dist/core/AbiError.d.ts +2 -2
  3. package/dist/core/AbiError.d.ts.map +1 -1
  4. package/dist/core/AbiError.js +6 -2
  5. package/dist/core/AbiError.js.map +1 -1
  6. package/dist/core/AbiEvent.d.ts +71 -1
  7. package/dist/core/AbiEvent.d.ts.map +1 -1
  8. package/dist/core/AbiEvent.js +160 -19
  9. package/dist/core/AbiEvent.js.map +1 -1
  10. package/dist/core/AbiFunction.d.ts +1 -1
  11. package/dist/core/AbiFunction.d.ts.map +1 -1
  12. package/dist/core/AbiFunction.js +3 -5
  13. package/dist/core/AbiFunction.js.map +1 -1
  14. package/dist/core/AbiItem.d.ts.map +1 -1
  15. package/dist/core/AbiItem.js +18 -8
  16. package/dist/core/AbiItem.js.map +1 -1
  17. package/dist/core/Base32.d.ts +3 -3
  18. package/dist/core/Base32.d.ts.map +1 -1
  19. package/dist/core/Base32.js +5 -2
  20. package/dist/core/Base32.js.map +1 -1
  21. package/dist/core/Bytes.d.ts.map +1 -1
  22. package/dist/core/Bytes.js +4 -3
  23. package/dist/core/Bytes.js.map +1 -1
  24. package/dist/core/Caches.d.ts +1 -2
  25. package/dist/core/Caches.d.ts.map +1 -1
  26. package/dist/core/Caches.js +1 -4
  27. package/dist/core/Caches.js.map +1 -1
  28. package/dist/core/Cbor.d.ts.map +1 -1
  29. package/dist/core/Cbor.js +16 -2
  30. package/dist/core/Cbor.js.map +1 -1
  31. package/dist/core/CompactSize.d.ts +8 -1
  32. package/dist/core/CompactSize.d.ts.map +1 -1
  33. package/dist/core/CompactSize.js +9 -0
  34. package/dist/core/CompactSize.js.map +1 -1
  35. package/dist/core/Hex.d.ts.map +1 -1
  36. package/dist/core/Hex.js +9 -4
  37. package/dist/core/Hex.js.map +1 -1
  38. package/dist/core/Rlp.d.ts +9 -2
  39. package/dist/core/Rlp.d.ts.map +1 -1
  40. package/dist/core/Rlp.js +51 -8
  41. package/dist/core/Rlp.js.map +1 -1
  42. package/dist/core/RpcTransport.d.ts.map +1 -1
  43. package/dist/core/RpcTransport.js +11 -4
  44. package/dist/core/RpcTransport.js.map +1 -1
  45. package/dist/core/Siwe.d.ts.map +1 -1
  46. package/dist/core/Siwe.js +24 -9
  47. package/dist/core/Siwe.js.map +1 -1
  48. package/dist/core/TxEnvelope.d.ts.map +1 -1
  49. package/dist/core/TxEnvelope.js +5 -3
  50. package/dist/core/TxEnvelope.js.map +1 -1
  51. package/dist/core/TxEnvelopeEip1559.d.ts.map +1 -1
  52. package/dist/core/TxEnvelopeEip1559.js +6 -2
  53. package/dist/core/TxEnvelopeEip1559.js.map +1 -1
  54. package/dist/core/TxEnvelopeEip4844.d.ts.map +1 -1
  55. package/dist/core/TxEnvelopeEip4844.js +4 -0
  56. package/dist/core/TxEnvelopeEip4844.js.map +1 -1
  57. package/dist/core/TxEnvelopeEip7702.d.ts.map +1 -1
  58. package/dist/core/TxEnvelopeEip7702.js +4 -0
  59. package/dist/core/TxEnvelopeEip7702.js.map +1 -1
  60. package/dist/core/TypedData.d.ts +8 -1
  61. package/dist/core/TypedData.d.ts.map +1 -1
  62. package/dist/core/TypedData.js +55 -14
  63. package/dist/core/TypedData.js.map +1 -1
  64. package/dist/core/Value.d.ts.map +1 -1
  65. package/dist/core/Value.js +5 -3
  66. package/dist/core/Value.js.map +1 -1
  67. package/dist/core/internal/abiItem.d.ts +3 -1
  68. package/dist/core/internal/abiItem.d.ts.map +1 -1
  69. package/dist/core/internal/abiItem.js +46 -13
  70. package/dist/core/internal/abiItem.js.map +1 -1
  71. package/dist/core/internal/abiParameters.d.ts +2 -2
  72. package/dist/core/internal/abiParameters.d.ts.map +1 -1
  73. package/dist/core/internal/abiParameters.js +24 -7
  74. package/dist/core/internal/abiParameters.js.map +1 -1
  75. package/dist/core/internal/caches.d.ts +10 -0
  76. package/dist/core/internal/caches.d.ts.map +1 -0
  77. package/dist/core/internal/caches.js +10 -0
  78. package/dist/core/internal/caches.js.map +1 -0
  79. package/dist/core/internal/frameNonce.d.ts.map +1 -1
  80. package/dist/core/internal/frameNonce.js +2 -2
  81. package/dist/core/internal/frameNonce.js.map +1 -1
  82. package/dist/core/internal/rpcSchemas/eth.d.ts +3 -2
  83. package/dist/core/internal/rpcSchemas/eth.d.ts.map +1 -1
  84. package/dist/erc4337/UserOperation.d.ts +15 -2
  85. package/dist/erc4337/UserOperation.d.ts.map +1 -1
  86. package/dist/erc4337/UserOperation.js +8 -2
  87. package/dist/erc4337/UserOperation.js.map +1 -1
  88. package/dist/erc8021/Attribution.d.ts.map +1 -1
  89. package/dist/erc8021/Attribution.js +12 -3
  90. package/dist/erc8021/Attribution.js.map +1 -1
  91. package/dist/tempo/AccountOperation.d.ts +8 -0
  92. package/dist/tempo/AccountOperation.d.ts.map +1 -1
  93. package/dist/tempo/AccountOperation.js +26 -6
  94. package/dist/tempo/AccountOperation.js.map +1 -1
  95. package/dist/tempo/KeyAuthorization.d.ts +21 -6
  96. package/dist/tempo/KeyAuthorization.d.ts.map +1 -1
  97. package/dist/tempo/KeyAuthorization.js +7 -4
  98. package/dist/tempo/KeyAuthorization.js.map +1 -1
  99. package/dist/tempo/SignatureEnvelope.d.ts +4 -4
  100. package/dist/tempo/Tick.d.ts.map +1 -1
  101. package/dist/tempo/Tick.js +4 -3
  102. package/dist/tempo/Tick.js.map +1 -1
  103. package/dist/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  104. package/dist/tempo/TxEnvelopeTempo.js +6 -2
  105. package/dist/tempo/TxEnvelopeTempo.js.map +1 -1
  106. package/dist/zod/Address.d.ts.map +1 -1
  107. package/dist/zod/Address.js +2 -1
  108. package/dist/zod/Address.js.map +1 -1
  109. package/dist/zod/FrameRequest.d.ts.map +1 -1
  110. package/dist/zod/FrameRequest.js +2 -1
  111. package/dist/zod/FrameRequest.js.map +1 -1
  112. package/dist/zod/Hex.d.ts.map +1 -1
  113. package/dist/zod/Hex.js +2 -1
  114. package/dist/zod/Hex.js.map +1 -1
  115. package/dist/zod/Solidity.d.ts.map +1 -1
  116. package/dist/zod/Solidity.js +12 -7
  117. package/dist/zod/Solidity.js.map +1 -1
  118. package/dist/zod/TypedData.d.ts +12 -12
  119. package/package.json +5 -2
  120. package/src/core/AbiError.ts +33 -22
  121. package/src/core/AbiEvent.ts +177 -18
  122. package/src/core/AbiFunction.ts +10 -7
  123. package/src/core/AbiItem.ts +17 -8
  124. package/src/core/Base32.ts +8 -3
  125. package/src/core/Bytes.ts +4 -3
  126. package/src/core/Caches.ts +1 -6
  127. package/src/core/Cbor.ts +20 -2
  128. package/src/core/CompactSize.ts +13 -0
  129. package/src/core/Hex.ts +10 -5
  130. package/src/core/Rlp.ts +55 -5
  131. package/src/core/RpcTransport.ts +11 -4
  132. package/src/core/Siwe.ts +26 -11
  133. package/src/core/TxEnvelope.ts +5 -3
  134. package/src/core/TxEnvelopeEip1559.ts +8 -2
  135. package/src/core/TxEnvelopeEip4844.ts +6 -0
  136. package/src/core/TxEnvelopeEip7702.ts +6 -0
  137. package/src/core/TypedData.ts +62 -13
  138. package/src/core/Value.ts +6 -3
  139. package/src/core/_test/AbiError.test-d.ts +10 -0
  140. package/src/core/_test/AbiError.test.ts +73 -0
  141. package/src/core/_test/AbiEvent.fuzz.ts +260 -0
  142. package/src/core/_test/AbiEvent.snap-d.ts +9 -0
  143. package/src/core/_test/AbiEvent.test.ts +421 -0
  144. package/src/core/_test/AbiFunction.snap-d.ts +25 -0
  145. package/src/core/_test/AbiFunction.test.ts +101 -18
  146. package/src/core/_test/AbiItem.snap-d.ts +11 -0
  147. package/src/core/_test/AbiItem.test.ts +393 -5
  148. package/src/core/_test/AbiParameters.decode.test.ts +140 -1
  149. package/src/core/_test/Base32.test.ts +16 -0
  150. package/src/core/_test/Bytes.test.ts +15 -0
  151. package/src/core/_test/Caches.test.ts +10 -1
  152. package/src/core/_test/Cbor.test.ts +23 -0
  153. package/src/core/_test/CompactSize.test.ts +14 -0
  154. package/src/core/_test/Hex.test.ts +25 -0
  155. package/src/core/_test/Rlp.test.ts +51 -0
  156. package/src/core/_test/RpcSchema.test-d.ts +23 -1
  157. package/src/core/_test/RpcTransport.test.ts +47 -0
  158. package/src/core/_test/Siwe.test.ts +28 -0
  159. package/src/core/_test/TransactionEnvelopeEip1559.test.ts +24 -0
  160. package/src/core/_test/TransactionEnvelopeEip4844.test.ts +13 -0
  161. package/src/core/_test/TransactionEnvelopeEip7702.test.ts +13 -0
  162. package/src/core/_test/TypedData.test.ts +203 -1
  163. package/src/core/internal/abiItem.ts +58 -18
  164. package/src/core/internal/abiParameters.ts +26 -8
  165. package/src/core/internal/caches.ts +12 -0
  166. package/src/core/internal/frameNonce.ts +3 -4
  167. package/src/core/internal/rpcSchemas/eth.ts +2 -1
  168. package/src/erc4337/UserOperation.ts +30 -3
  169. package/src/erc4337/_test/UserOperation.test.ts +132 -35
  170. package/src/erc8021/Attribution.ts +9 -7
  171. package/src/erc8021/_test/Attribution.test.ts +37 -0
  172. package/src/tempo/AccountOperation.test.ts +116 -0
  173. package/src/tempo/AccountOperation.ts +38 -5
  174. package/src/tempo/AccountSimulation.test.ts +1 -1
  175. package/src/tempo/KeyAuthorization.test.ts +6 -4
  176. package/src/tempo/KeyAuthorization.ts +26 -8
  177. package/src/tempo/SignatureEnvelope.test.ts +12 -0
  178. package/src/tempo/SignatureEnvelope.ts +4 -4
  179. package/src/tempo/Tick.test.ts +10 -0
  180. package/src/tempo/Tick.ts +5 -3
  181. package/src/tempo/TxEnvelopeTempo.test.ts +26 -0
  182. package/src/tempo/TxEnvelopeTempo.ts +8 -2
  183. package/src/tempo/e2e.test.ts +73 -17
  184. package/src/version.ts +1 -1
  185. package/src/zod/Address.ts +3 -3
  186. package/src/zod/FrameRequest.ts +3 -4
  187. package/src/zod/Hex.ts +3 -1
  188. package/src/zod/Solidity.ts +15 -18
@@ -2,6 +2,7 @@ import type * as Abi from './Abi.js'
2
2
  import * as Errors from './Errors.js'
3
3
  import * as Hash from './Hash.js'
4
4
  import * as Hex from './Hex.js'
5
+ import { caches } from './internal/caches.js'
5
6
  import * as formatAbiItem from './internal/human-readable/formatAbiItem.js'
6
7
  import * as parseAbiItem from './internal/human-readable/parseAbiItem.js'
7
8
  import * as internal from './internal/abiItem.js'
@@ -314,14 +315,14 @@ export function fromAbi<
314
315
  } as never
315
316
 
316
317
  let matchedAbiItem: AbiItem | undefined
318
+ // Without `args`, a zero-input overload is the preferred pick, but the other
319
+ // overloads are still attached so callers can resolve by selector.
320
+ let zeroArgAbiItem: AbiItem | undefined
317
321
  for (const abiItem of abiItems) {
318
322
  if (!('inputs' in abiItem)) continue
319
323
  if (!args || args.length === 0) {
320
- if (!abiItem.inputs || abiItem.inputs.length === 0)
321
- return {
322
- ...abiItem,
323
- ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),
324
- } as never
324
+ if (!zeroArgAbiItem && (!abiItem.inputs || abiItem.inputs.length === 0))
325
+ zeroArgAbiItem = abiItem
325
326
  continue
326
327
  }
327
328
  if (!abiItem.inputs) continue
@@ -363,8 +364,9 @@ export function fromAbi<
363
364
 
364
365
  const abiItem = (() => {
365
366
  if (matchedAbiItem) return matchedAbiItem
366
- const [abiItem, ...overloads] = abiItems
367
- return { ...abiItem!, overloads }
367
+ const chosen = zeroArgAbiItem ?? abiItems[0]
368
+ const overloads = abiItems.filter((item) => item !== chosen)
369
+ return { ...chosen!, overloads }
368
370
  })()
369
371
 
370
372
  if (!abiItem) throw new NotFoundError({ name: name as string })
@@ -640,7 +642,14 @@ export function getSignatureHash(
640
642
  })()
641
643
  if (typeof abiItem !== 'string' && 'hash' in abiItem && abiItem.hash)
642
644
  return abiItem.hash as Hex.Hex
643
- return Hash.keccak256(Hex.fromString(getSignature(abiItem)))
645
+ // Keyed by the normalized signature, so equal signatures share one hash
646
+ // regardless of how the ABI item was written.
647
+ const signature = getSignature(abiItem)
648
+ const cached = caches.signatureHash.get(signature)
649
+ if (cached) return cached
650
+ const hash = Hash.keccak256(Hex.fromString(signature))
651
+ caches.signatureHash.set(signature, hash)
652
+ return hash
644
653
  }
645
654
 
646
655
  export declare namespace getSignatureHash {
@@ -62,7 +62,7 @@ export declare namespace fromHex {
62
62
  * ```ts twoslash
63
63
  * import { Base32 } from 'ox'
64
64
  *
65
- * const value = Base32.toBytes('qqsa0')
65
+ * const value = Base32.toBytes('qrlsq')
66
66
  * ```
67
67
  *
68
68
  * @param value - The Base32 encoded string.
@@ -91,11 +91,16 @@ export function toBytes(value: string): Bytes.Bytes {
91
91
  bytes[n++] = (acc >>> bits) & 0xff
92
92
  }
93
93
  }
94
+ // Reject leftover bits that do not fill a whole symbol, or that are non-zero.
95
+ if (bits >= 5 || acc & ((1 << bits) - 1)) throw new InvalidPaddingError()
94
96
  return bytes.subarray(0, n)
95
97
  }
96
98
 
97
99
  export declare namespace toBytes {
98
- type ErrorType = InvalidCharacterError | Errors.GlobalErrorType
100
+ type ErrorType =
101
+ | InvalidCharacterError
102
+ | InvalidPaddingError
103
+ | Errors.GlobalErrorType
99
104
  }
100
105
 
101
106
  /**
@@ -105,7 +110,7 @@ export declare namespace toBytes {
105
110
  * ```ts twoslash
106
111
  * import { Base32 } from 'ox'
107
112
  *
108
- * const value = Base32.toHex('qqsa0')
113
+ * const value = Base32.toHex('qrlsq')
109
114
  * ```
110
115
  *
111
116
  * @param value - The Base32 encoded string.
package/src/core/Bytes.ts CHANGED
@@ -224,9 +224,10 @@ export function fromHex(value: Hex.Hex, options: fromHex.Options = {}): Bytes {
224
224
  const { size } = options
225
225
  if (typeof size === 'number') {
226
226
  internal_hex.assertSize(value, size)
227
- // Right-pad the hex string before parsing to preserve odd-nibble
228
- // semantics of the previous implementation.
229
- return hexToBytes(internal_hex.pad(value, { dir: 'right', size }))
227
+ // An odd-length value gets its leading `0` before right-padding, so the
228
+ // padding lands after the value's bytes instead of between its nibbles.
229
+ const hex = value.length % 2 ? (`0x0${value.slice(2)}` as const) : value
230
+ return hexToBytes(internal_hex.pad(hex, { dir: 'right', size }))
230
231
  }
231
232
  return hexToBytes(value)
232
233
  }
@@ -1,9 +1,4 @@
1
- import type * as Address from './Address.js'
2
- import { BoundedMap } from './internal/lru.js'
3
-
4
- const caches = {
5
- checksum: /*#__PURE__*/ new BoundedMap<Address.Address>(32_768),
6
- }
1
+ import { caches } from './internal/caches.js'
7
2
 
8
3
  export const checksum = caches.checksum
9
4
 
package/src/core/Cbor.ts CHANGED
@@ -856,7 +856,7 @@ namespace decodeCursor {
856
856
  ? String(key)
857
857
  : String(key)
858
858
  const value = decodeCursor(cursor)
859
- result[keyStr] = value
859
+ setEntry(result, keyStr, value)
860
860
  }
861
861
 
862
862
  return result
@@ -875,7 +875,7 @@ namespace decodeCursor {
875
875
  ? String(key)
876
876
  : String(key)
877
877
  const value = decodeCursor(cursor)
878
- result[keyStr] = value
878
+ setEntry(result, keyStr, value)
879
879
  }
880
880
 
881
881
  return result
@@ -886,6 +886,24 @@ namespace decodeCursor {
886
886
  type ErrorType = readLength.ErrorType | Errors.GlobalErrorType
887
887
  }
888
888
 
889
+ /** @internal */
890
+ function setEntry(
891
+ result: Record<string, unknown>,
892
+ key: string,
893
+ value: unknown,
894
+ ) {
895
+ // Define `__proto__` as an own property instead of assigning it, which
896
+ // would replace the prototype of `result` and drop the entry.
897
+ if (key === '__proto__')
898
+ Object.defineProperty(result, key, {
899
+ configurable: true,
900
+ enumerable: true,
901
+ value,
902
+ writable: true,
903
+ })
904
+ else result[key] = value
905
+ }
906
+
889
907
  /** @internal */
890
908
  export function readSimpleOrFloat(
891
909
  cursor: Cursor.Cursor,
@@ -31,6 +31,7 @@ export function toBytes(value: bigint | number): Bytes.Bytes {
31
31
  throw new InvalidValueError({ value })
32
32
  const n = BigInt(value)
33
33
  if (n < 0n) throw new NegativeValueError({ value: n })
34
+ if (n > 0xffffffffffffffffn) throw new ValueTooLargeError({ value: n })
34
35
  if (n <= 252n) return new Uint8Array([Number(n)])
35
36
  if (n <= 0xffffn) {
36
37
  const buf = new Uint8Array(3)
@@ -57,6 +58,7 @@ export declare namespace toBytes {
57
58
  type ErrorType =
58
59
  | InvalidValueError
59
60
  | NegativeValueError
61
+ | ValueTooLargeError
60
62
  | Errors.GlobalErrorType
61
63
  }
62
64
 
@@ -173,6 +175,17 @@ export class NegativeValueError extends Errors.BaseError {
173
175
  }
174
176
  }
175
177
 
178
+ /** Thrown when a CompactSize value does not fit in 64 bits. */
179
+ export class ValueTooLargeError extends Errors.BaseError {
180
+ override readonly name = 'CompactSize.ValueTooLargeError'
181
+
182
+ constructor({ value }: { value: bigint }) {
183
+ super(
184
+ `CompactSize value must be at most 18446744073709551615, got ${value}.`,
185
+ )
186
+ }
187
+ }
188
+
176
189
  /** Thrown when there are insufficient bytes to decode a CompactSize value. */
177
190
  export class InsufficientBytesError extends Errors.BaseError {
178
191
  override readonly name = 'CompactSize.InsufficientBytesError'
package/src/core/Hex.ts CHANGED
@@ -15,6 +15,8 @@ import * as Json from './Json.js'
15
15
  /** Root type for a Hex string. */
16
16
  export type Hex = `0x${string}`
17
17
 
18
+ const hexRegex = /^0x[0-9a-fA-F]*$/
19
+
18
20
  /**
19
21
  * Asserts if the given value is {@link ox#Hex.Hex}.
20
22
  *
@@ -38,7 +40,7 @@ export function assert(
38
40
  const { even = false, strict = false } = options
39
41
  if (typeof value !== 'string') throw new InvalidHexTypeError(value)
40
42
  if (strict) {
41
- if (!/^0x[0-9a-fA-F]*$/.test(value)) throw new InvalidHexValueError(value)
43
+ if (!hexRegex.test(value)) throw new InvalidHexValueError(value)
42
44
  }
43
45
  if (!value.startsWith('0x')) throw new InvalidHexValueError(value)
44
46
  if (even && value.length % 2 !== 0) throw new InvalidLengthError(value as Hex)
@@ -284,7 +286,9 @@ export function fromNumber(
284
286
  maxValue = BigInt(Number.MAX_SAFE_INTEGER)
285
287
  }
286
288
 
287
- const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0
289
+ // Negative values need a `size` to encode as two's complement.
290
+ const minValue =
291
+ size && typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0
288
292
 
289
293
  if ((maxValue && value_ > maxValue) || value_ < minValue) {
290
294
  const suffix = typeof value === 'bigint' ? 'n' : ''
@@ -609,9 +613,7 @@ export function toBigInt(hex: Hex, options: toBigInt.Options = {}): bigint {
609
613
  const value = BigInt(hex)
610
614
  if (!signed) return value
611
615
 
612
- const size = (hex.length - 2) / 2
613
-
614
- const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n
616
+ const max_unsigned = (1n << (BigInt(size(hex)) * 8n)) - 1n
615
617
  const max_signed = max_unsigned >> 1n
616
618
 
617
619
  if (value <= max_signed) return value
@@ -691,6 +693,9 @@ export function toBytes(hex: Hex, options: toBytes.Options = {}): Uint8Array {
691
693
  let value = hex
692
694
  if (typeof size === 'number') {
693
695
  internal.assertSize(value, size)
696
+ // An odd-length value gets its leading `0` before right-padding, so the
697
+ // padding lands after the value's bytes instead of between its nibbles.
698
+ if (value.length % 2) value = `0x0${value.slice(2)}`
694
699
  value = padRight(value, size)
695
700
  }
696
701
  return hexToBytes(value)
package/src/core/Rlp.ts CHANGED
@@ -118,6 +118,14 @@ export function decodeRlpCursor<to extends 'Hex' | 'Bytes' = 'Hex'>(
118
118
  if (prefix < 0xc0) {
119
119
  const length = readLength(cursor, prefix, 0x80)
120
120
  const bytes = cursor.readBytes(length)
121
+ // A single byte below `0x80` must be its own encoding (no length
122
+ // prefix); wrapping it in an explicit one-byte-length prefix is a
123
+ // non-canonical alternate encoding of the same value (Yellow Paper,
124
+ // Appendix B).
125
+ if (prefix >= 0x80 && length === 1 && bytes[0]! < 0x80)
126
+ throw new NonCanonicalError({
127
+ reason: `single byte \`0x${bytes[0]!.toString(16).padStart(2, '0')}\` is wrapped in an explicit length prefix instead of being encoded as itself`,
128
+ })
121
129
  return (
122
130
  to === 'Hex' ? Hex.fromBytes(bytes) : bytes
123
131
  ) as decodeRlpCursor.ReturnType<to>
@@ -141,6 +149,7 @@ export declare namespace decodeRlpCursor {
141
149
  | readLength.ErrorType
142
150
  | readList.ErrorType
143
151
  | DepthLimitExceededError
152
+ | NonCanonicalError
144
153
  | Errors.GlobalErrorType
145
154
  }
146
155
 
@@ -152,16 +161,48 @@ export function readLength(
152
161
  ) {
153
162
  if (offset === 0x80 && prefix < 0x80) return 1
154
163
  if (prefix <= offset + 55) return prefix - offset
155
- if (prefix === offset + 55 + 1) return cursor.readUint8()
156
- if (prefix === offset + 55 + 2) return cursor.readUint16()
157
- if (prefix === offset + 55 + 3) return cursor.readUint24()
158
- if (prefix === offset + 55 + 4) return cursor.readUint32()
164
+ // Long-form lengths must use the minimal number of length-bytes: a value
165
+ // that fits in fewer bytes (or in the short form, i.e. <= 55) encoded via
166
+ // a longer form is a non-canonical alternate encoding of the same value
167
+ // (Yellow Paper, Appendix B).
168
+ if (prefix === offset + 55 + 1) {
169
+ const length = cursor.readUint8()
170
+ if (length <= 55)
171
+ throw new NonCanonicalError({
172
+ reason: `length \`${length}\` fits in the short form and must not use a one-byte length prefix`,
173
+ })
174
+ return length
175
+ }
176
+ if (prefix === offset + 55 + 2) {
177
+ const length = cursor.readUint16()
178
+ if (length <= 0xff)
179
+ throw new NonCanonicalError({
180
+ reason: `length \`${length}\` fits in fewer length-bytes and must not use a two-byte length prefix`,
181
+ })
182
+ return length
183
+ }
184
+ if (prefix === offset + 55 + 3) {
185
+ const length = cursor.readUint24()
186
+ if (length <= 0xffff)
187
+ throw new NonCanonicalError({
188
+ reason: `length \`${length}\` fits in fewer length-bytes and must not use a three-byte length prefix`,
189
+ })
190
+ return length
191
+ }
192
+ if (prefix === offset + 55 + 4) {
193
+ const length = cursor.readUint32()
194
+ if (length <= 0xffffff)
195
+ throw new NonCanonicalError({
196
+ reason: `length \`${length}\` fits in fewer length-bytes and must not use a four-byte length prefix`,
197
+ })
198
+ return length
199
+ }
159
200
  throw new Errors.BaseError('Invalid RLP prefix')
160
201
  }
161
202
 
162
203
  /** @internal */
163
204
  export declare namespace readLength {
164
- type ErrorType = Errors.BaseError | Errors.GlobalErrorType
205
+ type ErrorType = NonCanonicalError | Errors.BaseError | Errors.GlobalErrorType
165
206
  }
166
207
 
167
208
  /** @internal */
@@ -873,3 +914,12 @@ export class TrailingBytesError extends Errors.BaseError {
873
914
  )
874
915
  }
875
916
  }
917
+
918
+ /** Thrown when an RLP payload uses a non-canonical alternate encoding of a value. */
919
+ export class NonCanonicalError extends Errors.BaseError {
920
+ override readonly name = 'Rlp.NonCanonicalError'
921
+
922
+ constructor({ reason }: { reason: string }) {
923
+ super(`RLP payload is not canonically encoded: ${reason}.`)
924
+ }
925
+ }
@@ -116,13 +116,20 @@ export function fromHttp<
116
116
  if (typeof AbortSignal.any !== 'function') return signals[0]!
117
117
  return AbortSignal.any(signals)
118
118
  })()
119
+ // Merge through `Headers` so a caller's header replaces the default
120
+ // whatever its casing, and keep a plain object for `fetchFn`.
121
+ const headers: Record<string, string> = {}
122
+ for (const source of [
123
+ { 'Content-Type': 'application/json' },
124
+ fetchOptions?.headers,
125
+ ])
126
+ new Headers(source).forEach((value, key) => {
127
+ headers[key] = value
128
+ })
119
129
  const init: RequestInit = {
120
130
  ...fetchOptions,
121
131
  body,
122
- headers: {
123
- 'Content-Type': 'application/json',
124
- ...Object.fromEntries(new Headers(fetchOptions?.headers)),
125
- },
132
+ headers,
126
133
  method: fetchOptions?.method ?? 'POST',
127
134
  signal: composedSignal,
128
135
  }
package/src/core/Siwe.ts CHANGED
@@ -26,6 +26,18 @@ export const suffixRegex =
26
26
  const siweDateTimeRegex =
27
27
  /^(\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
28
 
29
+ // URI validation (see `isUri`).
30
+ const uriIllegalCharacterRegex = /[^a-z0-9:/?#[\]@!$&'()*+,;=.\-_~%]/i
31
+ const uriInvalidEscapeRegex = /%[^0-9a-f]/i
32
+ const uriIncompleteEscapeRegex = /%[0-9a-f](:?[^0-9a-f]|$)/i
33
+ const uriSchemeRegex = /^[a-z][a-z0-9+\-.]*$/
34
+ const uriPartsRegex =
35
+ /(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/
36
+ const authorityHostRegex = /^(?:[a-z0-9._~!$&'()*+,;=:%-]*@)?(.*)$/i
37
+ const authorityIpLiteralRegex = /^\[([^\]]+)\](?::\d*)?$/
38
+ const authorityIpFutureRegex = /^v[0-9a-f]+\.[a-z0-9._~!$&'()*+,;=:-]+$/i
39
+ const authorityRegNameRegex = /^(?:[a-z0-9._~!$&'()*+,;=%-]*)(?::\d*)?$/i
40
+
29
41
  function parseSiweDateTime(value: string): Date {
30
42
  const match = value.match(siweDateTimeRegex)
31
43
  if (!match) return new Date(Number.NaN)
@@ -315,11 +327,11 @@ export function generateNonce(): string {
315
327
  // based on https://github.com/ogt/valid-url
316
328
  export function isUri(value: string): false | string {
317
329
  // check for illegal characters
318
- if (/[^a-z0-9:/?#[\]@!$&'()*+,;=.\-_~%]/i.test(value)) return false
330
+ if (uriIllegalCharacterRegex.test(value)) return false
319
331
 
320
332
  // check for hex escapes that aren't complete
321
- if (/%[^0-9a-f]/i.test(value)) return false
322
- if (/%[0-9a-f](:?[^0-9a-f]|$)/i.test(value)) return false
333
+ if (uriInvalidEscapeRegex.test(value)) return false
334
+ if (uriIncompleteEscapeRegex.test(value)) return false
323
335
 
324
336
  // from RFC 3986
325
337
  const splitted = splitUri(value)
@@ -342,7 +354,7 @@ export function isUri(value: string): false | string {
342
354
  }
343
355
 
344
356
  // scheme must begin with a letter, then consist of letters, digits, +, ., or -
345
- if (!/^[a-z][a-z0-9+\-.]*$/.test(scheme.toLowerCase())) return false
357
+ if (!uriSchemeRegex.test(scheme.toLowerCase())) return false
346
358
 
347
359
  let out = ''
348
360
  // re-assemble the URL per section 5.3 in RFC 3986
@@ -358,12 +370,12 @@ export function isUri(value: string): false | string {
358
370
  }
359
371
 
360
372
  function isAuthority(value: string) {
361
- const host = value.match(/^(?:[a-z0-9._~!$&'()*+,;=:%-]*@)?(.*)$/i)?.[1]
373
+ const host = value.match(authorityHostRegex)?.[1]
362
374
  if (host === undefined) return false
363
375
 
364
- const ipLiteral = host.match(/^\[([^\]]+)\](?::\d*)?$/)?.[1]
376
+ const ipLiteral = host.match(authorityIpLiteralRegex)?.[1]
365
377
  if (ipLiteral) {
366
- if (/^v[0-9a-f]+\.[a-z0-9._~!$&'()*+,;=:-]+$/i.test(ipLiteral)) return true
378
+ if (authorityIpFutureRegex.test(ipLiteral)) return true
367
379
  try {
368
380
  new URL(`http://[${ipLiteral}]`)
369
381
  return true
@@ -372,13 +384,11 @@ function isAuthority(value: string) {
372
384
  }
373
385
  }
374
386
 
375
- return /^(?:[a-z0-9._~!$&'()*+,;=%-]*)(?::\d*)?$/i.test(host)
387
+ return authorityRegNameRegex.test(host)
376
388
  }
377
389
 
378
390
  function splitUri(value: string) {
379
- return value.match(
380
- /(?:([^:/?#]+):)?(?:\/\/([^/?#]*))?([^?#]*)(?:\?([^#]*))?(?:#(.*))?/,
381
- )!
391
+ return value.match(uriPartsRegex)!
382
392
  }
383
393
 
384
394
  /**
@@ -490,6 +500,11 @@ export function validateMessage(value: validateMessage.Value): boolean {
490
500
  if (nonce && message.nonce !== nonce) return false
491
501
  if (scheme && message.scheme !== scheme) return false
492
502
 
503
+ // EIP-4361 requires `nonce = 8*( ALPHA / DIGIT )` and `version = "1"`.
504
+ if (message.nonce !== undefined && !nonceRegex.test(message.nonce))
505
+ return false
506
+ if (message.version !== undefined && message.version !== '1') return false
507
+
493
508
  if (Number.isNaN(time.getTime())) return false
494
509
 
495
510
  if (message.expirationTime) {
@@ -877,7 +877,7 @@ export class FeeCapTooHighError extends Errors.BaseError {
877
877
  } = {}) {
878
878
  super(
879
879
  `The fee cap (\`maxFeePerGas\`/\`maxPriorityFeePerGas\`${
880
- feeCap ? ` = ${Value.formatGwei(feeCap)} gwei` : ''
880
+ typeof feeCap === 'bigint' ? ` = ${Value.formatGwei(feeCap)} gwei` : ''
881
881
  }) cannot be higher than the maximum allowed value (2^256-1).`,
882
882
  )
883
883
  }
@@ -1021,11 +1021,13 @@ export class TipAboveFeeCapError extends Errors.BaseError {
1021
1021
  super(
1022
1022
  [
1023
1023
  `The provided tip (\`maxPriorityFeePerGas\`${
1024
- maxPriorityFeePerGas
1024
+ typeof maxPriorityFeePerGas === 'bigint'
1025
1025
  ? ` = ${Value.formatGwei(maxPriorityFeePerGas)} gwei`
1026
1026
  : ''
1027
1027
  }) cannot be higher than the fee cap (\`maxFeePerGas\`${
1028
- maxFeePerGas ? ` = ${Value.formatGwei(maxFeePerGas)} gwei` : ''
1028
+ typeof maxFeePerGas === 'bigint'
1029
+ ? ` = ${Value.formatGwei(maxFeePerGas)} gwei`
1030
+ : ''
1029
1031
  }).`,
1030
1032
  ].join('\n'),
1031
1033
  )
@@ -77,8 +77,8 @@ export function assert(envelope: PartialBy<TxEnvelopeEip1559, 'type'>) {
77
77
  if (maxFeePerGas && BigInt(maxFeePerGas) > 2n ** 256n - 1n)
78
78
  throw new TransactionEnvelope.FeeCapTooHighError({ feeCap: maxFeePerGas })
79
79
  if (
80
- maxPriorityFeePerGas &&
81
- maxFeePerGas &&
80
+ typeof maxPriorityFeePerGas === 'bigint' &&
81
+ typeof maxFeePerGas === 'bigint' &&
82
82
  maxPriorityFeePerGas > maxFeePerGas
83
83
  )
84
84
  throw new TransactionEnvelope.TipAboveFeeCapError({
@@ -182,6 +182,12 @@ export function deserialize(
182
182
  Tx.bytesToBigIntOrUndefined(maxPriorityFeePerGas)
183
183
  if (maxPriorityFeePerGas_ !== undefined)
184
184
  transaction.maxPriorityFeePerGas = maxPriorityFeePerGas_
185
+ // An empty `maxFeePerGas` encodes zero, so a tip above it is rejected.
186
+ if (
187
+ transaction.maxPriorityFeePerGas &&
188
+ typeof transaction.maxFeePerGas === 'undefined'
189
+ )
190
+ transaction.maxFeePerGas = 0n
185
191
  if ((accessList as unknown as readonly unknown[]).length !== 0)
186
192
  transaction.accessList = AccessList.fromTupleList(
187
193
  Tx.bytesTreeToHex(accessList as never) as never,
@@ -274,6 +274,12 @@ export function deserialize(
274
274
  )
275
275
  if (maxPriorityFeePerGas_ !== undefined)
276
276
  transaction.maxPriorityFeePerGas = maxPriorityFeePerGas_
277
+ // An empty `maxFeePerGas` encodes zero, so a tip above it is rejected.
278
+ if (
279
+ transaction.maxPriorityFeePerGas &&
280
+ typeof transaction.maxFeePerGas === 'undefined'
281
+ )
282
+ transaction.maxFeePerGas = 0n
277
283
  if (accessList && (accessList as readonly unknown[]).length !== 0)
278
284
  transaction.accessList = AccessList.fromTupleList(
279
285
  Tx.bytesTreeToHex(accessList as never) as never,
@@ -185,6 +185,12 @@ export function deserialize(
185
185
  Tx.bytesToBigIntOrUndefined(maxPriorityFeePerGas)
186
186
  if (maxPriorityFeePerGas_ !== undefined)
187
187
  transaction.maxPriorityFeePerGas = maxPriorityFeePerGas_
188
+ // An empty `maxFeePerGas` encodes zero, so a tip above it is rejected.
189
+ if (
190
+ transaction.maxPriorityFeePerGas &&
191
+ typeof transaction.maxFeePerGas === 'undefined'
192
+ )
193
+ transaction.maxFeePerGas = 0n
188
194
  if ((accessList as unknown as readonly unknown[]).length !== 0)
189
195
  transaction.accessList = AccessList.fromTupleList(
190
196
  Tx.bytesTreeToHex(accessList as never) as never,
@@ -162,11 +162,8 @@ export function assert<
162
162
  })
163
163
  }
164
164
 
165
- const struct = types[type]
166
- if (struct) {
167
- validateReference(type)
168
- validateData(struct, value as Record<string, unknown>)
169
- }
165
+ if (Object.hasOwn(types, type))
166
+ validateData(types[type]!, value as Record<string, unknown>)
170
167
  }
171
168
 
172
169
  const validateData = (
@@ -179,6 +176,12 @@ export function assert<
179
176
  }
180
177
  }
181
178
 
179
+ // Validate struct types and their field types, including structs that are
180
+ // only referenced as array elements.
181
+ for (const type of Object.keys(types)) validateReference(type)
182
+ for (const struct of Object.values(types))
183
+ for (const field of struct ?? []) validateField(field.type, types)
184
+
182
185
  // Validate domain types.
183
186
  if (types.EIP712Domain && domain) {
184
187
  if (typeof domain !== 'object') throw new InvalidDomainError({ domain })
@@ -204,6 +207,8 @@ export declare namespace assert {
204
207
  | InvalidArrayError
205
208
  | InvalidArrayLengthError
206
209
  | InvalidPrimaryTypeError
210
+ | InvalidStructTypeError
211
+ | InvalidTypeError
207
212
  | Hex.fromNumber.ErrorType
208
213
  | Hex.size.ErrorType
209
214
  | Errors.GlobalErrorType
@@ -808,7 +813,24 @@ export class InvalidStructTypeError extends Errors.BaseError {
808
813
 
809
814
  constructor({ type }: { type: string }) {
810
815
  super(`Struct type "${type}" is invalid.`, {
811
- metaMessages: ['Struct type must not be a Solidity type.'],
816
+ metaMessages: [
817
+ 'Struct type must contain only letters, digits, "_", "$" and ":", and must not be a Solidity type.',
818
+ ],
819
+ })
820
+ }
821
+ }
822
+
823
+ /** Thrown when a field type is not a valid EIP-712 type. */
824
+ export class InvalidTypeError extends Errors.BaseError {
825
+ override readonly name = 'TypedData.InvalidTypeError'
826
+
827
+ constructor({ type }: { type: string }) {
828
+ // Suggest the canonical type only for the `int`/`uint` aliases.
829
+ const isAlias = /^u?int(\[[0-9]*\])*$/.test(type)
830
+ super(`Type "${type}" is not a valid EIP-712 type.`, {
831
+ metaMessages: isAlias
832
+ ? [`Use "${type.replace(/^(u?int)/, '$&256')}" instead.`]
833
+ : undefined,
812
834
  })
813
835
  }
814
836
  }
@@ -997,6 +1019,10 @@ export declare namespace encodeField {
997
1019
  | Errors.GlobalErrorType
998
1020
  }
999
1021
 
1022
+ const arraySuffixRegex = /(\[[0-9]*\])+$/
1023
+ const structNameRegex = /^[A-Za-z0-9_$:]+$/
1024
+ const solidityTypeNameRegex = /^(u?int|bytes)[0-9]*$/
1025
+
1000
1026
  /** @internal */
1001
1027
  export function findTypeDependencies(
1002
1028
  value: {
@@ -1006,9 +1032,7 @@ export function findTypeDependencies(
1006
1032
  results: Set<string> = new Set(),
1007
1033
  ): Set<string> {
1008
1034
  const { primaryType: primaryType_, types } = value
1009
- // `/^\w*/u` always matches, so `match` is never null.
1010
- const match = primaryType_.match(/^\w*/u)!
1011
- const primaryType = match[0]!
1035
+ const primaryType = primaryType_.replace(arraySuffixRegex, '')
1012
1036
  if (results.has(primaryType) || types[primaryType] === undefined)
1013
1037
  return results
1014
1038
 
@@ -1024,16 +1048,41 @@ export declare namespace findTypeDependencies {
1024
1048
  type ErrorType = Errors.GlobalErrorType
1025
1049
  }
1026
1050
 
1051
+ /** @internal */
1052
+ function validateField(type: string, types: TypedData) {
1053
+ const baseType = type.replace(arraySuffixRegex, '')
1054
+ if (baseType === 'int' || baseType === 'uint')
1055
+ throw new InvalidTypeError({ type })
1056
+ // A field type must be a struct defined in `types` or an EIP-712 atomic or
1057
+ // dynamic type, so a type such as `uint7` or `bytes0` is not hashed.
1058
+ if (!Object.hasOwn(types, baseType) && !isSolidityType(baseType))
1059
+ throw new InvalidTypeError({ type })
1060
+ }
1061
+
1062
+ /** @internal */
1063
+ function isSolidityType(type: string) {
1064
+ return (
1065
+ type === 'address' ||
1066
+ type === 'bool' ||
1067
+ type === 'string' ||
1068
+ Solidity.bytesRegex.test(type) ||
1069
+ Solidity.integerRegex.test(type)
1070
+ )
1071
+ }
1072
+
1027
1073
  /** @internal */
1028
1074
  function validateReference(type: string) {
1029
- // Struct type must not be a Solidity type.
1075
+ // Struct type must contain only letters, digits, `_`, `$` and `:`, and must
1076
+ // not be a Solidity type, so it cannot shadow a Solidity type or an array of
1077
+ // one. A struct such as `intent` or `bytesInfo` is valid, while `uint7` or
1078
+ // `bytes33` is rejected, since other implementations parse it as a Solidity
1079
+ // type.
1030
1080
  if (
1081
+ !structNameRegex.test(type) ||
1031
1082
  type === 'address' ||
1032
1083
  type === 'bool' ||
1033
1084
  type === 'string' ||
1034
- type.startsWith('bytes') ||
1035
- type.startsWith('uint') ||
1036
- type.startsWith('int')
1085
+ solidityTypeNameRegex.test(type)
1037
1086
  )
1038
1087
  throw new InvalidStructTypeError({ type })
1039
1088
  }