@wagmi/core 0.10.10 → 1.0.0-next.1

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 (34) hide show
  1. package/README.md +2 -2
  2. package/connectors/walletConnectV1/package.json +4 -0
  3. package/dist/{chunk-VQG3VKOR.js → chunk-LF3Y5HFO.js} +714 -1242
  4. package/dist/index-fc9ab085.d.ts +22 -0
  5. package/dist/index.d.ts +1039 -1291
  6. package/dist/index.js +17 -45
  7. package/dist/internal/index.d.ts +18 -8
  8. package/dist/internal/index.js +5 -3
  9. package/dist/internal/test.d.ts +771 -9
  10. package/dist/internal/test.js +46 -34
  11. package/dist/providers/alchemy.d.ts +4 -6
  12. package/dist/providers/alchemy.js +9 -26
  13. package/dist/providers/infura.d.ts +4 -6
  14. package/dist/providers/infura.js +9 -26
  15. package/dist/providers/jsonRpc.d.ts +4 -7
  16. package/dist/providers/jsonRpc.js +4 -20
  17. package/dist/providers/public.d.ts +4 -7
  18. package/dist/providers/public.js +3 -18
  19. package/dist/window.d.ts +7 -0
  20. package/dist/window.js +0 -0
  21. package/internal/dist/wagmi-core-internal.cjs.d.ts +11 -0
  22. package/internal/dist/wagmi-core-internal.cjs.js +16 -0
  23. package/package.json +11 -6
  24. package/providers/alchemy/dist/wagmi-core-providers-alchemy.cjs.d.ts +11 -0
  25. package/providers/alchemy/dist/wagmi-core-providers-alchemy.cjs.js +16 -0
  26. package/providers/infura/dist/wagmi-core-providers-infura.cjs.d.ts +11 -0
  27. package/providers/infura/dist/wagmi-core-providers-infura.cjs.js +16 -0
  28. package/providers/jsonRpc/dist/wagmi-core-providers-jsonRpc.cjs.d.ts +11 -0
  29. package/providers/jsonRpc/dist/wagmi-core-providers-jsonRpc.cjs.js +16 -0
  30. package/providers/public/dist/wagmi-core-providers-public.cjs.d.ts +11 -0
  31. package/providers/public/dist/wagmi-core-providers-public.cjs.js +16 -0
  32. package/window/package.json +4 -0
  33. package/dist/getContract-2443b222.d.ts +0 -310
  34. package/dist/index-35b6525c.d.ts +0 -49
@@ -9,23 +9,23 @@ import {
9
9
  } from "./chunk-MQXBDTVK.js";
10
10
 
11
11
  // src/utils/configureChains.ts
12
- import { providers } from "ethers";
13
- function configureChains(defaultChains, providers2, {
14
- minQuorum = 1,
12
+ import { createPublicClient, fallback, http, webSocket } from "viem";
13
+ function configureChains(defaultChains, providers, {
14
+ batch = { multicall: { wait: 32 } },
15
15
  pollingInterval = 4e3,
16
- targetQuorum = 1,
16
+ rank,
17
+ retryCount,
18
+ retryDelay,
17
19
  stallTimeout
18
20
  } = {}) {
19
21
  if (!defaultChains.length)
20
22
  throw new Error("must have at least one chain");
21
- if (targetQuorum < minQuorum)
22
- throw new Error("quorum cannot be lower than minQuorum");
23
23
  let chains = [];
24
- const providers_ = {};
25
- const webSocketProviders_ = {};
24
+ const httpUrls = {};
25
+ const wsUrls = {};
26
26
  for (const chain of defaultChains) {
27
27
  let configExists = false;
28
- for (const provider of providers2) {
28
+ for (const provider of providers) {
29
29
  const apiConfig = provider(chain);
30
30
  if (!apiConfig)
31
31
  continue;
@@ -33,14 +33,14 @@ function configureChains(defaultChains, providers2, {
33
33
  if (!chains.some(({ id }) => id === chain.id)) {
34
34
  chains = [...chains, apiConfig.chain];
35
35
  }
36
- providers_[chain.id] = [
37
- ...providers_[chain.id] || [],
38
- apiConfig.provider
36
+ httpUrls[chain.id] = [
37
+ ...httpUrls[chain.id] || [],
38
+ ...apiConfig.rpcUrls.http
39
39
  ];
40
- if (apiConfig.webSocketProvider) {
41
- webSocketProviders_[chain.id] = [
42
- ...webSocketProviders_[chain.id] || [],
43
- apiConfig.webSocketProvider
40
+ if (apiConfig.rpcUrls.webSocket) {
41
+ wsUrls[chain.id] = [
42
+ ...wsUrls[chain.id] || [],
43
+ ...apiConfig.rpcUrls.webSocket
44
44
  ];
45
45
  }
46
46
  }
@@ -57,121 +57,89 @@ function configureChains(defaultChains, providers2, {
57
57
  }
58
58
  return {
59
59
  chains,
60
- provider: ({ chainId }) => {
60
+ publicClient: ({ chainId }) => {
61
61
  const activeChain = chains.find((x) => x.id === chainId) ?? defaultChains[0];
62
- const chainProviders = providers_[activeChain.id];
63
- if (!chainProviders || !chainProviders[0])
62
+ const chainHttpUrls = httpUrls[activeChain.id];
63
+ if (!chainHttpUrls || !chainHttpUrls[0])
64
64
  throw new Error(`No providers configured for chain "${activeChain.id}"`);
65
- let provider;
66
- if (chainProviders.length === 1) {
67
- provider = chainProviders[0]();
68
- } else {
69
- provider = fallbackProvider(targetQuorum, minQuorum, chainProviders, {
70
- stallTimeout
71
- });
72
- }
73
- if (activeChain.id === 42220) {
74
- provider.formatter.formats.block = {
75
- ...provider.formatter.formats.block,
76
- difficulty: () => 0,
77
- gasLimit: () => 0
78
- };
79
- }
80
- return Object.assign(provider, {
81
- chains,
65
+ const publicClient = createPublicClient({
66
+ batch,
67
+ chain: activeChain,
68
+ transport: fallback(
69
+ chainHttpUrls.map((url) => http(url, { timeout: stallTimeout })),
70
+ { rank, retryCount, retryDelay }
71
+ ),
82
72
  pollingInterval
83
73
  });
74
+ return Object.assign(publicClient, {
75
+ chains
76
+ });
84
77
  },
85
- webSocketProvider: ({ chainId }) => {
78
+ webSocketPublicClient: ({ chainId }) => {
86
79
  const activeChain = chains.find((x) => x.id === chainId) ?? defaultChains[0];
87
- const chainWebSocketProviders = webSocketProviders_[activeChain.id];
88
- if (!chainWebSocketProviders)
80
+ const chainWsUrls = wsUrls[activeChain.id];
81
+ if (!chainWsUrls || !chainWsUrls[0])
89
82
  return void 0;
90
- const provider = chainWebSocketProviders[0]?.();
91
- if (provider && activeChain.id === 42220) {
92
- provider.formatter.formats.block = {
93
- ...provider.formatter.formats.block,
94
- difficulty: () => 0,
95
- gasLimit: () => 0
96
- };
97
- }
98
- return Object.assign(provider || {}, {
83
+ const publicClient = createPublicClient({
84
+ batch,
85
+ chain: activeChain,
86
+ transport: fallback(
87
+ chainWsUrls.map((url) => webSocket(url, { timeout: stallTimeout })),
88
+ { rank, retryCount, retryDelay }
89
+ ),
90
+ pollingInterval
91
+ });
92
+ return Object.assign(publicClient, {
99
93
  chains
100
94
  });
101
95
  }
102
96
  };
103
97
  }
104
- function fallbackProvider(targetQuorum, minQuorum, providers_, { stallTimeout }) {
105
- try {
106
- return new providers.FallbackProvider(
107
- providers_.map((chainProvider, index) => {
108
- const provider = chainProvider();
109
- return {
110
- provider,
111
- priority: provider.priority ?? index,
112
- stallTimeout: provider.stallTimeout ?? stallTimeout,
113
- weight: provider.weight
114
- };
115
- }),
116
- targetQuorum
98
+
99
+ // src/errors.ts
100
+ import { ConnectorNotFoundError } from "@wagmi/connectors";
101
+ var ChainMismatchError = class extends Error {
102
+ constructor({
103
+ activeChain,
104
+ targetChain
105
+ }) {
106
+ super(
107
+ `Chain mismatch: Expected "${targetChain}", received "${activeChain}".`
117
108
  );
118
- } catch (error) {
119
- if (error?.message?.includes(
120
- "quorum will always fail; larger than total weight"
121
- )) {
122
- if (targetQuorum === minQuorum)
123
- throw error;
124
- return fallbackProvider(targetQuorum - 1, minQuorum, providers_, {
125
- stallTimeout
126
- });
127
- }
128
- throw error;
109
+ this.name = "ChainMismatchError";
129
110
  }
130
- }
131
-
132
- // src/client.ts
133
- import { persist, subscribeWithSelector } from "zustand/middleware";
134
- import { createStore } from "zustand/vanilla";
135
-
136
- // src/utils/assertActiveChain.ts
137
- function assertActiveChain({
138
- chainId,
139
- signer
140
- }) {
141
- const { chain: activeChain, chains } = getNetwork();
142
- const activeChainId = activeChain?.id;
143
- if (activeChainId && chainId !== activeChainId) {
144
- throw new ChainMismatchError({
145
- activeChain: chains.find((x) => x.id === activeChainId)?.name ?? `Chain ${activeChainId}`,
146
- targetChain: chains.find((x) => x.id === chainId)?.name ?? `Chain ${chainId}`
147
- });
111
+ };
112
+ var ChainNotConfiguredError = class extends Error {
113
+ constructor({
114
+ chainId,
115
+ connectorId
116
+ }) {
117
+ super(
118
+ `Chain "${chainId}" not configured${connectorId ? ` for connector "${connectorId}"` : ""}.`
119
+ );
120
+ this.name = "ChainNotConfigured";
148
121
  }
149
- if (signer) {
150
- const signerChainId = signer.provider?.network?.chainId;
151
- if (signerChainId && chainId !== signerChainId) {
152
- const connector = getClient().connector;
153
- throw new ChainNotConfiguredError({
154
- chainId,
155
- connectorId: connector?.id ?? "unknown"
156
- });
157
- }
122
+ };
123
+ var ConnectorAlreadyConnectedError = class extends Error {
124
+ constructor() {
125
+ super(...arguments);
126
+ this.name = "ConnectorAlreadyConnectedError";
127
+ this.message = "Connector already connected";
158
128
  }
159
- }
160
-
161
- // src/utils/debounce.ts
162
- function debounce(fn, waitTime = 0) {
163
- let timeout;
164
- return function(...args) {
165
- if (!waitTime)
166
- return fn(...args);
167
- if (timeout)
168
- clearTimeout(timeout);
169
- timeout = setTimeout(function() {
170
- timeout = null;
171
- fn(...args);
172
- }, waitTime);
173
- };
174
- }
129
+ };
130
+ var ClientChainsNotFound = class extends Error {
131
+ constructor() {
132
+ super(...arguments);
133
+ this.name = "ClientChainsNotFound";
134
+ this.message = "No chains were found on the wagmi Client. Some functions that require a chain may not work.";
135
+ }
136
+ };
137
+ var SwitchChainNotSupportedError = class extends Error {
138
+ constructor({ connector }) {
139
+ super(`"${connector.name}" does not support programmatic chain switching.`);
140
+ this.name = "SwitchChainNotSupportedError";
141
+ }
142
+ };
175
143
 
176
144
  // src/utils/deepEqual.ts
177
145
  function deepEqual(a, b) {
@@ -213,7 +181,6 @@ function deepEqual(a, b) {
213
181
  }
214
182
 
215
183
  // src/utils/deserialize.ts
216
- import { BigNumber } from "ethers";
217
184
  var findAndReplace = (cacheRef, {
218
185
  find,
219
186
  replace
@@ -240,136 +207,51 @@ var findAndReplace = (cacheRef, {
240
207
  };
241
208
  function deserialize(cachedString) {
242
209
  const cache = JSON.parse(cachedString);
243
- const deserializedCacheWithBigNumbers = findAndReplace(cache, {
244
- find: (data) => data.type === "BigNumber",
245
- replace: (data) => BigNumber.from(data.hex)
210
+ const deserializedCacheWithBigInts = findAndReplace(cache, {
211
+ find: (data) => typeof data === "string" && data.startsWith("#bigint."),
212
+ replace: (data) => BigInt(data.replace("#bigint.", ""))
246
213
  });
247
- return deserializedCacheWithBigNumbers;
248
- }
249
-
250
- // src/utils/normalizeFunctionName.ts
251
- import { BigNumber as BigNumber2 } from "ethers";
252
- import { FunctionFragment, isAddress } from "ethers/lib/utils.js";
253
- function normalizeFunctionName({
254
- contract,
255
- functionName,
256
- args = []
257
- }) {
258
- if (functionName in contract.functions)
259
- return functionName;
260
- const argsLength = args?.length ?? 0;
261
- const overloadFunctions = Object.keys(contract.functions).filter((x) => x.startsWith(`${functionName}(`)).map((x) => ({ name: x, fragment: FunctionFragment.fromString(x) })).filter((x) => argsLength === x.fragment.inputs.length);
262
- for (const overloadFunction of overloadFunctions) {
263
- const matched = args.every((arg, index) => {
264
- const abiParameter = overloadFunction.fragment.inputs[index];
265
- return isArgOfType(arg, abiParameter);
266
- });
267
- if (matched)
268
- return overloadFunction.name;
269
- }
270
- return functionName;
271
- }
272
- function isArgOfType(arg, abiParameter) {
273
- const argType = typeof arg;
274
- const abiParameterType = abiParameter.type;
275
- switch (abiParameterType) {
276
- case "address":
277
- return isAddress(arg);
278
- case "bool":
279
- return argType === "boolean";
280
- case "function":
281
- return argType === "string";
282
- case "string":
283
- return argType === "string";
284
- default: {
285
- if (abiParameterType === "tuple" && "components" in abiParameter)
286
- return Object.values(abiParameter.components).every(
287
- (component, index) => {
288
- return isArgOfType(
289
- Object.values(arg)[index],
290
- component
291
- );
292
- }
293
- );
294
- if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(
295
- abiParameterType
296
- ))
297
- return argType === "number" || argType === "bigint" || BigNumber2.isBigNumber(arg);
298
- if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
299
- return argType === "string" || arg instanceof Uint8Array;
300
- if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
301
- return Array.isArray(arg) && arg.every(
302
- (x) => isArgOfType(x, {
303
- ...abiParameter,
304
- type: abiParameterType.replace(/(\[[0-9]{0,}\])$/, "")
305
- })
306
- );
307
- }
308
- return false;
309
- }
310
- }
214
+ return deserializedCacheWithBigInts;
311
215
  }
312
216
 
313
- // src/utils/logger.ts
314
- function logWarn(message) {
315
- getClient()?.config.logger?.warn?.(message);
316
- }
317
-
318
- // src/utils/minimizeContractInterface.ts
319
- import { Contract } from "ethers";
320
- import { FormatTypes } from "ethers/lib/utils.js";
321
- function minimizeContractInterface(config) {
322
- try {
323
- const minimizedAbi = config.abi.filter(
324
- (x) => x.type === "function" && x.name === config.functionName
325
- );
326
- if (minimizedAbi.length === 0)
327
- throw new Error("Invalid ABI");
328
- return minimizedAbi;
329
- } catch (error) {
330
- const abi = Contract.getInterface(config.abi).format(
331
- FormatTypes.full
332
- );
333
- const minimizedInterface = Array.isArray(abi) ? abi : [abi];
334
- return minimizedInterface.filter((i) => i.includes(config.functionName));
335
- }
217
+ // src/utils/getParameters.ts
218
+ function getCallParameters(args) {
219
+ return {
220
+ accessList: args.accessList,
221
+ blockNumber: args.blockNumber,
222
+ blockTag: args.blockTag,
223
+ data: args.data,
224
+ gas: args.gas,
225
+ gasPrice: args.gasPrice,
226
+ maxFeePerGas: args.maxFeePerGas,
227
+ maxPriorityFeePerGas: args.maxPriorityFeePerGas,
228
+ nonce: args.nonce,
229
+ to: args.to,
230
+ value: args.value
231
+ };
336
232
  }
337
-
338
- // src/utils/normalizeChainId.ts
339
- function normalizeChainId(chainId) {
340
- if (typeof chainId === "string")
341
- return Number.parseInt(
342
- chainId,
343
- chainId.trim().substring(0, 2) === "0x" ? 16 : 10
344
- );
345
- if (typeof chainId === "bigint")
346
- return Number(chainId);
347
- return chainId;
233
+ function getSendTransactionParameters(args) {
234
+ return {
235
+ accessList: args.accessList,
236
+ data: args.data,
237
+ gas: args.gas,
238
+ gasPrice: args.gasPrice,
239
+ maxFeePerGas: args.maxFeePerGas,
240
+ maxPriorityFeePerGas: args.maxPriorityFeePerGas,
241
+ nonce: args.nonce,
242
+ to: args.to,
243
+ value: args.value
244
+ };
348
245
  }
349
246
 
350
- // src/utils/parseContractResult.ts
351
- import { Contract as Contract2 } from "ethers";
352
- function isPlainArray(value) {
353
- return Array.isArray(value) && Object.keys(value).length === value.length;
354
- }
355
- function parseContractResult({
356
- abi,
357
- data,
358
- functionName
359
- }) {
360
- if (data && isPlainArray(data)) {
361
- const iface = Contract2.getInterface(abi);
362
- const fragment = iface.getFunction(functionName);
363
- const isTuple = (fragment.outputs?.length || 0) > 1;
364
- const data_ = isTuple ? data : [data];
365
- const encodedResult = iface.encodeFunctionResult(functionName, data_);
366
- const decodedResult = iface.decodeFunctionResult(
367
- functionName,
368
- encodedResult
369
- );
370
- return isTuple ? decodedResult : decodedResult[0];
371
- }
372
- return data;
247
+ // src/utils/getUnit.ts
248
+ import { weiUnits } from "viem";
249
+ function getUnit(unit) {
250
+ if (typeof unit === "number")
251
+ return unit;
252
+ if (unit === "wei")
253
+ return 0;
254
+ return Math.abs(weiUnits[unit]);
373
255
  }
374
256
 
375
257
  // src/utils/serialize.ts
@@ -421,11 +303,18 @@ function createReplacer(replacer, circularReplacer) {
421
303
  function serialize(value, replacer, indent, circularReplacer) {
422
304
  return JSON.stringify(
423
305
  value,
424
- createReplacer(replacer, circularReplacer),
306
+ createReplacer((key, value_) => {
307
+ const value2 = typeof value_ === "bigint" ? `#bigint.${value_.toString()}` : value_;
308
+ return replacer?.(key, value2) || value2;
309
+ }, circularReplacer),
425
310
  indent ?? void 0
426
311
  );
427
312
  }
428
313
 
314
+ // src/client.ts
315
+ import { persist, subscribeWithSelector } from "zustand/middleware";
316
+ import { createStore } from "zustand/vanilla";
317
+
429
318
  // src/storage.ts
430
319
  var noopStorage = {
431
320
  getItem: (_key) => "",
@@ -471,27 +360,27 @@ var Client = class {
471
360
  constructor({
472
361
  autoConnect = false,
473
362
  connectors = [new InjectedConnector()],
474
- provider,
363
+ publicClient,
475
364
  storage = createStorage({
476
365
  storage: typeof window !== "undefined" ? window.localStorage : noopStorage
477
366
  }),
478
367
  logger = {
479
368
  warn: console.warn
480
369
  },
481
- webSocketProvider
370
+ webSocketPublicClient
482
371
  }) {
483
372
  __privateAdd(this, _addEffects);
484
- this.providers = /* @__PURE__ */ new Map();
485
- this.webSocketProviders = /* @__PURE__ */ new Map();
373
+ this.publicClients = /* @__PURE__ */ new Map();
374
+ this.webSocketPublicClients = /* @__PURE__ */ new Map();
486
375
  __privateAdd(this, _isAutoConnecting, void 0);
487
376
  __privateAdd(this, _lastUsedConnector, void 0);
488
377
  this.config = {
489
378
  autoConnect,
490
379
  connectors,
491
380
  logger,
492
- provider,
381
+ publicClient,
493
382
  storage,
494
- webSocketProvider
383
+ webSocketPublicClient
495
384
  };
496
385
  let status = "disconnected";
497
386
  let chainId;
@@ -504,14 +393,16 @@ var Client = class {
504
393
  } catch (_error) {
505
394
  }
506
395
  }
396
+ const connectors_ = typeof connectors === "function" ? connectors() : connectors;
397
+ connectors_.forEach((connector) => connector.setStorage(storage));
507
398
  this.store = createStore(
508
399
  subscribeWithSelector(
509
400
  persist(
510
401
  () => ({
511
- connectors: typeof connectors === "function" ? connectors() : connectors,
512
- provider: this.getProvider({ chainId }),
402
+ connectors: connectors_,
403
+ publicClient: this.getPublicClient({ chainId }),
513
404
  status,
514
- webSocketProvider: this.getWebSocketProvider({ chainId })
405
+ webSocketPublicClient: this.getWebSocketPublicClient({ chainId })
515
406
  }),
516
407
  {
517
408
  name: storeKey,
@@ -554,8 +445,8 @@ var Client = class {
554
445
  get lastUsedChainId() {
555
446
  return this.data?.chain?.id;
556
447
  }
557
- get provider() {
558
- return this.store.getState().provider;
448
+ get publicClient() {
449
+ return this.store.getState().publicClient;
559
450
  }
560
451
  get status() {
561
452
  return this.store.getState().status;
@@ -563,8 +454,8 @@ var Client = class {
563
454
  get subscribe() {
564
455
  return this.store.subscribe;
565
456
  }
566
- get webSocketProvider() {
567
- return this.store.getState().webSocketProvider;
457
+ get webSocketPublicClient() {
458
+ return this.store.getState().webSocketPublicClient;
568
459
  }
569
460
  setState(updater) {
570
461
  const newState = typeof updater === "function" ? updater(this.store.getState()) : updater;
@@ -625,27 +516,30 @@ var Client = class {
625
516
  __privateSet(this, _isAutoConnecting, false);
626
517
  return this.data;
627
518
  }
628
- getProvider({ bust, chainId } = {}) {
629
- let provider_ = this.providers.get(chainId ?? -1);
630
- if (provider_ && !bust)
631
- return provider_;
632
- const { provider } = this.config;
633
- provider_ = typeof provider === "function" ? provider({ chainId }) : provider;
634
- this.providers.set(chainId ?? -1, provider_);
635
- return provider_;
636
- }
637
- getWebSocketProvider({
638
- bust,
639
- chainId
640
- } = {}) {
641
- let webSocketProvider_ = this.webSocketProviders.get(chainId ?? -1);
642
- if (webSocketProvider_ && !bust)
643
- return webSocketProvider_;
644
- const { webSocketProvider } = this.config;
645
- webSocketProvider_ = typeof webSocketProvider === "function" ? webSocketProvider({ chainId }) : webSocketProvider;
646
- if (webSocketProvider_)
647
- this.webSocketProviders.set(chainId ?? -1, webSocketProvider_);
648
- return webSocketProvider_;
519
+ getPublicClient({ chainId } = {}) {
520
+ let publicClient_ = this.publicClients.get(-1);
521
+ if (publicClient_ && publicClient_?.chain.id === chainId)
522
+ return publicClient_;
523
+ publicClient_ = this.publicClients.get(chainId ?? -1);
524
+ if (publicClient_)
525
+ return publicClient_;
526
+ const { publicClient } = this.config;
527
+ publicClient_ = typeof publicClient === "function" ? publicClient({ chainId }) : publicClient;
528
+ this.publicClients.set(chainId ?? -1, publicClient_);
529
+ return publicClient_;
530
+ }
531
+ getWebSocketPublicClient({ chainId } = {}) {
532
+ let webSocketPublicClient_ = this.webSocketPublicClients.get(-1);
533
+ if (webSocketPublicClient_ && webSocketPublicClient_?.chain.id === chainId)
534
+ return webSocketPublicClient_;
535
+ webSocketPublicClient_ = this.webSocketPublicClients.get(chainId ?? -1);
536
+ if (webSocketPublicClient_)
537
+ return webSocketPublicClient_;
538
+ const { webSocketPublicClient } = this.config;
539
+ webSocketPublicClient_ = typeof webSocketPublicClient === "function" ? webSocketPublicClient({ chainId }) : webSocketPublicClient;
540
+ if (webSocketPublicClient_)
541
+ this.webSocketPublicClients.set(chainId ?? -1, webSocketPublicClient_);
542
+ return webSocketPublicClient_;
649
543
  }
650
544
  setLastUsedConnector(lastUsedConnector = null) {
651
545
  this.storage?.setItem("wallet", lastUsedConnector);
@@ -680,18 +574,17 @@ addEffects_fn = function() {
680
574
  connector.on?.("error", onError);
681
575
  }
682
576
  );
683
- const { provider, webSocketProvider } = this.config;
684
- const subscribeProvider = typeof provider === "function";
685
- const subscribeWebSocketProvider = typeof webSocketProvider === "function";
686
- if (subscribeProvider || subscribeWebSocketProvider)
577
+ const { publicClient, webSocketPublicClient } = this.config;
578
+ const subscribePublicClient = typeof publicClient === "function";
579
+ const subscribeWebSocketPublicClient = typeof webSocketPublicClient === "function";
580
+ if (subscribePublicClient || subscribeWebSocketPublicClient)
687
581
  this.store.subscribe(
688
582
  ({ data }) => data?.chain?.id,
689
583
  (chainId) => {
690
584
  this.setState((x) => ({
691
585
  ...x,
692
- provider: this.getProvider({ bust: true, chainId }),
693
- webSocketProvider: this.getWebSocketProvider({
694
- bust: true,
586
+ publicClient: this.getPublicClient({ chainId }),
587
+ webSocketPublicClient: this.getWebSocketPublicClient({
695
588
  chainId
696
589
  })
697
590
  }));
@@ -714,10 +607,7 @@ function getClient() {
714
607
  }
715
608
 
716
609
  // src/actions/accounts/connect.ts
717
- async function connect({
718
- chainId,
719
- connector
720
- }) {
610
+ async function connect({ chainId, connector }) {
721
611
  const client2 = getClient();
722
612
  const activeConnector = client2.connector;
723
613
  if (activeConnector && connector.id === activeConnector.id)
@@ -756,7 +646,12 @@ async function disconnect() {
756
646
  }
757
647
 
758
648
  // src/actions/accounts/fetchBalance.ts
759
- import { formatUnits as formatUnits3, parseBytes32String as parseBytes32String2 } from "ethers/lib/utils.js";
649
+ import {
650
+ ContractFunctionExecutionError as ContractFunctionExecutionError3,
651
+ formatUnits as formatUnits2,
652
+ hexToString as hexToString2,
653
+ trim as trim2
654
+ } from "viem";
760
655
 
761
656
  // src/constants/abis.ts
762
657
  var erc20ABI = [
@@ -1477,49 +1372,6 @@ var erc721ABI = [
1477
1372
  outputs: []
1478
1373
  }
1479
1374
  ];
1480
- var multicallABI = [
1481
- {
1482
- inputs: [
1483
- {
1484
- components: [
1485
- {
1486
- name: "target",
1487
- type: "address"
1488
- },
1489
- {
1490
- name: "allowFailure",
1491
- type: "bool"
1492
- },
1493
- {
1494
- name: "callData",
1495
- type: "bytes"
1496
- }
1497
- ],
1498
- name: "calls",
1499
- type: "tuple[]"
1500
- }
1501
- ],
1502
- name: "aggregate3",
1503
- outputs: [
1504
- {
1505
- components: [
1506
- {
1507
- name: "success",
1508
- type: "bool"
1509
- },
1510
- {
1511
- name: "returnData",
1512
- type: "bytes"
1513
- }
1514
- ],
1515
- name: "returnData",
1516
- type: "tuple[]"
1517
- }
1518
- ],
1519
- stateMutability: "view",
1520
- type: "function"
1521
- }
1522
- ];
1523
1375
  var erc4626ABI = [
1524
1376
  {
1525
1377
  anonymous: false,
@@ -2029,23 +1881,17 @@ var erc4626ABI = [
2029
1881
  }
2030
1882
  ];
2031
1883
 
2032
- // src/constants/units.ts
2033
- var units = [
2034
- "wei",
2035
- "kwei",
2036
- "mwei",
2037
- "gwei",
2038
- "szabo",
2039
- "finney",
2040
- "ether"
2041
- ];
2042
-
2043
1884
  // src/actions/contracts/fetchToken.ts
2044
- import { formatUnits, parseBytes32String } from "ethers/lib/utils.js";
1885
+ import {
1886
+ ContractFunctionExecutionError,
1887
+ formatUnits,
1888
+ hexToString,
1889
+ trim
1890
+ } from "viem";
2045
1891
  async function fetchToken({
2046
1892
  address,
2047
1893
  chainId,
2048
- formatUnits: units2 = "ether"
1894
+ formatUnits: unit = 18
2049
1895
  }) {
2050
1896
  async function fetchToken_({ abi }) {
2051
1897
  const erc20Config = { address, abi, chainId };
@@ -2064,7 +1910,7 @@ async function fetchToken({
2064
1910
  name,
2065
1911
  symbol,
2066
1912
  totalSupply: {
2067
- formatted: formatUnits(totalSupply, units2),
1913
+ formatted: formatUnits(totalSupply, getUnit(unit)),
2068
1914
  value: totalSupply
2069
1915
  }
2070
1916
  };
@@ -2072,13 +1918,13 @@ async function fetchToken({
2072
1918
  try {
2073
1919
  return await fetchToken_({ abi: erc20ABI });
2074
1920
  } catch (err) {
2075
- if (err instanceof ContractResultDecodeError) {
1921
+ if (err instanceof ContractFunctionExecutionError) {
2076
1922
  const { name, symbol, ...rest } = await fetchToken_({
2077
1923
  abi: erc20ABI_bytes32
2078
1924
  });
2079
1925
  return {
2080
- name: parseBytes32String(name),
2081
- symbol: parseBytes32String(symbol),
1926
+ name: hexToString(trim(name, { dir: "right" })),
1927
+ symbol: hexToString(trim(symbol, { dir: "right" })),
2082
1928
  ...rest
2083
1929
  };
2084
1930
  }
@@ -2086,289 +1932,208 @@ async function fetchToken({
2086
1932
  }
2087
1933
  }
2088
1934
 
2089
- // src/actions/contracts/getContract.ts
2090
- import { Contract as EthersContract } from "ethers";
2091
- function getContract({
2092
- address,
2093
- abi,
2094
- signerOrProvider
2095
- }) {
2096
- return new EthersContract(
2097
- address,
2098
- abi,
2099
- signerOrProvider
2100
- );
2101
- }
2102
-
2103
- // src/actions/contracts/prepareWriteContract.ts
2104
- async function prepareWriteContract({
2105
- abi,
2106
- address,
2107
- chainId,
2108
- functionName,
2109
- overrides,
2110
- signer: signer_,
2111
- ...config
2112
- }) {
2113
- const signer = signer_ ?? await fetchSigner({ chainId });
2114
- if (!signer)
2115
- throw new ConnectorNotFoundError();
1935
+ // src/actions/viem/getPublicClient.ts
1936
+ function getPublicClient({ chainId } = {}) {
1937
+ const client2 = getClient();
2116
1938
  if (chainId)
2117
- assertActiveChain({ chainId, signer });
2118
- const contract = getContract({
2119
- address,
2120
- abi,
2121
- signerOrProvider: signer
2122
- });
2123
- const args = config.args;
2124
- const normalizedFunctionName = normalizeFunctionName({
2125
- contract,
2126
- functionName,
2127
- args
2128
- });
2129
- const populateTransactionFn = contract.populateTransaction[normalizedFunctionName];
2130
- if (!populateTransactionFn)
2131
- throw new ContractMethodDoesNotExistError({
2132
- address,
2133
- functionName: normalizedFunctionName
2134
- });
2135
- const params = [...args ?? [], ...overrides ? [overrides] : []];
2136
- const unsignedTransaction = await populateTransactionFn(
2137
- ...params
2138
- );
2139
- const gasLimit = unsignedTransaction.gasLimit || await signer.estimateGas(unsignedTransaction);
2140
- const minimizedAbi = minimizeContractInterface({
2141
- abi,
2142
- functionName
2143
- });
2144
- return {
2145
- abi: minimizedAbi,
2146
- address,
2147
- chainId,
2148
- functionName,
2149
- mode: "prepared",
2150
- request: {
2151
- ...unsignedTransaction,
2152
- gasLimit
2153
- }
2154
- };
1939
+ return client2.getPublicClient({ chainId }) || client2.publicClient;
1940
+ return client2.publicClient;
2155
1941
  }
2156
1942
 
2157
- // src/actions/providers/getProvider.ts
2158
- function getProvider({
1943
+ // src/actions/viem/getWalletClient.ts
1944
+ async function getWalletClient({
2159
1945
  chainId
2160
1946
  } = {}) {
2161
1947
  const client2 = getClient();
2162
- if (chainId)
2163
- return client2.getProvider({ chainId }) || client2.provider;
2164
- return client2.provider;
1948
+ const walletClient = await client2.connector?.getWalletClient?.({ chainId }) || null;
1949
+ return walletClient;
2165
1950
  }
2166
1951
 
2167
- // src/actions/providers/getWebSocketProvider.ts
2168
- function getWebSocketProvider({
1952
+ // src/actions/viem/getWebSocketPublicClient.ts
1953
+ function getWebSocketPublicClient({
2169
1954
  chainId
2170
1955
  } = {}) {
2171
1956
  const client2 = getClient();
2172
1957
  if (chainId)
2173
- return client2.getWebSocketProvider({ chainId }) || client2.webSocketProvider;
2174
- return client2.webSocketProvider;
1958
+ return client2.getWebSocketPublicClient({ chainId }) || client2.webSocketPublicClient;
1959
+ return client2.webSocketPublicClient;
2175
1960
  }
2176
1961
 
2177
- // src/actions/providers/watchProvider.ts
2178
- function watchProvider(args, callback) {
1962
+ // src/actions/viem/watchPublicClient.ts
1963
+ function watchPublicClient(args, callback) {
2179
1964
  const client2 = getClient();
2180
- const handleChange = async () => callback(getProvider(args));
2181
- const unsubscribe = client2.subscribe(({ provider }) => provider, handleChange);
1965
+ const handleChange = async () => callback(getPublicClient(args));
1966
+ const unsubscribe = client2.subscribe(
1967
+ ({ publicClient }) => publicClient,
1968
+ handleChange
1969
+ );
2182
1970
  return unsubscribe;
2183
1971
  }
2184
1972
 
2185
- // src/actions/providers/watchWebSocketProvider.ts
2186
- function watchWebSocketProvider(args, callback) {
1973
+ // src/actions/viem/watchWalletClient.ts
1974
+ import { shallow } from "zustand/shallow";
1975
+ function watchWalletClient({ chainId }, callback) {
2187
1976
  const client2 = getClient();
2188
- const handleChange = async () => callback(getWebSocketProvider(args));
1977
+ const handleChange = async () => {
1978
+ const walletClient = await getWalletClient({ chainId });
1979
+ if (!getClient().connector)
1980
+ return callback(null);
1981
+ return callback(walletClient);
1982
+ };
2189
1983
  const unsubscribe = client2.subscribe(
2190
- ({ webSocketProvider }) => webSocketProvider,
2191
- handleChange
1984
+ ({ data, connector }) => ({
1985
+ account: data?.account,
1986
+ chainId: data?.chain?.id,
1987
+ connector
1988
+ }),
1989
+ handleChange,
1990
+ {
1991
+ equalityFn: shallow
1992
+ }
2192
1993
  );
2193
1994
  return unsubscribe;
2194
1995
  }
2195
1996
 
2196
- // src/actions/contracts/multicall.ts
2197
- async function multicall({
2198
- allowFailure = true,
2199
- chainId: chainIdOverride,
2200
- contracts,
2201
- overrides
2202
- }) {
2203
- const provider = getProvider({ chainId: chainIdOverride });
2204
- if (!provider.chains?.[0])
2205
- throw new ProviderChainsNotFound();
2206
- const chainId = provider.network.chainId;
2207
- if (typeof chainIdOverride !== "undefined" && chainIdOverride !== chainId)
2208
- throw new ChainNotConfiguredError({ chainId: chainIdOverride });
2209
- const chain = provider.chains.find((chain2) => chain2.id === chainId);
2210
- if (!chain)
2211
- throw new ChainNotConfiguredError({ chainId });
2212
- if (!chain?.contracts?.multicall3)
2213
- throw new ChainDoesNotSupportMulticallError({ chain });
2214
- if (typeof overrides?.blockTag === "number" && overrides?.blockTag < (chain.contracts.multicall3.blockCreated ?? 0))
2215
- throw new ChainDoesNotSupportMulticallError({
2216
- blockNumber: overrides?.blockTag,
2217
- chain
2218
- });
2219
- const multicallContract = getContract({
2220
- address: chain.contracts.multicall3.address,
2221
- abi: multicallABI,
2222
- signerOrProvider: provider
2223
- });
2224
- const calls = contracts.map(
2225
- ({ address, abi, functionName, ...config }) => {
2226
- const { args } = config || {};
2227
- const contract = getContract({ address, abi });
2228
- const params2 = args ?? [];
2229
- const normalizedFunctionName = normalizeFunctionName({
2230
- contract,
2231
- functionName,
2232
- args
2233
- });
2234
- try {
2235
- const contractFunction = contract[normalizedFunctionName];
2236
- if (!contractFunction)
2237
- logWarn(
2238
- `"${normalizedFunctionName}" is not in the interface for contract "${address}"`
2239
- );
2240
- const callData = contract.interface.encodeFunctionData(
2241
- normalizedFunctionName,
2242
- params2
2243
- );
2244
- return {
2245
- target: address,
2246
- allowFailure,
2247
- callData
2248
- };
2249
- } catch (err) {
2250
- if (!allowFailure)
2251
- throw err;
2252
- return {
2253
- target: address,
2254
- allowFailure,
2255
- callData: "0x"
2256
- };
2257
- }
2258
- }
2259
- );
2260
- const params = [...[calls], ...overrides ? [overrides] : []];
2261
- const results = await multicallContract.aggregate3(
2262
- ...params
1997
+ // src/actions/viem/watchWebSocketPublicClient.ts
1998
+ function watchWebSocketPublicClient(args, callback) {
1999
+ const client2 = getClient();
2000
+ const handleChange = async () => callback(getWebSocketPublicClient(args));
2001
+ const unsubscribe = client2.subscribe(
2002
+ ({ webSocketPublicClient }) => webSocketPublicClient,
2003
+ handleChange
2263
2004
  );
2264
- return results.map(({ returnData, success }, i) => {
2265
- const { address, abi, functionName, ...rest } = contracts[i];
2266
- const contract = getContract({
2267
- address,
2268
- abi
2269
- });
2270
- const args = rest.args;
2271
- const normalizedFunctionName = normalizeFunctionName({
2272
- contract,
2273
- functionName,
2274
- args
2275
- });
2276
- if (!success) {
2277
- let error;
2278
- try {
2279
- contract.interface.decodeFunctionResult(
2280
- normalizedFunctionName,
2281
- returnData
2282
- );
2283
- } catch (err) {
2284
- error = new ContractMethodRevertedError({
2285
- address,
2286
- args,
2287
- chainId: chain.id,
2288
- functionName: normalizedFunctionName,
2289
- errorMessage: err.message
2290
- });
2291
- if (!allowFailure)
2292
- throw error;
2293
- logWarn(error.message);
2294
- }
2295
- return null;
2296
- }
2297
- if (returnData === "0x") {
2298
- const error = new ContractMethodNoResultError({
2299
- address,
2300
- args,
2301
- chainId: chain.id,
2302
- functionName: normalizedFunctionName
2303
- });
2304
- if (!allowFailure)
2305
- throw error;
2306
- logWarn(error.message);
2307
- return null;
2308
- }
2309
- try {
2310
- const result = contract.interface.decodeFunctionResult(
2311
- normalizedFunctionName,
2312
- returnData
2313
- );
2314
- return Array.isArray(result) && result.length === 1 ? result[0] : result;
2315
- } catch (err) {
2316
- const error = new ContractResultDecodeError({
2317
- address,
2318
- args,
2319
- chainId: chain.id,
2320
- functionName: normalizedFunctionName,
2321
- errorMessage: err.message
2322
- });
2323
- if (!allowFailure)
2324
- throw error;
2325
- logWarn(error.message);
2326
- return null;
2327
- }
2328
- });
2005
+ return unsubscribe;
2329
2006
  }
2330
2007
 
2331
- // src/actions/contracts/readContract.ts
2332
- async function readContract({
2008
+ // src/actions/contracts/prepareWriteContract.ts
2009
+ async function prepareWriteContract({
2010
+ abi,
2333
2011
  address,
2012
+ args,
2334
2013
  chainId,
2335
- abi,
2336
2014
  functionName,
2337
- overrides,
2015
+ walletClient: walletClient_,
2338
2016
  ...config
2339
2017
  }) {
2340
- const provider = getProvider({ chainId });
2341
- const contract = getContract({
2342
- address,
2018
+ const publicClient = getPublicClient({ chainId });
2019
+ const walletClient = walletClient_ ?? await getWalletClient({ chainId });
2020
+ if (!walletClient)
2021
+ throw new ConnectorNotFoundError();
2022
+ if (chainId)
2023
+ assertActiveChain({ chainId, walletClient });
2024
+ const {
2025
+ accessList,
2026
+ blockNumber,
2027
+ blockTag,
2028
+ gas,
2029
+ gasPrice,
2030
+ maxFeePerGas,
2031
+ maxPriorityFeePerGas,
2032
+ nonce,
2033
+ value
2034
+ } = getCallParameters(config);
2035
+ const { result, request } = await publicClient.simulateContract({
2343
2036
  abi,
2344
- signerOrProvider: provider
2345
- });
2346
- const args = config.args;
2347
- const normalizedFunctionName = normalizeFunctionName({
2348
- contract,
2037
+ address,
2349
2038
  functionName,
2350
- args
2039
+ args,
2040
+ account: walletClient.account,
2041
+ accessList,
2042
+ blockNumber,
2043
+ blockTag,
2044
+ gas,
2045
+ gasPrice,
2046
+ maxFeePerGas,
2047
+ maxPriorityFeePerGas,
2048
+ nonce,
2049
+ value
2050
+ });
2051
+ const minimizedAbi = abi.filter(
2052
+ (abiItem) => "name" in abiItem && abiItem.name === functionName
2053
+ );
2054
+ return {
2055
+ mode: "prepared",
2056
+ request: {
2057
+ ...request,
2058
+ abi: minimizedAbi,
2059
+ chainId
2060
+ },
2061
+ result
2062
+ };
2063
+ }
2064
+
2065
+ // src/actions/contracts/getContract.ts
2066
+ import { getContract as getContract_ } from "viem";
2067
+ function getContract({
2068
+ address,
2069
+ abi,
2070
+ chainId,
2071
+ walletClient
2072
+ }) {
2073
+ const publicClient = getPublicClient({ chainId });
2074
+ return getContract_({
2075
+ address,
2076
+ abi,
2077
+ publicClient,
2078
+ walletClient
2079
+ });
2080
+ }
2081
+
2082
+ // src/actions/contracts/multicall.ts
2083
+ async function multicall({
2084
+ chainId,
2085
+ contracts,
2086
+ blockNumber,
2087
+ blockTag,
2088
+ ...args
2089
+ }) {
2090
+ const publicClient = getPublicClient({ chainId });
2091
+ if (!publicClient.chains)
2092
+ throw new ClientChainsNotFound();
2093
+ if (chainId && publicClient.chain.id !== chainId)
2094
+ throw new ChainNotConfiguredError({ chainId });
2095
+ return publicClient.multicall({
2096
+ allowFailure: args.allowFailure ?? true,
2097
+ blockNumber,
2098
+ blockTag,
2099
+ contracts
2100
+ });
2101
+ }
2102
+
2103
+ // src/actions/contracts/readContract.ts
2104
+ async function readContract({
2105
+ address,
2106
+ chainId,
2107
+ abi,
2108
+ args,
2109
+ functionName,
2110
+ blockNumber,
2111
+ blockTag
2112
+ }) {
2113
+ const publicClient = getPublicClient({ chainId });
2114
+ return publicClient.readContract({
2115
+ abi,
2116
+ address,
2117
+ functionName,
2118
+ args,
2119
+ blockNumber,
2120
+ blockTag
2351
2121
  });
2352
- const contractFunction = contract[normalizedFunctionName];
2353
- if (!contractFunction)
2354
- throw new ContractMethodDoesNotExistError({
2355
- address,
2356
- functionName: normalizedFunctionName
2357
- });
2358
- const params = [...args ?? [], ...overrides ? [overrides] : []];
2359
- return contractFunction?.(...params);
2360
2122
  }
2361
2123
 
2362
2124
  // src/actions/contracts/readContracts.ts
2125
+ import { ContractFunctionExecutionError as ContractFunctionExecutionError2 } from "viem";
2363
2126
  async function readContracts({
2364
- allowFailure = true,
2365
2127
  contracts,
2366
- overrides
2128
+ blockNumber,
2129
+ blockTag,
2130
+ ...args
2367
2131
  }) {
2132
+ const { allowFailure = true } = args;
2368
2133
  try {
2369
- const provider = getProvider();
2134
+ const publicClient = getPublicClient();
2370
2135
  const contractsByChainId = contracts.reduce((contracts2, contract, index) => {
2371
- const chainId = contract.chainId ?? provider.network.chainId;
2136
+ const chainId = contract.chainId ?? publicClient.chain.id;
2372
2137
  return {
2373
2138
  ...contracts2,
2374
2139
  [chainId]: [...contracts2[chainId] || [], { contract, index }]
@@ -2378,149 +2143,109 @@ async function readContracts({
2378
2143
  ([chainId, contracts2]) => multicall({
2379
2144
  allowFailure,
2380
2145
  chainId: parseInt(chainId),
2381
- contracts: contracts2.map(({ contract }) => contract),
2382
- overrides
2146
+ contracts: contracts2.map(
2147
+ ({ contract }) => contract
2148
+ ),
2149
+ blockNumber,
2150
+ blockTag
2383
2151
  })
2384
2152
  );
2385
- let multicallResults;
2386
- if (allowFailure) {
2387
- multicallResults = (await Promise.allSettled(promises())).map((result) => {
2388
- if (result.status === "fulfilled")
2389
- return result.value;
2390
- if (result.reason instanceof ChainDoesNotSupportMulticallError) {
2391
- logWarn(result.reason.message);
2392
- throw result.reason;
2393
- }
2394
- return null;
2395
- }).flat();
2396
- } else {
2397
- multicallResults = (await Promise.all(promises())).flat();
2398
- }
2399
- const resultIndexes = Object.values(contractsByChainId).map((contracts2) => contracts2.map(({ index }) => index)).flat();
2153
+ const multicallResults = (await Promise.all(promises())).flat();
2154
+ const resultIndexes = Object.values(contractsByChainId).flatMap(
2155
+ (contracts2) => contracts2.map(({ index }) => index)
2156
+ );
2400
2157
  return multicallResults.reduce((results, result, index) => {
2401
2158
  if (results)
2402
2159
  results[resultIndexes[index]] = result;
2403
2160
  return results;
2404
2161
  }, []);
2405
2162
  } catch (err) {
2406
- if (err instanceof ContractResultDecodeError)
2407
- throw err;
2408
- if (err instanceof ContractMethodNoResultError)
2409
- throw err;
2410
- if (err instanceof ContractMethodRevertedError)
2163
+ if (err instanceof ContractFunctionExecutionError2)
2411
2164
  throw err;
2412
2165
  const promises = () => contracts.map(
2413
- (contract) => readContract({ ...contract, overrides })
2166
+ (contract) => readContract({ ...contract, blockNumber, blockTag })
2414
2167
  );
2415
2168
  if (allowFailure)
2416
- return (await Promise.allSettled(promises())).map((result, i) => {
2169
+ return (await Promise.allSettled(promises())).map((result) => {
2417
2170
  if (result.status === "fulfilled")
2418
- return result.value;
2419
- const { address, args, chainId, functionName } = contracts[i];
2420
- const error = new ContractMethodRevertedError({
2421
- address,
2422
- functionName,
2423
- chainId: chainId ?? 1,
2424
- args,
2425
- errorMessage: result.reason
2426
- });
2427
- logWarn(error.message);
2428
- return null;
2171
+ return { result: result.value, status: "success" };
2172
+ return { error: result.reason, result: void 0, status: "failure" };
2429
2173
  });
2430
2174
  return await Promise.all(promises());
2431
2175
  }
2432
2176
  }
2433
2177
 
2434
2178
  // src/actions/contracts/watchContractEvent.ts
2435
- import { shallow } from "zustand/shallow";
2179
+ import { shallow as shallow2 } from "zustand/shallow";
2436
2180
  function watchContractEvent({
2437
2181
  address,
2438
2182
  abi,
2439
2183
  chainId,
2440
- eventName,
2441
- once
2184
+ eventName
2442
2185
  }, callback) {
2443
- const handler = (...event) => callback(...event);
2444
- let contract;
2186
+ let unwatch;
2445
2187
  const watchEvent = async () => {
2446
- if (contract)
2447
- contract?.off(eventName, handler);
2448
- const signerOrProvider = getWebSocketProvider({ chainId }) || getProvider({ chainId });
2449
- contract = getContract({
2188
+ if (unwatch)
2189
+ unwatch();
2190
+ const publicClient = getWebSocketPublicClient({ chainId }) || getPublicClient({ chainId });
2191
+ unwatch = publicClient.watchContractEvent({
2450
2192
  address,
2451
2193
  abi,
2452
- signerOrProvider
2194
+ eventName,
2195
+ onLogs: callback
2453
2196
  });
2454
- if (once)
2455
- contract.once(eventName, handler);
2456
- else
2457
- contract.on(eventName, handler);
2458
2197
  };
2459
2198
  watchEvent();
2460
2199
  const client2 = getClient();
2461
2200
  const unsubscribe = client2.subscribe(
2462
- ({ provider, webSocketProvider }) => ({
2463
- provider,
2464
- webSocketProvider
2201
+ ({ publicClient, webSocketPublicClient }) => ({
2202
+ publicClient,
2203
+ webSocketPublicClient
2465
2204
  }),
2466
2205
  watchEvent,
2467
- { equalityFn: shallow }
2206
+ { equalityFn: shallow2 }
2468
2207
  );
2469
2208
  return () => {
2470
- contract?.off(eventName, handler);
2209
+ unwatch?.();
2471
2210
  unsubscribe();
2472
2211
  };
2473
2212
  }
2474
2213
 
2475
2214
  // src/actions/network-status/watchBlockNumber.ts
2476
- import { shallow as shallow2 } from "zustand/shallow";
2477
-
2478
- // src/actions/network-status/fetchBlockNumber.ts
2479
- async function fetchBlockNumber({
2480
- chainId
2481
- } = {}) {
2482
- const provider = getProvider({ chainId });
2483
- const blockNumber = await provider.getBlockNumber();
2484
- return blockNumber;
2485
- }
2486
-
2487
- // src/actions/network-status/watchBlockNumber.ts
2215
+ import { shallow as shallow3 } from "zustand/shallow";
2488
2216
  function watchBlockNumber(args, callback) {
2489
- const debouncedCallback = debounce(callback, 1);
2490
- let previousProvider;
2491
- const createListener = (provider) => {
2492
- if (previousProvider) {
2493
- previousProvider?.off("block", debouncedCallback);
2494
- }
2495
- provider.on("block", debouncedCallback);
2496
- previousProvider = provider;
2217
+ let unwatch;
2218
+ const createListener = (publicClient) => {
2219
+ if (unwatch)
2220
+ unwatch();
2221
+ unwatch = publicClient.watchBlockNumber({
2222
+ onBlockNumber: callback,
2223
+ emitOnBegin: true,
2224
+ poll: true
2225
+ });
2497
2226
  };
2498
- const provider_ = getWebSocketProvider({ chainId: args.chainId }) ?? getProvider({ chainId: args.chainId });
2227
+ const publicClient_ = getWebSocketPublicClient({ chainId: args.chainId }) ?? getPublicClient({ chainId: args.chainId });
2499
2228
  if (args.listen)
2500
- createListener(provider_);
2501
- let active = true;
2229
+ createListener(publicClient_);
2502
2230
  const client2 = getClient();
2503
2231
  const unsubscribe = client2.subscribe(
2504
- ({ provider, webSocketProvider }) => ({ provider, webSocketProvider }),
2505
- async ({ provider, webSocketProvider }) => {
2506
- const provider_2 = webSocketProvider ?? provider;
2507
- if (args.listen && !args.chainId && provider_2) {
2508
- createListener(provider_2);
2509
- }
2510
- const blockNumber = await fetchBlockNumber({ chainId: args.chainId });
2511
- if (!active)
2512
- return;
2513
- callback(blockNumber);
2232
+ ({ publicClient, webSocketPublicClient }) => ({
2233
+ publicClient,
2234
+ webSocketPublicClient
2235
+ }),
2236
+ async ({ publicClient, webSocketPublicClient }) => {
2237
+ const publicClient_2 = webSocketPublicClient ?? publicClient;
2238
+ if (args.listen && !args.chainId && publicClient_2) {
2239
+ createListener(publicClient_2);
2240
+ }
2514
2241
  },
2515
2242
  {
2516
- equalityFn: shallow2
2243
+ equalityFn: shallow3
2517
2244
  }
2518
2245
  );
2519
2246
  return () => {
2520
- active = false;
2521
2247
  unsubscribe();
2522
- provider_?.off("block", debouncedCallback);
2523
- previousProvider?.off("block", debouncedCallback);
2248
+ unwatch?.();
2524
2249
  };
2525
2250
  }
2526
2251
 
@@ -2529,7 +2254,10 @@ function watchMulticall(config, callback) {
2529
2254
  const client2 = getClient();
2530
2255
  const handleChange = async () => callback(await multicall(config));
2531
2256
  const unwatch = config.listenToBlock ? watchBlockNumber({ listen: true }, handleChange) : void 0;
2532
- const unsubscribe = client2.subscribe(({ provider }) => provider, handleChange);
2257
+ const unsubscribe = client2.subscribe(
2258
+ ({ publicClient }) => publicClient,
2259
+ handleChange
2260
+ );
2533
2261
  return () => {
2534
2262
  unsubscribe();
2535
2263
  unwatch?.();
@@ -2541,7 +2269,10 @@ function watchReadContract(config, callback) {
2541
2269
  const client2 = getClient();
2542
2270
  const handleChange = async () => callback(await readContract(config));
2543
2271
  const unwatch = config.listenToBlock ? watchBlockNumber({ listen: true }, handleChange) : void 0;
2544
- const unsubscribe = client2.subscribe(({ provider }) => provider, handleChange);
2272
+ const unsubscribe = client2.subscribe(
2273
+ ({ publicClient }) => publicClient,
2274
+ handleChange
2275
+ );
2545
2276
  return () => {
2546
2277
  unsubscribe();
2547
2278
  unwatch?.();
@@ -2553,251 +2284,36 @@ function watchReadContracts(config, callback) {
2553
2284
  const client2 = getClient();
2554
2285
  const handleChange = async () => callback(await readContracts(config));
2555
2286
  const unwatch = config.listenToBlock ? watchBlockNumber({ listen: true }, handleChange) : void 0;
2556
- const unsubscribe = client2.subscribe(({ provider }) => provider, handleChange);
2557
- return () => {
2558
- unsubscribe();
2559
- unwatch?.();
2560
- };
2561
- }
2562
-
2563
- // src/actions/transactions/fetchTransaction.ts
2564
- async function fetchTransaction({
2565
- chainId,
2566
- hash
2567
- }) {
2568
- const provider = getProvider({ chainId });
2569
- return provider.getTransaction(hash);
2570
- }
2571
-
2572
- // src/actions/transactions/prepareSendTransaction.ts
2573
- import { isAddress as isAddress2 } from "ethers/lib/utils.js";
2574
-
2575
- // src/actions/ens/fetchEnsAddress.ts
2576
- import { getAddress } from "ethers/lib/utils.js";
2577
- async function fetchEnsAddress({
2578
- chainId,
2579
- name
2580
- }) {
2581
- const provider = getProvider({ chainId });
2582
- const address = await provider.resolveName(name);
2583
- try {
2584
- return address ? getAddress(address) : null;
2585
- } catch (_error) {
2586
- return null;
2587
- }
2588
- }
2589
-
2590
- // src/actions/ens/fetchEnsAvatar.ts
2591
- async function fetchEnsAvatar({
2592
- address,
2593
- chainId
2594
- }) {
2595
- const provider = getProvider({ chainId });
2596
- const avatar = await provider.getAvatar(address);
2597
- return avatar;
2598
- }
2599
-
2600
- // src/actions/ens/fetchEnsName.ts
2601
- import { getAddress as getAddress2 } from "ethers/lib/utils.js";
2602
- async function fetchEnsName({
2603
- address,
2604
- chainId
2605
- }) {
2606
- const provider = getProvider({ chainId });
2607
- return provider.lookupAddress(getAddress2(address));
2608
- }
2609
-
2610
- // src/actions/ens/fetchEnsResolver.ts
2611
- async function fetchEnsResolver({
2612
- chainId,
2613
- name
2614
- }) {
2615
- const provider = getProvider({ chainId });
2616
- const resolver = await provider.getResolver(name);
2617
- return resolver;
2618
- }
2619
-
2620
- // src/actions/transactions/prepareSendTransaction.ts
2621
- async function prepareSendTransaction({
2622
- chainId,
2623
- request,
2624
- signer: signer_
2625
- }) {
2626
- const signer = signer_ ?? await fetchSigner({ chainId });
2627
- if (!signer)
2628
- throw new ConnectorNotFoundError();
2629
- if (chainId)
2630
- assertActiveChain({ chainId, signer });
2631
- const [to, gasLimit] = await Promise.all([
2632
- isAddress2(request.to) ? Promise.resolve(request.to) : fetchEnsAddress({ name: request.to }),
2633
- request.gasLimit ? Promise.resolve(request.gasLimit) : signer.estimateGas(request)
2634
- ]);
2635
- if (!to)
2636
- throw new Error("Could not resolve ENS name");
2637
- return {
2638
- ...chainId ? { chainId } : {},
2639
- request: { ...request, gasLimit, to },
2640
- mode: "prepared"
2641
- };
2642
- }
2643
-
2644
- // src/actions/transactions/sendTransaction.ts
2645
- async function sendTransaction({
2646
- chainId,
2647
- mode,
2648
- request
2649
- }) {
2650
- const signer = await fetchSigner();
2651
- if (!signer)
2652
- throw new ConnectorNotFoundError();
2653
- if (mode === "prepared") {
2654
- if (!request.gasLimit)
2655
- throw new Error("`gasLimit` is required");
2656
- if (!request.to)
2657
- throw new Error("`to` is required");
2658
- }
2659
- if (chainId)
2660
- assertActiveChain({ chainId, signer });
2661
- try {
2662
- const uncheckedSigner = signer.connectUnchecked?.();
2663
- const { hash, wait } = await (uncheckedSigner ?? signer).sendTransaction(
2664
- request
2665
- );
2666
- return { hash, wait };
2667
- } catch (error) {
2668
- if (error.code === 4001 || error.code === "ACTION_REJECTED")
2669
- throw new UserRejectedRequestError(error);
2670
- throw error;
2671
- }
2672
- }
2673
-
2674
- // src/actions/transactions/waitForTransaction.ts
2675
- import { toUtf8String } from "ethers/lib/utils.js";
2676
-
2677
- // src/actions/network-status/fetchFeeData.ts
2678
- import { formatUnits as formatUnits2 } from "ethers/lib/utils.js";
2679
- async function fetchFeeData({
2680
- chainId,
2681
- formatUnits: units2 = "wei"
2682
- } = {}) {
2683
- const provider = getProvider({ chainId });
2684
- const feeData = await provider.getFeeData();
2685
- const formatted = {
2686
- gasPrice: feeData.gasPrice ? formatUnits2(feeData.gasPrice, units2) : null,
2687
- maxFeePerGas: feeData.maxFeePerGas ? formatUnits2(feeData.maxFeePerGas, units2) : null,
2688
- maxPriorityFeePerGas: feeData.maxPriorityFeePerGas ? formatUnits2(feeData.maxPriorityFeePerGas, units2) : null
2689
- };
2690
- return { ...feeData, formatted };
2691
- }
2692
-
2693
- // src/actions/transactions/waitForTransaction.ts
2694
- async function waitForTransaction({
2695
- chainId,
2696
- confirmations = 1,
2697
- hash,
2698
- onSpeedUp,
2699
- timeout = 0
2700
- }) {
2701
- const provider = getProvider({ chainId });
2702
- const [blockNumber, transaction] = await Promise.all([
2703
- fetchBlockNumber(),
2704
- fetchTransaction({ hash })
2705
- ]);
2706
- let replaceable = null;
2707
- if (confirmations !== 0 && transaction?.to) {
2708
- replaceable = {
2709
- data: transaction.data,
2710
- from: transaction.from,
2711
- nonce: transaction.nonce,
2712
- startBlock: blockNumber,
2713
- to: transaction.to,
2714
- value: transaction.value
2715
- };
2716
- }
2717
- try {
2718
- const receipt = await provider._waitForTransaction(
2719
- hash,
2720
- confirmations,
2721
- timeout,
2722
- replaceable
2723
- );
2724
- if (receipt.status === 0) {
2725
- const code = await provider.call(receipt, receipt.blockNumber);
2726
- const reason = toUtf8String(`0x${code.substring(138)}`);
2727
- throw new Error(reason);
2728
- }
2729
- return receipt;
2730
- } catch (err) {
2731
- if (err?.reason === "repriced") {
2732
- onSpeedUp?.(err.replacement);
2733
- return waitForTransaction({
2734
- hash: err.replacement?.hash,
2735
- confirmations,
2736
- timeout
2737
- });
2738
- }
2739
- throw err;
2740
- }
2741
- }
2742
-
2743
- // src/actions/transactions/watchPendingTransactions.ts
2744
- import { shallow as shallow3 } from "zustand/shallow";
2745
- function watchPendingTransactions(args, callback) {
2746
- let previousProvider;
2747
- const createListener = (provider) => {
2748
- if (previousProvider) {
2749
- previousProvider?.off("pending", callback);
2750
- }
2751
- provider.on("pending", callback);
2752
- previousProvider = provider;
2753
- };
2754
- const provider_ = getWebSocketProvider({ chainId: args.chainId }) ?? getProvider({ chainId: args.chainId });
2755
- createListener(provider_);
2756
- const client2 = getClient();
2757
2287
  const unsubscribe = client2.subscribe(
2758
- ({ provider, webSocketProvider }) => ({ provider, webSocketProvider }),
2759
- async ({ provider, webSocketProvider }) => {
2760
- const provider_2 = webSocketProvider ?? provider;
2761
- if (!args.chainId && provider_2) {
2762
- createListener(provider_2);
2763
- }
2764
- },
2765
- {
2766
- equalityFn: shallow3
2767
- }
2288
+ ({ publicClient }) => publicClient,
2289
+ handleChange
2768
2290
  );
2769
2291
  return () => {
2770
2292
  unsubscribe();
2771
- provider_?.off("pending", callback);
2772
- previousProvider?.off("pending", callback);
2293
+ unwatch?.();
2773
2294
  };
2774
2295
  }
2775
2296
 
2776
2297
  // src/actions/contracts/writeContract.ts
2777
2298
  async function writeContract(config) {
2778
- const signer = await fetchSigner();
2779
- if (!signer)
2299
+ const walletClient = await getWalletClient();
2300
+ if (!walletClient)
2780
2301
  throw new ConnectorNotFoundError();
2781
2302
  if (config.chainId)
2782
- assertActiveChain({ chainId: config.chainId, signer });
2303
+ assertActiveChain({ chainId: config.chainId, walletClient });
2783
2304
  let request;
2784
2305
  if (config.mode === "prepared") {
2785
- request = config.request;
2306
+ request = config;
2786
2307
  } else {
2787
- request = (await prepareWriteContract({
2788
- address: config.address,
2789
- args: config.args,
2790
- chainId: config.chainId,
2791
- abi: config.abi,
2792
- functionName: config.functionName,
2793
- overrides: config.overrides
2794
- })).request;
2308
+ const { chainId, mode, ...args } = config;
2309
+ const res = await prepareWriteContract(args);
2310
+ request = res.request;
2795
2311
  }
2796
- const transaction = await sendTransaction({
2797
- request,
2798
- mode: "prepared"
2312
+ const hash = await walletClient.writeContract({
2313
+ ...request,
2314
+ chain: null
2799
2315
  });
2800
- return transaction;
2316
+ return { hash };
2801
2317
  }
2802
2318
 
2803
2319
  // src/actions/accounts/fetchBalance.ts
@@ -2808,7 +2324,7 @@ async function fetchBalance({
2808
2324
  token
2809
2325
  }) {
2810
2326
  const client2 = getClient();
2811
- const provider = getProvider({ chainId });
2327
+ const publicClient = getPublicClient({ chainId });
2812
2328
  if (token) {
2813
2329
  const fetchContractBalance = async ({ abi }) => {
2814
2330
  const erc20Config = { abi, address: token, chainId };
@@ -2826,7 +2342,7 @@ async function fetchBalance({
2826
2342
  });
2827
2343
  return {
2828
2344
  decimals,
2829
- formatted: formatUnits3(value2 ?? "0", unit ?? decimals),
2345
+ formatted: formatUnits2(value2 ?? "0", getUnit(unit ?? decimals)),
2830
2346
  symbol,
2831
2347
  value: value2
2832
2348
  };
@@ -2834,38 +2350,32 @@ async function fetchBalance({
2834
2350
  try {
2835
2351
  return await fetchContractBalance({ abi: erc20ABI });
2836
2352
  } catch (err) {
2837
- if (err instanceof ContractResultDecodeError) {
2353
+ if (err instanceof ContractFunctionExecutionError3) {
2838
2354
  const { symbol, ...rest } = await fetchContractBalance({
2839
2355
  abi: erc20ABI_bytes32
2840
2356
  });
2841
2357
  return {
2842
- symbol: parseBytes32String2(symbol),
2358
+ symbol: hexToString2(trim2(symbol, { dir: "right" })),
2843
2359
  ...rest
2844
2360
  };
2845
2361
  }
2846
2362
  throw err;
2847
2363
  }
2848
2364
  }
2849
- const chains = [...client2.provider.chains || [], ...client2.chains ?? []];
2850
- const value = await provider.getBalance(address);
2851
- const chain = chains.find((x) => x.id === provider.network.chainId);
2365
+ const chains = [
2366
+ ...client2.publicClient.chains || [],
2367
+ ...client2.chains ?? []
2368
+ ];
2369
+ const value = await publicClient.getBalance({ address });
2370
+ const chain = chains.find((x) => x.id === publicClient.chain.id);
2852
2371
  return {
2853
2372
  decimals: chain?.nativeCurrency.decimals ?? 18,
2854
- formatted: formatUnits3(value ?? "0", unit ?? "ether"),
2373
+ formatted: formatUnits2(value ?? "0", getUnit(unit ?? 18)),
2855
2374
  symbol: chain?.nativeCurrency.symbol ?? "ETH",
2856
2375
  value
2857
2376
  };
2858
2377
  }
2859
2378
 
2860
- // src/actions/accounts/fetchSigner.ts
2861
- async function fetchSigner({
2862
- chainId
2863
- } = {}) {
2864
- const client2 = getClient();
2865
- const signer = await client2.connector?.getSigner?.({ chainId }) || null;
2866
- return signer;
2867
- }
2868
-
2869
2379
  // src/actions/accounts/getAccount.ts
2870
2380
  function getAccount() {
2871
2381
  const { data, connector, status } = getClient();
@@ -2918,9 +2428,10 @@ function getNetwork() {
2918
2428
  const client2 = getClient();
2919
2429
  const chainId = client2.data?.chain?.id;
2920
2430
  const activeChains = client2.chains ?? [];
2921
- const activeChain = [...client2.provider.chains || [], ...activeChains].find(
2922
- (x) => x.id === chainId
2923
- ) ?? {
2431
+ const activeChain = [
2432
+ ...client2.publicClient?.chains || [],
2433
+ ...activeChains
2434
+ ].find((x) => x.id === chainId) ?? {
2924
2435
  id: chainId,
2925
2436
  name: `Chain ${chainId}`,
2926
2437
  network: `${chainId}`,
@@ -2942,44 +2453,33 @@ function getNetwork() {
2942
2453
 
2943
2454
  // src/actions/accounts/signMessage.ts
2944
2455
  async function signMessage(args) {
2945
- try {
2946
- const signer = await fetchSigner();
2947
- if (!signer)
2948
- throw new ConnectorNotFoundError();
2949
- return await signer.signMessage(
2950
- args.message
2951
- );
2952
- } catch (error) {
2953
- if (error.code === 4001 || error.code === "ACTION_REJECTED")
2954
- throw new UserRejectedRequestError(error);
2955
- throw error;
2956
- }
2456
+ const walletClient = await getWalletClient();
2457
+ if (!walletClient)
2458
+ throw new ConnectorNotFoundError();
2459
+ return await walletClient.signMessage({
2460
+ message: args.message
2461
+ });
2957
2462
  }
2958
2463
 
2959
2464
  // src/actions/accounts/signTypedData.ts
2960
2465
  async function signTypedData({
2961
2466
  domain,
2962
- types,
2963
- value
2467
+ message,
2468
+ primaryType,
2469
+ types
2964
2470
  }) {
2965
- const signer = await fetchSigner();
2966
- if (!signer)
2471
+ const walletClient = await getWalletClient();
2472
+ if (!walletClient)
2967
2473
  throw new ConnectorNotFoundError();
2968
- const { chainId: chainId_ } = domain;
2969
- const chainId = chainId_ ? normalizeChainId(chainId_) : void 0;
2474
+ const { chainId } = domain;
2970
2475
  if (chainId)
2971
- assertActiveChain({ chainId, signer });
2972
- const types_ = Object.entries(types).filter(([key]) => key !== "EIP712Domain").reduce((types2, [key, attributes]) => {
2973
- types2[key] = attributes.filter((attr) => attr.type !== "EIP712Domain");
2974
- return types2;
2975
- }, {});
2976
- try {
2977
- return await signer._signTypedData(domain, types_, value);
2978
- } catch (error) {
2979
- if (error.code === 4001 || error.code === "ACTION_REJECTED")
2980
- throw new UserRejectedRequestError(error);
2981
- throw error;
2982
- }
2476
+ assertActiveChain({ chainId, walletClient });
2477
+ return walletClient.signTypedData({
2478
+ message,
2479
+ primaryType,
2480
+ types,
2481
+ domain
2482
+ });
2983
2483
  }
2984
2484
 
2985
2485
  // src/actions/accounts/switchNetwork.ts
@@ -3030,291 +2530,264 @@ function watchNetwork(callback, { selector = (x) => x } = {}) {
3030
2530
  return unsubscribe;
3031
2531
  }
3032
2532
 
3033
- // src/actions/accounts/watchSigner.ts
2533
+ // src/actions/ens/fetchEnsAddress.ts
2534
+ import { getAddress } from "viem";
2535
+ import { normalize } from "viem/ens";
2536
+ async function fetchEnsAddress({
2537
+ chainId,
2538
+ name
2539
+ }) {
2540
+ const publicClient = getPublicClient({ chainId });
2541
+ const address = await publicClient.getEnsAddress({
2542
+ name: normalize(name)
2543
+ });
2544
+ try {
2545
+ if (address === "0x0000000000000000000000000000000000000000")
2546
+ return null;
2547
+ return address ? getAddress(address) : null;
2548
+ } catch (_error) {
2549
+ return null;
2550
+ }
2551
+ }
2552
+
2553
+ // src/actions/ens/fetchEnsAvatar.ts
2554
+ import { normalize as normalize2 } from "viem/ens";
2555
+ async function fetchEnsAvatar({
2556
+ name,
2557
+ chainId
2558
+ }) {
2559
+ const publicClient = getPublicClient({ chainId });
2560
+ const avatar = await publicClient.getEnsAvatar({ name: normalize2(name) });
2561
+ return avatar;
2562
+ }
2563
+
2564
+ // src/actions/ens/fetchEnsName.ts
2565
+ import { getAddress as getAddress2 } from "viem";
2566
+ async function fetchEnsName({
2567
+ address,
2568
+ chainId
2569
+ }) {
2570
+ const publicClient = getPublicClient({ chainId });
2571
+ return publicClient.getEnsName({
2572
+ address: getAddress2(address)
2573
+ });
2574
+ }
2575
+
2576
+ // src/actions/ens/fetchEnsResolver.ts
2577
+ import { normalize as normalize3 } from "viem/ens";
2578
+ async function fetchEnsResolver({
2579
+ chainId,
2580
+ name
2581
+ }) {
2582
+ const publicClient = getPublicClient({ chainId });
2583
+ const resolver = await publicClient.getEnsResolver({ name: normalize3(name) });
2584
+ return resolver;
2585
+ }
2586
+
2587
+ // src/actions/network-status/fetchBlockNumber.ts
2588
+ async function fetchBlockNumber({
2589
+ chainId
2590
+ } = {}) {
2591
+ const publicClient = getPublicClient({ chainId });
2592
+ const blockNumber = await publicClient.getBlockNumber();
2593
+ return blockNumber;
2594
+ }
2595
+
2596
+ // src/actions/network-status/fetchFeeData.ts
2597
+ import { formatUnits as formatUnits3, parseGwei } from "viem";
2598
+ async function fetchFeeData({
2599
+ chainId,
2600
+ formatUnits: units = "gwei"
2601
+ } = {}) {
2602
+ const publicClient = getPublicClient({ chainId });
2603
+ const block = await publicClient.getBlock();
2604
+ let gasPrice = null;
2605
+ try {
2606
+ gasPrice = await publicClient.getGasPrice();
2607
+ } catch {
2608
+ }
2609
+ let lastBaseFeePerGas = null;
2610
+ let maxFeePerGas = null;
2611
+ let maxPriorityFeePerGas = null;
2612
+ if (block?.baseFeePerGas) {
2613
+ lastBaseFeePerGas = block.baseFeePerGas;
2614
+ maxPriorityFeePerGas = parseGwei("1");
2615
+ maxFeePerGas = block.baseFeePerGas * 2n + maxPriorityFeePerGas;
2616
+ }
2617
+ const unit = getUnit(units);
2618
+ const formatted = {
2619
+ gasPrice: gasPrice ? formatUnits3(gasPrice, unit) : null,
2620
+ maxFeePerGas: maxFeePerGas ? formatUnits3(maxFeePerGas, unit) : null,
2621
+ maxPriorityFeePerGas: maxPriorityFeePerGas ? formatUnits3(maxPriorityFeePerGas, unit) : null
2622
+ };
2623
+ return {
2624
+ lastBaseFeePerGas,
2625
+ gasPrice,
2626
+ maxFeePerGas,
2627
+ maxPriorityFeePerGas,
2628
+ formatted
2629
+ };
2630
+ }
2631
+
2632
+ // src/actions/transactions/fetchTransaction.ts
2633
+ async function fetchTransaction({
2634
+ chainId,
2635
+ hash
2636
+ }) {
2637
+ const publicClient = getPublicClient({ chainId });
2638
+ return publicClient.getTransaction({ hash });
2639
+ }
2640
+
2641
+ // src/actions/transactions/prepareSendTransaction.ts
2642
+ import { isAddress } from "viem";
2643
+ async function prepareSendTransaction({
2644
+ chainId,
2645
+ request,
2646
+ walletClient: walletClient_
2647
+ }) {
2648
+ const walletClient = walletClient_ ?? await getWalletClient({ chainId });
2649
+ if (!walletClient)
2650
+ throw new ConnectorNotFoundError();
2651
+ if (chainId)
2652
+ assertActiveChain({ chainId, walletClient });
2653
+ const to = (request.to && !isAddress(request.to) ? await fetchEnsAddress({ name: request.to }) : request.to) || void 0;
2654
+ if (to && !isAddress(to))
2655
+ throw new Error("Invalid address");
2656
+ return {
2657
+ ...chainId ? { chainId } : {},
2658
+ request: { ...request, to },
2659
+ mode: "prepared"
2660
+ };
2661
+ }
2662
+
2663
+ // src/actions/transactions/sendTransaction.ts
2664
+ async function sendTransaction({
2665
+ chainId,
2666
+ mode,
2667
+ request
2668
+ }) {
2669
+ const walletClient = await getWalletClient();
2670
+ if (!walletClient)
2671
+ throw new ConnectorNotFoundError();
2672
+ if (chainId)
2673
+ assertActiveChain({ chainId, walletClient });
2674
+ if (mode !== "prepared") {
2675
+ const res = await prepareSendTransaction({ chainId, request });
2676
+ request = res.request;
2677
+ }
2678
+ const hash = await walletClient.sendTransaction({
2679
+ ...request,
2680
+ chain: null
2681
+ });
2682
+ return { hash };
2683
+ }
2684
+
2685
+ // src/actions/transactions/waitForTransaction.ts
2686
+ import { hexToString as hexToString3 } from "viem";
2687
+ async function waitForTransaction({
2688
+ chainId,
2689
+ confirmations = 1,
2690
+ hash,
2691
+ onReplaced,
2692
+ timeout = 0
2693
+ }) {
2694
+ const publicClient = getPublicClient({ chainId });
2695
+ const receipt = await publicClient.waitForTransactionReceipt({
2696
+ hash,
2697
+ confirmations,
2698
+ onReplaced,
2699
+ timeout
2700
+ });
2701
+ if (receipt.status === "reverted") {
2702
+ const txn = await publicClient.getTransaction({
2703
+ hash: receipt.transactionHash
2704
+ });
2705
+ const code = await publicClient.call({
2706
+ ...txn,
2707
+ gasPrice: txn.type !== "eip1559" ? txn.gasPrice : void 0,
2708
+ maxFeePerGas: txn.type === "eip1559" ? txn.maxFeePerGas : void 0,
2709
+ maxPriorityFeePerGas: txn.type === "eip1559" ? txn.maxPriorityFeePerGas : void 0
2710
+ });
2711
+ const reason = hexToString3(`0x${code.substring(138)}`);
2712
+ throw new Error(reason);
2713
+ }
2714
+ return receipt;
2715
+ }
2716
+
2717
+ // src/actions/transactions/watchPendingTransactions.ts
3034
2718
  import { shallow as shallow6 } from "zustand/shallow";
3035
- function watchSigner({ chainId }, callback) {
3036
- const client2 = getClient();
3037
- const handleChange = async () => {
3038
- const signer = await fetchSigner({ chainId });
3039
- if (!getClient().connector)
3040
- return callback(null);
3041
- return callback(signer);
2719
+ function watchPendingTransactions(args, callback) {
2720
+ let unwatch;
2721
+ const createListener = (publicClient) => {
2722
+ if (unwatch)
2723
+ unwatch();
2724
+ unwatch = publicClient.watchPendingTransactions({
2725
+ onTransactions: callback,
2726
+ poll: true
2727
+ });
3042
2728
  };
2729
+ const publicClient_ = getWebSocketPublicClient({ chainId: args.chainId }) ?? getPublicClient({ chainId: args.chainId });
2730
+ createListener(publicClient_);
2731
+ const client2 = getClient();
3043
2732
  const unsubscribe = client2.subscribe(
3044
- ({ data, connector }) => ({
3045
- account: data?.account,
3046
- chainId: data?.chain?.id,
3047
- connector
2733
+ ({ publicClient, webSocketPublicClient }) => ({
2734
+ publicClient,
2735
+ webSocketPublicClient
3048
2736
  }),
3049
- handleChange,
2737
+ async ({ publicClient, webSocketPublicClient }) => {
2738
+ const publicClient_2 = webSocketPublicClient ?? publicClient;
2739
+ if (!args.chainId && publicClient_2) {
2740
+ createListener(publicClient_2);
2741
+ }
2742
+ },
3050
2743
  {
3051
2744
  equalityFn: shallow6
3052
2745
  }
3053
2746
  );
3054
- return unsubscribe;
2747
+ return () => {
2748
+ unsubscribe();
2749
+ unwatch?.();
2750
+ };
3055
2751
  }
3056
2752
 
3057
- // src/errors.ts
3058
- var RpcError = class extends Error {
3059
- constructor(message, options) {
3060
- const { cause, code, data } = options;
3061
- if (!Number.isInteger(code))
3062
- throw new Error('"code" must be an integer.');
3063
- if (!message || typeof message !== "string")
3064
- throw new Error('"message" must be a nonempty string.');
3065
- super(message);
3066
- this.cause = cause;
3067
- this.code = code;
3068
- this.data = data;
3069
- }
3070
- };
3071
- var ProviderRpcError = class extends RpcError {
3072
- constructor(message, options) {
3073
- const { cause, code, data } = options;
3074
- if (!(Number.isInteger(code) && code >= 1e3 && code <= 4999))
3075
- throw new Error(
3076
- '"code" must be an integer such that: 1000 <= code <= 4999'
3077
- );
3078
- super(message, { cause, code, data });
3079
- }
3080
- };
3081
- var AddChainError = class extends Error {
3082
- constructor() {
3083
- super(...arguments);
3084
- this.name = "AddChainError";
3085
- this.message = "Error adding chain";
3086
- }
3087
- };
3088
- var ChainDoesNotSupportMulticallError = class extends Error {
3089
- constructor({ blockNumber, chain }) {
3090
- super(
3091
- `Chain "${chain.name}" does not support multicall${blockNumber ? ` on block ${blockNumber}` : ""}.`
3092
- );
3093
- this.name = "ChainDoesNotSupportMulticall";
3094
- }
3095
- };
3096
- var ChainMismatchError = class extends Error {
3097
- constructor({
3098
- activeChain,
3099
- targetChain
3100
- }) {
3101
- super(
3102
- `Chain mismatch: Expected "${targetChain}", received "${activeChain}".`
3103
- );
3104
- this.name = "ChainMismatchError";
3105
- }
3106
- };
3107
- var ChainNotConfiguredError = class extends Error {
3108
- constructor({
3109
- chainId,
3110
- connectorId
3111
- }) {
3112
- super(
3113
- `Chain "${chainId}" not configured${connectorId ? ` for connector "${connectorId}"` : ""}.`
3114
- );
3115
- this.name = "ChainNotConfigured";
3116
- }
3117
- };
3118
- var ConnectorAlreadyConnectedError = class extends Error {
3119
- constructor() {
3120
- super(...arguments);
3121
- this.name = "ConnectorAlreadyConnectedError";
3122
- this.message = "Connector already connected";
3123
- }
3124
- };
3125
- var ConnectorNotFoundError = class extends Error {
3126
- constructor() {
3127
- super(...arguments);
3128
- this.name = "ConnectorNotFoundError";
3129
- this.message = "Connector not found";
3130
- }
3131
- };
3132
- var ContractMethodDoesNotExistError = class extends Error {
3133
- constructor({
3134
- address,
3135
- chainId,
3136
- functionName
3137
- }) {
3138
- const { chains, network } = getProvider();
3139
- const chain = chains?.find(({ id }) => id === (chainId || network.chainId));
3140
- const blockExplorer = chain?.blockExplorers?.default;
3141
- super(
3142
- [
3143
- `Function "${functionName}" on contract "${address}" does not exist.`,
3144
- ...blockExplorer ? [
3145
- "",
3146
- `${blockExplorer?.name}: ${blockExplorer?.url}/address/${address}#readContract`
3147
- ] : []
3148
- ].join("\n")
3149
- );
3150
- this.name = "ContractMethodDoesNotExistError";
3151
- }
3152
- };
3153
- var ContractMethodNoResultError = class extends Error {
3154
- constructor({
3155
- address,
3156
- args,
3157
- chainId,
3158
- functionName
3159
- }) {
3160
- super(
3161
- [
3162
- "Contract read returned an empty response. This could be due to any of the following:",
3163
- `- The contract does not have the function "${functionName}",`,
3164
- "- The parameters passed to the contract function may be invalid, or",
3165
- "- The address is not a contract.",
3166
- "",
3167
- `Config:`,
3168
- JSON.stringify(
3169
- {
3170
- address,
3171
- abi: "...",
3172
- functionName,
3173
- chainId,
3174
- args
3175
- },
3176
- null,
3177
- 2
3178
- )
3179
- ].join("\n")
3180
- );
3181
- this.name = "ContractMethodNoResultError";
3182
- }
3183
- };
3184
- var ContractMethodRevertedError = class extends Error {
3185
- constructor({
3186
- address,
3187
- args,
3188
- chainId,
3189
- functionName,
3190
- errorMessage
3191
- }) {
3192
- super(
3193
- [
3194
- "Contract method reverted with an error.",
3195
- "",
3196
- `Config:`,
3197
- JSON.stringify(
3198
- {
3199
- address,
3200
- abi: "...",
3201
- functionName,
3202
- chainId,
3203
- args
3204
- },
3205
- null,
3206
- 2
3207
- ),
3208
- "",
3209
- `Details: ${errorMessage}`
3210
- ].join("\n")
3211
- );
3212
- this.name = "ContractMethodRevertedError";
3213
- }
3214
- };
3215
- var ContractResultDecodeError = class extends Error {
3216
- constructor({
3217
- address,
3218
- args,
3219
- chainId,
3220
- functionName,
3221
- errorMessage
3222
- }) {
3223
- super(
3224
- [
3225
- "Failed to decode contract function result.",
3226
- "",
3227
- `Config:`,
3228
- JSON.stringify(
3229
- {
3230
- address,
3231
- abi: "...",
3232
- functionName,
3233
- chainId,
3234
- args
3235
- },
3236
- null,
3237
- 2
3238
- ),
3239
- "",
3240
- `Details: ${errorMessage}`
3241
- ].join("\n")
3242
- );
3243
- this.name = "ContractResultDecodeError";
3244
- }
3245
- };
3246
- var ProviderChainsNotFound = class extends Error {
3247
- constructor() {
3248
- super(...arguments);
3249
- this.name = "ProviderChainsNotFound";
3250
- this.message = [
3251
- "No chains were found on the wagmi provider. Some functions that require a chain may not work.",
3252
- "",
3253
- "It is recommended to add a list of chains to the provider in `createClient`.",
3254
- "",
3255
- "Example:",
3256
- "",
3257
- "```",
3258
- "import { getDefaultProvider } from 'ethers'",
3259
- "import { chain, createClient } from 'wagmi'",
3260
- "",
3261
- "createClient({",
3262
- " provider: Object.assign(getDefaultProvider(), { chains: [chain.mainnet] })",
3263
- "})",
3264
- "```"
3265
- ].join("\n");
3266
- }
3267
- };
3268
- var ResourceUnavailableError = class extends RpcError {
3269
- constructor(cause) {
3270
- super("Resource unavailable", { cause, code: -32002 });
3271
- this.name = "ResourceUnavailable";
3272
- }
3273
- };
3274
- var SwitchChainError = class extends ProviderRpcError {
3275
- constructor(cause) {
3276
- super("Error switching chain", { cause, code: 4902 });
3277
- this.name = "SwitchChainError";
3278
- }
3279
- };
3280
- var SwitchChainNotSupportedError = class extends Error {
3281
- constructor({ connector }) {
3282
- super(`"${connector.name}" does not support programmatic chain switching.`);
3283
- this.name = "SwitchChainNotSupportedError";
2753
+ // src/utils/assertActiveChain.ts
2754
+ function assertActiveChain({
2755
+ chainId,
2756
+ walletClient
2757
+ }) {
2758
+ const { chain: activeChain, chains } = getNetwork();
2759
+ const activeChainId = activeChain?.id;
2760
+ if (activeChainId && chainId !== activeChainId) {
2761
+ throw new ChainMismatchError({
2762
+ activeChain: chains.find((x) => x.id === activeChainId)?.name ?? `Chain ${activeChainId}`,
2763
+ targetChain: chains.find((x) => x.id === chainId)?.name ?? `Chain ${chainId}`
2764
+ });
3284
2765
  }
3285
- };
3286
- var UserRejectedRequestError = class extends ProviderRpcError {
3287
- constructor(cause) {
3288
- super("User rejected request", { cause, code: 4001 });
3289
- this.name = "UserRejectedRequestError";
2766
+ if (walletClient) {
2767
+ const walletClientChainId = walletClient.chain.id;
2768
+ if (walletClientChainId && chainId !== walletClientChainId) {
2769
+ const connector = getClient().connector;
2770
+ throw new ChainNotConfiguredError({
2771
+ chainId,
2772
+ connectorId: connector?.id ?? "unknown"
2773
+ });
2774
+ }
3290
2775
  }
3291
- };
2776
+ }
3292
2777
 
3293
2778
  export {
3294
2779
  configureChains,
3295
- RpcError,
3296
- ProviderRpcError,
3297
- AddChainError,
3298
- ChainDoesNotSupportMulticallError,
3299
2780
  ChainMismatchError,
3300
2781
  ChainNotConfiguredError,
3301
2782
  ConnectorAlreadyConnectedError,
3302
- ConnectorNotFoundError,
3303
- ContractMethodDoesNotExistError,
3304
- ContractMethodNoResultError,
3305
- ContractMethodRevertedError,
3306
- ContractResultDecodeError,
3307
- ProviderChainsNotFound,
3308
- ResourceUnavailableError,
3309
- SwitchChainError,
2783
+ ClientChainsNotFound,
3310
2784
  SwitchChainNotSupportedError,
3311
- UserRejectedRequestError,
3312
- debounce,
2785
+ ConnectorNotFoundError,
3313
2786
  deepEqual,
3314
2787
  deserialize,
3315
- minimizeContractInterface,
3316
- normalizeChainId,
3317
- parseContractResult,
2788
+ getCallParameters,
2789
+ getSendTransactionParameters,
2790
+ getUnit,
3318
2791
  serialize,
3319
2792
  noopStorage,
3320
2793
  createStorage,
@@ -3326,36 +2799,25 @@ export {
3326
2799
  erc20ABI,
3327
2800
  erc721ABI,
3328
2801
  erc4626ABI,
3329
- units,
3330
2802
  fetchToken,
3331
- getContract,
2803
+ getPublicClient,
2804
+ getWalletClient,
2805
+ getWebSocketPublicClient,
2806
+ watchPublicClient,
2807
+ watchWalletClient,
2808
+ watchWebSocketPublicClient,
3332
2809
  prepareWriteContract,
3333
- getProvider,
3334
- getWebSocketProvider,
3335
- watchProvider,
3336
- watchWebSocketProvider,
2810
+ getContract,
3337
2811
  multicall,
3338
2812
  readContract,
3339
2813
  readContracts,
3340
2814
  watchContractEvent,
3341
- fetchBlockNumber,
3342
2815
  watchBlockNumber,
3343
2816
  watchMulticall,
3344
2817
  watchReadContract,
3345
2818
  watchReadContracts,
3346
- fetchTransaction,
3347
- fetchEnsAddress,
3348
- fetchEnsAvatar,
3349
- fetchEnsName,
3350
- fetchEnsResolver,
3351
- prepareSendTransaction,
3352
- sendTransaction,
3353
- fetchFeeData,
3354
- waitForTransaction,
3355
- watchPendingTransactions,
3356
2819
  writeContract,
3357
2820
  fetchBalance,
3358
- fetchSigner,
3359
2821
  getAccount,
3360
2822
  getNetwork,
3361
2823
  signMessage,
@@ -3363,5 +2825,15 @@ export {
3363
2825
  switchNetwork,
3364
2826
  watchAccount,
3365
2827
  watchNetwork,
3366
- watchSigner
2828
+ fetchEnsAddress,
2829
+ fetchEnsAvatar,
2830
+ fetchEnsName,
2831
+ fetchEnsResolver,
2832
+ fetchBlockNumber,
2833
+ fetchFeeData,
2834
+ fetchTransaction,
2835
+ prepareSendTransaction,
2836
+ sendTransaction,
2837
+ waitForTransaction,
2838
+ watchPendingTransactions
3367
2839
  };