ox 0.14.65 → 0.14.66

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (166) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/_cjs/core/AbiError.js +25 -4
  3. package/_cjs/core/AbiError.js.map +1 -1
  4. package/_cjs/core/AbiEvent.js +18 -3
  5. package/_cjs/core/AbiEvent.js.map +1 -1
  6. package/_cjs/core/AbiFunction.js +27 -3
  7. package/_cjs/core/AbiFunction.js.map +1 -1
  8. package/_cjs/core/Address.js +1 -0
  9. package/_cjs/core/Address.js.map +1 -1
  10. package/_cjs/core/Authorization.js +29 -2
  11. package/_cjs/core/Authorization.js.map +1 -1
  12. package/_cjs/core/Keystore.js +18 -0
  13. package/_cjs/core/Keystore.js.map +1 -1
  14. package/_cjs/core/Secp256k1.js +5 -1
  15. package/_cjs/core/Secp256k1.js.map +1 -1
  16. package/_cjs/core/Signature.js +4 -2
  17. package/_cjs/core/Signature.js.map +1 -1
  18. package/_cjs/core/Siwe.js +22 -3
  19. package/_cjs/core/Siwe.js.map +1 -1
  20. package/_cjs/core/TxEnvelopeEip1559.js +2 -1
  21. package/_cjs/core/TxEnvelopeEip1559.js.map +1 -1
  22. package/_cjs/core/TxEnvelopeEip2930.js +2 -1
  23. package/_cjs/core/TxEnvelopeEip2930.js.map +1 -1
  24. package/_cjs/core/TxEnvelopeEip7702.js +5 -1
  25. package/_cjs/core/TxEnvelopeEip7702.js.map +1 -1
  26. package/_cjs/core/TxEnvelopeLegacy.js +41 -8
  27. package/_cjs/core/TxEnvelopeLegacy.js.map +1 -1
  28. package/_cjs/core/TypedData.js +7 -9
  29. package/_cjs/core/TypedData.js.map +1 -1
  30. package/_cjs/core/Value.js +8 -3
  31. package/_cjs/core/Value.js.map +1 -1
  32. package/_cjs/core/internal/abiParameters.js +6 -2
  33. package/_cjs/core/internal/abiParameters.js.map +1 -1
  34. package/_cjs/core/internal/cursor.js +30 -1
  35. package/_cjs/core/internal/cursor.js.map +1 -1
  36. package/_cjs/erc4337/UserOperation.js +1 -1
  37. package/_cjs/erc4337/UserOperation.js.map +1 -1
  38. package/_cjs/erc7821/Execute.js +41 -3
  39. package/_cjs/erc7821/Execute.js.map +1 -1
  40. package/_cjs/tempo/KeyAuthorization.js +22 -1
  41. package/_cjs/tempo/KeyAuthorization.js.map +1 -1
  42. package/_cjs/tempo/SignatureEnvelope.js +37 -12
  43. package/_cjs/tempo/SignatureEnvelope.js.map +1 -1
  44. package/_cjs/tempo/TxEnvelopeTempo.js +34 -3
  45. package/_cjs/tempo/TxEnvelopeTempo.js.map +1 -1
  46. package/_cjs/version.js +1 -1
  47. package/_cjs/webauthn/Registration.js +2 -6
  48. package/_cjs/webauthn/Registration.js.map +1 -1
  49. package/_esm/core/AbiError.js +64 -3
  50. package/_esm/core/AbiError.js.map +1 -1
  51. package/_esm/core/AbiEvent.js +24 -3
  52. package/_esm/core/AbiEvent.js.map +1 -1
  53. package/_esm/core/AbiFunction.js +64 -3
  54. package/_esm/core/AbiFunction.js.map +1 -1
  55. package/_esm/core/Address.js +17 -1
  56. package/_esm/core/Address.js.map +1 -1
  57. package/_esm/core/Authorization.js +47 -2
  58. package/_esm/core/Authorization.js.map +1 -1
  59. package/_esm/core/Keystore.js +33 -2
  60. package/_esm/core/Keystore.js.map +1 -1
  61. package/_esm/core/Secp256k1.js +5 -1
  62. package/_esm/core/Secp256k1.js.map +1 -1
  63. package/_esm/core/Signature.js +4 -2
  64. package/_esm/core/Signature.js.map +1 -1
  65. package/_esm/core/Siwe.js +29 -3
  66. package/_esm/core/Siwe.js.map +1 -1
  67. package/_esm/core/TxEnvelopeEip1559.js +2 -1
  68. package/_esm/core/TxEnvelopeEip1559.js.map +1 -1
  69. package/_esm/core/TxEnvelopeEip2930.js +2 -1
  70. package/_esm/core/TxEnvelopeEip2930.js.map +1 -1
  71. package/_esm/core/TxEnvelopeEip7702.js +6 -1
  72. package/_esm/core/TxEnvelopeEip7702.js.map +1 -1
  73. package/_esm/core/TxEnvelopeLegacy.js +49 -9
  74. package/_esm/core/TxEnvelopeLegacy.js.map +1 -1
  75. package/_esm/core/TypedData.js +9 -9
  76. package/_esm/core/TypedData.js.map +1 -1
  77. package/_esm/core/Value.js +14 -3
  78. package/_esm/core/Value.js.map +1 -1
  79. package/_esm/core/internal/abiParameters.js +9 -2
  80. package/_esm/core/internal/abiParameters.js.map +1 -1
  81. package/_esm/core/internal/cursor.js +32 -0
  82. package/_esm/core/internal/cursor.js.map +1 -1
  83. package/_esm/erc4337/UserOperation.js +1 -1
  84. package/_esm/erc4337/UserOperation.js.map +1 -1
  85. package/_esm/erc7821/Execute.js +76 -2
  86. package/_esm/erc7821/Execute.js.map +1 -1
  87. package/_esm/index.js +1 -1
  88. package/_esm/tempo/KeyAuthorization.js +21 -0
  89. package/_esm/tempo/KeyAuthorization.js.map +1 -1
  90. package/_esm/tempo/SignatureEnvelope.js +46 -13
  91. package/_esm/tempo/SignatureEnvelope.js.map +1 -1
  92. package/_esm/tempo/TxEnvelopeTempo.js +56 -2
  93. package/_esm/tempo/TxEnvelopeTempo.js.map +1 -1
  94. package/_esm/version.js +1 -1
  95. package/_esm/webauthn/Registration.js +2 -6
  96. package/_esm/webauthn/Registration.js.map +1 -1
  97. package/_types/core/AbiError.d.ts +51 -5
  98. package/_types/core/AbiError.d.ts.map +1 -1
  99. package/_types/core/AbiEvent.d.ts +4 -2
  100. package/_types/core/AbiEvent.d.ts.map +1 -1
  101. package/_types/core/AbiFunction.d.ts +48 -2
  102. package/_types/core/AbiFunction.d.ts.map +1 -1
  103. package/_types/core/Address.d.ts +17 -2
  104. package/_types/core/Address.d.ts.map +1 -1
  105. package/_types/core/Authorization.d.ts +24 -2
  106. package/_types/core/Authorization.d.ts.map +1 -1
  107. package/_types/core/Keystore.d.ts +31 -2
  108. package/_types/core/Keystore.d.ts.map +1 -1
  109. package/_types/core/Secp256k1.d.ts.map +1 -1
  110. package/_types/core/Signature.d.ts +1 -1
  111. package/_types/core/Signature.d.ts.map +1 -1
  112. package/_types/core/Siwe.d.ts +4 -0
  113. package/_types/core/Siwe.d.ts.map +1 -1
  114. package/_types/core/TxEnvelopeEip1559.d.ts.map +1 -1
  115. package/_types/core/TxEnvelopeEip2930.d.ts.map +1 -1
  116. package/_types/core/TxEnvelopeEip7702.d.ts +1 -1
  117. package/_types/core/TxEnvelopeEip7702.d.ts.map +1 -1
  118. package/_types/core/TxEnvelopeLegacy.d.ts.map +1 -1
  119. package/_types/core/TypedData.d.ts +3 -1
  120. package/_types/core/TypedData.d.ts.map +1 -1
  121. package/_types/core/Value.d.ts.map +1 -1
  122. package/_types/core/internal/abiParameters.d.ts +1 -1
  123. package/_types/core/internal/abiParameters.d.ts.map +1 -1
  124. package/_types/core/internal/cursor.d.ts +13 -0
  125. package/_types/core/internal/cursor.d.ts.map +1 -1
  126. package/_types/erc7821/Execute.d.ts +46 -1
  127. package/_types/erc7821/Execute.d.ts.map +1 -1
  128. package/_types/index.d.ts +1 -1
  129. package/_types/tempo/KeyAuthorization.d.ts +9 -3
  130. package/_types/tempo/KeyAuthorization.d.ts.map +1 -1
  131. package/_types/tempo/SignatureEnvelope.d.ts +1 -1
  132. package/_types/tempo/SignatureEnvelope.d.ts.map +1 -1
  133. package/_types/tempo/TxEnvelopeTempo.d.ts +30 -1
  134. package/_types/tempo/TxEnvelopeTempo.d.ts.map +1 -1
  135. package/_types/version.d.ts +1 -1
  136. package/_types/webauthn/Registration.d.ts +2 -0
  137. package/_types/webauthn/Registration.d.ts.map +1 -1
  138. package/core/AbiError.ts +81 -7
  139. package/core/AbiEvent.ts +50 -11
  140. package/core/AbiFunction.ts +76 -4
  141. package/core/Address.ts +18 -1
  142. package/core/Authorization.ts +47 -4
  143. package/core/Keystore.ts +40 -3
  144. package/core/Secp256k1.ts +5 -1
  145. package/core/Signature.ts +7 -2
  146. package/core/Siwe.ts +29 -3
  147. package/core/TxEnvelopeEip1559.ts +4 -1
  148. package/core/TxEnvelopeEip2930.ts +4 -1
  149. package/core/TxEnvelopeEip7702.ts +9 -2
  150. package/core/TxEnvelopeLegacy.ts +56 -10
  151. package/core/TypedData.ts +10 -9
  152. package/core/Value.ts +14 -3
  153. package/core/internal/abiParameters.ts +8 -2
  154. package/core/internal/cursor.ts +36 -0
  155. package/erc4337/UserOperation.ts +1 -1
  156. package/erc7821/Execute.ts +84 -3
  157. package/index.ts +1 -1
  158. package/package.json +1 -1
  159. package/tempo/KeyAuthorization.test.ts +91 -0
  160. package/tempo/KeyAuthorization.ts +32 -3
  161. package/tempo/SignatureEnvelope.test.ts +211 -27
  162. package/tempo/SignatureEnvelope.ts +55 -11
  163. package/tempo/TxEnvelopeTempo.test.ts +310 -0
  164. package/tempo/TxEnvelopeTempo.ts +64 -1
  165. package/version.ts +1 -1
  166. package/webauthn/Registration.ts +4 -6
@@ -65,7 +65,10 @@ export type Type = typeof type
65
65
  export function assert(envelope: PartialBy<TxEnvelopeLegacy, 'type'>) {
66
66
  const { chainId, gasPrice, to } = envelope
67
67
  if (to) Address.assert(to, { strict: false })
68
- if (typeof chainId !== 'undefined' && chainId <= 0)
68
+ if (
69
+ typeof chainId !== 'undefined' &&
70
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
71
+ )
69
72
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
70
73
  if (gasPrice && BigInt(gasPrice) > 2n ** 256n - 1n)
71
74
  throw new TransactionEnvelope.GasPriceTooHighError({ gasPrice })
@@ -106,7 +109,12 @@ export function deserialize(serialized: Hex.Hex): Compute<TxEnvelopeLegacy> {
106
109
  const [nonce, gasPrice, gas, to, value, data, chainIdOrV_, r, s] =
107
110
  tuple as readonly Hex.Hex[]
108
111
 
109
- if (!(tuple.length === 6 || tuple.length === 9))
112
+ if (
113
+ !Array.isArray(tuple) ||
114
+ !(tuple.length === 6 || tuple.length === 9) ||
115
+ // Every field is a byte string, never a nested list.
116
+ tuple.some((item) => typeof item !== 'string')
117
+ )
110
118
  throw new TransactionEnvelope.InvalidSerializedError({
111
119
  attributes: {
112
120
  nonce,
@@ -136,21 +144,44 @@ export function deserialize(serialized: Hex.Hex): Compute<TxEnvelopeLegacy> {
136
144
  if (Hex.validate(nonce))
137
145
  transaction.nonce = nonce === '0x' ? 0n : BigInt(nonce)
138
146
  if (Hex.validate(value) && value !== '0x') transaction.value = BigInt(value)
147
+ // `gasPrice`, `r` and `s` are bounded by byte length, so that an oversized
148
+ // value is rejected before it is converted.
149
+ if (Hex.size(gasPrice as Hex.Hex) > 32)
150
+ throw new TransactionEnvelope.GasPriceTooHighError()
139
151
  if (Hex.validate(gasPrice) && gasPrice !== '0x')
140
152
  transaction.gasPrice = BigInt(gasPrice)
141
153
 
142
- if (tuple.length === 6) return transaction
154
+ if (tuple.length === 6) {
155
+ assert(transaction)
156
+ return transaction
157
+ }
143
158
 
144
- const chainIdOrV =
145
- Hex.validate(chainIdOrV_) && chainIdOrV_ !== '0x'
146
- ? Number(chainIdOrV_ as Hex.Hex)
147
- : 0
159
+ // `chainId` and `yParity` are derived from `v` as a number, so `v` must be a
160
+ // safe integer (which fits in 7 bytes).
161
+ const chainIdOrV = (() => {
162
+ if (Hex.size(chainIdOrV_ as Hex.Hex) > 7) return Number.NaN
163
+ if (Hex.validate(chainIdOrV_) && chainIdOrV_ !== '0x')
164
+ return Number(chainIdOrV_ as Hex.Hex)
165
+ return 0
166
+ })()
167
+ if (!Number.isSafeInteger(chainIdOrV))
168
+ throw new TransactionEnvelope.InvalidSerializedError({
169
+ attributes: {},
170
+ serialized,
171
+ type,
172
+ })
148
173
 
149
174
  if (s === '0x' && r === '0x') {
150
175
  if (chainIdOrV > 0) transaction.chainId = Number(chainIdOrV)
176
+ assert(transaction)
151
177
  return transaction
152
178
  }
153
179
 
180
+ if (Hex.size(r as Hex.Hex) > 32)
181
+ throw new Signature.InvalidRError({ value: r })
182
+ if (Hex.size(s as Hex.Hex) > 32)
183
+ throw new Signature.InvalidSError({ value: s })
184
+
154
185
  const v = chainIdOrV
155
186
  const chainId: number | undefined = Math.floor((v - 35) / 2)
156
187
  if (chainId > 0) transaction.chainId = chainId
@@ -380,11 +411,18 @@ export function hash<presign extends boolean = false>(
380
411
  options: hash.Options<presign> = {},
381
412
  ): hash.ReturnType {
382
413
  const { presign } = options
414
+ const { chainId, v } = envelope
383
415
  return Hash.keccak256(
384
416
  serialize({
385
417
  ...envelope,
386
418
  ...(presign
387
419
  ? {
420
+ // An EIP-155 `v` carries the chain ID when `chainId` is absent.
421
+ chainId:
422
+ chainId ??
423
+ (typeof v === 'number' && v >= 37
424
+ ? Math.floor((v - 35) / 2)
425
+ : undefined),
388
426
  r: undefined,
389
427
  s: undefined,
390
428
  yParity: undefined,
@@ -495,6 +533,17 @@ export function serialize(
495
533
 
496
534
  if (signature) {
497
535
  const v = (() => {
536
+ // EIP-155 (explicit chainId)
537
+ if (chainId > 0) {
538
+ if (signature.v >= 35) {
539
+ // `v` must encode the same chain as `chainId`.
540
+ if (Math.floor((signature.v - 35) / 2) !== chainId)
541
+ throw new TransactionEnvelope.InvalidChainIdError({ chainId })
542
+ return signature.v
543
+ }
544
+ return chainId * 2 + 35 + Signature.vToYParity(signature.v)
545
+ }
546
+
498
547
  // EIP-155 (inferred chainId)
499
548
  if (signature.v >= 35) {
500
549
  const inferredChainId = Math.floor((signature.v - 35) / 2)
@@ -502,9 +551,6 @@ export function serialize(
502
551
  return 27 + (signature.v === 35 ? 0 : 1)
503
552
  }
504
553
 
505
- // EIP-155 (explicit chainId)
506
- if (chainId > 0) return chainId * 2 + 35 + signature.v - 27
507
-
508
554
  // Pre-EIP-155 (no chainId)
509
555
  const v = 27 + (signature.v === 27 ? 0 : 1)
510
556
  if (signature.v !== v)
package/core/TypedData.ts CHANGED
@@ -146,6 +146,8 @@ export function assert<
146
146
  expectedSize: Number.parseInt(size, 10),
147
147
  givenSize: Hex.size(value as Hex.Hex),
148
148
  })
149
+ if (size && (value as Hex.Hex).length % 2 !== 0)
150
+ throw new Hex.InvalidLengthError(value as Hex.Hex)
149
151
  }
150
152
 
151
153
  if (Object.hasOwn(types, type))
@@ -184,6 +186,7 @@ export declare namespace assert {
184
186
  | InvalidPrimaryTypeError
185
187
  | InvalidStructTypeError
186
188
  | InvalidTypeError
189
+ | Hex.InvalidLengthError
187
190
  | Hex.fromNumber.ErrorType
188
191
  | Hex.size.ErrorType
189
192
  | Errors.GlobalErrorType
@@ -372,6 +375,8 @@ export declare namespace encodeType {
372
375
  /**
373
376
  * Gets [EIP-712 Typed Data](https://eips.ethereum.org/EIPS/eip-712) schema for EIP-721 domain.
374
377
  *
378
+ * A field is part of the schema when it is present on the domain (not `undefined` or `null`).
379
+ *
375
380
  * @example
376
381
  * ```ts twoslash
377
382
  * import { TypedData } from 'ox'
@@ -397,18 +402,14 @@ export function extractEip712DomainTypes(
397
402
  domain: Domain | undefined,
398
403
  ): Parameter[] {
399
404
  return [
400
- typeof domain?.name === 'string' && { name: 'name', type: 'string' },
401
- typeof domain?.version === 'string' && { name: 'version', type: 'string' },
402
- (typeof domain?.chainId === 'number' ||
403
- typeof domain?.chainId === 'bigint') && {
404
- name: 'chainId',
405
- type: 'uint256',
406
- },
407
- domain?.verifyingContract && {
405
+ domain?.name != null && { name: 'name', type: 'string' },
406
+ domain?.version != null && { name: 'version', type: 'string' },
407
+ domain?.chainId != null && { name: 'chainId', type: 'uint256' },
408
+ domain?.verifyingContract != null && {
408
409
  name: 'verifyingContract',
409
410
  type: 'address',
410
411
  },
411
- domain?.salt && { name: 'salt', type: 'bytes32' },
412
+ domain?.salt != null && { name: 'salt', type: 'bytes32' },
412
413
  ].filter(Boolean) as Parameter[]
413
414
  }
414
415
 
package/core/Value.ts CHANGED
@@ -10,7 +10,6 @@ export const exponents = {
10
10
  } as const
11
11
 
12
12
  const decimalNumberRegex = /^(-?)([0-9]*)\.?([0-9]*)$/
13
- const trailingZerosRegex = /(0+)$/
14
13
 
15
14
  /**
16
15
  * Formats a `bigint` Value to its string representation (divided by the given exponent).
@@ -39,7 +38,7 @@ export function format(value: bigint, decimals = 0) {
39
38
  display.slice(0, display.length - decimals),
40
39
  display.slice(display.length - decimals),
41
40
  ]
42
- fraction = fraction.replace(trailingZerosRegex, '')
41
+ fraction = trimTrailingZeros(fraction)
43
42
  return `${negative ? '-' : ''}${integer || '0'}${
44
43
  fraction ? `.${fraction}` : ''
45
44
  }`
@@ -123,7 +122,7 @@ export function from(value: string, decimals = 0) {
123
122
  if (negative) integer = integer.slice(1)
124
123
 
125
124
  // trim trailing zeros.
126
- fraction = fraction.replace(trailingZerosRegex, '')
125
+ fraction = trimTrailingZeros(fraction)
127
126
 
128
127
  // round off if the fraction is larger than the number of decimals.
129
128
  if (decimals === 0) {
@@ -159,6 +158,18 @@ export declare namespace from {
159
158
  type ErrorType = Errors.GlobalErrorType
160
159
  }
161
160
 
161
+ /**
162
+ * Removes trailing zeros with a backward scan, which stays linear in the
163
+ * length of the value.
164
+ *
165
+ * @internal
166
+ */
167
+ function trimTrailingZeros(value: string): string {
168
+ let end = value.length
169
+ while (end > 0 && value.charCodeAt(end - 1) === 48) end--
170
+ return value.slice(0, end)
171
+ }
172
+
162
173
  /**
163
174
  * Parses a string representation of Ether to a `bigint` Value (default: wei).
164
175
  *
@@ -280,8 +280,9 @@ export function decodeBytes(
280
280
  return [Hex.fromBytes(data), 32]
281
281
  }
282
282
 
283
- const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size, 10), 32))
284
- return [value, 32]
283
+ // Read the whole slot so that a slot cut short of its padding is out of bounds.
284
+ const word = cursor.readBytes(32)
285
+ return [Hex.fromBytes(word.subarray(0, Number.parseInt(size, 10))), 32]
285
286
  }
286
287
 
287
288
  export declare namespace decodeBytes {
@@ -664,6 +665,9 @@ export function encodeBytes(
664
665
  const [, parametersize] = type.split('bytes')
665
666
  const bytesSize = Hex.size(value)
666
667
  if (!parametersize) {
668
+ // An unpaired nibble has no byte to belong to, so reject it instead of
669
+ // guessing which half of a byte it is.
670
+ if (value.length % 2 !== 0) throw new Hex.InvalidLengthError(value)
667
671
  let value_ = value
668
672
  // If the size is not divisible by 32 bytes, pad the end
669
673
  // with empty bytes to the ceiling 32 bytes.
@@ -682,12 +686,14 @@ export function encodeBytes(
682
686
  expectedSize: Number.parseInt(parametersize, 10),
683
687
  value,
684
688
  })
689
+ if (value.length % 2 !== 0) throw new Hex.InvalidLengthError(value)
685
690
  return { dynamic: false, encoded: Hex.padRight(value) }
686
691
  }
687
692
 
688
693
  /** @internal */
689
694
  export declare namespace encodeBytes {
690
695
  type ErrorType =
696
+ | Hex.InvalidLengthError
691
697
  | Hex.padLeft.ErrorType
692
698
  | Hex.padRight.ErrorType
693
699
  | Hex.fromNumber.ErrorType
@@ -7,10 +7,15 @@ export type Cursor = {
7
7
  dataView: DataView
8
8
  position: number
9
9
  positionReadCount: Map<number, number>
10
+ /** Total number of bytes read. */
11
+ readSize: number
12
+ /** Maximum total number of bytes that can be read. */
13
+ readSizeLimit: number
10
14
  recursiveReadCount: number
11
15
  recursiveReadLimit: number
12
16
  remaining: number
13
17
  assertReadLimit(position?: number): void
18
+ assertReadSize(length: number): void
14
19
  assertPosition(position: number): void
15
20
  decrementPosition(offset: number): void
16
21
  getReadCount(position?: number): number
@@ -42,6 +47,8 @@ const staticCursor: Cursor = {
42
47
  dataView: new DataView(new ArrayBuffer(0)),
43
48
  position: 0,
44
49
  positionReadCount: new Map(),
50
+ readSize: 0,
51
+ readSizeLimit: Number.POSITIVE_INFINITY,
45
52
  recursiveReadCount: 0,
46
53
  recursiveReadLimit: Number.POSITIVE_INFINITY,
47
54
  assertReadLimit() {
@@ -51,6 +58,14 @@ const staticCursor: Cursor = {
51
58
  limit: this.recursiveReadLimit,
52
59
  })
53
60
  },
61
+ assertReadSize(length) {
62
+ this.readSize += length
63
+ if (this.readSize > this.readSizeLimit)
64
+ throw new ReadSizeLimitExceededError({
65
+ limit: this.readSizeLimit,
66
+ size: this.readSize,
67
+ })
68
+ },
54
69
  assertPosition(position) {
55
70
  if (position < 0 || position > this.bytes.length - 1)
56
71
  throw new PositionOutOfBoundsError({
@@ -141,6 +156,7 @@ const staticCursor: Cursor = {
141
156
  this.assertReadLimit()
142
157
  this._touch()
143
158
  const value = this.inspectByte()
159
+ this.assertReadSize(1)
144
160
  this.position++
145
161
  return value
146
162
  },
@@ -148,6 +164,7 @@ const staticCursor: Cursor = {
148
164
  this.assertReadLimit()
149
165
  this._touch()
150
166
  const value = this.inspectBytes(length)
167
+ this.assertReadSize(length)
151
168
  this.position += size ?? length
152
169
  return value
153
170
  },
@@ -155,6 +172,7 @@ const staticCursor: Cursor = {
155
172
  this.assertReadLimit()
156
173
  this._touch()
157
174
  const value = this.inspectUint8()
175
+ this.assertReadSize(1)
158
176
  this.position += 1
159
177
  return value
160
178
  },
@@ -162,6 +180,7 @@ const staticCursor: Cursor = {
162
180
  this.assertReadLimit()
163
181
  this._touch()
164
182
  const value = this.inspectUint16()
183
+ this.assertReadSize(2)
165
184
  this.position += 2
166
185
  return value
167
186
  },
@@ -169,6 +188,7 @@ const staticCursor: Cursor = {
169
188
  this.assertReadLimit()
170
189
  this._touch()
171
190
  const value = this.inspectUint24()
191
+ this.assertReadSize(3)
172
192
  this.position += 3
173
193
  return value
174
194
  },
@@ -176,6 +196,7 @@ const staticCursor: Cursor = {
176
196
  this.assertReadLimit()
177
197
  this._touch()
178
198
  const value = this.inspectUint32()
199
+ this.assertReadSize(4)
179
200
  this.position += 4
180
201
  return value
181
202
  },
@@ -210,6 +231,10 @@ export function create(
210
231
  )
211
232
  cursor.positionReadCount = new Map()
212
233
  cursor.recursiveReadLimit = recursiveReadLimit
234
+ // `recursiveReadLimit` allows one read per position plus that many repeated
235
+ // reads. Allow as many bytes as that number of 32-byte reads, so that reads
236
+ // of any length are bounded by the size of the data as well.
237
+ cursor.readSizeLimit = 32 * (bytes.length + recursiveReadLimit)
213
238
  return cursor
214
239
  }
215
240
 
@@ -240,6 +265,17 @@ export class PositionOutOfBoundsError extends Errors.BaseError {
240
265
  }
241
266
  }
242
267
 
268
+ /** @internal */
269
+ export class ReadSizeLimitExceededError extends Errors.BaseError {
270
+ override readonly name = 'Cursor.ReadSizeLimitExceededError'
271
+
272
+ constructor({ limit, size }: { limit: number; size: number }) {
273
+ super(
274
+ `Read size limit of \`${limit}\` bytes exceeded (read size: \`${size}\` bytes).`,
275
+ )
276
+ }
277
+ }
278
+
243
279
  /** @internal */
244
280
  export class RecursiveReadLimitExceededError extends Errors.BaseError {
245
281
  override readonly name = 'Cursor.RecursiveReadLimitExceededError'
@@ -500,7 +500,7 @@ export function hash<
500
500
  Hex.padLeft(Hex.fromNumber(maxFeePerGas), 16),
501
501
  )
502
502
  const initCode_hashed = Hash.keccak256(
503
- factory && factoryData ? Hex.concat(factory, factoryData) : '0x',
503
+ toInitCode({ factory, factoryData }),
504
504
  )
505
505
  const paymasterAndData_hashed = Hash.keccak256(
506
506
  paymaster
@@ -1,5 +1,6 @@
1
1
  import * as AbiFunction from '../core/AbiFunction.js'
2
- import type * as Hex from '../core/Hex.js'
2
+ import * as Errors from '../core/Errors.js'
3
+ import * as Hex from '../core/Hex.js'
3
4
  import { AbiParameters } from '../index.js'
4
5
  import * as Calls from './Calls.js'
5
6
 
@@ -39,6 +40,10 @@ export const mode = {
39
40
  /**
40
41
  * Decodes calls from ERC-7821 `execute` function data.
41
42
  *
43
+ * Decodes the single batch modes only (`mode.default` and `mode.opData`). Throws
44
+ * `Execute.UnsupportedModeError` for the "batch of batches" mode (use
45
+ * `Execute.decodeBatchOfBatchesData` instead) and for unknown modes.
46
+ *
42
47
  * @example
43
48
  * ```ts twoslash
44
49
  * import { Execute } from 'ox/erc7821'
@@ -54,7 +59,13 @@ export function decodeData(data: Hex.Hex): decodeData.ReturnType {
54
59
  Hex.Hex,
55
60
  Hex.Hex,
56
61
  ]
57
- return Calls.decode(executionData, { opData: m !== mode.default })
62
+ const name = getModeName(m)
63
+ if (name !== 'default' && name !== 'opData')
64
+ throw new UnsupportedModeError({
65
+ mode: m,
66
+ supported: ['default', 'opData'],
67
+ })
68
+ return Calls.decode(executionData, { opData: name === 'opData' })
58
69
  }
59
70
 
60
71
  export declare namespace decodeData {
@@ -62,11 +73,15 @@ export declare namespace decodeData {
62
73
  calls: Call[]
63
74
  opData?: Hex.Hex | undefined
64
75
  }
76
+
77
+ type ErrorType = UnsupportedModeError | Errors.GlobalErrorType
65
78
  }
66
79
 
67
80
  /**
68
81
  * Decodes batches from ERC-7821 `execute` function data in "batch of batches" mode.
69
82
  *
83
+ * Throws `Execute.UnsupportedModeError` for any other mode.
84
+ *
70
85
  * @example
71
86
  * ```ts twoslash
72
87
  * import { Execute } from 'ox/erc7821'
@@ -80,10 +95,12 @@ export declare namespace decodeData {
80
95
  export function decodeBatchOfBatchesData(
81
96
  data: Hex.Hex,
82
97
  ): decodeBatchOfBatchesData.ReturnType {
83
- const [, executionData] = AbiFunction.decodeData(abiFunction, data) as [
98
+ const [m, executionData] = AbiFunction.decodeData(abiFunction, data) as [
84
99
  Hex.Hex,
85
100
  Hex.Hex,
86
101
  ]
102
+ if (getModeName(m) !== 'batchOfBatches')
103
+ throw new UnsupportedModeError({ mode: m, supported: ['batchOfBatches'] })
87
104
 
88
105
  const [encodedBatches] = AbiParameters.decode(
89
106
  AbiParameters.from('bytes[]'),
@@ -112,6 +129,8 @@ export function decodeBatchOfBatchesData(
112
129
 
113
130
  export declare namespace decodeBatchOfBatchesData {
114
131
  type ReturnType = Batch[]
132
+
133
+ type ErrorType = UnsupportedModeError | Errors.GlobalErrorType
115
134
  }
116
135
 
117
136
  /**
@@ -195,3 +214,65 @@ export declare namespace encodeData {
195
214
  opData?: Hex.Hex | undefined
196
215
  }
197
216
  }
217
+
218
+ /**
219
+ * Thrown when the mode of ERC-7821 `execute` function data is not supported by the decoder.
220
+ *
221
+ * @example
222
+ * ```ts twoslash
223
+ * import { Execute } from 'ox/erc7821'
224
+ *
225
+ * const data = Execute.encodeBatchOfBatchesData([
226
+ * {
227
+ * calls: [
228
+ * {
229
+ * data: '0xcafebabe',
230
+ * to: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',
231
+ * value: 1n
232
+ * }
233
+ * ]
234
+ * }
235
+ * ])
236
+ *
237
+ * Execute.decodeData(data)
238
+ * // @error: Execute.UnsupportedModeError: Execution mode `0x0100000000007821000200000000000000000000000000000000000000000000` is not supported.
239
+ * ```
240
+ */
241
+ export class UnsupportedModeError extends Errors.BaseError {
242
+ override readonly name = 'Execute.UnsupportedModeError'
243
+
244
+ constructor({ mode, supported }: UnsupportedModeError.Options) {
245
+ super(`Execution mode \`${mode}\` is not supported.`, {
246
+ metaMessages: [
247
+ `Supported modes: ${supported.map((name) => `\`${name}\``).join(', ')}.`,
248
+ ],
249
+ })
250
+ }
251
+ }
252
+
253
+ export declare namespace UnsupportedModeError {
254
+ /** Options for `Execute.UnsupportedModeError`. */
255
+ type Options = {
256
+ /** Mode of the `execute` function data. */
257
+ mode: Hex.Hex
258
+ /** Names of the modes (keys of `Execute.mode`) the decoder supports. */
259
+ supported: readonly (keyof typeof mode)[]
260
+ }
261
+ }
262
+
263
+ /**
264
+ * Identifies an ERC-7821 execution mode the way the reference implementation
265
+ * (`_executionModeId`) does. Bytes `[0..1]` (call type and execution type) and
266
+ * bytes `[6..9]` (mode selector) identify the mode. Bytes `[2..5]` (reserved by
267
+ * ERC-7579) and bytes `[10..31]` (unused) are ignored.
268
+ *
269
+ * @internal
270
+ */
271
+ function getModeName(m: Hex.Hex): keyof typeof mode | undefined {
272
+ if (Hex.slice(m, 0, 2) !== '0x0100') return undefined
273
+ const selector = Hex.slice(m, 6, 10)
274
+ if (selector === '0x00000000') return 'default'
275
+ if (selector === '0x78210001') return 'opData'
276
+ if (selector === '0x78210002') return 'batchOfBatches'
277
+ return undefined
278
+ }
package/index.ts CHANGED
@@ -259,7 +259,7 @@ export * as AbiConstructor from './core/AbiConstructor.js'
259
259
  * const abi = Abi.from([...])
260
260
  * const error = AbiError.fromAbi(abi, 'InvalidSignature')
261
261
  *
262
- * const value = AbiError.decode(error, '0xecde634900000000000000000000000000000000000000000000000000000000000001a400000000000000000000000000000000000000000000000000000000000000450000000000000000000000000000000000000000000000000000000000000001') // [!code focus]
262
+ * const value = AbiError.decode(error, '0xe466f0a500000000000000000000000000000000000000000000000000000000000001a400000000000000000000000000000000000000000000000000000000000000450000000000000000000000000000000000000000000000000000000000000001') // [!code focus]
263
263
  * // @log: [420n, 69n, 1]
264
264
  * ```
265
265
  *
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ox",
3
3
  "description": "Ethereum Standard Library",
4
- "version": "0.14.65",
4
+ "version": "0.14.66",
5
5
  "main": "./_cjs/index.js",
6
6
  "module": "./_esm/index.js",
7
7
  "types": "./_types/index.d.ts",
@@ -223,6 +223,44 @@ describe('from', () => {
223
223
  }).toEqual(limitsVectors)
224
224
  })
225
225
 
226
+ test('error: rejects recipients without a selector', () => {
227
+ const base = { address, chainId: 4217n, type: 'secp256k1' } as const
228
+ const recipients = ['0x1111111111111111111111111111111111111111'] as const
229
+ expect(() =>
230
+ KeyAuthorization.from({
231
+ ...base,
232
+ scopes: [{ address: token, recipients }],
233
+ }),
234
+ ).toThrowErrorMatchingInlineSnapshot(
235
+ `[KeyAuthorization.InvalidScopeError: Scope for \`0x20c0000000000000000000000000000000000001\` has \`recipients\` but no \`selector\`; a recipient allowlist requires a selector.]`,
236
+ )
237
+ expect(() =>
238
+ KeyAuthorization.from({
239
+ ...base,
240
+ scopes: [
241
+ { address: token, selector: 'transfer(address,uint256)' },
242
+ { address: token, recipients },
243
+ ],
244
+ }),
245
+ ).toThrowErrorMatchingInlineSnapshot(
246
+ `[KeyAuthorization.InvalidScopeError: Scope for \`0x20c0000000000000000000000000000000000001\` has \`recipients\` but no \`selector\`; a recipient allowlist requires a selector.]`,
247
+ )
248
+ expect(
249
+ KeyAuthorization.from({
250
+ ...base,
251
+ scopes: [{ address: token, recipients: [] }],
252
+ }).scopes,
253
+ ).toMatchInlineSnapshot(`
254
+ [
255
+ {
256
+ "address": "0x20c0000000000000000000000000000000000001",
257
+ "recipients": [],
258
+ "selector": undefined,
259
+ },
260
+ ]
261
+ `)
262
+ })
263
+
226
264
  test('accepts configurable grants and delegates', () => {
227
265
  const signed = KeyAuthorization.from(
228
266
  {
@@ -1547,6 +1585,25 @@ describe('serialize', () => {
1547
1585
  })
1548
1586
 
1549
1587
  describe('toRpc', () => {
1588
+ test('error: rejects recipients without a selector', () => {
1589
+ expect(() =>
1590
+ KeyAuthorization.toRpc({
1591
+ address,
1592
+ chainId: 4217n,
1593
+ scopes: [
1594
+ {
1595
+ address: token,
1596
+ recipients: ['0x1111111111111111111111111111111111111111'],
1597
+ },
1598
+ ],
1599
+ signature: SignatureEnvelope.from(signature_secp256k1),
1600
+ type: 'secp256k1',
1601
+ }),
1602
+ ).toThrowErrorMatchingInlineSnapshot(
1603
+ `[KeyAuthorization.InvalidScopeError: Scope for \`0x20c0000000000000000000000000000000000001\` has \`recipients\` but no \`selector\`; a recipient allowlist requires a selector.]`,
1604
+ )
1605
+ })
1606
+
1550
1607
  test('behavior: configurable key type uses the RPC configurableAccount key type', () => {
1551
1608
  const authorization = KeyAuthorization.from(
1552
1609
  { account: address, address, chainId: 1n, type: 'configurable' },
@@ -1829,6 +1886,40 @@ describe('toRpc', () => {
1829
1886
  })
1830
1887
 
1831
1888
  describe('toTuple', () => {
1889
+ test('error: rejects recipients without a selector', () => {
1890
+ const authorization = {
1891
+ address,
1892
+ chainId: 4217n,
1893
+ scopes: [
1894
+ {
1895
+ address: token,
1896
+ recipients: ['0x1111111111111111111111111111111111111111'],
1897
+ },
1898
+ ],
1899
+ type: 'secp256k1',
1900
+ } as const
1901
+ expect(() =>
1902
+ KeyAuthorization.toTuple(authorization),
1903
+ ).toThrowErrorMatchingInlineSnapshot(
1904
+ `[KeyAuthorization.InvalidScopeError: Scope for \`0x20c0000000000000000000000000000000000001\` has \`recipients\` but no \`selector\`; a recipient allowlist requires a selector.]`,
1905
+ )
1906
+ expect(() =>
1907
+ KeyAuthorization.getSignPayload(authorization),
1908
+ ).toThrowErrorMatchingInlineSnapshot(
1909
+ `[KeyAuthorization.InvalidScopeError: Scope for \`0x20c0000000000000000000000000000000000001\` has \`recipients\` but no \`selector\`; a recipient allowlist requires a selector.]`,
1910
+ )
1911
+ expect(() =>
1912
+ KeyAuthorization.hash(authorization),
1913
+ ).toThrowErrorMatchingInlineSnapshot(
1914
+ `[KeyAuthorization.InvalidScopeError: Scope for \`0x20c0000000000000000000000000000000000001\` has \`recipients\` but no \`selector\`; a recipient allowlist requires a selector.]`,
1915
+ )
1916
+ expect(() =>
1917
+ KeyAuthorization.serialize(authorization),
1918
+ ).toThrowErrorMatchingInlineSnapshot(
1919
+ `[KeyAuthorization.InvalidScopeError: Scope for \`0x20c0000000000000000000000000000000000001\` has \`recipients\` but no \`selector\`; a recipient allowlist requires a selector.]`,
1920
+ )
1921
+ })
1922
+
1832
1923
  test('behavior: round-trips Tempo node limits encoding', () => {
1833
1924
  for (const { hash, rlp } of Object.values(limitsVectors)) {
1834
1925
  const authorization = KeyAuthorization.fromTuple([