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
package/core/AbiEvent.ts CHANGED
@@ -191,9 +191,7 @@ export function assertArgs<const abiEvent extends AbiEvent>(
191
191
  given: matchArgs,
192
192
  })
193
193
  }
194
- }
195
-
196
- if (
194
+ } else if (
197
195
  typeof args === 'object' &&
198
196
  !Array.isArray(args) &&
199
197
  typeof matchArgs === 'object' &&
@@ -201,7 +199,10 @@ export function assertArgs<const abiEvent extends AbiEvent>(
201
199
  )
202
200
  for (const [key, value] of Object.entries(matchArgs)) {
203
201
  if (value === null || value === undefined) continue
204
- const input = abiEvent.inputs.find((input) => input.name === key)
202
+ // `decode` keys an unnamed input by its index.
203
+ const input = abiEvent.inputs.find(
204
+ (input, index) => (input.name || `${index}`) === key,
205
+ )
205
206
  if (!input) throw new InputNotFoundError({ abiEvent, name: key })
206
207
  const value_ = Array.isArray(value) ? value : [value]
207
208
  let equal = false
@@ -216,6 +217,20 @@ export function assertArgs<const abiEvent extends AbiEvent>(
216
217
  given: matchArgs,
217
218
  })
218
219
  }
220
+ // Positional and keyed arguments cannot be compared with each other. A
221
+ // filter without values matches any arguments.
222
+ else if (
223
+ typeof matchArgs === 'object' &&
224
+ matchArgs !== null &&
225
+ Object.values(matchArgs).some(
226
+ (value) => value !== null && value !== undefined,
227
+ )
228
+ )
229
+ throw new ArgsMismatchError({
230
+ abiEvent,
231
+ expected: args,
232
+ given: matchArgs,
233
+ })
219
234
  }
220
235
 
221
236
  export declare namespace assertArgs {
@@ -269,6 +284,8 @@ export declare namespace assertArgs {
269
284
  *
270
285
  * You can also specify an entire ABI object and an event name as parameters to {@link ox#AbiEvent.(decode:function)}:
271
286
  *
287
+ * When the ABI holds several events with that name, the overload is resolved from the selector in `topics[0]`.
288
+ *
272
289
  * ```ts twoslash
273
290
  * // @noErrors
274
291
  * import { Abi, AbiEvent } from 'ox'
@@ -379,7 +396,7 @@ export function decode(
379
396
  ]
380
397
  | [abiEvent: AbiEvent, log: decode.Log]
381
398
  ): decode.ReturnType {
382
- const [abiEvent, log] = (() => {
399
+ const [abiEvent_, log] = (() => {
383
400
  if (Array.isArray(parameters[0])) {
384
401
  const [abi, name, log] = parameters as [
385
402
  Abi.Abi | readonly unknown[],
@@ -393,6 +410,20 @@ export function decode(
393
410
 
394
411
  const { data, topics } = log
395
412
 
413
+ // An event extracted by name carries its other overloads, and `topics[0]`
414
+ // holds the selector of the overload that was emitted. Anonymous overloads
415
+ // omit the selector topic, so they are never matched by it.
416
+ const abiEvent = (() => {
417
+ const { overloads } = abiEvent_ as AbiEvent
418
+ if (!overloads) return abiEvent_
419
+ const selector = topics[0]
420
+ return (
421
+ [abiEvent_, ...overloads].find(
422
+ (item) => item.anonymous !== true && getSelector(item) === selector,
423
+ ) ?? abiEvent_
424
+ )
425
+ })()
426
+
396
427
  // Anonymous events omit the selector topic, so every topic is an indexed
397
428
  // input.
398
429
  const isAnonymous = abiEvent.anonymous === true
@@ -488,12 +519,20 @@ export declare namespace decode {
488
519
  abiEvent,
489
520
  AbiEvent
490
521
  > extends true
491
- ? abiEvent['inputs'] extends readonly []
492
- ? undefined
493
- : internal.ParametersToPrimitiveTypes<
494
- abiEvent['inputs'],
495
- { EnableUnion: false; IndexedOnly: false; Required: true }
496
- >
522
+ ? // distribute over the event and its overloads
523
+ | abiEvent
524
+ | (abiEvent['overloads'] extends readonly AbiEvent[]
525
+ ? abiEvent['overloads'][number]
526
+ : never) extends infer item extends AbiEvent
527
+ ? item extends AbiEvent
528
+ ? item['inputs'] extends readonly []
529
+ ? undefined
530
+ : internal.ParametersToPrimitiveTypes<
531
+ item['inputs'],
532
+ { EnableUnion: false; IndexedOnly: false; Required: true }
533
+ >
534
+ : never
535
+ : never
497
536
  : unknown
498
537
 
499
538
  type ErrorType =
@@ -2,7 +2,7 @@ import * as abitype from 'abitype'
2
2
  import type * as Abi from './Abi.js'
3
3
  import * as AbiItem from './AbiItem.js'
4
4
  import * as AbiParameters from './AbiParameters.js'
5
- import type * as Errors from './Errors.js'
5
+ import * as Errors from './Errors.js'
6
6
  import * as Hex from './Hex.js'
7
7
  import type * as internal from './internal/abiFunction.js'
8
8
  import type * as AbiItem_internal from './internal/abiItem.js'
@@ -158,9 +158,17 @@ export function decodeData(
158
158
 
159
159
  if (Hex.size(data) < 4) throw new AbiItem.InvalidSelectorSizeError({ data })
160
160
 
161
- const item = overloads
162
- ? fromAbi([abiFunction, ...overloads], data as never)
163
- : abiFunction
161
+ // Hex is case-insensitive. Selectors are lowercase.
162
+ const selector = Hex.slice(data, 0, 4).toLowerCase() as Hex.Hex
163
+ const item = [abiFunction, ...(overloads ?? [])].find(
164
+ (item) => getSelector(item) === selector,
165
+ )
166
+ if (!item)
167
+ throw new SelectorMismatchError({
168
+ abiFunction,
169
+ actual: selector,
170
+ expected: getSelector(abiFunction),
171
+ })
164
172
 
165
173
  if (item.inputs.length === 0) return undefined
166
174
  if (Hex.size(data) <= 4) return undefined
@@ -187,9 +195,11 @@ export declare namespace decodeData {
187
195
 
188
196
  type ErrorType =
189
197
  | fromAbi.ErrorType
198
+ | getSelector.ErrorType
190
199
  | AbiParameters.decode.ErrorType
191
200
  | Hex.size.ErrorType
192
201
  | Hex.slice.ErrorType
202
+ | SelectorMismatchError
193
203
  | Errors.GlobalErrorType
194
204
  }
195
205
 
@@ -1055,3 +1065,65 @@ export function getSelector(abiItem: string | AbiFunction): Hex.Hex {
1055
1065
  export declare namespace getSelector {
1056
1066
  type ErrorType = AbiItem.getSelector.ErrorType | Errors.GlobalErrorType
1057
1067
  }
1068
+
1069
+ /**
1070
+ * Thrown when the selector of the provided data does not match the selector of the function, or of one of its overloads.
1071
+ *
1072
+ * @example
1073
+ * ```ts twoslash
1074
+ * // @noErrors
1075
+ * import { AbiFunction } from 'ox'
1076
+ *
1077
+ * const transfer = AbiFunction.from(
1078
+ * 'function transfer(address to, uint256 amount)'
1079
+ * )
1080
+ *
1081
+ * AbiFunction.decodeData(
1082
+ * transfer,
1083
+ * '0x095ea7b3000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000000001'
1084
+ * )
1085
+ * // @error: AbiFunction.SelectorMismatchError: Selector "0x095ea7b3" does not match the expected selector "0xa9059cbb".
1086
+ * // @error: Function: function transfer(address to, uint256 amount)
1087
+ * // @error: Selector: 0xa9059cbb
1088
+ * ```
1089
+ *
1090
+ * ### Solution
1091
+ *
1092
+ * Ensure that the data was encoded for the function.
1093
+ *
1094
+ * ```ts twoslash
1095
+ * import { AbiFunction } from 'ox'
1096
+ *
1097
+ * const transfer = AbiFunction.from(
1098
+ * 'function transfer(address to, uint256 amount)'
1099
+ * )
1100
+ *
1101
+ * AbiFunction.decodeData(
1102
+ * transfer,
1103
+ * '0xa9059cbb000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa960450000000000000000000000000000000000000000000000000000000000000001'
1104
+ * )
1105
+ * ```
1106
+ */
1107
+ export class SelectorMismatchError extends Errors.BaseError {
1108
+ override readonly name = 'AbiFunction.SelectorMismatchError'
1109
+
1110
+ constructor({
1111
+ abiFunction,
1112
+ actual,
1113
+ expected,
1114
+ }: {
1115
+ abiFunction: AbiFunction
1116
+ actual: Hex.Hex
1117
+ expected: Hex.Hex
1118
+ }) {
1119
+ super(
1120
+ `Selector "${actual}" does not match the expected selector "${expected}".`,
1121
+ {
1122
+ metaMessages: [
1123
+ `Function: ${format(abiFunction)}`,
1124
+ `Selector: ${expected}`,
1125
+ ],
1126
+ },
1127
+ )
1128
+ }
1129
+ }
package/core/Address.ts CHANGED
@@ -181,7 +181,22 @@ export declare namespace from {
181
181
  * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'
182
182
  * ```
183
183
  *
184
- * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.
184
+ * @example
185
+ * ### Compressed Public Keys
186
+ *
187
+ * The address is derived from both coordinates, so a compressed public key throws.
188
+ *
189
+ * ```ts twoslash
190
+ * import { Address, PublicKey } from 'ox'
191
+ *
192
+ * const publicKey = PublicKey.from(
193
+ * '0x038318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed75'
194
+ * )
195
+ * const address = Address.fromPublicKey(publicKey)
196
+ * // @error: PublicKey.InvalidPrefixError: Prefix "3" is invalid.
197
+ * ```
198
+ *
199
+ * @param publicKey - The uncompressed ECDSA public key to convert to an {@link ox#Address.Address}.
185
200
  * @param options - Conversion options.
186
201
  * @returns The {@link ox#Address.Address} corresponding to the public key.
187
202
  */
@@ -189,6 +204,7 @@ export function fromPublicKey(
189
204
  publicKey: PublicKey.PublicKey,
190
205
  options: fromPublicKey.Options = {},
191
206
  ): Address {
207
+ PublicKey.assert(publicKey, { compressed: false })
192
208
  const address = Hash.keccak256(
193
209
  `0x${PublicKey.toHex(publicKey).slice(4)}`,
194
210
  ).substring(26)
@@ -207,6 +223,7 @@ export declare namespace fromPublicKey {
207
223
 
208
224
  type ErrorType =
209
225
  | Hash.keccak256.ErrorType
226
+ | PublicKey.assert.ErrorType
210
227
  | PublicKey.toHex.ErrorType
211
228
  | Errors.GlobalErrorType
212
229
  }
@@ -1,5 +1,5 @@
1
1
  import type * as Address from './Address.js'
2
- import type * as Errors from './Errors.js'
2
+ import * as Errors from './Errors.js'
3
3
  import * as Hash from './Hash.js'
4
4
  import * as Hex from './Hex.js'
5
5
  import type { Compute, Mutable, Undefined } from './internal/types.js'
@@ -183,7 +183,7 @@ export function fromRpc(authorization: Rpc): Signed {
183
183
 
184
184
  return {
185
185
  address,
186
- chainId: Number(chainId),
186
+ chainId: toChainId(chainId),
187
187
  nonce: BigInt(nonce),
188
188
  ...signature,
189
189
  }
@@ -270,10 +270,14 @@ export declare namespace fromRpcList {
270
270
  export function fromTuple<const tuple extends Tuple>(
271
271
  tuple: tuple,
272
272
  ): fromTuple.ReturnType<tuple> {
273
+ if (tuple.length !== 3 && tuple.length !== 6)
274
+ throw new InvalidError(
275
+ 'Expected [chainId, address, nonce] or [chainId, address, nonce, yParity, r, s].',
276
+ )
273
277
  const [chainId, address, nonce, yParity, r, s] = tuple
274
278
  let args = {
275
279
  address,
276
- chainId: chainId === '0x' ? 0 : Number(chainId),
280
+ chainId: chainId === '0x' ? 0 : toChainId(chainId),
277
281
  nonce: nonce === '0x' ? 0n : BigInt(nonce),
278
282
  }
279
283
  if (yParity && r && s) {
@@ -296,7 +300,7 @@ export declare namespace fromTuple {
296
300
  Authorization<authorization extends Tuple<true> ? true : false>
297
301
  >
298
302
 
299
- type ErrorType = Errors.GlobalErrorType
303
+ type ErrorType = InvalidError | Errors.GlobalErrorType
300
304
  }
301
305
 
302
306
  /**
@@ -646,6 +650,19 @@ export declare namespace toTupleList {
646
650
  type ErrorType = Errors.GlobalErrorType
647
651
  }
648
652
 
653
+ // Converts an EIP-7702 authorization `chainId` to a number, and asserts that
654
+ // it is a safe integer.
655
+ function toChainId(chainId: Hex.Hex) {
656
+ const value = Number(chainId)
657
+ if (Number.isSafeInteger(value)) return value
658
+ throw new Hex.IntegerOutOfRangeError({
659
+ max: `${Number.MAX_SAFE_INTEGER}`,
660
+ min: '0',
661
+ signed: false,
662
+ value: `${value}`,
663
+ })
664
+ }
665
+
649
666
  // Asserts that an EIP-7702 authorization `yParity` fits in one byte.
650
667
  function assertYParity(yParity: number) {
651
668
  if (Number.isInteger(yParity) && yParity >= 0 && yParity < 256) return
@@ -657,3 +674,29 @@ function assertYParity(yParity: number) {
657
674
  value: `${yParity}`,
658
675
  })
659
676
  }
677
+
678
+ /**
679
+ * Thrown when an EIP-7702 Authorization tuple is structurally invalid.
680
+ *
681
+ * @example
682
+ * ```ts twoslash
683
+ * // @noErrors
684
+ * import { Authorization } from 'ox'
685
+ *
686
+ * Authorization.fromTuple([
687
+ * '0x1',
688
+ * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',
689
+ * '0x3',
690
+ * '0x1'
691
+ * ])
692
+ * // @error: Authorization.InvalidError: Invalid authorization.
693
+ * // @error: Details: Expected [chainId, address, nonce] or [chainId, address, nonce, yParity, r, s].
694
+ * ```
695
+ */
696
+ export class InvalidError extends Errors.BaseError {
697
+ override readonly name = 'Authorization.InvalidError'
698
+
699
+ constructor(details: string) {
700
+ super('Invalid authorization.', { details })
701
+ }
702
+ }
package/core/Keystore.ts CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  } from '@noble/hashes/scrypt'
10
10
  import { sha256 } from '@noble/hashes/sha2'
11
11
  import * as Bytes from './Bytes.js'
12
- import type * as Errors from './Errors.js'
12
+ import * as Errors from './Errors.js'
13
13
  import * as Hash from './Hash.js'
14
14
  import type * as Hex from './Hex.js'
15
15
  import type { OneOf } from './internal/types.js'
@@ -92,7 +92,7 @@ export type ScryptDeriveOpts = BaseDeriveOpts<
92
92
  * ```
93
93
  *
94
94
  * @param keystore - JSON keystore.
95
- * @param key - Key to use for decryption.
95
+ * @param key - Key to use for decryption. Must contain at least 32 bytes; the first 32 bytes are used.
96
96
  * @param options - Decryption options.
97
97
  * @returns Decrypted private key.
98
98
  */
@@ -103,6 +103,7 @@ export function decrypt<as extends 'Hex' | 'Bytes' = 'Hex'>(
103
103
  ): decrypt.ReturnType<as> {
104
104
  const { as = 'Hex' } = options
105
105
  const key_ = Bytes.from(typeof key === 'function' ? key() : key)
106
+ if (key_.length < 32) throw new InvalidKeySizeError({ size: key_.length })
106
107
 
107
108
  const encKey = Bytes.slice(key_, 0, 16)
108
109
  const macKey = Bytes.slice(key_, 16, 32)
@@ -131,6 +132,8 @@ export declare namespace decrypt {
131
132
  type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =
132
133
  | (as extends 'Hex' ? Hex.Hex : never)
133
134
  | (as extends 'Bytes' ? Bytes.Bytes : never)
135
+
136
+ type ErrorType = InvalidKeySizeError | Errors.GlobalErrorType
134
137
  }
135
138
 
136
139
  /**
@@ -175,7 +178,7 @@ export declare namespace decrypt {
175
178
  * ```
176
179
  *
177
180
  * @param privateKey - Private key to encrypt.
178
- * @param key - Key to use for encryption.
181
+ * @param key - Key to use for encryption. Must contain at least 32 bytes; the first 32 bytes are used.
179
182
  * @param options - Encryption options.
180
183
  * @returns Encrypted keystore.
181
184
  */
@@ -187,6 +190,7 @@ export function encrypt(
187
190
  const { id = crypto.randomUUID(), kdf, kdfparams, iv } = options
188
191
 
189
192
  const key_ = Bytes.from(typeof key === 'function' ? key() : key)
193
+ if (key_.length < 32) throw new InvalidKeySizeError({ size: key_.length })
190
194
  const value_ = Bytes.from(privateKey)
191
195
 
192
196
  const encKey = Bytes.slice(key_, 0, 16)
@@ -214,6 +218,8 @@ export declare namespace encrypt {
214
218
  /** UUID. */
215
219
  id?: string | undefined
216
220
  }
221
+
222
+ type ErrorType = InvalidKeySizeError | Errors.GlobalErrorType
217
223
  }
218
224
 
219
225
  /**
@@ -521,6 +527,37 @@ export declare namespace toKeyAsync {
521
527
  }
522
528
  }
523
529
 
530
+ /**
531
+ * Thrown when a key contains fewer than 32 bytes.
532
+ *
533
+ * @example
534
+ * ```ts twoslash
535
+ * import { Keystore } from 'ox'
536
+ *
537
+ * const [, opts] = Keystore.pbkdf2({
538
+ * password: 'testpassword'
539
+ * })
540
+ *
541
+ * Keystore.encrypt('0x01', '0x0123456789abcdef', opts)
542
+ * // @error: Keystore.InvalidKeySizeError: Key must contain at least 32 bytes. Received 8 bytes.
543
+ * ```
544
+ */
545
+ export class InvalidKeySizeError extends Errors.BaseError {
546
+ override readonly name = 'Keystore.InvalidKeySizeError'
547
+
548
+ constructor(options: InvalidKeySizeError.Options) {
549
+ super(`Key must contain at least 32 bytes. Received ${options.size} bytes.`)
550
+ }
551
+ }
552
+
553
+ export declare namespace InvalidKeySizeError {
554
+ /** Options for `Keystore.InvalidKeySizeError`. */
555
+ type Options = {
556
+ /** Received key size. */
557
+ size: number
558
+ }
559
+ }
560
+
524
561
  ///////////////////////////////////////////////////////////////////////////
525
562
 
526
563
  /** @internal */
package/core/Secp256k1.ts CHANGED
@@ -2,6 +2,7 @@ import { secp256k1 } from '@noble/curves/secp256k1'
2
2
  import * as Address from './Address.js'
3
3
  import * as Bytes from './Bytes.js'
4
4
  import * as Errors from './Errors.js'
5
+ import * as Hash from './Hash.js'
5
6
  import * as Hex from './Hex.js'
6
7
  import * as Entropy from './internal/entropy.js'
7
8
  import * as keyDerivation from './internal/keyDerivation.js'
@@ -502,7 +503,10 @@ export function verify(options: verify.Options): boolean {
502
503
  if (options.address)
503
504
  return Address.isEqual(
504
505
  options.address,
505
- recoverAddress({ payload, signature: options.signature }),
506
+ recoverAddress({
507
+ payload: hash === true ? Hash.sha256(payload) : payload,
508
+ signature: options.signature,
509
+ }),
506
510
  )
507
511
  return secp256k1.verify(
508
512
  options.signature,
package/core/Signature.ts CHANGED
@@ -72,14 +72,17 @@ export function assert(
72
72
  throw new MissingPropertiesError({ signature })
73
73
  if (typeof signature.s === 'undefined')
74
74
  throw new MissingPropertiesError({ signature })
75
- if (recovered && typeof signature.yParity === 'undefined')
75
+ if (
76
+ recovered &&
77
+ (signature.yParity === undefined || signature.yParity === null)
78
+ )
76
79
  throw new MissingPropertiesError({ signature })
77
80
  if (signature.r < 0n || signature.r > Solidity.maxUint256)
78
81
  throw new InvalidRError({ value: signature.r })
79
82
  if (signature.s < 0n || signature.s > Solidity.maxUint256)
80
83
  throw new InvalidSError({ value: signature.s })
81
84
  if (
82
- typeof signature.yParity === 'number' &&
85
+ signature.yParity !== undefined &&
83
86
  signature.yParity !== 0 &&
84
87
  signature.yParity !== 1
85
88
  )
@@ -672,6 +675,7 @@ export declare namespace toRpc {
672
675
  * @returns The {@link ox#Signature.Tuple}.
673
676
  */
674
677
  export function toTuple(signature: Signature): Tuple {
678
+ assert(signature, { recovered: true })
675
679
  const { r, s, yParity } = signature
676
680
 
677
681
  return [
@@ -683,6 +687,7 @@ export function toTuple(signature: Signature): Tuple {
683
687
 
684
688
  export declare namespace toTuple {
685
689
  type ErrorType =
690
+ | assert.ErrorType
686
691
  | Hex.trimLeft.ErrorType
687
692
  | Hex.fromNumber.ErrorType
688
693
  | Errors.GlobalErrorType
package/core/Siwe.ts CHANGED
@@ -23,6 +23,9 @@ export const prefixRegex =
23
23
  export const suffixRegex =
24
24
  /(?:URI: (?<uri>.+))\n(?:Version: (?<version>.+))\n(?:Chain ID: (?<chainId>\d+))\n(?:Nonce: (?<nonce>[a-zA-Z0-9]+))\n(?:Issued At: (?<issuedAt>.+))(?:\nExpiration Time: (?<expirationTime>.+))?(?:\nNot Before: (?<notBefore>.+))?(?:\nRequest ID: (?<requestId>.*))?(?:\nResources:(?<resources>(?:\n- .+)*))?/
25
25
 
26
+ // Matches `suffixRegex` from the start of the input to its end.
27
+ const anchoredSuffixRegex = new RegExp(`^(?:${suffixRegex.source})$`)
28
+
26
29
  // URI validation (see `isUri`).
27
30
  const uriIllegalCharacterRegex = /[^a-z0-9:/?#[\]@!$&'()*+,;=.\-_~%]/i
28
31
  const uriInvalidEscapeRegex = /%[^0-9a-f]/i
@@ -211,6 +214,15 @@ export function createMessage(value: Message): string {
211
214
  `Provided value: ${statement}`,
212
215
  ],
213
216
  })
217
+ if (requestId && /[\n\r]/.test(requestId))
218
+ throw new InvalidMessageFieldError({
219
+ field: 'requestId',
220
+ metaMessages: [
221
+ "- Request ID must not include '\\n' or '\\r'.",
222
+ '',
223
+ `Provided value: ${requestId}`,
224
+ ],
225
+ })
214
226
  }
215
227
 
216
228
  // Construct message
@@ -341,6 +353,10 @@ function splitUri(value: string) {
341
353
  /**
342
354
  * [EIP-4361](https://eips.ethereum.org/EIPS/eip-4361) formatted message into message fields object.
343
355
  *
356
+ * The message can be the prefix (up to the statement), the suffix (from `URI`), or both.
357
+ * Returns an empty object when the message has any other text, such as fields that are
358
+ * out of order or text after the last field.
359
+ *
344
360
  * @example
345
361
  * ```ts twoslash
346
362
  * import { Siwe } from 'ox'
@@ -371,13 +387,23 @@ function splitUri(value: string) {
371
387
  * @returns Message fields object.
372
388
  */
373
389
  export function parseMessage(message: string): ExactPartial<Message> {
374
- const { scheme, statement, ...prefix } = (message.match(prefixRegex)
375
- ?.groups ?? {}) as {
390
+ const prefixMatch = message.match(prefixRegex)
391
+ const { scheme, statement, ...prefix } = (prefixMatch?.groups ?? {}) as {
376
392
  address: Address.Address
377
393
  domain: string
378
394
  scheme?: string
379
395
  statement?: string
380
396
  }
397
+ // The suffix starts where the prefix ends. Without a statement, the prefix
398
+ // is followed by one more line feed (as `createMessage` emits) or by none.
399
+ const rest = (() => {
400
+ const rest = message.slice(prefixMatch?.[0].length ?? 0)
401
+ if (prefixMatch && statement === undefined && rest.startsWith('\n'))
402
+ return rest.slice(1)
403
+ return rest
404
+ })()
405
+ const suffixMatch = rest.match(anchoredSuffixRegex)
406
+ if (rest && !suffixMatch) return {}
381
407
  const {
382
408
  chainId,
383
409
  expirationTime,
@@ -386,7 +412,7 @@ export function parseMessage(message: string): ExactPartial<Message> {
386
412
  requestId,
387
413
  resources: resources_,
388
414
  ...suffix
389
- } = (message.match(suffixRegex)?.groups ?? {}) as {
415
+ } = (suffixMatch?.groups ?? {}) as {
390
416
  chainId: string
391
417
  expirationTime?: string
392
418
  issuedAt?: string
@@ -68,7 +68,10 @@ export type Type = typeof type
68
68
  */
69
69
  export function assert(envelope: PartialBy<TxEnvelopeEip1559, 'type'>) {
70
70
  const { chainId, maxPriorityFeePerGas, maxFeePerGas, to } = envelope
71
- if (chainId <= 0)
71
+ if (
72
+ typeof chainId !== 'undefined' &&
73
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
74
+ )
72
75
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
73
76
  if (to) Address.assert(to, { strict: false })
74
77
  if (maxFeePerGas && BigInt(maxFeePerGas) > 2n ** 256n - 1n)
@@ -66,7 +66,10 @@ export type Type = typeof type
66
66
  */
67
67
  export function assert(envelope: PartialBy<TxEnvelopeEip2930, 'type'>) {
68
68
  const { chainId, gasPrice, to } = envelope
69
- if (chainId <= 0)
69
+ if (
70
+ typeof chainId !== 'undefined' &&
71
+ (!Number.isSafeInteger(chainId) || chainId <= 0)
72
+ )
70
73
  throw new TransactionEnvelope.InvalidChainIdError({ chainId })
71
74
  if (to) Address.assert(to, { strict: false })
72
75
  if (gasPrice && BigInt(gasPrice) > 2n ** 256n - 1n)
@@ -183,10 +183,17 @@ export function deserialize(
183
183
  transaction.maxFeePerGas = 0n
184
184
  if (accessList!.length !== 0 && accessList !== '0x')
185
185
  transaction.accessList = AccessList.fromTupleList(accessList as never)
186
- if (authorizationList !== '0x')
186
+ if (authorizationList !== '0x') {
187
+ // A transaction holds signed authorizations only.
188
+ for (const tuple of authorizationList as never as readonly unknown[])
189
+ if (!Array.isArray(tuple) || tuple.length !== 6)
190
+ throw new Authorization.InvalidError(
191
+ 'Expected [chainId, address, nonce, yParity, r, s].',
192
+ )
187
193
  transaction.authorizationList = Authorization.fromTupleList(
188
194
  authorizationList as never,
189
195
  )
196
+ }
190
197
 
191
198
  const signature =
192
199
  r && s && yParity ? Signature.fromTuple([yParity, r, s]) : undefined
@@ -202,7 +209,7 @@ export function deserialize(
202
209
  }
203
210
 
204
211
  export declare namespace deserialize {
205
- type ErrorType = Errors.GlobalErrorType
212
+ type ErrorType = Authorization.InvalidError | Errors.GlobalErrorType
206
213
  }
207
214
 
208
215
  /**