viem 2.57.19 → 2.57.20

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 (111) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/_cjs/accounts/index.js +2 -1
  3. package/_cjs/accounts/index.js.map +1 -1
  4. package/_cjs/accounts/utils/publicKeyToAddress.js +15 -0
  5. package/_cjs/accounts/utils/publicKeyToAddress.js.map +1 -1
  6. package/_cjs/actions/public/call.js +19 -3
  7. package/_cjs/actions/public/call.js.map +1 -1
  8. package/_cjs/actions/public/estimateMaxPriorityFeePerGas.js +1 -1
  9. package/_cjs/actions/public/estimateMaxPriorityFeePerGas.js.map +1 -1
  10. package/_cjs/actions/wallet/prepareTransactionRequest.js +99 -76
  11. package/_cjs/actions/wallet/prepareTransactionRequest.js.map +1 -1
  12. package/_cjs/chains/definitions/darwinia.js +1 -1
  13. package/_cjs/chains/definitions/darwinia.js.map +1 -1
  14. package/_cjs/chains/definitions/flowMainnet.js +1 -1
  15. package/_cjs/chains/definitions/flowMainnet.js.map +1 -1
  16. package/_cjs/errors/encoding.js +9 -1
  17. package/_cjs/errors/encoding.js.map +1 -1
  18. package/_cjs/errors/version.js +1 -1
  19. package/_cjs/index.js +6 -5
  20. package/_cjs/index.js.map +1 -1
  21. package/_cjs/utils/address/getAddress.js +7 -6
  22. package/_cjs/utils/address/getAddress.js.map +1 -1
  23. package/_cjs/utils/address/isAddress.js +8 -12
  24. package/_cjs/utils/address/isAddress.js.map +1 -1
  25. package/_cjs/utils/encoding/fromRlp.js +33 -8
  26. package/_cjs/utils/encoding/fromRlp.js.map +1 -1
  27. package/_cjs/utils/index.js +5 -4
  28. package/_cjs/utils/index.js.map +1 -1
  29. package/_cjs/utils/promise/createBatchScheduler.js +7 -2
  30. package/_cjs/utils/promise/createBatchScheduler.js.map +1 -1
  31. package/_cjs/utils/typedData.js +5 -9
  32. package/_cjs/utils/typedData.js.map +1 -1
  33. package/_esm/accounts/index.js +1 -1
  34. package/_esm/accounts/index.js.map +1 -1
  35. package/_esm/accounts/utils/publicKeyToAddress.js +20 -1
  36. package/_esm/accounts/utils/publicKeyToAddress.js.map +1 -1
  37. package/_esm/actions/public/call.js +19 -3
  38. package/_esm/actions/public/call.js.map +1 -1
  39. package/_esm/actions/public/estimateMaxPriorityFeePerGas.js +1 -1
  40. package/_esm/actions/public/estimateMaxPriorityFeePerGas.js.map +1 -1
  41. package/_esm/actions/wallet/prepareTransactionRequest.js +111 -79
  42. package/_esm/actions/wallet/prepareTransactionRequest.js.map +1 -1
  43. package/_esm/chains/definitions/darwinia.js +1 -1
  44. package/_esm/chains/definitions/darwinia.js.map +1 -1
  45. package/_esm/chains/definitions/flowMainnet.js +1 -1
  46. package/_esm/chains/definitions/flowMainnet.js.map +1 -1
  47. package/_esm/errors/encoding.js +8 -0
  48. package/_esm/errors/encoding.js.map +1 -1
  49. package/_esm/errors/version.js +1 -1
  50. package/_esm/index.js +1 -1
  51. package/_esm/index.js.map +1 -1
  52. package/_esm/tempo/internal/relay/feePayer.js +1 -1
  53. package/_esm/tempo/internal/relay/feePayer.js.map +1 -1
  54. package/_esm/utils/address/getAddress.js +32 -6
  55. package/_esm/utils/address/getAddress.js.map +1 -1
  56. package/_esm/utils/address/isAddress.js +32 -12
  57. package/_esm/utils/address/isAddress.js.map +1 -1
  58. package/_esm/utils/encoding/fromRlp.js +37 -9
  59. package/_esm/utils/encoding/fromRlp.js.map +1 -1
  60. package/_esm/utils/index.js +1 -1
  61. package/_esm/utils/index.js.map +1 -1
  62. package/_esm/utils/promise/createBatchScheduler.js +7 -2
  63. package/_esm/utils/promise/createBatchScheduler.js.map +1 -1
  64. package/_esm/utils/typedData.js +7 -9
  65. package/_esm/utils/typedData.js.map +1 -1
  66. package/_types/accounts/index.d.ts +1 -1
  67. package/_types/accounts/index.d.ts.map +1 -1
  68. package/_types/accounts/utils/publicKeyToAddress.d.ts +16 -2
  69. package/_types/accounts/utils/publicKeyToAddress.d.ts.map +1 -1
  70. package/_types/actions/public/call.d.ts +1 -1
  71. package/_types/actions/public/call.d.ts.map +1 -1
  72. package/_types/actions/public/estimateMaxPriorityFeePerGas.d.ts +1 -1
  73. package/_types/actions/public/estimateMaxPriorityFeePerGas.d.ts.map +1 -1
  74. package/_types/actions/wallet/prepareTransactionRequest.d.ts.map +1 -1
  75. package/_types/chains/definitions/darwinia.d.ts +1 -1
  76. package/_types/chains/definitions/darwinia.d.ts.map +1 -1
  77. package/_types/chains/definitions/flowMainnet.d.ts +1 -1
  78. package/_types/chains/definitions/flowMainnet.d.ts.map +1 -1
  79. package/_types/errors/encoding.d.ts +9 -0
  80. package/_types/errors/encoding.d.ts.map +1 -1
  81. package/_types/errors/version.d.ts +1 -1
  82. package/_types/index.d.ts +1 -1
  83. package/_types/index.d.ts.map +1 -1
  84. package/_types/utils/address/getAddress.d.ts +23 -0
  85. package/_types/utils/address/getAddress.d.ts.map +1 -1
  86. package/_types/utils/address/isAddress.d.ts +22 -0
  87. package/_types/utils/address/isAddress.d.ts.map +1 -1
  88. package/_types/utils/encoding/fromRlp.d.ts +3 -3
  89. package/_types/utils/encoding/fromRlp.d.ts.map +1 -1
  90. package/_types/utils/index.d.ts +1 -1
  91. package/_types/utils/index.d.ts.map +1 -1
  92. package/_types/utils/promise/createBatchScheduler.d.ts.map +1 -1
  93. package/_types/utils/typedData.d.ts.map +1 -1
  94. package/accounts/index.ts +2 -0
  95. package/accounts/utils/publicKeyToAddress.ts +27 -1
  96. package/actions/public/call.ts +20 -3
  97. package/actions/public/estimateMaxPriorityFeePerGas.ts +2 -2
  98. package/actions/wallet/prepareTransactionRequest.ts +136 -107
  99. package/chains/definitions/darwinia.ts +1 -1
  100. package/chains/definitions/flowMainnet.ts +1 -1
  101. package/errors/encoding.ts +12 -0
  102. package/errors/version.ts +1 -1
  103. package/index.ts +2 -0
  104. package/package.json +2 -2
  105. package/tempo/internal/relay/feePayer.ts +1 -1
  106. package/utils/address/getAddress.ts +31 -6
  107. package/utils/address/isAddress.ts +31 -10
  108. package/utils/encoding/fromRlp.ts +37 -5
  109. package/utils/index.ts +2 -0
  110. package/utils/promise/createBatchScheduler.ts +10 -2
  111. package/utils/typedData.ts +7 -9
@@ -13,6 +13,7 @@ import {
13
13
  type EstimateGasParameters,
14
14
  estimateGas,
15
15
  } from '../../actions/public/estimateGas.js'
16
+ import { internal_estimateMaxPriorityFeePerGas } from '../../actions/public/estimateMaxPriorityFeePerGas.js'
16
17
  import {
17
18
  type GetBlockErrorType,
18
19
  getBlock as getBlock_,
@@ -610,133 +611,161 @@ export async function prepareTransactionRequest<
610
611
  )) ?? request
611
612
  }
612
613
 
613
- let block: Block | undefined
614
- async function getBlock(): Promise<Block> {
615
- if (block) return block
616
- block = await getAction(
617
- client,
618
- getBlock_,
619
- 'getBlock',
620
- )({ blockTag: 'latest' })
614
+ let block: Promise<Block> | undefined
615
+ function getBlock(): Promise<Block> {
616
+ block ??= getAction(client, getBlock_, 'getBlock')({ blockTag: 'latest' })
621
617
  return block
622
618
  }
623
619
 
624
- if (
620
+ // Chain fee hooks receive the block and the request, so the requests they
621
+ // depend on are made in sequence.
622
+ const hasFeeHooks = Object.values(chain?.fees ?? {}).some(
623
+ (fee) => typeof fee === 'function',
624
+ )
625
+
626
+ // The nonce does not depend on the type or the fees, so it is fetched
627
+ // concurrently with them.
628
+ const noncePromise =
625
629
  parameters.includes('nonce') &&
626
630
  typeof nonce === 'undefined' &&
627
631
  account &&
628
632
  !nonceManager
629
- )
630
- request.nonce = await getAction(
631
- client,
632
- getTransactionCount,
633
- 'getTransactionCount',
634
- )({
635
- address: account.address,
636
- blockTag: 'pending',
637
- })
638
-
639
- if (
640
- (parameters.includes('blobVersionedHashes') ||
641
- parameters.includes('sidecars')) &&
642
- blobs &&
643
- kzg
644
- ) {
645
- const commitments = blobsToCommitments({ blobs, kzg })
646
-
647
- if (parameters.includes('blobVersionedHashes')) {
648
- const versionedHashes = commitmentsToVersionedHashes({
649
- commitments,
650
- to: 'hex',
651
- })
652
- request.blobVersionedHashes = versionedHashes
653
- }
654
- if (parameters.includes('sidecars')) {
655
- const proofs = blobsToProofs({ blobs, commitments, kzg })
656
- const sidecars = toBlobSidecars({
657
- blobs,
658
- commitments,
659
- proofs,
660
- to: 'hex',
661
- })
662
- request.sidecars = sidecars
633
+ ? getAction(
634
+ client,
635
+ getTransactionCount,
636
+ 'getTransactionCount',
637
+ )({
638
+ address: account.address,
639
+ blockTag: 'pending',
640
+ })
641
+ : undefined
642
+ // A rejection is thrown when the nonce is awaited.
643
+ noncePromise?.catch(() => {})
644
+ if (noncePromise && hasFeeHooks) request.nonce = await noncePromise
645
+
646
+ try {
647
+ if (
648
+ (parameters.includes('blobVersionedHashes') ||
649
+ parameters.includes('sidecars')) &&
650
+ blobs &&
651
+ kzg
652
+ ) {
653
+ const commitments = blobsToCommitments({ blobs, kzg })
654
+
655
+ if (parameters.includes('blobVersionedHashes')) {
656
+ const versionedHashes = commitmentsToVersionedHashes({
657
+ commitments,
658
+ to: 'hex',
659
+ })
660
+ request.blobVersionedHashes = versionedHashes
661
+ }
662
+ if (parameters.includes('sidecars')) {
663
+ const proofs = blobsToProofs({ blobs, commitments, kzg })
664
+ const sidecars = toBlobSidecars({
665
+ blobs,
666
+ commitments,
667
+ proofs,
668
+ to: 'hex',
669
+ })
670
+ request.sidecars = sidecars
671
+ }
663
672
  }
664
- }
665
673
 
666
- if (parameters.includes('chainId')) request.chainId = await getChainId()
674
+ if (parameters.includes('chainId')) request.chainId = await getChainId()
667
675
 
668
- if (
669
- (parameters.includes('fees') || parameters.includes('type')) &&
670
- typeof type === 'undefined'
671
- ) {
672
- try {
673
- request.type = getTransactionType(
674
- request as TransactionSerializable,
675
- ) as any
676
- } catch {
677
- let isEip1559Network = eip1559NetworkCache.get(client.uid)
678
- if (typeof isEip1559Network === 'undefined') {
679
- const block = await getBlock()
680
- isEip1559Network = typeof block?.baseFeePerGas === 'bigint'
681
- eip1559NetworkCache.set(client.uid, isEip1559Network)
676
+ if (
677
+ (parameters.includes('fees') || parameters.includes('type')) &&
678
+ typeof type === 'undefined'
679
+ ) {
680
+ try {
681
+ request.type = getTransactionType(
682
+ request as TransactionSerializable,
683
+ ) as any
684
+ } catch {
685
+ let isEip1559Network = eip1559NetworkCache.get(client.uid)
686
+ if (typeof isEip1559Network === 'undefined') {
687
+ const block = await getBlock()
688
+ isEip1559Network = typeof block?.baseFeePerGas === 'bigint'
689
+ eip1559NetworkCache.set(client.uid, isEip1559Network)
690
+ }
691
+ request.type = isEip1559Network ? 'eip1559' : 'legacy'
682
692
  }
683
- request.type = isEip1559Network ? 'eip1559' : 'legacy'
684
693
  }
685
- }
686
694
 
687
- if (parameters.includes('fees')) {
688
- // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.
689
-
690
- if (request.type !== 'legacy' && request.type !== 'eip2930') {
691
- // EIP-1559 fees
692
- if (
693
- typeof request.maxFeePerGas === 'undefined' ||
694
- typeof request.maxPriorityFeePerGas === 'undefined'
695
- ) {
696
- const block = await getBlock()
697
- const { maxFeePerGas, maxPriorityFeePerGas } =
698
- await internal_estimateFeesPerGas(client, {
699
- block: block as Block,
700
- chain,
701
- request: request as PrepareTransactionRequestParameters,
702
- })
695
+ if (parameters.includes('fees')) {
696
+ // TODO(4844): derive blob base fees once https://github.com/ethereum/execution-apis/pull/486 is merged.
703
697
 
698
+ if (request.type !== 'legacy' && request.type !== 'eip2930') {
699
+ // EIP-1559 fees
704
700
  if (
705
- typeof request.maxPriorityFeePerGas === 'undefined' &&
706
- typeof request.maxFeePerGas === 'bigint' &&
707
- request.maxFeePerGas < maxPriorityFeePerGas
708
- )
709
- throw new MaxFeePerGasTooLowError({
710
- maxPriorityFeePerGas,
711
- })
712
-
713
- request.maxPriorityFeePerGas = maxPriorityFeePerGas
714
- request.maxFeePerGas = maxFeePerGas
715
- }
716
- } else {
717
- // Legacy fees
718
- if (
719
- typeof request.maxFeePerGas !== 'undefined' ||
720
- typeof request.maxPriorityFeePerGas !== 'undefined'
721
- )
722
- throw new Eip1559FeesNotSupportedError()
723
-
724
- if (typeof request.gasPrice === 'undefined') {
725
- const block = await getBlock()
726
- const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(
727
- client,
728
- {
729
- block: block as Block,
730
- chain,
731
- request: request as PrepareTransactionRequestParameters,
732
- type: 'legacy',
733
- },
701
+ typeof request.maxFeePerGas === 'undefined' ||
702
+ typeof request.maxPriorityFeePerGas === 'undefined'
703
+ ) {
704
+ // Without chain fee hooks, the priority fee does not depend on the
705
+ // block, so it is estimated concurrently with the block request.
706
+ const [block, priorityFee] = await Promise.all([
707
+ getBlock(),
708
+ hasFeeHooks || typeof request.maxPriorityFeePerGas === 'bigint'
709
+ ? undefined
710
+ : internal_estimateMaxPriorityFeePerGas(client, {
711
+ block: getBlock(),
712
+ chain,
713
+ request: request as PrepareTransactionRequestParameters,
714
+ }),
715
+ ])
716
+ const { maxFeePerGas, maxPriorityFeePerGas } =
717
+ await internal_estimateFeesPerGas(client, {
718
+ block,
719
+ chain,
720
+ request: (typeof priorityFee === 'bigint'
721
+ ? { ...request, maxPriorityFeePerGas: priorityFee }
722
+ : request) as PrepareTransactionRequestParameters,
723
+ })
724
+
725
+ if (
726
+ typeof request.maxPriorityFeePerGas === 'undefined' &&
727
+ typeof request.maxFeePerGas === 'bigint' &&
728
+ request.maxFeePerGas < maxPriorityFeePerGas
729
+ )
730
+ throw new MaxFeePerGasTooLowError({
731
+ maxPriorityFeePerGas,
732
+ })
733
+
734
+ request.maxPriorityFeePerGas = maxPriorityFeePerGas
735
+ request.maxFeePerGas = maxFeePerGas
736
+ }
737
+ } else {
738
+ // Legacy fees
739
+ if (
740
+ typeof request.maxFeePerGas !== 'undefined' ||
741
+ typeof request.maxPriorityFeePerGas !== 'undefined'
734
742
  )
735
- request.gasPrice = gasPrice_
743
+ throw new Eip1559FeesNotSupportedError()
744
+
745
+ if (typeof request.gasPrice === 'undefined') {
746
+ const block = await getBlock()
747
+ const { gasPrice: gasPrice_ } = await internal_estimateFeesPerGas(
748
+ client,
749
+ {
750
+ block: block as Block,
751
+ chain,
752
+ request: request as PrepareTransactionRequestParameters,
753
+ type: 'legacy',
754
+ },
755
+ )
756
+ request.gasPrice = gasPrice_
757
+ }
736
758
  }
737
759
  }
760
+ } catch (error) {
761
+ // A failed nonce request takes precedence over errors from the other
762
+ // parameters.
763
+ await noncePromise
764
+ throw error
738
765
  }
739
766
 
767
+ if (noncePromise) request.nonce = await noncePromise
768
+
740
769
  if (parameters.includes('gas') && typeof gas === 'undefined')
741
770
  request.gas = await getAction(
742
771
  client,
@@ -20,7 +20,7 @@ export const darwinia = /*#__PURE__*/ defineChain({
20
20
  contracts: {
21
21
  multicall3: {
22
22
  address: '0xca11bde05977b3631167028862be2a173976ca11',
23
- blockCreated: 69420,
23
+ blockCreated: 251739,
24
24
  },
25
25
  },
26
26
  })
@@ -22,7 +22,7 @@ export const flowMainnet = /*#__PURE__*/ defineChain({
22
22
  contracts: {
23
23
  multicall3: {
24
24
  address: '0xca11bde05977b3631167028862be2a173976ca11',
25
- blockCreated: 6205,
25
+ blockCreated: 968659,
26
26
  },
27
27
  },
28
28
  blockTime: 800,
@@ -89,6 +89,18 @@ export class RlpListBoundaryExceededError extends BaseError {
89
89
  }
90
90
  }
91
91
 
92
+ export type RlpNonCanonicalErrorType = RlpNonCanonicalError & {
93
+ name: 'RlpNonCanonicalError'
94
+ }
95
+ /** Thrown when an RLP payload uses a non-minimal length prefix or wraps a single byte below `0x80` in a length prefix. */
96
+ export class RlpNonCanonicalError extends BaseError {
97
+ constructor({ reason }: { reason: string }) {
98
+ super(`RLP payload is not canonically encoded: ${reason}.`, {
99
+ name: 'RlpNonCanonicalError',
100
+ })
101
+ }
102
+ }
103
+
92
104
  export type RlpTrailingBytesErrorType = RlpTrailingBytesError & {
93
105
  name: 'RlpTrailingBytesError'
94
106
  }
package/errors/version.ts CHANGED
@@ -1 +1 @@
1
- export const version = '2.57.19'
1
+ export const version = '2.57.20'
package/index.ts CHANGED
@@ -911,6 +911,8 @@ export {
911
911
  type RlpDepthLimitExceededErrorType,
912
912
  RlpListBoundaryExceededError,
913
913
  type RlpListBoundaryExceededErrorType,
914
+ RlpNonCanonicalError,
915
+ type RlpNonCanonicalErrorType,
914
916
  RlpTrailingBytesError,
915
917
  type RlpTrailingBytesErrorType,
916
918
  SizeOverflowError,
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "viem",
3
3
  "description": "TypeScript Interface for Ethereum",
4
- "version": "2.57.19",
4
+ "version": "2.57.20",
5
5
  "main": "./_cjs/index.js",
6
6
  "module": "./_esm/index.js",
7
7
  "types": "./_types/index.d.ts",
@@ -233,7 +233,7 @@
233
233
  "@scure/bip39": "1.6.0",
234
234
  "abitype": "1.2.3",
235
235
  "isows": "1.0.7",
236
- "ox": "0.14.65",
236
+ "ox": "0.14.67",
237
237
  "ws": "8.21.0"
238
238
  },
239
239
  "license": "MIT",
@@ -652,7 +652,7 @@ function isCanonical(serialized: `0x76${string}` | `0x78${string}`) {
652
652
  : TxEnvelopeTempo.serialize(envelope)
653
653
  return serialized_parsed === serialized.toLowerCase()
654
654
  } catch {
655
- // Serialization refuses parsed values outside the safe integer range.
655
+ // An envelope that cannot be parsed or serialized has no canonical encoding.
656
656
  return false
657
657
  }
658
658
  }
@@ -17,6 +17,12 @@ export type ChecksumAddressErrorType =
17
17
  | StringToBytesErrorType
18
18
  | ErrorType
19
19
 
20
+ /**
21
+ * Returns the [EIP-55](https://eips.ethereum.org/EIPS/eip-55) checksummed form
22
+ * of an address. The input's casing is ignored.
23
+ *
24
+ * Does not validate the input; use {@link getAddress} for untrusted strings.
25
+ */
20
26
  export function checksumAddress(
21
27
  address_: Address,
22
28
  /**
@@ -31,12 +37,14 @@ export function checksumAddress(
31
37
  */
32
38
  chainId?: number | undefined,
33
39
  ): Address {
34
- if (checksumAddressCache.has(`${address_}.${chainId}`))
35
- return checksumAddressCache.get(`${address_}.${chainId}`)!
40
+ // The checksum depends only on the lowercase address, so every casing of an
41
+ // address shares one cache entry.
42
+ const lower = address_.toLowerCase()
43
+ const cacheKey = `${lower}.${chainId}`
44
+ const cached = checksumAddressCache.get(cacheKey)
45
+ if (cached) return cached
36
46
 
37
- const hexAddress = chainId
38
- ? `${chainId}${address_.toLowerCase()}`
39
- : address_.substring(2).toLowerCase()
47
+ const hexAddress = chainId ? `${chainId}${lower}` : lower.substring(2)
40
48
  const hash = keccak256(stringToBytes(hexAddress), 'bytes')
41
49
 
42
50
  const address = (
@@ -52,7 +60,7 @@ export function checksumAddress(
52
60
  }
53
61
 
54
62
  const result = `0x${address.join('')}` as const
55
- checksumAddressCache.set(`${address_}.${chainId}`, result)
63
+ checksumAddressCache.set(cacheKey, result)
56
64
  return result
57
65
  }
58
66
 
@@ -61,6 +69,23 @@ export type GetAddressErrorType =
61
69
  | IsAddressErrorType
62
70
  | ErrorType
63
71
 
72
+ /**
73
+ * Converts an address into its [EIP-55](https://eips.ethereum.org/EIPS/eip-55)
74
+ * checksummed form. Throws if the string is not a `0x`-prefixed, 20-byte hex
75
+ * string.
76
+ *
77
+ * The input's casing is ignored, so an address with a wrong checksum is
78
+ * returned with the correct one. To reject a wrong checksum, check the input
79
+ * with {@link isAddress} first.
80
+ *
81
+ * - Docs: https://viem.sh/docs/utilities/getAddress
82
+ *
83
+ * @example
84
+ * import { getAddress } from 'viem'
85
+ *
86
+ * getAddress('0x787bc77f1700dce0f8c1581c18a12d3153d1b150')
87
+ * // '0x787bc77F1700DCE0f8c1581c18A12d3153D1B150'
88
+ */
64
89
  export function getAddress(
65
90
  address: string,
66
91
  /**
@@ -19,21 +19,42 @@ export type IsAddressOptions = {
19
19
 
20
20
  export type IsAddressErrorType = ErrorType
21
21
 
22
+ /**
23
+ * Checks if a string is a valid address.
24
+ *
25
+ * In strict mode (the default), a mixed-case address must match its
26
+ * [EIP-55](https://eips.ethereum.org/EIPS/eip-55) checksum. An all-lowercase
27
+ * address has no checksum and is valid.
28
+ *
29
+ * Use this to validate user input. {@link getAddress} does not validate the
30
+ * checksum; it returns the checksummed form of any casing.
31
+ *
32
+ * - Docs: https://viem.sh/docs/utilities/isAddress
33
+ *
34
+ * @example
35
+ * import { isAddress } from 'viem'
36
+ *
37
+ * isAddress('0x787bc77F1700DCE0f8c1581c18A12d3153D1B150')
38
+ * // true
39
+ * isAddress('0x787bc77F1700DCE0f8c1581c18A12d3153D1b150') // last `B` lowercased
40
+ * // false
41
+ * isAddress('0x787bc77f1700dce0f8c1581c18a12d3153d1b150')
42
+ * // true
43
+ */
22
44
  export function isAddress(
23
45
  address: string,
24
46
  options?: IsAddressOptions | undefined,
25
47
  ): address is Address {
26
48
  const { strict = true } = options ?? {}
27
- const cacheKey = `${address}.${strict}`
49
+ if (!addressRegex.test(address)) return false
50
+ if (!strict || address.toLowerCase() === address) return true
28
51
 
29
- if (isAddressCache.has(cacheKey)) return isAddressCache.get(cacheKey)!
30
-
31
- const result = (() => {
32
- if (!addressRegex.test(address)) return false
33
- if (address.toLowerCase() === address) return true
34
- if (strict) return checksumAddress(address as Address) === address
35
- return true
36
- })()
37
- isAddressCache.set(cacheKey, result)
52
+ // Only the checksum comparison is cached; the checks above are cheaper than a
53
+ // cache lookup.
54
+ let result = isAddressCache.get(address)
55
+ if (result === undefined) {
56
+ result = checksumAddress(address as Address) === address
57
+ isAddressCache.set(address, result)
58
+ }
38
59
  return result
39
60
  }
@@ -6,6 +6,8 @@ import {
6
6
  type RlpDepthLimitExceededErrorType,
7
7
  RlpListBoundaryExceededError,
8
8
  type RlpListBoundaryExceededErrorType,
9
+ RlpNonCanonicalError,
10
+ type RlpNonCanonicalErrorType,
9
11
  RlpTrailingBytesError,
10
12
  type RlpTrailingBytesErrorType,
11
13
  } from '../../errors/encoding.js'
@@ -35,6 +37,7 @@ export type FromRlpErrorType =
35
37
  | HexToBytesErrorType
36
38
  | InvalidHexValueErrorType
37
39
  | RlpDepthLimitExceededErrorType
40
+ | RlpNonCanonicalErrorType
38
41
  | RlpTrailingBytesErrorType
39
42
  | ErrorType
40
43
 
@@ -91,6 +94,11 @@ function fromRlpCursor<to extends To = 'hex'>(
91
94
  if (prefix < 0xc0) {
92
95
  const length = readLength(cursor, prefix, 0x80)
93
96
  const bytes = cursor.readBytes(length)
97
+ // A single byte below `0x80` is its own encoding (Yellow Paper, Appendix B).
98
+ if (prefix >= 0x80 && length === 1 && bytes[0]! < 0x80)
99
+ throw new RlpNonCanonicalError({
100
+ reason: 'single byte below `0x80` has a length prefix',
101
+ })
94
102
  return (to === 'hex' ? bytesToHex(bytes) : bytes) as FromRlpReturnType<to>
95
103
  }
96
104
 
@@ -104,18 +112,42 @@ function fromRlpCursor<to extends To = 'hex'>(
104
112
  ) as {} as FromRlpReturnType<to>
105
113
  }
106
114
 
107
- type ReadLengthErrorType = BaseErrorType | ErrorType
115
+ type ReadLengthErrorType = BaseErrorType | RlpNonCanonicalErrorType | ErrorType
108
116
 
109
117
  function readLength(cursor: Cursor, prefix: number, offset: number) {
110
118
  if (offset === 0x80 && prefix < 0x80) return 1
111
119
  if (prefix <= offset + 55) return prefix - offset
112
- if (prefix === offset + 55 + 1) return cursor.readUint8()
113
- if (prefix === offset + 55 + 2) return cursor.readUint16()
114
- if (prefix === offset + 55 + 3) return cursor.readUint24()
115
- if (prefix === offset + 55 + 4) return cursor.readUint32()
120
+ // Long-form lengths must be above 55 and have no leading zero bytes
121
+ // (Yellow Paper, Appendix B).
122
+ if (prefix === offset + 55 + 1) {
123
+ const length = cursor.readUint8()
124
+ if (length <= 55) throw nonCanonicalLengthError(length)
125
+ return length
126
+ }
127
+ if (prefix === offset + 55 + 2) {
128
+ const length = cursor.readUint16()
129
+ if (length <= 0xff) throw nonCanonicalLengthError(length)
130
+ return length
131
+ }
132
+ if (prefix === offset + 55 + 3) {
133
+ const length = cursor.readUint24()
134
+ if (length <= 0xffff) throw nonCanonicalLengthError(length)
135
+ return length
136
+ }
137
+ if (prefix === offset + 55 + 4) {
138
+ const length = cursor.readUint32()
139
+ if (length <= 0xffffff) throw nonCanonicalLengthError(length)
140
+ return length
141
+ }
116
142
  throw new BaseError('Invalid RLP prefix')
117
143
  }
118
144
 
145
+ function nonCanonicalLengthError(length: number) {
146
+ return new RlpNonCanonicalError({
147
+ reason: `length \`${length}\` does not use the shortest length prefix`,
148
+ })
149
+ }
150
+
119
151
  type ReadListErrorType = RlpListBoundaryExceededErrorType | ErrorType
120
152
 
121
153
  function readList<to extends To>(
package/utils/index.ts CHANGED
@@ -14,6 +14,8 @@ export {
14
14
  parseAccount,
15
15
  } from '../accounts/utils/parseAccount.js'
16
16
  export {
17
+ InvalidPublicKeyError,
18
+ type InvalidPublicKeyErrorType,
17
19
  type PublicKeyToAddressErrorType,
18
20
  publicKeyToAddress,
19
21
  } from '../accounts/utils/publicKeyToAddress.js'
@@ -38,6 +38,10 @@ type CreateBatchSchedulerReturnType<
38
38
  export type CreateBatchSchedulerErrorType = ErrorType
39
39
 
40
40
  const schedulerCache = /*#__PURE__*/ new Map<number | string, SchedulerItem[]>()
41
+ const timerCache = /*#__PURE__*/ new Map<
42
+ number | string,
43
+ ReturnType<typeof setTimeout>
44
+ >()
41
45
 
42
46
  /** @internal */
43
47
  export function createBatchScheduler<
@@ -78,7 +82,11 @@ export function createBatchScheduler<
78
82
  })
79
83
  }
80
84
 
81
- const flush = () => schedulerCache.delete(id)
85
+ const flush = () => {
86
+ clearTimeout(timerCache.get(id))
87
+ timerCache.delete(id)
88
+ schedulerCache.delete(id)
89
+ }
82
90
 
83
91
  const getBatchedArgs = () =>
84
92
  getScheduler().map(({ args }) => args) as parameters[]
@@ -104,7 +112,7 @@ export function createBatchScheduler<
104
112
  }
105
113
 
106
114
  setScheduler({ args, resolve, reject })
107
- setTimeout(exec, wait)
115
+ timerCache.set(id, setTimeout(exec, wait))
108
116
  return promise
109
117
  },
110
118
  } as unknown as CreateBatchSchedulerReturnType<parameters, returnType>
@@ -145,19 +145,17 @@ export function getTypesForEIP712Domain({
145
145
  }: {
146
146
  domain?: TypedDataDomain | undefined
147
147
  }): TypedDataParameter[] {
148
+ // A field is part of the schema when it is present on the domain (not
149
+ // `undefined` or `null`).
148
150
  return [
149
- typeof domain?.name === 'string' && { name: 'name', type: 'string' },
150
- typeof domain?.version === 'string' && { name: 'version', type: 'string' },
151
- (typeof domain?.chainId === 'number' ||
152
- typeof domain?.chainId === 'bigint') && {
153
- name: 'chainId',
154
- type: 'uint256',
155
- },
156
- domain?.verifyingContract && {
151
+ domain?.name != null && { name: 'name', type: 'string' },
152
+ domain?.version != null && { name: 'version', type: 'string' },
153
+ domain?.chainId != null && { name: 'chainId', type: 'uint256' },
154
+ domain?.verifyingContract != null && {
157
155
  name: 'verifyingContract',
158
156
  type: 'address',
159
157
  },
160
- domain?.salt && { name: 'salt', type: 'bytes32' },
158
+ domain?.salt != null && { name: 'salt', type: 'bytes32' },
161
159
  ].filter(Boolean) as TypedDataParameter[]
162
160
  }
163
161