ox 1.8.13 → 1.8.15

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 (158) hide show
  1. package/CHANGELOG.md +52 -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/TypedData.d.ts.map +1 -1
  49. package/dist/core/TypedData.js +13 -9
  50. package/dist/core/TypedData.js.map +1 -1
  51. package/dist/core/Value.d.ts.map +1 -1
  52. package/dist/core/Value.js +5 -3
  53. package/dist/core/Value.js.map +1 -1
  54. package/dist/core/internal/abiItem.d.ts +3 -1
  55. package/dist/core/internal/abiItem.d.ts.map +1 -1
  56. package/dist/core/internal/abiItem.js +5 -3
  57. package/dist/core/internal/abiItem.js.map +1 -1
  58. package/dist/core/internal/caches.d.ts +10 -0
  59. package/dist/core/internal/caches.d.ts.map +1 -0
  60. package/dist/core/internal/caches.js +10 -0
  61. package/dist/core/internal/caches.js.map +1 -0
  62. package/dist/core/internal/frameNonce.d.ts.map +1 -1
  63. package/dist/core/internal/frameNonce.js +2 -2
  64. package/dist/core/internal/frameNonce.js.map +1 -1
  65. package/dist/erc4337/UserOperation.d.ts +15 -2
  66. package/dist/erc4337/UserOperation.d.ts.map +1 -1
  67. package/dist/erc4337/UserOperation.js +8 -2
  68. package/dist/erc4337/UserOperation.js.map +1 -1
  69. package/dist/erc8021/Attribution.d.ts.map +1 -1
  70. package/dist/erc8021/Attribution.js +12 -3
  71. package/dist/erc8021/Attribution.js.map +1 -1
  72. package/dist/tempo/AccountOperation.d.ts +8 -0
  73. package/dist/tempo/AccountOperation.d.ts.map +1 -1
  74. package/dist/tempo/AccountOperation.js +26 -6
  75. package/dist/tempo/AccountOperation.js.map +1 -1
  76. package/dist/tempo/SignatureEnvelope.d.ts +4 -4
  77. package/dist/tempo/SignaturePreAuthorized.d.ts +192 -0
  78. package/dist/tempo/SignaturePreAuthorized.d.ts.map +1 -0
  79. package/dist/tempo/SignaturePreAuthorized.js +299 -0
  80. package/dist/tempo/SignaturePreAuthorized.js.map +1 -0
  81. package/dist/tempo/Tick.d.ts.map +1 -1
  82. package/dist/tempo/Tick.js +4 -3
  83. package/dist/tempo/Tick.js.map +1 -1
  84. package/dist/tempo/index.d.ts +26 -0
  85. package/dist/tempo/index.d.ts.map +1 -1
  86. package/dist/tempo/index.js +26 -0
  87. package/dist/tempo/index.js.map +1 -1
  88. package/dist/zod/Address.d.ts.map +1 -1
  89. package/dist/zod/Address.js +2 -1
  90. package/dist/zod/Address.js.map +1 -1
  91. package/dist/zod/FrameRequest.d.ts.map +1 -1
  92. package/dist/zod/FrameRequest.js +2 -1
  93. package/dist/zod/FrameRequest.js.map +1 -1
  94. package/dist/zod/Hex.d.ts.map +1 -1
  95. package/dist/zod/Hex.js +2 -1
  96. package/dist/zod/Hex.js.map +1 -1
  97. package/dist/zod/Solidity.d.ts.map +1 -1
  98. package/dist/zod/Solidity.js +12 -7
  99. package/dist/zod/Solidity.js.map +1 -1
  100. package/dist/zod/TypedData.d.ts +12 -12
  101. package/package.json +6 -1
  102. package/src/core/AbiError.ts +33 -22
  103. package/src/core/AbiEvent.ts +177 -18
  104. package/src/core/AbiFunction.ts +10 -7
  105. package/src/core/AbiItem.ts +17 -8
  106. package/src/core/Base32.ts +8 -3
  107. package/src/core/Bytes.ts +4 -3
  108. package/src/core/Caches.ts +1 -6
  109. package/src/core/Cbor.ts +20 -2
  110. package/src/core/CompactSize.ts +13 -0
  111. package/src/core/Hex.ts +10 -5
  112. package/src/core/Rlp.ts +55 -5
  113. package/src/core/RpcTransport.ts +11 -4
  114. package/src/core/Siwe.ts +26 -11
  115. package/src/core/TypedData.ts +14 -9
  116. package/src/core/Value.ts +6 -3
  117. package/src/core/_test/AbiError.test-d.ts +10 -0
  118. package/src/core/_test/AbiError.test.ts +73 -0
  119. package/src/core/_test/AbiEvent.fuzz.ts +260 -0
  120. package/src/core/_test/AbiEvent.snap-d.ts +9 -0
  121. package/src/core/_test/AbiEvent.test.ts +421 -0
  122. package/src/core/_test/AbiFunction.snap-d.ts +25 -0
  123. package/src/core/_test/AbiFunction.test.ts +101 -18
  124. package/src/core/_test/AbiItem.snap-d.ts +11 -0
  125. package/src/core/_test/AbiItem.test.ts +155 -1
  126. package/src/core/_test/Base32.test.ts +16 -0
  127. package/src/core/_test/Bytes.test.ts +15 -0
  128. package/src/core/_test/Caches.test.ts +10 -1
  129. package/src/core/_test/Cbor.test.ts +23 -0
  130. package/src/core/_test/CompactSize.test.ts +14 -0
  131. package/src/core/_test/Hex.test.ts +25 -0
  132. package/src/core/_test/Rlp.test.ts +51 -0
  133. package/src/core/_test/RpcTransport.test.ts +47 -0
  134. package/src/core/_test/Siwe.test.ts +28 -0
  135. package/src/core/_test/TypedData.test.ts +17 -2
  136. package/src/core/internal/abiItem.ts +16 -7
  137. package/src/core/internal/caches.ts +12 -0
  138. package/src/core/internal/frameNonce.ts +3 -4
  139. package/src/erc4337/UserOperation.ts +30 -3
  140. package/src/erc4337/_test/UserOperation.test.ts +132 -35
  141. package/src/erc8021/Attribution.ts +9 -7
  142. package/src/erc8021/_test/Attribution.test.ts +37 -0
  143. package/src/tempo/AccountOperation.test.ts +116 -0
  144. package/src/tempo/AccountOperation.ts +38 -5
  145. package/src/tempo/AccountSimulation.test.ts +1 -1
  146. package/src/tempo/SignatureEnvelope.test.ts +12 -0
  147. package/src/tempo/SignatureEnvelope.ts +4 -4
  148. package/src/tempo/SignaturePreAuthorized.test-d.ts +29 -0
  149. package/src/tempo/SignaturePreAuthorized.test.ts +410 -0
  150. package/src/tempo/SignaturePreAuthorized.ts +370 -0
  151. package/src/tempo/Tick.test.ts +10 -0
  152. package/src/tempo/Tick.ts +5 -3
  153. package/src/tempo/index.ts +26 -0
  154. package/src/version.ts +1 -1
  155. package/src/zod/Address.ts +3 -3
  156. package/src/zod/FrameRequest.ts +3 -4
  157. package/src/zod/Hex.ts +3 -1
  158. 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) {
@@ -814,7 +814,7 @@ export class InvalidStructTypeError extends Errors.BaseError {
814
814
  constructor({ type }: { type: string }) {
815
815
  super(`Struct type "${type}" is invalid.`, {
816
816
  metaMessages: [
817
- 'Struct type must contain only letters, digits, "_" and "$", and must not be a Solidity type.',
817
+ 'Struct type must contain only letters, digits, "_", "$" and ":", and must not be a Solidity type.',
818
818
  ],
819
819
  })
820
820
  }
@@ -1019,6 +1019,10 @@ export declare namespace encodeField {
1019
1019
  | Errors.GlobalErrorType
1020
1020
  }
1021
1021
 
1022
+ const arraySuffixRegex = /(\[[0-9]*\])+$/
1023
+ const structNameRegex = /^[A-Za-z0-9_$:]+$/
1024
+ const solidityTypeNameRegex = /^(u?int|bytes)[0-9]*$/
1025
+
1022
1026
  /** @internal */
1023
1027
  export function findTypeDependencies(
1024
1028
  value: {
@@ -1028,7 +1032,7 @@ export function findTypeDependencies(
1028
1032
  results: Set<string> = new Set(),
1029
1033
  ): Set<string> {
1030
1034
  const { primaryType: primaryType_, types } = value
1031
- const primaryType = primaryType_.replace(/(\[[0-9]*\])+$/, '')
1035
+ const primaryType = primaryType_.replace(arraySuffixRegex, '')
1032
1036
  if (results.has(primaryType) || types[primaryType] === undefined)
1033
1037
  return results
1034
1038
 
@@ -1046,7 +1050,7 @@ export declare namespace findTypeDependencies {
1046
1050
 
1047
1051
  /** @internal */
1048
1052
  function validateField(type: string, types: TypedData) {
1049
- const baseType = type.replace(/(\[[0-9]*\])+$/, '')
1053
+ const baseType = type.replace(arraySuffixRegex, '')
1050
1054
  if (baseType === 'int' || baseType === 'uint')
1051
1055
  throw new InvalidTypeError({ type })
1052
1056
  // A field type must be a struct defined in `types` or an EIP-712 atomic or
@@ -1068,16 +1072,17 @@ function isSolidityType(type: string) {
1068
1072
 
1069
1073
  /** @internal */
1070
1074
  function validateReference(type: string) {
1071
- // Struct type must contain only letters, digits, `_` and `$`, and must not be
1072
- // a Solidity type, so it cannot shadow a Solidity type or an array of one. A
1073
- // struct such as `intent` or `bytesInfo` is valid, while `uint7` or `bytes33`
1074
- // is rejected, since other implementations parse it as 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.
1075
1080
  if (
1076
- !/^[A-Za-z0-9_$]+$/.test(type) ||
1081
+ !structNameRegex.test(type) ||
1077
1082
  type === 'address' ||
1078
1083
  type === 'bool' ||
1079
1084
  type === 'string' ||
1080
- /^(u?int|bytes)[0-9]*$/.test(type)
1085
+ solidityTypeNameRegex.test(type)
1081
1086
  )
1082
1087
  throw new InvalidStructTypeError({ type })
1083
1088
  }
package/src/core/Value.ts CHANGED
@@ -9,6 +9,9 @@ export const exponents = {
9
9
  ether: 18,
10
10
  } as const
11
11
 
12
+ const decimalNumberRegex = /^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/
13
+ const trailingZerosRegex = /(0+)$/
14
+
12
15
  /**
13
16
  * Formats a `bigint` Value to its string representation (divided by the given exponent).
14
17
  *
@@ -39,7 +42,7 @@ export function format(value: bigint, decimals = 0) {
39
42
  display.slice(0, display.length - decimals),
40
43
  display.slice(display.length - decimals),
41
44
  ]
42
- fraction = fraction.replace(/(0+)$/, '')
45
+ fraction = fraction.replace(trailingZerosRegex, '')
43
46
  return `${negative ? '-' : ''}${integer || '0'}${
44
47
  fraction ? `.${fraction}` : ''
45
48
  }`
@@ -120,7 +123,7 @@ export function from(value: string, decimals = 0) {
120
123
  // Require at least one digit overall. Rejects '', '.', '-', '-.' which
121
124
  // the previous regex accepted (and which then either produced garbage or
122
125
  // threw a raw `SyntaxError` from `BigInt('')`).
123
- if (!/^-?(?:[0-9]+(?:\.[0-9]*)?|\.[0-9]+)$/.test(value))
126
+ if (!decimalNumberRegex.test(value))
124
127
  throw new InvalidDecimalNumberError({ value })
125
128
 
126
129
  let [integer = '', fraction = '0'] = value.split('.')
@@ -130,7 +133,7 @@ export function from(value: string, decimals = 0) {
130
133
  if (integer === '') integer = '0'
131
134
 
132
135
  // trim trailing zeros.
133
- fraction = fraction.replace(/(0+)$/, '')
136
+ fraction = fraction.replace(trailingZerosRegex, '')
134
137
 
135
138
  // round off if the fraction is larger than the number of decimals.
136
139
  if (decimals === 0) {
@@ -36,6 +36,16 @@ describe('AbiError.decode', () => {
36
36
  expectTypeOf(decoded).toEqualTypeOf<number>()
37
37
  })
38
38
 
39
+ test('behavior: with overloads', () => {
40
+ const abi = Abi.from([
41
+ 'error Example()',
42
+ 'error Example(uint256 amount)',
43
+ 'error Example(string reason)',
44
+ ])
45
+ const decoded = AbiError.decode(abi, 'Example', '0x')
46
+ expectTypeOf(decoded).toEqualTypeOf<bigint | string | undefined>()
47
+ })
48
+
39
49
  test('not narrowable', () => {
40
50
  const abiError = {} as AbiError.AbiError
41
51
  const decoded = AbiError.decode(abiError, '0x')
@@ -76,6 +76,37 @@ describe('decode', () => {
76
76
  expect(decoded).toEqual(1)
77
77
  })
78
78
 
79
+ test('behavior: with overloads, resolved by name', () => {
80
+ const abi = Abi.from([
81
+ 'error Example()',
82
+ 'error Example(uint256 amount)',
83
+ 'error Example(string reason)',
84
+ ])
85
+ expect(
86
+ AbiError.decode(
87
+ abi,
88
+ 'Example',
89
+ AbiError.encode(AbiError.from('error Example(uint256 amount)'), [5n]),
90
+ ),
91
+ ).toEqual(5n)
92
+ expect(
93
+ AbiError.decode(
94
+ abi,
95
+ 'Example',
96
+ AbiError.encode(AbiError.from('error Example(string reason)'), [
97
+ 'denied',
98
+ ]),
99
+ ),
100
+ ).toEqual('denied')
101
+ expect(
102
+ AbiError.decode(
103
+ abi,
104
+ 'Example',
105
+ AbiError.encode(AbiError.from('error Example()')),
106
+ ),
107
+ ).toEqual(undefined)
108
+ })
109
+
79
110
  test('error: invalid data', () => {
80
111
  const error = AbiError.from('error Example(uint256 a)')
81
112
  expect(() =>
@@ -828,6 +859,17 @@ describe('fromAbi', () => {
828
859
  "hash": "0xbfb4ebcfff8f360b39de1de85df1edc256d63337b743120bf6e2e2144b973d38",
829
860
  "inputs": [],
830
861
  "name": "Foo",
862
+ "overloads": [
863
+ {
864
+ "inputs": [
865
+ {
866
+ "type": "uint256",
867
+ },
868
+ ],
869
+ "name": "Foo",
870
+ "type": "error",
871
+ },
872
+ ],
831
873
  "type": "error",
832
874
  }
833
875
  `)
@@ -841,6 +883,17 @@ describe('fromAbi', () => {
841
883
  "hash": "0xbfb4ebcfff8f360b39de1de85df1edc256d63337b743120bf6e2e2144b973d38",
842
884
  "inputs": [],
843
885
  "name": "Foo",
886
+ "overloads": [
887
+ {
888
+ "inputs": [
889
+ {
890
+ "type": "uint256",
891
+ },
892
+ ],
893
+ "name": "Foo",
894
+ "type": "error",
895
+ },
896
+ ],
844
897
  "type": "error",
845
898
  }
846
899
  `)
@@ -858,6 +911,26 @@ describe('fromAbi', () => {
858
911
  "hash": "0x34c73884fbbb790762253ae313e57da96c00670344647f0cb8d41ee92b9f1971",
859
912
  "inputs": [],
860
913
  "name": "Mint",
914
+ "overloads": [
915
+ {
916
+ "inputs": [
917
+ {
918
+ "type": "uint256",
919
+ },
920
+ ],
921
+ "name": "Mint",
922
+ "type": "error",
923
+ },
924
+ {
925
+ "inputs": [
926
+ {
927
+ "type": "string",
928
+ },
929
+ ],
930
+ "name": "Mint",
931
+ "type": "error",
932
+ },
933
+ ],
861
934
  "type": "error",
862
935
  }
863
936
  `)