ox 0.14.63 → 0.14.64

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 (113) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/_cjs/core/AbiError.js +6 -2
  3. package/_cjs/core/AbiError.js.map +1 -1
  4. package/_cjs/core/AbiEvent.js +4 -0
  5. package/_cjs/core/AbiEvent.js.map +1 -1
  6. package/_cjs/core/AbiFunction.js +2 -2
  7. package/_cjs/core/AbiFunction.js.map +1 -1
  8. package/_cjs/core/AbiItem.js +6 -7
  9. package/_cjs/core/AbiItem.js.map +1 -1
  10. package/_cjs/core/Base32.js +15 -1
  11. package/_cjs/core/Base32.js.map +1 -1
  12. package/_cjs/core/Bytes.js +4 -5
  13. package/_cjs/core/Bytes.js.map +1 -1
  14. package/_cjs/core/Cbor.js +13 -2
  15. package/_cjs/core/Cbor.js.map +1 -1
  16. package/_cjs/core/Hex.js +2 -3
  17. package/_cjs/core/Hex.js.map +1 -1
  18. package/_cjs/core/Rlp.js +49 -8
  19. package/_cjs/core/Rlp.js.map +1 -1
  20. package/_cjs/core/RpcTransport.js +9 -4
  21. package/_cjs/core/RpcTransport.js.map +1 -1
  22. package/_cjs/core/Siwe.js +4 -0
  23. package/_cjs/core/Siwe.js.map +1 -1
  24. package/_cjs/core/TypedData.js +2 -2
  25. package/_cjs/core/TypedData.js.map +1 -1
  26. package/_cjs/core/internal/abiItem.js +1 -1
  27. package/_cjs/core/internal/abiItem.js.map +1 -1
  28. package/_cjs/erc4337/UserOperation.js +7 -4
  29. package/_cjs/erc4337/UserOperation.js.map +1 -1
  30. package/_cjs/erc8021/Attribution.js +13 -3
  31. package/_cjs/erc8021/Attribution.js.map +1 -1
  32. package/_cjs/tempo/Tick.js +3 -2
  33. package/_cjs/tempo/Tick.js.map +1 -1
  34. package/_cjs/version.js +1 -1
  35. package/_esm/core/AbiError.js +6 -2
  36. package/_esm/core/AbiError.js.map +1 -1
  37. package/_esm/core/AbiEvent.js +5 -0
  38. package/_esm/core/AbiEvent.js.map +1 -1
  39. package/_esm/core/AbiFunction.js +2 -2
  40. package/_esm/core/AbiFunction.js.map +1 -1
  41. package/_esm/core/AbiItem.js +8 -7
  42. package/_esm/core/AbiItem.js.map +1 -1
  43. package/_esm/core/Base32.js +17 -2
  44. package/_esm/core/Base32.js.map +1 -1
  45. package/_esm/core/Bytes.js +4 -5
  46. package/_esm/core/Bytes.js.map +1 -1
  47. package/_esm/core/Cbor.js +16 -2
  48. package/_esm/core/Cbor.js.map +1 -1
  49. package/_esm/core/Hex.js +3 -3
  50. package/_esm/core/Hex.js.map +1 -1
  51. package/_esm/core/Rlp.js +56 -8
  52. package/_esm/core/Rlp.js.map +1 -1
  53. package/_esm/core/RpcTransport.js +12 -4
  54. package/_esm/core/RpcTransport.js.map +1 -1
  55. package/_esm/core/Siwe.js +5 -0
  56. package/_esm/core/Siwe.js.map +1 -1
  57. package/_esm/core/TypedData.js +7 -6
  58. package/_esm/core/TypedData.js.map +1 -1
  59. package/_esm/core/internal/abiItem.js +2 -1
  60. package/_esm/core/internal/abiItem.js.map +1 -1
  61. package/_esm/erc4337/UserOperation.js +10 -4
  62. package/_esm/erc4337/UserOperation.js.map +1 -1
  63. package/_esm/erc8021/Attribution.js +15 -3
  64. package/_esm/erc8021/Attribution.js.map +1 -1
  65. package/_esm/tempo/Tick.js +4 -3
  66. package/_esm/tempo/Tick.js.map +1 -1
  67. package/_esm/version.js +1 -1
  68. package/_types/core/AbiError.d.ts +2 -2
  69. package/_types/core/AbiError.d.ts.map +1 -1
  70. package/_types/core/AbiEvent.d.ts.map +1 -1
  71. package/_types/core/AbiFunction.d.ts +1 -1
  72. package/_types/core/AbiFunction.d.ts.map +1 -1
  73. package/_types/core/AbiItem.d.ts.map +1 -1
  74. package/_types/core/Base32.d.ts +8 -3
  75. package/_types/core/Base32.d.ts.map +1 -1
  76. package/_types/core/Bytes.d.ts.map +1 -1
  77. package/_types/core/Cbor.d.ts.map +1 -1
  78. package/_types/core/Hex.d.ts.map +1 -1
  79. package/_types/core/Rlp.d.ts +9 -2
  80. package/_types/core/Rlp.d.ts.map +1 -1
  81. package/_types/core/RpcTransport.d.ts.map +1 -1
  82. package/_types/core/Siwe.d.ts.map +1 -1
  83. package/_types/core/internal/abiItem.d.ts +3 -1
  84. package/_types/core/internal/abiItem.d.ts.map +1 -1
  85. package/_types/erc4337/UserOperation.d.ts +20 -2
  86. package/_types/erc4337/UserOperation.d.ts.map +1 -1
  87. package/_types/erc8021/Attribution.d.ts.map +1 -1
  88. package/_types/package.json +1 -0
  89. package/_types/tempo/SignatureEnvelope.d.ts +4 -4
  90. package/_types/tempo/Tick.d.ts.map +1 -1
  91. package/_types/version.d.ts +1 -1
  92. package/core/AbiError.ts +33 -22
  93. package/core/AbiEvent.ts +7 -0
  94. package/core/AbiFunction.ts +7 -5
  95. package/core/AbiItem.ts +8 -7
  96. package/core/Base32.ts +17 -3
  97. package/core/Bytes.ts +3 -5
  98. package/core/Cbor.ts +20 -2
  99. package/core/Hex.ts +4 -4
  100. package/core/Rlp.ts +55 -5
  101. package/core/RpcTransport.ts +12 -4
  102. package/core/Siwe.ts +5 -0
  103. package/core/TypedData.ts +7 -6
  104. package/core/internal/abiItem.ts +13 -2
  105. package/erc4337/UserOperation.ts +37 -3
  106. package/erc8021/Attribution.ts +11 -7
  107. package/package.json +1 -1
  108. package/tempo/AccountSimulation.test.ts +1 -1
  109. package/tempo/SignatureEnvelope.test.ts +12 -0
  110. package/tempo/SignatureEnvelope.ts +4 -4
  111. package/tempo/Tick.test.ts +10 -0
  112. package/tempo/Tick.ts +5 -3
  113. package/version.ts +1 -1
package/core/AbiEvent.ts CHANGED
@@ -160,6 +160,13 @@ export function assertArgs<const abiEvent extends AbiEvent>(
160
160
  Solidity.bytesRegex.test(input.type)
161
161
  )
162
162
  return value.toLowerCase() === arg.toLowerCase()
163
+ // Small integers decode as numbers, so match a number or bigint either way.
164
+ if (
165
+ (typeof value === 'bigint' || Number.isInteger(value)) &&
166
+ (typeof arg === 'bigint' || Number.isInteger(arg)) &&
167
+ Solidity.integerRegex.test(input.type)
168
+ )
169
+ return BigInt(value as bigint | number) === BigInt(arg as bigint | number)
163
170
  return value === arg
164
171
  }
165
172
 
@@ -157,12 +157,12 @@ export function decodeData(
157
157
  const { overloads } = abiFunction
158
158
 
159
159
  if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data })
160
- if (abiFunction.inputs?.length === 0) return undefined
161
160
 
162
161
  const item = overloads
163
162
  ? fromAbi([abiFunction, ...overloads], data as never)
164
163
  : abiFunction
165
164
 
165
+ if (item.inputs.length === 0) return undefined
166
166
  if (Hex.size(data) <= 4) return undefined
167
167
  return AbiParameters.decode(item.inputs, Hex.slice(data, 4))
168
168
  }
@@ -172,15 +172,17 @@ export declare namespace decodeData {
172
172
  abiFunction,
173
173
  AbiFunction
174
174
  > extends true
175
- ? abiFunction['inputs'] extends readonly []
176
- ? undefined
177
- :
178
- | AbiParameters_internal.ToPrimitiveTypes<abiFunction['inputs']>
175
+ ? abiFunction extends AbiFunction
176
+ ?
177
+ | (abiFunction['inputs'] extends readonly []
178
+ ? undefined
179
+ : AbiParameters_internal.ToPrimitiveTypes<abiFunction['inputs']>)
179
180
  | (abiFunction['overloads'] extends readonly AbiFunction[]
180
181
  ? AbiParameters_internal.ToPrimitiveTypes<
181
182
  abiFunction['overloads'][number]['inputs']
182
183
  >
183
184
  : never)
185
+ : never
184
186
  : unknown
185
187
 
186
188
  type ErrorType =
package/core/AbiItem.ts CHANGED
@@ -359,14 +359,14 @@ export function fromAbi<
359
359
  } as never
360
360
 
361
361
  let matchedAbiItem: AbiItem | undefined
362
+ // Without `args`, a zero-input overload is the preferred pick, but the other
363
+ // overloads are still attached so callers can resolve by selector.
364
+ let zeroArgAbiItem: AbiItem | undefined
362
365
  for (const abiItem of abiItems) {
363
366
  if (!('inputs' in abiItem)) continue
364
367
  if (!args || args.length === 0) {
365
- if (!abiItem.inputs || abiItem.inputs.length === 0)
366
- return {
367
- ...abiItem,
368
- ...(prepare ? { hash: getSignatureHash(abiItem) } : {}),
369
- } as never
368
+ if (!zeroArgAbiItem && (!abiItem.inputs || abiItem.inputs.length === 0))
369
+ zeroArgAbiItem = abiItem
370
370
  continue
371
371
  }
372
372
  if (!abiItem.inputs) continue
@@ -408,8 +408,9 @@ export function fromAbi<
408
408
 
409
409
  const abiItem = (() => {
410
410
  if (matchedAbiItem) return matchedAbiItem
411
- const [abiItem, ...overloads] = abiItems
412
- return { ...abiItem!, overloads }
411
+ const chosen = zeroArgAbiItem ?? abiItems[0]
412
+ const overloads = abiItems.filter((item) => item !== chosen)
413
+ return { ...chosen!, overloads }
413
414
  })()
414
415
 
415
416
  if (!abiItem) throw new NotFoundError({ name: name as string })
package/core/Base32.ts CHANGED
@@ -71,7 +71,7 @@ export declare namespace fromHex {
71
71
  * ```ts twoslash
72
72
  * import { Base32 } from 'ox'
73
73
  *
74
- * const value = Base32.toBytes('qqsa0')
74
+ * const value = Base32.toBytes('qrlsq')
75
75
  * ```
76
76
  *
77
77
  * @param value - The Base32 encoded string.
@@ -96,11 +96,16 @@ export function toBytes(value: string): Bytes.Bytes {
96
96
  bytes.push((acc >>> bits) & 0xff)
97
97
  }
98
98
  }
99
+ // Reject leftover bits that do not fill a whole symbol, or that are non-zero.
100
+ if (bits >= 5 || acc & ((1 << bits) - 1)) throw new InvalidPaddingError()
99
101
  return new Uint8Array(bytes)
100
102
  }
101
103
 
102
104
  export declare namespace toBytes {
103
- type ErrorType = InvalidCharacterError | Errors.GlobalErrorType
105
+ type ErrorType =
106
+ | InvalidCharacterError
107
+ | InvalidPaddingError
108
+ | Errors.GlobalErrorType
104
109
  }
105
110
 
106
111
  /**
@@ -110,7 +115,7 @@ export declare namespace toBytes {
110
115
  * ```ts twoslash
111
116
  * import { Base32 } from 'ox'
112
117
  *
113
- * const value = Base32.toHex('qqsa0')
118
+ * const value = Base32.toHex('qrlsq')
114
119
  * ```
115
120
  *
116
121
  * @param value - The Base32 encoded string.
@@ -132,3 +137,12 @@ export class InvalidCharacterError extends Errors.BaseError {
132
137
  super(`Invalid bech32 base32 character: "${character}".`)
133
138
  }
134
139
  }
140
+
141
+ /** Thrown when a Base32 string contains non-canonical (non-zero) trailing bits. */
142
+ export class InvalidPaddingError extends Errors.BaseError {
143
+ override readonly name = 'Base32.InvalidPaddingError'
144
+
145
+ constructor() {
146
+ super('Non-canonical trailing bits in Base32 input.')
147
+ }
148
+ }
package/core/Bytes.ts CHANGED
@@ -212,15 +212,13 @@ export declare namespace fromBoolean {
212
212
  export function fromHex(value: Hex.Hex, options: fromHex.Options = {}): Bytes {
213
213
  const { size } = options
214
214
 
215
- let hex = value
215
+ let hexString = value.slice(2)
216
+ if (hexString.length % 2) hexString = `0${hexString}`
216
217
  if (size) {
217
218
  internal_hex.assertSize(value, size)
218
- hex = Hex.padRight(value, size)
219
+ hexString = hexString.padEnd(size * 2, '0')
219
220
  }
220
221
 
221
- let hexString = hex.slice(2) as string
222
- if (hexString.length % 2) hexString = `0${hexString}`
223
-
224
222
  const length = hexString.length / 2
225
223
  const bytes = new Uint8Array(length)
226
224
  for (let index = 0, j = 0; index < length; index++) {
package/core/Cbor.ts CHANGED
@@ -863,7 +863,7 @@ namespace decodeCursor {
863
863
  ? String(key)
864
864
  : String(key)
865
865
  const value = decodeCursor(cursor)
866
- result[keyStr] = value
866
+ setEntry(result, keyStr, value)
867
867
  }
868
868
 
869
869
  return result
@@ -882,7 +882,7 @@ namespace decodeCursor {
882
882
  ? String(key)
883
883
  : String(key)
884
884
  const value = decodeCursor(cursor)
885
- result[keyStr] = value
885
+ setEntry(result, keyStr, value)
886
886
  }
887
887
 
888
888
  return result
@@ -893,6 +893,24 @@ namespace decodeCursor {
893
893
  type ErrorType = readLength.ErrorType | Errors.GlobalErrorType
894
894
  }
895
895
 
896
+ /** @internal */
897
+ function setEntry(
898
+ result: Record<string, unknown>,
899
+ key: string,
900
+ value: unknown,
901
+ ) {
902
+ // Define `__proto__` as an own property instead of assigning it, which
903
+ // would replace the prototype of `result` and drop the entry.
904
+ if (key === '__proto__')
905
+ Object.defineProperty(result, key, {
906
+ configurable: true,
907
+ enumerable: true,
908
+ value,
909
+ writable: true,
910
+ })
911
+ else result[key] = value
912
+ }
913
+
896
914
  /** @internal */
897
915
  export function readSimpleOrFloat(
898
916
  cursor: Cursor.Cursor,
package/core/Hex.ts CHANGED
@@ -252,7 +252,9 @@ export function fromNumber(
252
252
  maxValue = BigInt(Number.MAX_SAFE_INTEGER)
253
253
  }
254
254
 
255
- const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0
255
+ // Negative values need a `size` to encode as two's complement.
256
+ const minValue =
257
+ size && typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0
256
258
 
257
259
  if ((maxValue && value_ > maxValue) || value_ < minValue) {
258
260
  const suffix = typeof value === 'bigint' ? 'n' : ''
@@ -568,9 +570,7 @@ export function toBigInt(hex: Hex, options: toBigInt.Options = {}): bigint {
568
570
  const value = BigInt(hex)
569
571
  if (!signed) return value
570
572
 
571
- const size = (hex.length - 2) / 2
572
-
573
- const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n
573
+ const max_unsigned = (1n << (BigInt(size(hex)) * 8n)) - 1n
574
574
  const max_signed = max_unsigned >> 1n
575
575
 
576
576
  if (value <= max_signed) return value
package/core/Rlp.ts CHANGED
@@ -109,6 +109,14 @@ export function decodeRlpCursor<to extends 'Hex' | 'Bytes' = 'Hex'>(
109
109
  if (prefix < 0xc0) {
110
110
  const length = readLength(cursor, prefix, 0x80)
111
111
  const bytes = cursor.readBytes(length)
112
+ // A single byte below `0x80` must be its own encoding (no length
113
+ // prefix); wrapping it in an explicit one-byte-length prefix is a
114
+ // non-canonical alternate encoding of the same value (Yellow Paper,
115
+ // Appendix B).
116
+ if (prefix >= 0x80 && length === 1 && bytes[0]! < 0x80)
117
+ throw new NonCanonicalError({
118
+ reason: `single byte \`0x${bytes[0]!.toString(16).padStart(2, '0')}\` is wrapped in an explicit length prefix instead of being encoded as itself`,
119
+ })
112
120
  return (
113
121
  to === 'Hex' ? Hex.fromBytes(bytes) : bytes
114
122
  ) as decodeRlpCursor.ReturnType<to>
@@ -126,6 +134,7 @@ export declare namespace decodeRlpCursor {
126
134
  | Hex.fromBytes.ErrorType
127
135
  | readLength.ErrorType
128
136
  | readList.ErrorType
137
+ | NonCanonicalError
129
138
  | Errors.GlobalErrorType
130
139
  }
131
140
 
@@ -137,16 +146,48 @@ export function readLength(
137
146
  ) {
138
147
  if (offset === 0x80 && prefix < 0x80) return 1
139
148
  if (prefix <= offset + 55) return prefix - offset
140
- if (prefix === offset + 55 + 1) return cursor.readUint8()
141
- if (prefix === offset + 55 + 2) return cursor.readUint16()
142
- if (prefix === offset + 55 + 3) return cursor.readUint24()
143
- if (prefix === offset + 55 + 4) return cursor.readUint32()
149
+ // Long-form lengths must use the minimal number of length-bytes: a value
150
+ // that fits in fewer bytes (or in the short form, i.e. <= 55) encoded via
151
+ // a longer form is a non-canonical alternate encoding of the same value
152
+ // (Yellow Paper, Appendix B).
153
+ if (prefix === offset + 55 + 1) {
154
+ const length = cursor.readUint8()
155
+ if (length <= 55)
156
+ throw new NonCanonicalError({
157
+ reason: `length \`${length}\` fits in the short form and must not use a one-byte length prefix`,
158
+ })
159
+ return length
160
+ }
161
+ if (prefix === offset + 55 + 2) {
162
+ const length = cursor.readUint16()
163
+ if (length <= 0xff)
164
+ throw new NonCanonicalError({
165
+ reason: `length \`${length}\` fits in fewer length-bytes and must not use a two-byte length prefix`,
166
+ })
167
+ return length
168
+ }
169
+ if (prefix === offset + 55 + 3) {
170
+ const length = cursor.readUint24()
171
+ if (length <= 0xffff)
172
+ throw new NonCanonicalError({
173
+ reason: `length \`${length}\` fits in fewer length-bytes and must not use a three-byte length prefix`,
174
+ })
175
+ return length
176
+ }
177
+ if (prefix === offset + 55 + 4) {
178
+ const length = cursor.readUint32()
179
+ if (length <= 0xffffff)
180
+ throw new NonCanonicalError({
181
+ reason: `length \`${length}\` fits in fewer length-bytes and must not use a four-byte length prefix`,
182
+ })
183
+ return length
184
+ }
144
185
  throw new Errors.BaseError('Invalid RLP prefix')
145
186
  }
146
187
 
147
188
  /** @internal */
148
189
  export declare namespace readLength {
149
- type ErrorType = Errors.BaseError | Errors.GlobalErrorType
190
+ type ErrorType = NonCanonicalError | Errors.BaseError | Errors.GlobalErrorType
150
191
  }
151
192
 
152
193
  /** @internal */
@@ -365,3 +406,12 @@ function getSizeOfLength(length: number) {
365
406
  if (length <= 0xff_ff_ff_ff) return 4
366
407
  throw new Errors.BaseError('Length is too large.')
367
408
  }
409
+
410
+ /** Thrown when an RLP payload uses a non-canonical alternate encoding of a value. */
411
+ export class NonCanonicalError extends Errors.BaseError {
412
+ override readonly name = 'Rlp.NonCanonicalError'
413
+
414
+ constructor({ reason }: { reason: string }) {
415
+ super(`RLP payload is not canonically encoded: ${reason}.`)
416
+ }
417
+ }
@@ -103,13 +103,21 @@ export function fromHttp<
103
103
  fetchOptions?.signal,
104
104
  timeout > 0 ? signal : null,
105
105
  ].filter((s): s is AbortSignal => Boolean(s))
106
+ // Merge through `Headers` so `Headers` instances and tuple arrays
107
+ // keep their entries, and a caller's header replaces the default
108
+ // whatever its casing.
109
+ const headers: Record<string, string> = {}
110
+ for (const source of [
111
+ { 'Content-Type': 'application/json' },
112
+ fetchOptions?.headers,
113
+ ])
114
+ new Headers(source).forEach((value, key) => {
115
+ headers[key] = value
116
+ })
106
117
  const init: RequestInit = {
107
118
  ...fetchOptions,
108
119
  body,
109
- headers: {
110
- 'Content-Type': 'application/json',
111
- ...fetchOptions?.headers,
112
- },
120
+ headers,
113
121
  method: fetchOptions?.method ?? 'POST',
114
122
  signal: (() => {
115
123
  if (signals.length < 2) return signals[0] ?? null
package/core/Siwe.ts CHANGED
@@ -445,6 +445,11 @@ export function validateMessage(value: validateMessage.Value): boolean {
445
445
  if (nonce && message.nonce !== nonce) return false
446
446
  if (scheme && message.scheme !== scheme) return false
447
447
 
448
+ // EIP-4361 requires `nonce = 8*( ALPHA / DIGIT )` and `version = "1"`.
449
+ if (message.nonce !== undefined && !nonceRegex.test(message.nonce))
450
+ return false
451
+ if (message.version !== undefined && message.version !== '1') return false
452
+
448
453
  if (message.expirationTime && time >= message.expirationTime) return false
449
454
  if (message.notBefore && time < message.notBefore) return false
450
455
 
package/core/TypedData.ts CHANGED
@@ -758,7 +758,7 @@ export class InvalidStructTypeError extends Errors.BaseError {
758
758
  constructor({ type }: { type: string }) {
759
759
  super(`Struct type "${type}" is invalid.`, {
760
760
  metaMessages: [
761
- 'Struct type must contain only letters, digits, "_" and "$", and must not be a Solidity type.',
761
+ 'Struct type must contain only letters, digits, "_", "$" and ":", and must not be a Solidity type.',
762
762
  ],
763
763
  })
764
764
  }
@@ -893,7 +893,7 @@ export declare namespace encodeField {
893
893
  }
894
894
 
895
895
  const arraySuffixRegex = /(\[[0-9]*\])+$/
896
- const structNameRegex = /^[A-Za-z0-9_$]+$/
896
+ const structNameRegex = /^[A-Za-z0-9_$:]+$/
897
897
  const solidityTypeNameRegex = /^(u?int|bytes)[0-9]*$/
898
898
 
899
899
  /** @internal */
@@ -945,10 +945,11 @@ function isSolidityType(type: string) {
945
945
 
946
946
  /** @internal */
947
947
  function validateReference(type: string) {
948
- // Struct type must contain only letters, digits, `_` and `$`, and must not be
949
- // a Solidity type, so it cannot shadow a Solidity type or an array of one. A
950
- // struct such as `intent` or `bytesInfo` is valid, while `uint7` or `bytes33`
951
- // is rejected, since other implementations parse it as a Solidity type.
948
+ // Struct type must contain only letters, digits, `_`, `$` and `:`, and must
949
+ // not be a Solidity type, so it cannot shadow a Solidity type or an array of
950
+ // one. A struct such as `intent` or `bytesInfo` is valid, while `uint7` or
951
+ // `bytes33` is rejected, since other implementations parse it as a Solidity
952
+ // type.
952
953
  if (
953
954
  !structNameRegex.test(type) ||
954
955
  type === 'address' ||
@@ -52,7 +52,17 @@ export type ExtractForArgs<
52
52
  >
53
53
  }
54
54
  >
55
- : TupleToUnion<abiItems, abi, name, args> // convert back to union (removes `never` tuple entries: `['foo', never, 'bar'][number]` => `'foo' | 'bar'`)
55
+ : readonly [] extends args
56
+ ? TupleToUnion<abiItems, abi, name, args> extends infer zero
57
+ ? Compute<
58
+ zero & {
59
+ readonly overloads: UnionToTuple<
60
+ Exclude<abiItems[number], zero>
61
+ >
62
+ }
63
+ >
64
+ : never
65
+ : TupleToUnion<abiItems, abi, name, args> // convert back to union (removes `never` tuple entries: `['foo', never, 'bar'][number]` => `'foo' | 'bar'`)
56
66
  : never
57
67
  : abiItem
58
68
  : never
@@ -556,7 +566,8 @@ export function isArgOfType(
556
566
  return false
557
567
  // An overload whose fixed size differs from the value does not match.
558
568
  const bytes = abiParameterType.slice(5)
559
- if (!bytes) return true
569
+ // Dynamic `bytes` is hex or raw bytes. A plain string is only `string`.
570
+ if (!bytes) return arg instanceof Uint8Array || Hex.validate(arg)
560
571
  if (arg instanceof Uint8Array)
561
572
  return arg.length === Number.parseInt(bytes, 10)
562
573
  if (!Hex.validate(arg)) return false
@@ -601,12 +601,24 @@ export declare namespace hash {
601
601
  * @param userOperation - The user operation to convert.
602
602
  * @returns The init code.
603
603
  */
604
- export function toInitCode(userOperation: Partial<UserOperation>): Hex.Hex {
604
+ export function toInitCode(
605
+ userOperation: Partial<UserOperation>,
606
+ options: toInitCode.Options = {},
607
+ ): Hex.Hex {
608
+ const { forHash } = options
605
609
  const { authorization, factory, factoryData } = userOperation
606
610
  if (
607
611
  factory === '0x7702' ||
608
612
  factory === '0x7702000000000000000000000000000000000000'
609
613
  ) {
614
+ // Onchain, the EntryPoint detects EIP-7702 by the 20-byte `0x7702` marker
615
+ // and reads the initialization data from `initCode[20:]`.
616
+ if (!forHash)
617
+ return Hex.concat(
618
+ '0x7702000000000000000000000000000000000000',
619
+ factoryData ?? '0x',
620
+ )
621
+ // For the hash, the EntryPoint replaces the marker with the delegate.
610
622
  if (!authorization) return '0x7702000000000000000000000000000000000000'
611
623
  const delegation = authorization.address
612
624
  return Hex.concat(delegation, factoryData ?? '0x')
@@ -615,6 +627,18 @@ export function toInitCode(userOperation: Partial<UserOperation>): Hex.Hex {
615
627
  return Hex.concat(factory, factoryData ?? '0x')
616
628
  }
617
629
 
630
+ export declare namespace toInitCode {
631
+ type Options = {
632
+ /**
633
+ * Prepares the init code for hashing: replaces the EIP-7702 `0x7702`
634
+ * marker with the delegate address.
635
+ */
636
+ forHash?: boolean | undefined
637
+ }
638
+
639
+ type ErrorType = Hex.concat.ErrorType | Errors.GlobalErrorType
640
+ }
641
+
618
642
  /**
619
643
  * Transforms a User Operation into "packed" format.
620
644
  *
@@ -641,6 +665,7 @@ export function toInitCode(userOperation: Partial<UserOperation>): Hex.Hex {
641
665
  */
642
666
  export function toPacked(
643
667
  userOperation: UserOperation<'0.7' | '0.8', true>,
668
+ options: toPacked.Options = {},
644
669
  ): Packed {
645
670
  const {
646
671
  callGasLimit,
@@ -661,7 +686,7 @@ export function toPacked(
661
686
  Hex.padLeft(Hex.fromNumber(verificationGasLimit || 0n), 16),
662
687
  Hex.padLeft(Hex.fromNumber(callGasLimit || 0n), 16),
663
688
  )
664
- const initCode = toInitCode(userOperation)
689
+ const initCode = toInitCode(userOperation, { forHash: options.forHash })
665
690
  const gasFees = Hex.concat(
666
691
  Hex.padLeft(Hex.fromNumber(maxPriorityFeePerGas || 0n), 16),
667
692
  Hex.padLeft(Hex.fromNumber(maxFeePerGas || 0n), 16),
@@ -690,6 +715,15 @@ export function toPacked(
690
715
  }
691
716
 
692
717
  export declare namespace toPacked {
718
+ /** Packing options. */
719
+ export type Options = {
720
+ /**
721
+ * Prepares for hashing: replaces the EIP-7702 `initCode` marker with the
722
+ * delegate.
723
+ */
724
+ forHash?: boolean | undefined
725
+ }
726
+
693
727
  export type ErrorType = Errors.GlobalErrorType
694
728
  }
695
729
 
@@ -905,7 +939,7 @@ export function toTypedData(
905
939
  ): TypedData.Definition<typeof toTypedData.types, 'PackedUserOperation'> {
906
940
  const { chainId, entryPointAddress } = options
907
941
 
908
- const packedUserOp = toPacked(userOperation)
942
+ const packedUserOp = toPacked(userOperation, { forHash: true })
909
943
 
910
944
  return {
911
945
  domain: {
@@ -319,6 +319,8 @@ export function fromData(data: Hex.Hex): Attribution | undefined {
319
319
  // Extract codes
320
320
  const codesStart = -ercSuffixSize - 2 - codesLength
321
321
  const codesEnd = -ercSuffixSize - 2
322
+ // `Hex.slice` clamps a negative start that runs past the beginning of `data`.
323
+ if (Hex.size(data) + codesStart < 0) return undefined
322
324
  const codesHex = Hex.slice(data, codesStart, codesEnd)
323
325
  const codesString = Hex.toString(codesHex)
324
326
  const codes = codesString.length > 0 ? codesString.split(',') : []
@@ -340,6 +342,8 @@ export function fromData(data: Hex.Hex): Attribution | undefined {
340
342
  // Extract codes
341
343
  const codesStart = -ercSuffixSize - 2 - codesLength
342
344
  const codesEnd = -ercSuffixSize - 2
345
+ // `Hex.slice` clamps a negative start that runs past the beginning of `data`.
346
+ if (Hex.size(data) + codesStart < 0) return undefined
343
347
  const codesHex = Hex.slice(data, codesStart, codesEnd)
344
348
  const codesString = Hex.toString(codesHex)
345
349
  const codes = codesString.length > 0 ? codesString.split(',') : []
@@ -475,16 +479,16 @@ function schema2ToDataSuffix(attribution: AttributionSchemaId2): Hex.Hex {
475
479
 
476
480
  function schema2FromData(data: Hex.Hex): AttributionSchemaId2 | undefined {
477
481
  // cborLength is 2 bytes before schema ID
478
- const cborLengthHex = Hex.slice(
479
- data,
480
- -ercSuffixSize - 1 - 2,
481
- -ercSuffixSize - 1,
482
- )
482
+ const cborLengthStart = -ercSuffixSize - 1 - 2
483
+ const cborLengthEnd = -ercSuffixSize - 1
484
+ if (Hex.size(data) + cborLengthStart < 0) return undefined
485
+ const cborLengthHex = Hex.slice(data, cborLengthStart, cborLengthEnd)
483
486
  const cborLength = Hex.toNumber(cborLengthHex)
484
487
 
485
488
  // Extract CBOR data
486
- const cborStart = -ercSuffixSize - 1 - 2 - cborLength
487
- const cborEnd = -ercSuffixSize - 1 - 2
489
+ const cborStart = cborLengthStart - cborLength
490
+ if (Hex.size(data) + cborStart < 0) return undefined
491
+ const cborEnd = cborLengthStart
488
492
  const cborHex = Hex.slice(data, cborStart, cborEnd)
489
493
 
490
494
  // Decode CBOR
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ox",
3
3
  "description": "Ethereum Standard Library",
4
- "version": "0.14.63",
4
+ "version": "0.14.64",
5
5
  "main": "./_cjs/index.js",
6
6
  "module": "./_esm/index.js",
7
7
  "types": "./_types/index.d.ts",
@@ -107,7 +107,7 @@ describe('fromRpc', () => {
107
107
  expect(() =>
108
108
  AccountSimulation.fromRpc({ ...rpc, config: noncanonical }),
109
109
  ).toThrowErrorMatchingInlineSnapshot(
110
- `[AccountSimulation.InvalidSimulationError: Invalid account simulation: invalid config encoding.]`,
110
+ `[Rlp.NonCanonicalError: RLP payload is not canonically encoded: single byte \`0x00\` is wrapped in an explicit length prefix instead of being encoded as itself.]`,
111
111
  )
112
112
  })
113
113
  })
@@ -1043,6 +1043,18 @@ describe('from', () => {
1043
1043
  expect(envelope.type).toBe('keychain')
1044
1044
  })
1045
1045
 
1046
+ test('behavior: defaults version to v2', () => {
1047
+ const envelope = SignatureEnvelope.from({
1048
+ inner: SignatureEnvelope.from(signature_secp256k1),
1049
+ userAddress: '0x1234567890123456789012345678901234567890',
1050
+ })
1051
+
1052
+ expect(envelope).toMatchObject({ version: 'v2' })
1053
+ expect(
1054
+ Hex.slice(SignatureEnvelope.serialize(envelope), 0, 1),
1055
+ ).toMatchInlineSnapshot(`"0x04"`)
1056
+ })
1057
+
1046
1058
  test('behavior: computes keyId from p256 inner publicKey', () => {
1047
1059
  const envelope = SignatureEnvelope.from({
1048
1060
  userAddress: '0x1234567890123456789012345678901234567890',
@@ -139,7 +139,7 @@ export type GetType<
139
139
  *
140
140
  * - **keychain** (type `0x03` V1, `0x04` V2): Access key signature that wraps an inner signature
141
141
  * (secp256k1, p256, or webAuthn). Format: type byte + user_address (20 bytes) + inner signature.
142
- * V2 binds the signature to the user account via `keccak256(sigHash || userAddress)`.
142
+ * V2 binds the signature to the user account via `keccak256(0x04 || sigHash || userAddress)`.
143
143
  * The protocol validates the access key authorization via the AccountKeychain precompile.
144
144
  *
145
145
  * - **configurable** (type `0x05`): Configurable account signature carrying the account address,
@@ -181,8 +181,8 @@ export type PrimitiveRpc = OneOf<Secp256k1Rpc | P256Rpc | WebAuthnRpc>
181
181
  * Keychain signature version.
182
182
  *
183
183
  * - `'v1'`: Legacy format. Inner signature signs the raw `sig_hash` directly. Deprecated at T1C.
184
- * - `'v2'`: Inner signature signs `keccak256(sig_hash || user_address)`, binding the signature
185
- * to the specific user account.
184
+ * - `'v2'`: Inner signature signs `keccak256(0x04 || sig_hash || user_address)`, binding the
185
+ * signature to the specific user account.
186
186
  */
187
187
  export type KeychainVersion = 'v1' | 'v2'
188
188
 
@@ -194,7 +194,7 @@ export type Keychain<bigintType = bigint, numberType = number> = {
194
194
  type: 'keychain'
195
195
  /** Root account address that this transaction is being executed for */
196
196
  userAddress: Address.Address
197
- /** Keychain signature version. @default 'v1' */
197
+ /** Keychain signature version. @default 'v2' */
198
198
  version?: KeychainVersion | undefined
199
199
  }
200
200
 
@@ -115,6 +115,16 @@ describe('fromPrice', () => {
115
115
  expect(Tick.fromPrice(' 1.0 ')).toBe(0)
116
116
  expect(Tick.fromPrice(' 1.001 ')).toBe(100)
117
117
  })
118
+
119
+ test('throws error when price is negative', () => {
120
+ expect(() => Tick.fromPrice('-0.999')).toThrowErrorMatchingInlineSnapshot(`
121
+ [Tick.PriceOutOfBoundsError: Price "-0.999" results in tick -199900 which is out of bounds.
122
+
123
+ Tick must be between -2000 and 2000.]
124
+ `)
125
+ expect(() => Tick.fromPrice('-0.98')).toThrow(Tick.PriceOutOfBoundsError)
126
+ expect(() => Tick.fromPrice('-0.99999')).toThrow(Tick.PriceOutOfBoundsError)
127
+ })
118
128
  })
119
129
 
120
130
  describe('round-trip conversions', () => {
package/tempo/Tick.ts CHANGED
@@ -101,14 +101,16 @@ export function fromPrice(price: fromPrice.Price): fromPrice.ReturnType {
101
101
  throw new InvalidPriceFormatError({ price })
102
102
 
103
103
  // Parse price using string manipulation to avoid float precision issues
104
- const [w, d = '0'] = priceStr.split('.')
104
+ const negative = priceStr.startsWith('-')
105
+ const [w, d = '0'] = (negative ? priceStr.slice(1) : priceStr).split('.')
105
106
  const whole = BigInt(w!)
106
107
 
107
108
  // Pad or truncate decimal to exactly 5 digits
108
109
  const decimal = BigInt(d.padEnd(5, '0').slice(0, 5))
109
110
 
110
- // Calculate price
111
- const priceInt = whole * BigInt(priceScale) + decimal
111
+ // Calculate price, applying the sign last since `BigInt('-0')` is `0n`
112
+ const priceInt =
113
+ (negative ? -1n : 1n) * (whole * BigInt(priceScale) + decimal)
112
114
 
113
115
  // Calculate tick
114
116
  const tick = Number(priceInt - BigInt(priceScale))
package/version.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  /** @internal */
2
- export const version = '0.14.63'
2
+ export const version = '0.14.64'