viem 0.3.24 → 0.3.27

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 (79) hide show
  1. package/dist/cjs/actions/public/waitForTransactionReceipt.js +14 -7
  2. package/dist/cjs/actions/public/waitForTransactionReceipt.js.map +1 -1
  3. package/dist/cjs/errors/abi.js +0 -2
  4. package/dist/cjs/errors/abi.js.map +1 -1
  5. package/dist/cjs/errors/data.js +2 -2
  6. package/dist/cjs/errors/data.js.map +1 -1
  7. package/dist/cjs/errors/version.js +1 -1
  8. package/dist/cjs/utils/abi/decodeAbiParameters.js +22 -14
  9. package/dist/cjs/utils/abi/decodeAbiParameters.js.map +1 -1
  10. package/dist/cjs/utils/abi/decodeEventLog.js +5 -5
  11. package/dist/cjs/utils/abi/decodeEventLog.js.map +1 -1
  12. package/dist/cjs/utils/data/isHex.js +2 -2
  13. package/dist/cjs/utils/data/isHex.js.map +1 -1
  14. package/dist/cjs/utils/data/size.js +1 -1
  15. package/dist/cjs/utils/data/size.js.map +1 -1
  16. package/dist/cjs/utils/data/slice.js +36 -12
  17. package/dist/cjs/utils/data/slice.js.map +1 -1
  18. package/dist/cjs/utils/hash/keccak256.js +1 -1
  19. package/dist/cjs/utils/hash/keccak256.js.map +1 -1
  20. package/dist/cjs/utils/promise/createBatchScheduler.js.map +1 -1
  21. package/dist/cjs/utils/rpc.js +49 -40
  22. package/dist/cjs/utils/rpc.js.map +1 -1
  23. package/dist/esm/actions/public/waitForTransactionReceipt.js +14 -7
  24. package/dist/esm/actions/public/waitForTransactionReceipt.js.map +1 -1
  25. package/dist/esm/errors/abi.js +0 -2
  26. package/dist/esm/errors/abi.js.map +1 -1
  27. package/dist/esm/errors/data.js +2 -2
  28. package/dist/esm/errors/data.js.map +1 -1
  29. package/dist/esm/errors/version.js +1 -1
  30. package/dist/esm/utils/abi/decodeAbiParameters.js +23 -15
  31. package/dist/esm/utils/abi/decodeAbiParameters.js.map +1 -1
  32. package/dist/esm/utils/abi/decodeEventLog.js +5 -5
  33. package/dist/esm/utils/abi/decodeEventLog.js.map +1 -1
  34. package/dist/esm/utils/data/isHex.js +2 -2
  35. package/dist/esm/utils/data/isHex.js.map +1 -1
  36. package/dist/esm/utils/data/size.js +1 -1
  37. package/dist/esm/utils/data/size.js.map +1 -1
  38. package/dist/esm/utils/data/slice.js +36 -12
  39. package/dist/esm/utils/data/slice.js.map +1 -1
  40. package/dist/esm/utils/hash/keccak256.js +1 -1
  41. package/dist/esm/utils/hash/keccak256.js.map +1 -1
  42. package/dist/esm/utils/promise/createBatchScheduler.js.map +1 -1
  43. package/dist/esm/utils/rpc.js +49 -40
  44. package/dist/esm/utils/rpc.js.map +1 -1
  45. package/dist/types/actions/public/getTransactionReceipt.d.ts +1 -1
  46. package/dist/types/actions/public/waitForTransactionReceipt.d.ts.map +1 -1
  47. package/dist/types/errors/abi.d.ts.map +1 -1
  48. package/dist/types/errors/data.d.ts +2 -1
  49. package/dist/types/errors/data.d.ts.map +1 -1
  50. package/dist/types/errors/version.d.ts +1 -1
  51. package/dist/types/types/contract.d.ts +7 -33
  52. package/dist/types/types/contract.d.ts.map +1 -1
  53. package/dist/types/types/log.d.ts +0 -2
  54. package/dist/types/types/log.d.ts.map +1 -1
  55. package/dist/types/utils/abi/decodeAbiParameters.d.ts.map +1 -1
  56. package/dist/types/utils/data/isHex.d.ts +3 -1
  57. package/dist/types/utils/data/isHex.d.ts.map +1 -1
  58. package/dist/types/utils/data/slice.d.ts +9 -3
  59. package/dist/types/utils/data/slice.d.ts.map +1 -1
  60. package/dist/types/utils/hash/keccak256.d.ts.map +1 -1
  61. package/dist/types/utils/promise/createBatchScheduler.d.ts +6 -4
  62. package/dist/types/utils/promise/createBatchScheduler.d.ts.map +1 -1
  63. package/dist/types/utils/rpc.d.ts.map +1 -1
  64. package/package.json +1 -1
  65. package/src/actions/public/getTransactionReceipt.ts +1 -1
  66. package/src/actions/public/waitForTransactionReceipt.ts +24 -6
  67. package/src/errors/abi.ts +0 -2
  68. package/src/errors/data.ts +8 -2
  69. package/src/errors/version.ts +1 -1
  70. package/src/types/contract.ts +11 -87
  71. package/src/types/log.ts +2 -2
  72. package/src/utils/abi/decodeAbiParameters.ts +36 -15
  73. package/src/utils/abi/decodeEventLog.ts +5 -5
  74. package/src/utils/data/isHex.ts +5 -2
  75. package/src/utils/data/size.ts +1 -1
  76. package/src/utils/data/slice.ts +43 -11
  77. package/src/utils/hash/keccak256.ts +3 -1
  78. package/src/utils/promise/createBatchScheduler.ts +24 -7
  79. package/src/utils/rpc.ts +59 -49
@@ -6,7 +6,6 @@ import type {
6
6
  } from 'abitype'
7
7
 
8
8
  import {
9
- AbiDecodingDataSizeInvalidError,
10
9
  AbiDecodingDataSizeTooSmallError,
11
10
  AbiDecodingZeroDataError,
12
11
  InvalidAbiDecodingTypeError,
@@ -38,8 +37,12 @@ export function decodeAbiParameters<
38
37
  >(params: Narrow<TParams>, data: Hex): DecodeAbiParametersReturnType<TParams> {
39
38
  if (data === '0x' && (params as unknown[]).length > 0)
40
39
  throw new AbiDecodingZeroDataError()
41
- if (size(data) % 32 !== 0)
42
- throw new AbiDecodingDataSizeInvalidError({ data, size: size(data) })
40
+ if (size(data) && size(data) < 32)
41
+ throw new AbiDecodingDataSizeTooSmallError({
42
+ data,
43
+ params: params as readonly AbiParameter[],
44
+ size: size(data),
45
+ })
43
46
  return decodeParams({
44
47
  data,
45
48
  params: params as readonly AbiParameter[],
@@ -102,7 +105,7 @@ function decodeParam({
102
105
  return decodeBytes(data, { param, position })
103
106
  }
104
107
 
105
- const value = slice(data, position, position + 32) as Hex
108
+ const value = slice(data, position, position + 32, { strict: true }) as Hex
106
109
  if (param.type.startsWith('uint') || param.type.startsWith('int')) {
107
110
  return decodeNumber(value, { param })
108
111
  }
@@ -139,9 +142,13 @@ function decodeArray<TParam extends AbiParameter>(
139
142
  // we will need to decode the offset of the array data.
140
143
  if (!length) {
141
144
  // Get the offset of the array data.
142
- const offset = hexToNumber(slice(data, position, position + 32))
145
+ const offset = hexToNumber(
146
+ slice(data, position, position + 32, { strict: true }),
147
+ )
143
148
  // Get the length of the array from the offset.
144
- const length = hexToNumber(slice(data, offset, offset + 32))
149
+ const length = hexToNumber(
150
+ slice(data, offset, offset + 32, { strict: true }),
151
+ )
145
152
 
146
153
  let consumed = 0
147
154
  const value: AbiParameterToPrimitiveType<TParam>[] = []
@@ -169,7 +176,9 @@ function decodeArray<TParam extends AbiParameter>(
169
176
  let consumed = 0
170
177
  const value: AbiParameterToPrimitiveType<TParam>[] = []
171
178
  for (let i = 0; i < length; ++i) {
172
- const offset = hexToNumber(slice(data, position, position + 32))
179
+ const offset = hexToNumber(
180
+ slice(data, position, position + 32, { strict: true }),
181
+ )
173
182
  const decodedChild = decodeParam({
174
183
  data: slice(data, offset),
175
184
  param,
@@ -210,15 +219,23 @@ function decodeBytes<TParam extends AbiParameter>(
210
219
  if (!size) {
211
220
  // If we don't have a size, we're dealing with a dynamic-size array
212
221
  // so we need to read the offset of the data part first.
213
- const offset = hexToNumber(slice(data, position, position + 32))
214
- const length = hexToNumber(slice(data, offset, offset + 32))
222
+ const offset = hexToNumber(
223
+ slice(data, position, position + 32, { strict: true }),
224
+ )
225
+ const length = hexToNumber(
226
+ slice(data, offset, offset + 32, { strict: true }),
227
+ )
215
228
  // If there is no length, we have zero data.
216
229
  if (length === 0) return { consumed: 32, value: '0x' }
217
- const value = slice(data, offset + 32, offset + 32 + length)
230
+ const value = slice(data, offset + 32, offset + 32 + length, {
231
+ strict: true,
232
+ })
218
233
  return { consumed: 32, value }
219
234
  }
220
235
 
221
- const value = slice(data, position, position + parseInt(size))
236
+ const value = slice(data, position, position + parseInt(size), {
237
+ strict: true,
238
+ })
222
239
  return { consumed: 32, value }
223
240
  }
224
241
 
@@ -238,12 +255,14 @@ function decodeNumber<TParam extends AbiParameter>(
238
255
  }
239
256
 
240
257
  function decodeString(data: Hex, { position }: { position: number }) {
241
- const offset = hexToNumber(slice(data, position, position + 32))
242
- const length = hexToNumber(slice(data, offset, offset + 32))
258
+ const offset = hexToNumber(
259
+ slice(data, position, position + 32, { strict: true }),
260
+ )
261
+ const length = hexToNumber(slice(data, offset, offset + 32, { strict: true }))
243
262
  // If there is no length, we have zero data (empty string).
244
263
  if (length === 0) return { consumed: 32, value: '' }
245
264
  const value = hexToString(
246
- trim(slice(data, offset + 32, offset + 32 + length)),
265
+ trim(slice(data, offset + 32, offset + 32 + length, { strict: true })),
247
266
  )
248
267
  return { consumed: 32, value }
249
268
  }
@@ -266,7 +285,9 @@ function decodeTuple<
266
285
  // If the tuple has a dynamic child, we must first decode the offset to the
267
286
  // tuple data.
268
287
  if (hasDynamicChild(param)) {
269
- const offset = hexToNumber(slice(data, position, position + 32))
288
+ const offset = hexToNumber(
289
+ slice(data, position, position + 32, { strict: true }),
290
+ )
270
291
  // Decode each component of the tuple, starting at the offset.
271
292
  for (let i = 0; i < param.components.length; ++i) {
272
293
  const component = param.components[i]
@@ -93,8 +93,8 @@ export function decodeEventLog<
93
93
  let args: any = isUnnamed ? [] : {}
94
94
 
95
95
  // Decode topics (indexed args).
96
+ const indexedInputs = inputs.filter((x) => 'indexed' in x && x.indexed)
96
97
  if (argTopics.length > 0) {
97
- const indexedInputs = inputs.filter((x) => 'indexed' in x && x.indexed)
98
98
  for (let i = 0; i < indexedInputs.length; i++) {
99
99
  const param = indexedInputs[i]
100
100
  const topic = argTopics[i]
@@ -108,15 +108,15 @@ export function decodeEventLog<
108
108
  }
109
109
 
110
110
  // Decode data (non-indexed args).
111
+ const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))
111
112
  if (data && data !== '0x') {
112
- const params = inputs.filter((x) => !('indexed' in x && x.indexed))
113
113
  try {
114
- const decodedData = decodeAbiParameters(params, data)
114
+ const decodedData = decodeAbiParameters(nonIndexedInputs, data)
115
115
  if (decodedData) {
116
116
  if (isUnnamed) args = [...args, ...decodedData]
117
117
  else {
118
- for (let i = 0; i < params.length; i++) {
119
- args[params[i].name!] = decodedData[i]
118
+ for (let i = 0; i < nonIndexedInputs.length; i++) {
119
+ args[nonIndexedInputs[i].name!] = decodedData[i]
120
120
  }
121
121
  }
122
122
  }
@@ -1,7 +1,10 @@
1
1
  import type { Hex } from '../../types/misc.js'
2
2
 
3
- export function isHex(value: unknown): value is Hex {
3
+ export function isHex(
4
+ value: unknown,
5
+ { strict = true }: { strict?: boolean } = {},
6
+ ): value is Hex {
4
7
  if (!value) return false
5
8
  if (typeof value !== 'string') return false
6
- return /^0x[0-9a-fA-F]*$/.test(value)
9
+ return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x')
7
10
  }
@@ -9,6 +9,6 @@ import { isHex } from './isHex.js'
9
9
  * @returns The size of the value (in bytes).
10
10
  */
11
11
  export function size(value: Hex | ByteArray) {
12
- if (isHex(value)) return Math.ceil((value.length - 2) / 2)
12
+ if (isHex(value, { strict: false })) return Math.ceil((value.length - 2) / 2)
13
13
  return value.length
14
14
  }
@@ -19,15 +19,38 @@ export function slice<TValue extends ByteArray | Hex>(
19
19
  value: TValue,
20
20
  start?: number,
21
21
  end?: number,
22
+ { strict }: { strict?: boolean } = {},
22
23
  ): SliceReturnType<TValue> {
23
- if (isHex(value))
24
- return sliceHex(value as Hex, start, end) as SliceReturnType<TValue>
25
- return sliceBytes(value as ByteArray, start, end) as SliceReturnType<TValue>
24
+ if (isHex(value, { strict: false }))
25
+ return sliceHex(value as Hex, start, end, {
26
+ strict,
27
+ }) as SliceReturnType<TValue>
28
+ return sliceBytes(value as ByteArray, start, end, {
29
+ strict,
30
+ }) as SliceReturnType<TValue>
26
31
  }
27
32
 
28
33
  function assertStartOffset(value: Hex | ByteArray, start?: number) {
29
34
  if (typeof start === 'number' && start > 0 && start > size(value) - 1)
30
- throw new SliceOffsetOutOfBoundsError({ offset: start, size: size(value) })
35
+ throw new SliceOffsetOutOfBoundsError({
36
+ offset: start,
37
+ position: 'start',
38
+ size: size(value),
39
+ })
40
+ }
41
+
42
+ function assertEndOffset(value: Hex | ByteArray, start?: number, end?: number) {
43
+ if (
44
+ typeof start === 'number' &&
45
+ typeof end === 'number' &&
46
+ size(value) !== end - start
47
+ ) {
48
+ throw new SliceOffsetOutOfBoundsError({
49
+ offset: end,
50
+ position: 'end',
51
+ size: size(value),
52
+ })
53
+ }
31
54
  }
32
55
 
33
56
  /**
@@ -38,12 +61,15 @@ function assertStartOffset(value: Hex | ByteArray, start?: number) {
38
61
  * @param end The end offset (in bytes).
39
62
  */
40
63
  export function sliceBytes(
41
- value: ByteArray,
64
+ value_: ByteArray,
42
65
  start?: number,
43
66
  end?: number,
67
+ { strict }: { strict?: boolean } = {},
44
68
  ): ByteArray {
45
- assertStartOffset(value, start)
46
- return value.slice(start, end)
69
+ assertStartOffset(value_, start)
70
+ const value = value_.slice(start, end)
71
+ if (strict) assertEndOffset(value, start, end)
72
+ return value
47
73
  }
48
74
 
49
75
  /**
@@ -53,10 +79,16 @@ export function sliceBytes(
53
79
  * @param start The start offset (in bytes).
54
80
  * @param end The end offset (in bytes).
55
81
  */
56
- export function sliceHex(value_: Hex, start?: number, end?: number): Hex {
82
+ export function sliceHex(
83
+ value_: Hex,
84
+ start?: number,
85
+ end?: number,
86
+ { strict }: { strict?: boolean } = {},
87
+ ): Hex {
57
88
  assertStartOffset(value_, start)
58
- const value = value_
89
+ const value = `0x${value_
59
90
  .replace('0x', '')
60
- .slice((start ?? 0) * 2, (end ?? value_.length) * 2)
61
- return `0x${value}`
91
+ .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}` as const
92
+ if (strict) assertEndOffset(value, start, end)
93
+ return value
62
94
  }
@@ -16,7 +16,9 @@ export function keccak256<TTo extends To = 'hex'>(
16
16
  to_?: TTo,
17
17
  ): Keccak256Hash<TTo> {
18
18
  const to = to_ || 'hex'
19
- const bytes = keccak_256(isHex(value) ? toBytes(value) : value)
19
+ const bytes = keccak_256(
20
+ isHex(value, { strict: false }) ? toBytes(value) : value,
21
+ )
20
22
  if (to === 'bytes') return bytes as Keccak256Hash<TTo>
21
23
  return toHex(bytes) as Keccak256Hash<TTo>
22
24
  }
@@ -10,6 +10,25 @@ type PendingPromise<TReturnType extends readonly unknown[] = any> = {
10
10
 
11
11
  type SchedulerItem = { args: unknown; pendingPromise: PendingPromise }
12
12
 
13
+ export type CreateBatchSchedulerArguments<
14
+ TParameters = unknown,
15
+ TReturnType extends readonly unknown[] = readonly unknown[],
16
+ > = {
17
+ fn: (args: TParameters[]) => Promise<TReturnType>
18
+ id: number | string
19
+ shouldSplitBatch?: (args: TParameters[]) => boolean
20
+ wait?: number
21
+ }
22
+ export type CreateBatchSchedulerReturnType<
23
+ TParameters = unknown,
24
+ TReturnType extends readonly unknown[] = readonly unknown[],
25
+ > = {
26
+ flush: () => void
27
+ schedule: TParameters extends undefined
28
+ ? (args?: TParameters) => Promise<Resolved<TReturnType>>
29
+ : (args: TParameters) => Promise<Resolved<TReturnType>>
30
+ }
31
+
13
32
  const schedulerCache = new Map<number | string, SchedulerItem[]>()
14
33
 
15
34
  export function createBatchScheduler<
@@ -20,12 +39,10 @@ export function createBatchScheduler<
20
39
  id,
21
40
  shouldSplitBatch,
22
41
  wait = 0,
23
- }: {
24
- fn: (args: TParameters[]) => Promise<TReturnType>
25
- id: number | string
26
- shouldSplitBatch?: (args: TParameters[]) => boolean
27
- wait?: number
28
- }) {
42
+ }: CreateBatchSchedulerArguments<
43
+ TParameters,
44
+ TReturnType
45
+ >): CreateBatchSchedulerReturnType<TParameters, TReturnType> {
29
46
  const exec = async () => {
30
47
  const scheduler = getScheduler()
31
48
  flush()
@@ -78,5 +95,5 @@ export function createBatchScheduler<
78
95
  setTimeout(exec, wait)
79
96
  return promise
80
97
  },
81
- }
98
+ } as unknown as CreateBatchSchedulerReturnType<TParameters, TReturnType>
82
99
  }
package/src/utils/rpc.ts CHANGED
@@ -7,6 +7,7 @@ import {
7
7
  WebSocketRequestError,
8
8
  } from '../errors/request.js'
9
9
 
10
+ import { createBatchScheduler } from './promise/createBatchScheduler.js'
10
11
  import { withTimeout } from './promise/withTimeout.js'
11
12
  import { stringify } from './stringify.js'
12
13
 
@@ -146,61 +147,70 @@ export async function getSocket(url_: string) {
146
147
  // If the socket already exists, return it.
147
148
  if (socket) return socket
148
149
 
149
- let WebSocket = await import('isomorphic-ws')
150
- // Workaround for Vite.
151
- // https://github.com/vitejs/vite/issues/9703
152
- // TODO: Remove when issue is resolved.
153
- if (
154
- (WebSocket as unknown as { default?: typeof WebSocket }).default
155
- ?.constructor
156
- )
157
- WebSocket = (WebSocket as unknown as { default: typeof WebSocket }).default
158
- else WebSocket = WebSocket.WebSocket
159
-
160
- const webSocket = new WebSocket(url)
161
-
162
- // Set up a cache for incoming "synchronous" requests.
163
- const requests = new Map<Id, CallbackFn>()
150
+ const { schedule } = createBatchScheduler<undefined, [Socket]>({
151
+ id: urlKey,
152
+ fn: async () => {
153
+ let WebSocket = await import('isomorphic-ws')
154
+ // Workaround for Vite.
155
+ // https://github.com/vitejs/vite/issues/9703
156
+ // TODO: Remove when issue is resolved.
157
+ if (
158
+ (WebSocket as unknown as { default?: typeof WebSocket }).default
159
+ ?.constructor
160
+ )
161
+ WebSocket = (WebSocket as unknown as { default: typeof WebSocket })
162
+ .default
163
+ else WebSocket = WebSocket.WebSocket
164
+
165
+ const webSocket = new WebSocket(url)
166
+
167
+ // Set up a cache for incoming "synchronous" requests.
168
+ const requests = new Map<Id, CallbackFn>()
169
+
170
+ // Set up a cache for subscriptions (eth_subscribe).
171
+ const subscriptions = new Map<Id, CallbackFn>()
172
+
173
+ const onMessage: (event: MessageEvent) => void = ({ data }) => {
174
+ const message: RpcResponse = JSON.parse(data as string)
175
+ const isSubscription = message.method === 'eth_subscription'
176
+ const id = isSubscription ? message.params.subscription : message.id
177
+ const cache = isSubscription ? subscriptions : requests
178
+ const callback = cache.get(id)
179
+ if (callback) callback({ data })
180
+ if (!isSubscription) cache.delete(id)
181
+ }
182
+ const onClose = () => {
183
+ sockets.delete(urlKey)
184
+ webSocket.removeEventListener('close', onClose)
185
+ webSocket.removeEventListener('message', onMessage)
186
+ }
164
187
 
165
- // Set up a cache for subscriptions (eth_subscribe).
166
- const subscriptions = new Map<Id, CallbackFn>()
188
+ // Setup event listeners for RPC & subscription responses.
189
+ webSocket.addEventListener('close', onClose)
190
+ webSocket.addEventListener('message', onMessage)
167
191
 
168
- const onMessage: (event: MessageEvent) => void = ({ data }) => {
169
- const message: RpcResponse = JSON.parse(data as string)
170
- const isSubscription = message.method === 'eth_subscription'
171
- const id = isSubscription ? message.params.subscription : message.id
172
- const cache = isSubscription ? subscriptions : requests
173
- const callback = cache.get(id)
174
- if (callback) callback({ data })
175
- if (!isSubscription) cache.delete(id)
176
- }
177
- const onClose = () => {
178
- sockets.delete(urlKey)
179
- webSocket.removeEventListener('close', onClose)
180
- webSocket.removeEventListener('message', onMessage)
181
- }
182
-
183
- // Setup event listeners for RPC & subscription responses.
184
- webSocket.addEventListener('close', onClose)
185
- webSocket.addEventListener('message', onMessage)
192
+ // Wait for the socket to open.
193
+ if (webSocket.readyState === WebSocket.CONNECTING) {
194
+ await new Promise((resolve, reject) => {
195
+ if (!webSocket) return
196
+ webSocket.onopen = resolve
197
+ webSocket.onerror = reject
198
+ })
199
+ }
186
200
 
187
- // Wait for the socket to open.
188
- if (webSocket.readyState === WebSocket.CONNECTING) {
189
- await new Promise((resolve, reject) => {
190
- if (!webSocket) return
191
- webSocket.onopen = resolve
192
- webSocket.onerror = reject
193
- })
194
- }
201
+ // Create a new socket instance.
202
+ socket = Object.assign(webSocket, {
203
+ requests,
204
+ subscriptions,
205
+ })
206
+ sockets.set(urlKey, socket)
195
207
 
196
- // Create a new socket instance.
197
- socket = Object.assign(webSocket, {
198
- requests,
199
- subscriptions,
208
+ return [socket]
209
+ },
200
210
  })
201
- sockets.set(urlKey, socket)
202
211
 
203
- return socket
212
+ const [_, [socket_]] = await schedule()
213
+ return socket_
204
214
  }
205
215
 
206
216
  function webSocket(