ox 0.14.62 → 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 (121) hide show
  1. package/CHANGELOG.md +42 -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/AccountOperation.js +26 -6
  33. package/_cjs/tempo/AccountOperation.js.map +1 -1
  34. package/_cjs/tempo/Tick.js +3 -2
  35. package/_cjs/tempo/Tick.js.map +1 -1
  36. package/_cjs/version.js +1 -1
  37. package/_esm/core/AbiError.js +6 -2
  38. package/_esm/core/AbiError.js.map +1 -1
  39. package/_esm/core/AbiEvent.js +5 -0
  40. package/_esm/core/AbiEvent.js.map +1 -1
  41. package/_esm/core/AbiFunction.js +2 -2
  42. package/_esm/core/AbiFunction.js.map +1 -1
  43. package/_esm/core/AbiItem.js +8 -7
  44. package/_esm/core/AbiItem.js.map +1 -1
  45. package/_esm/core/Base32.js +17 -2
  46. package/_esm/core/Base32.js.map +1 -1
  47. package/_esm/core/Bytes.js +4 -5
  48. package/_esm/core/Bytes.js.map +1 -1
  49. package/_esm/core/Cbor.js +16 -2
  50. package/_esm/core/Cbor.js.map +1 -1
  51. package/_esm/core/Hex.js +3 -3
  52. package/_esm/core/Hex.js.map +1 -1
  53. package/_esm/core/Rlp.js +56 -8
  54. package/_esm/core/Rlp.js.map +1 -1
  55. package/_esm/core/RpcTransport.js +12 -4
  56. package/_esm/core/RpcTransport.js.map +1 -1
  57. package/_esm/core/Siwe.js +5 -0
  58. package/_esm/core/Siwe.js.map +1 -1
  59. package/_esm/core/TypedData.js +7 -6
  60. package/_esm/core/TypedData.js.map +1 -1
  61. package/_esm/core/internal/abiItem.js +2 -1
  62. package/_esm/core/internal/abiItem.js.map +1 -1
  63. package/_esm/erc4337/UserOperation.js +10 -4
  64. package/_esm/erc4337/UserOperation.js.map +1 -1
  65. package/_esm/erc8021/Attribution.js +15 -3
  66. package/_esm/erc8021/Attribution.js.map +1 -1
  67. package/_esm/tempo/AccountOperation.js +26 -6
  68. package/_esm/tempo/AccountOperation.js.map +1 -1
  69. package/_esm/tempo/Tick.js +4 -3
  70. package/_esm/tempo/Tick.js.map +1 -1
  71. package/_esm/version.js +1 -1
  72. package/_types/core/AbiError.d.ts +2 -2
  73. package/_types/core/AbiError.d.ts.map +1 -1
  74. package/_types/core/AbiEvent.d.ts.map +1 -1
  75. package/_types/core/AbiFunction.d.ts +1 -1
  76. package/_types/core/AbiFunction.d.ts.map +1 -1
  77. package/_types/core/AbiItem.d.ts.map +1 -1
  78. package/_types/core/Base32.d.ts +8 -3
  79. package/_types/core/Base32.d.ts.map +1 -1
  80. package/_types/core/Bytes.d.ts.map +1 -1
  81. package/_types/core/Cbor.d.ts.map +1 -1
  82. package/_types/core/Hex.d.ts.map +1 -1
  83. package/_types/core/Rlp.d.ts +9 -2
  84. package/_types/core/Rlp.d.ts.map +1 -1
  85. package/_types/core/RpcTransport.d.ts.map +1 -1
  86. package/_types/core/Siwe.d.ts.map +1 -1
  87. package/_types/core/internal/abiItem.d.ts +3 -1
  88. package/_types/core/internal/abiItem.d.ts.map +1 -1
  89. package/_types/erc4337/UserOperation.d.ts +20 -2
  90. package/_types/erc4337/UserOperation.d.ts.map +1 -1
  91. package/_types/erc8021/Attribution.d.ts.map +1 -1
  92. package/_types/package.json +1 -0
  93. package/_types/tempo/AccountOperation.d.ts +8 -0
  94. package/_types/tempo/AccountOperation.d.ts.map +1 -1
  95. package/_types/tempo/SignatureEnvelope.d.ts +4 -4
  96. package/_types/tempo/Tick.d.ts.map +1 -1
  97. package/_types/version.d.ts +1 -1
  98. package/core/AbiError.ts +33 -22
  99. package/core/AbiEvent.ts +7 -0
  100. package/core/AbiFunction.ts +7 -5
  101. package/core/AbiItem.ts +8 -7
  102. package/core/Base32.ts +17 -3
  103. package/core/Bytes.ts +3 -5
  104. package/core/Cbor.ts +20 -2
  105. package/core/Hex.ts +4 -4
  106. package/core/Rlp.ts +55 -5
  107. package/core/RpcTransport.ts +12 -4
  108. package/core/Siwe.ts +5 -0
  109. package/core/TypedData.ts +7 -6
  110. package/core/internal/abiItem.ts +13 -2
  111. package/erc4337/UserOperation.ts +37 -3
  112. package/erc8021/Attribution.ts +11 -7
  113. package/package.json +1 -1
  114. package/tempo/AccountOperation.test.ts +116 -0
  115. package/tempo/AccountOperation.ts +38 -5
  116. package/tempo/AccountSimulation.test.ts +1 -1
  117. package/tempo/SignatureEnvelope.test.ts +12 -0
  118. package/tempo/SignatureEnvelope.ts +4 -4
  119. package/tempo/Tick.test.ts +10 -0
  120. package/tempo/Tick.ts +5 -3
  121. package/version.ts +1 -1
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.62",
4
+ "version": "0.14.64",
5
5
  "main": "./_cjs/index.js",
6
6
  "module": "./_esm/index.js",
7
7
  "types": "./_types/index.d.ts",
@@ -388,6 +388,83 @@ describe('serializeKeyAuthorization', () => {
388
388
  })
389
389
 
390
390
  describe('serializeTransaction', () => {
391
+ test('access key transactions', async () => {
392
+ const userAddress = '0x4444444444444444444444444444444444444444'
393
+ const results = []
394
+ for (const transaction_ of [
395
+ transaction,
396
+ TxEnvelopeTempo.serialize(TxEnvelopeTempo.deserialize(transaction), {
397
+ format: 'feePayer',
398
+ sender: userAddress,
399
+ }),
400
+ ]) {
401
+ const hash = AccountOperation.getHash({
402
+ account,
403
+ config: currentConfig,
404
+ transaction: transaction_,
405
+ type: 'transaction',
406
+ userAddress,
407
+ })
408
+ const selection = await AccountOperation.selectApprovals({
409
+ account,
410
+ approvals: [
411
+ signApproval(owners[0]!, hash),
412
+ signApproval(owners[1]!, hash),
413
+ ],
414
+ config: currentConfig,
415
+ hash,
416
+ })
417
+ const operation = AccountOperation.from({
418
+ account,
419
+ approvals: selection.approvals,
420
+ config: currentConfig,
421
+ createdAt: 1,
422
+ hash,
423
+ signatureCount: selection.signatureCount,
424
+ status: 'pending',
425
+ threshold: selection.threshold,
426
+ transaction: transaction_,
427
+ type: 'transaction',
428
+ updatedAt: 1,
429
+ userAddress,
430
+ weight: selection.weight,
431
+ })
432
+ const value = TxEnvelopeTempo.deserialize(
433
+ AccountOperation.serializeTransaction(operation, {
434
+ approvals: selection.selectedApprovals,
435
+ }),
436
+ )
437
+ const { signature } = value
438
+ if (signature?.type !== 'keychain') throw new Error('expected keychain')
439
+ results.push({
440
+ from: value.from,
441
+ innerAccount:
442
+ signature.inner.type === 'configurable'
443
+ ? signature.inner.account
444
+ : undefined,
445
+ userAddress: signature.userAddress,
446
+ version: signature.version,
447
+ })
448
+ }
449
+
450
+ expect(results).toMatchInlineSnapshot(`
451
+ [
452
+ {
453
+ "from": "0x4444444444444444444444444444444444444444",
454
+ "innerAccount": "0xb3cc0b31026c7a54a9c45e468c674722c3c5b3b5",
455
+ "userAddress": "0x4444444444444444444444444444444444444444",
456
+ "version": "v2",
457
+ },
458
+ {
459
+ "from": "0x4444444444444444444444444444444444444444",
460
+ "innerAccount": "0xb3cc0b31026c7a54a9c45e468c674722c3c5b3b5",
461
+ "userAddress": "0x4444444444444444444444444444444444444444",
462
+ "version": "v2",
463
+ },
464
+ ]
465
+ `)
466
+ })
467
+
391
468
  test('current and initial transactions', async () => {
392
469
  const results = []
393
470
  for (const applicableConfig of [currentConfig, config]) {
@@ -586,6 +663,45 @@ describe('serializeTransaction', () => {
586
663
  })
587
664
 
588
665
  describe('from', () => {
666
+ test('error: access key transaction hash without userAddress', () => {
667
+ const userAddress = '0x4444444444444444444444444444444444444444'
668
+ const hash = AccountOperation.getHash({
669
+ account,
670
+ config: currentConfig,
671
+ transaction,
672
+ type: 'transaction',
673
+ userAddress,
674
+ })
675
+ const base = {
676
+ account,
677
+ approvals: [],
678
+ config: currentConfig,
679
+ createdAt: 1,
680
+ hash,
681
+ signatureCount: 0,
682
+ status: 'pending',
683
+ threshold: 2,
684
+ transaction,
685
+ type: 'transaction',
686
+ updatedAt: 1,
687
+ weight: 0,
688
+ } as const
689
+
690
+ expect(() =>
691
+ AccountOperation.from(base),
692
+ ).toThrowErrorMatchingInlineSnapshot(
693
+ `[AccountOperation.InvalidOperationError: Invalid account operation: hash does not match the operation payload.]`,
694
+ )
695
+ expect(() =>
696
+ AccountOperation.from({ ...base, userAddress: account }),
697
+ ).toThrowErrorMatchingInlineSnapshot(
698
+ `[AccountOperation.InvalidOperationError: Invalid account operation: a configurable account cannot be its own access key.]`,
699
+ )
700
+ expect(AccountOperation.from({ ...base, userAddress }).userAddress).toBe(
701
+ userAddress,
702
+ )
703
+ })
704
+
589
705
  test('transaction states', () => {
590
706
  const pending = AccountOperation.from(transactionPending)
591
707
  const submitting = AccountOperation.from({