@wagmi/core 0.7.6 → 0.7.7

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.
@@ -217,8 +217,43 @@ function deepEqual(a, b) {
217
217
  return a !== a && b !== b;
218
218
  }
219
219
 
220
- // src/utils/normalizeFunctionName.ts
220
+ // src/utils/deserialize.ts
221
221
  import { BigNumber } from "ethers";
222
+ var findAndReplace = (cacheRef, {
223
+ find,
224
+ replace
225
+ }) => {
226
+ if (cacheRef && find(cacheRef)) {
227
+ return replace(cacheRef);
228
+ }
229
+ if (typeof cacheRef !== "object") {
230
+ return cacheRef;
231
+ }
232
+ if (Array.isArray(cacheRef)) {
233
+ return cacheRef.map((item) => findAndReplace(item, { find, replace }));
234
+ }
235
+ if (cacheRef instanceof Object) {
236
+ return Object.entries(cacheRef).reduce(
237
+ (curr, [key, value]) => ({
238
+ ...curr,
239
+ [key]: findAndReplace(value, { find, replace })
240
+ }),
241
+ {}
242
+ );
243
+ }
244
+ return cacheRef;
245
+ };
246
+ function deserialize(cachedString) {
247
+ const cache = JSON.parse(cachedString);
248
+ const deserializedCacheWithBigNumbers = findAndReplace(cache, {
249
+ find: (data) => data.type === "BigNumber",
250
+ replace: (data) => BigNumber.from(data.hex)
251
+ });
252
+ return deserializedCacheWithBigNumbers;
253
+ }
254
+
255
+ // src/utils/normalizeFunctionName.ts
256
+ import { BigNumber as BigNumber2 } from "ethers";
222
257
  import { FunctionFragment, isAddress } from "ethers/lib/utils.js";
223
258
  function normalizeFunctionName({
224
259
  contract,
@@ -264,7 +299,7 @@ function isArgOfType(arg, abiParameter) {
264
299
  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(
265
300
  abiParameterType
266
301
  ))
267
- return argType === "number" || argType === "bigint" || BigNumber.isBigNumber(arg);
302
+ return argType === "number" || argType === "bigint" || BigNumber2.isBigNumber(arg);
268
303
  if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))
269
304
  return argType === "string" || arg instanceof Uint8Array;
270
305
  if (/[a-z]+[1-9]{0,3}(\[[0-9]{0,}\])+$/.test(abiParameterType)) {
@@ -399,6 +434,60 @@ function parseContractResult({
399
434
  return data;
400
435
  }
401
436
 
437
+ // src/utils/serialize.ts
438
+ function getReferenceKey(keys, cutoff) {
439
+ return keys.slice(0, cutoff).join(".") || ".";
440
+ }
441
+ function getCutoff(array, value) {
442
+ const { length } = array;
443
+ for (let index = 0; index < length; ++index) {
444
+ if (array[index] === value) {
445
+ return index + 1;
446
+ }
447
+ }
448
+ return 0;
449
+ }
450
+ function createReplacer(replacer, circularReplacer) {
451
+ const hasReplacer = typeof replacer === "function";
452
+ const hasCircularReplacer = typeof circularReplacer === "function";
453
+ const cache = [];
454
+ const keys = [];
455
+ return function replace(key, value) {
456
+ if (typeof value === "object") {
457
+ if (cache.length) {
458
+ const thisCutoff = getCutoff(cache, this);
459
+ if (thisCutoff === 0) {
460
+ cache[cache.length] = this;
461
+ } else {
462
+ cache.splice(thisCutoff);
463
+ keys.splice(thisCutoff);
464
+ }
465
+ keys[keys.length] = key;
466
+ const valueCutoff = getCutoff(cache, value);
467
+ if (valueCutoff !== 0) {
468
+ return hasCircularReplacer ? circularReplacer.call(
469
+ this,
470
+ key,
471
+ value,
472
+ getReferenceKey(keys, valueCutoff)
473
+ ) : `[ref=${getReferenceKey(keys, valueCutoff)}]`;
474
+ }
475
+ } else {
476
+ cache[0] = value;
477
+ keys[0] = key;
478
+ }
479
+ }
480
+ return hasReplacer ? replacer.call(this, key, value) : value;
481
+ };
482
+ }
483
+ function serialize(value, replacer, indent, circularReplacer) {
484
+ return JSON.stringify(
485
+ value,
486
+ createReplacer(replacer, circularReplacer),
487
+ indent ?? void 0
488
+ );
489
+ }
490
+
402
491
  // src/connectors/base.ts
403
492
  import { default as EventEmitter } from "eventemitter3";
404
493
 
@@ -1930,15 +2019,17 @@ var noopStorage = {
1930
2019
  removeItem: (_key) => null
1931
2020
  };
1932
2021
  function createStorage({
1933
- storage,
1934
- key: prefix = "wagmi"
2022
+ deserialize: deserialize2 = deserialize,
2023
+ key: prefix = "wagmi",
2024
+ serialize: serialize2 = serialize,
2025
+ storage
1935
2026
  }) {
1936
2027
  return {
1937
2028
  ...storage,
1938
2029
  getItem: (key, defaultState = null) => {
1939
2030
  const value = storage.getItem(`${prefix}.${key}`);
1940
2031
  try {
1941
- return value ? JSON.parse(value) : defaultState;
2032
+ return value ? deserialize2(value) : defaultState;
1942
2033
  } catch (error) {
1943
2034
  console.warn(error);
1944
2035
  return defaultState;
@@ -1949,7 +2040,7 @@ function createStorage({
1949
2040
  storage.removeItem(`${prefix}.${key}`);
1950
2041
  } else {
1951
2042
  try {
1952
- storage.setItem(`${prefix}.${key}`, JSON.stringify(value));
2043
+ storage.setItem(`${prefix}.${key}`, serialize2(value));
1953
2044
  } catch (err) {
1954
2045
  console.error(err);
1955
2046
  }
@@ -2009,6 +2100,7 @@ var Client = class {
2009
2100
  webSocketProvider: this.getWebSocketProvider({ chainId: chainId2 })
2010
2101
  }),
2011
2102
  {
2103
+ deserialize: (state) => state,
2012
2104
  name: storeKey,
2013
2105
  getStorage: () => storage,
2014
2106
  partialize: (state) => ({
@@ -2020,7 +2112,8 @@ var Client = class {
2020
2112
  },
2021
2113
  chains: state?.chains
2022
2114
  }),
2023
- version: 1
2115
+ serialize: (state) => state,
2116
+ version: 2
2024
2117
  }
2025
2118
  )
2026
2119
  )
@@ -2215,7 +2308,7 @@ async function connect({
2215
2308
  }) {
2216
2309
  const client2 = getClient();
2217
2310
  const activeConnector = client2.connector;
2218
- if (connector.id === activeConnector?.id)
2311
+ if (activeConnector && connector.id === activeConnector.id)
2219
2312
  throw new ConnectorAlreadyConnectedError();
2220
2313
  try {
2221
2314
  client2.setState((x) => ({ ...x, status: "connecting" }));
@@ -3440,9 +3533,11 @@ export {
3440
3533
  configureChains,
3441
3534
  debounce,
3442
3535
  deepEqual,
3536
+ deserialize,
3443
3537
  minimizeContractInterface,
3444
3538
  normalizeChainId,
3445
3539
  parseContractResult,
3540
+ serialize,
3446
3541
  erc20ABI,
3447
3542
  erc721ABI,
3448
3543
  erc4626ABI,
@@ -5,7 +5,7 @@ import {
5
5
  SwitchChainError,
6
6
  UserRejectedRequestError,
7
7
  normalizeChainId
8
- } from "../chunk-MS4CUBFJ.js";
8
+ } from "../chunk-TYXJCTXO.js";
9
9
  import "../chunk-4DNFSL2K.js";
10
10
  import {
11
11
  __privateAdd,
@@ -4,7 +4,7 @@ import {
4
4
  ResourceUnavailableError,
5
5
  UserRejectedRequestError,
6
6
  getClient
7
- } from "../chunk-MS4CUBFJ.js";
7
+ } from "../chunk-TYXJCTXO.js";
8
8
  import "../chunk-4DNFSL2K.js";
9
9
  import {
10
10
  __privateAdd,
@@ -2,7 +2,7 @@ import {
2
2
  Connector,
3
3
  UserRejectedRequestError,
4
4
  normalizeChainId
5
- } from "../../chunk-MS4CUBFJ.js";
5
+ } from "../../chunk-TYXJCTXO.js";
6
6
  import "../../chunk-4DNFSL2K.js";
7
7
  import {
8
8
  __privateAdd,
@@ -4,7 +4,7 @@ import {
4
4
  UserRejectedRequestError,
5
5
  getClient,
6
6
  normalizeChainId
7
- } from "../chunk-MS4CUBFJ.js";
7
+ } from "../chunk-TYXJCTXO.js";
8
8
  import "../chunk-4DNFSL2K.js";
9
9
  import {
10
10
  __privateAdd,
@@ -138,10 +138,18 @@ switchChain_fn = async function(chainId) {
138
138
  const provider = await this.getProvider();
139
139
  const id = hexValue(chainId);
140
140
  try {
141
- await provider.request({
142
- method: "wallet_switchEthereumChain",
143
- params: [{ chainId: id }]
144
- });
141
+ await Promise.race([
142
+ provider.request({
143
+ method: "wallet_switchEthereumChain",
144
+ params: [{ chainId: id }]
145
+ }),
146
+ new Promise(
147
+ (res) => this.on("change", ({ chain }) => {
148
+ if (chain?.id === chainId)
149
+ res(chainId);
150
+ })
151
+ )
152
+ ]);
145
153
  return this.chains.find((x) => x.id === chainId) ?? {
146
154
  id: chainId,
147
155
  name: `Chain ${id}`,
package/dist/index.d.ts CHANGED
@@ -779,9 +779,11 @@ declare type ClientStorage = {
779
779
  removeItem(key: string): void;
780
780
  };
781
781
  declare const noopStorage: BaseStorage;
782
- declare function createStorage({ storage, key: prefix, }: {
783
- storage: BaseStorage;
782
+ declare function createStorage({ deserialize, key: prefix, serialize, storage, }: {
783
+ deserialize?: <T>(value: string) => T;
784
784
  key?: string;
785
+ serialize?: <T>(value: T) => string;
786
+ storage: BaseStorage;
785
787
  }): ClientStorage;
786
788
 
787
789
  declare type ClientConfig<TProvider extends Provider = Provider, TWebSocketProvider extends WebSocketProvider = WebSocketProvider> = {
@@ -1724,6 +1726,8 @@ declare function configureChains<TProvider extends Provider = Provider, TWebSock
1724
1726
  /** Forked from https://github.com/epoberezkin/fast-deep-equal */
1725
1727
  declare function deepEqual(a: any, b: any): boolean;
1726
1728
 
1729
+ declare function deserialize(cachedString: string): any;
1730
+
1727
1731
  declare function minimizeContractInterface<TAbi extends Abi | readonly unknown[]>(config: {
1728
1732
  abi: TAbi;
1729
1733
  functionName: TAbi extends Abi ? ExtractAbiFunctionNames<TAbi> : string;
@@ -1737,4 +1741,21 @@ declare function parseContractResult({ abi, data, functionName, }: {
1737
1741
  functionName: string;
1738
1742
  }): any;
1739
1743
 
1740
- export { AddChainError, ChainDoesNotSupportMulticallError, ChainMismatchError, ChainNotConfiguredError, Client, ClientConfig, ConfigureChainsConfig, ConnectArgs, ConnectResult, ConnectorAlreadyConnectedError, ConnectorNotFoundError, ContractMethodDoesNotExistError, ContractMethodNoResultError, ContractMethodRevertedError, ContractResultDecodeError, FetchBalanceArgs, FetchBalanceResult, FetchBlockNumberArgs, FetchBlockNumberResult, FetchEnsAddressArgs, FetchEnsAddressResult, FetchEnsAvatarArgs, FetchEnsAvatarResult, FetchEnsNameArgs, FetchEnsNameResult, FetchEnsResolverArgs, FetchEnsResolverResult, FetchFeeDataArgs, FetchFeeDataResult, FetchSignerArgs, FetchSignerResult, FetchTokenArgs, FetchTokenResult, FetchTransactionArgs, FetchTransactionResult, GetAccountResult, GetContractArgs, GetContractResult, GetNetworkResult, GetProviderArgs, GetProviderResult, GetWebSocketProviderArgs, GetWebSocketProviderResult, MulticallConfig, MulticallResult, PrepareSendTransactionArgs, PrepareSendTransactionResult, PrepareWriteContractConfig, PrepareWriteContractResult, ProviderChainsNotFound, ProviderRpcError, ReadContractConfig, ReadContractResult, ReadContractsConfig, ReadContractsResult, ResourceUnavailableError, RpcError, SendTransactionArgs, SendTransactionPreparedRequest, SendTransactionResult, SendTransactionUnpreparedRequest, SignMessageArgs, SignMessageResult, SignTypedDataArgs, SignTypedDataResult, ClientStorage as Storage, SwitchChainError, SwitchChainNotSupportedError, SwitchNetworkArgs, SwitchNetworkResult, UserRejectedRequestError, WaitForTransactionArgs, WaitForTransactionResult, WatchAccountCallback, WatchBlockNumberArgs, WatchBlockNumberCallback, WatchMulticallCallback, WatchMulticallConfig, WatchNetworkCallback, WatchProviderCallback, WatchReadContractCallback, WatchReadContractConfig, WatchReadContractsCallback, WatchReadContractsConfig, WatchSignerCallback, WatchWebSocketProviderCallback, WriteContractArgs, WriteContractPreparedArgs, WriteContractResult, WriteContractUnpreparedArgs, configureChains, connect, createClient, createStorage, deepEqual, disconnect, erc20ABI, erc4626ABI, erc721ABI, fetchBalance, fetchBlockNumber, fetchEnsAddress, fetchEnsAvatar, fetchEnsName, fetchEnsResolver, fetchFeeData, fetchSigner, fetchToken, fetchTransaction, getAccount, getContract, getNetwork, getProvider, getWebSocketProvider, minimizeContractInterface, multicall, noopStorage, normalizeChainId, parseContractResult, prepareSendTransaction, prepareWriteContract, readContract, readContracts, sendTransaction, signMessage, signTypedData, switchNetwork, waitForTransaction, watchAccount, watchBlockNumber, watchContractEvent, watchMulticall, watchNetwork, watchProvider, watchReadContract, watchReadContracts, watchSigner, watchWebSocketProvider, writeContract };
1744
+ declare type StandardReplacer = (key: string, value: any) => any;
1745
+ declare type CircularReplacer = (key: string, value: any, referenceKey: string) => any;
1746
+ /**
1747
+ * @function stringify
1748
+ *
1749
+ * @description
1750
+ * stringifier that handles circular values
1751
+ * Forked from https://github.com/planttheidea/fast-stringify
1752
+ *
1753
+ * @param value to stringify
1754
+ * @param [replacer] a custom replacer function for handling standard values
1755
+ * @param [indent] the number of spaces to indent the output by
1756
+ * @param [circularReplacer] a custom replacer function for handling circular values
1757
+ * @returns the stringified output
1758
+ */
1759
+ declare function serialize(value: any, replacer?: StandardReplacer | null | undefined, indent?: number | null | undefined, circularReplacer?: CircularReplacer | null | undefined): string;
1760
+
1761
+ export { AddChainError, ChainDoesNotSupportMulticallError, ChainMismatchError, ChainNotConfiguredError, Client, ClientConfig, ConfigureChainsConfig, ConnectArgs, ConnectResult, ConnectorAlreadyConnectedError, ConnectorNotFoundError, ContractMethodDoesNotExistError, ContractMethodNoResultError, ContractMethodRevertedError, ContractResultDecodeError, FetchBalanceArgs, FetchBalanceResult, FetchBlockNumberArgs, FetchBlockNumberResult, FetchEnsAddressArgs, FetchEnsAddressResult, FetchEnsAvatarArgs, FetchEnsAvatarResult, FetchEnsNameArgs, FetchEnsNameResult, FetchEnsResolverArgs, FetchEnsResolverResult, FetchFeeDataArgs, FetchFeeDataResult, FetchSignerArgs, FetchSignerResult, FetchTokenArgs, FetchTokenResult, FetchTransactionArgs, FetchTransactionResult, GetAccountResult, GetContractArgs, GetContractResult, GetNetworkResult, GetProviderArgs, GetProviderResult, GetWebSocketProviderArgs, GetWebSocketProviderResult, MulticallConfig, MulticallResult, PrepareSendTransactionArgs, PrepareSendTransactionResult, PrepareWriteContractConfig, PrepareWriteContractResult, ProviderChainsNotFound, ProviderRpcError, ReadContractConfig, ReadContractResult, ReadContractsConfig, ReadContractsResult, ResourceUnavailableError, RpcError, SendTransactionArgs, SendTransactionPreparedRequest, SendTransactionResult, SendTransactionUnpreparedRequest, SignMessageArgs, SignMessageResult, SignTypedDataArgs, SignTypedDataResult, ClientStorage as Storage, SwitchChainError, SwitchChainNotSupportedError, SwitchNetworkArgs, SwitchNetworkResult, UserRejectedRequestError, WaitForTransactionArgs, WaitForTransactionResult, WatchAccountCallback, WatchBlockNumberArgs, WatchBlockNumberCallback, WatchMulticallCallback, WatchMulticallConfig, WatchNetworkCallback, WatchProviderCallback, WatchReadContractCallback, WatchReadContractConfig, WatchReadContractsCallback, WatchReadContractsConfig, WatchSignerCallback, WatchWebSocketProviderCallback, WriteContractArgs, WriteContractPreparedArgs, WriteContractResult, WriteContractUnpreparedArgs, configureChains, connect, createClient, createStorage, deepEqual, deserialize, disconnect, erc20ABI, erc4626ABI, erc721ABI, fetchBalance, fetchBlockNumber, fetchEnsAddress, fetchEnsAvatar, fetchEnsName, fetchEnsResolver, fetchFeeData, fetchSigner, fetchToken, fetchTransaction, getAccount, getContract, getNetwork, getProvider, getWebSocketProvider, minimizeContractInterface, multicall, noopStorage, normalizeChainId, parseContractResult, prepareSendTransaction, prepareWriteContract, readContract, readContracts, sendTransaction, serialize, signMessage, signTypedData, switchNetwork, waitForTransaction, watchAccount, watchBlockNumber, watchContractEvent, watchMulticall, watchNetwork, watchProvider, watchReadContract, watchReadContracts, watchSigner, watchWebSocketProvider, writeContract };
package/dist/index.js CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  createClient,
25
25
  createStorage,
26
26
  deepEqual,
27
+ deserialize,
27
28
  disconnect,
28
29
  erc20ABI,
29
30
  erc4626ABI,
@@ -53,6 +54,7 @@ import {
53
54
  readContract,
54
55
  readContracts,
55
56
  sendTransaction,
57
+ serialize,
56
58
  signMessage,
57
59
  signTypedData,
58
60
  switchNetwork,
@@ -69,7 +71,7 @@ import {
69
71
  watchSigner,
70
72
  watchWebSocketProvider,
71
73
  writeContract
72
- } from "./chunk-MS4CUBFJ.js";
74
+ } from "./chunk-TYXJCTXO.js";
73
75
  import {
74
76
  alchemyRpcUrls,
75
77
  allChains,
@@ -114,6 +116,7 @@ export {
114
116
  deepEqual,
115
117
  defaultChains,
116
118
  defaultL2Chains,
119
+ deserialize,
117
120
  disconnect,
118
121
  erc20ABI,
119
122
  erc4626ABI,
@@ -146,6 +149,7 @@ export {
146
149
  readContract,
147
150
  readContracts,
148
151
  sendTransaction,
152
+ serialize,
149
153
  signMessage,
150
154
  signTypedData,
151
155
  switchNetwork,
package/dist/internal.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  debounce
3
- } from "./chunk-MS4CUBFJ.js";
3
+ } from "./chunk-TYXJCTXO.js";
4
4
  import "./chunk-4DNFSL2K.js";
5
5
  import "./chunk-MQXBDTVK.js";
6
6
  export {
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@wagmi/core",
3
3
  "description": "Vanilla JS library for Ethereum",
4
4
  "license": "MIT",
5
- "version": "0.7.6",
5
+ "version": "0.7.7",
6
6
  "repository": {
7
7
  "type": "git",
8
8
  "url": "https://github.com/wagmi-dev/wagmi.git",