@reown/appkit-ethers-react-native 0.0.0-fix-fetch-error-improvements-20241114124235 → 0.0.0-fix-fetch-error-improvements-20241114125438

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.
@@ -0,0 +1,787 @@
1
+ import { BrowserProvider, Contract, InfuraProvider, JsonRpcProvider, JsonRpcSigner, formatEther, formatUnits, getAddress, hexlify, isHexString, parseUnits, toUtf8Bytes } from 'ethers';
2
+ import { AppKitScaffold } from '@reown/appkit-scaffold-react-native';
3
+ import { erc20ABI, ErrorUtil, NamesUtil, NetworkUtil } from '@reown/appkit-common-react-native';
4
+ import { ConstantsUtil, PresetsUtil, HelpersUtil, StorageUtil, EthersConstantsUtil, EthersHelpersUtil, EthersStoreUtil } from '@reown/appkit-scaffold-utils-react-native';
5
+ import EthereumProvider, { OPTIONAL_METHODS } from '@walletconnect/ethereum-provider';
6
+ import { getAuthCaipNetworks, getWalletConnectCaipNetworks } from './utils/helpers';
7
+
8
+ // -- Types ---------------------------------------------------------------------
9
+
10
+ // @ts-expect-error: Overriden state type is correct
11
+
12
+ // -- Client --------------------------------------------------------------------
13
+ export class AppKit extends AppKitScaffold {
14
+ hasSyncedConnectedAccount = false;
15
+ options = undefined;
16
+ constructor(options) {
17
+ const {
18
+ config,
19
+ siweConfig,
20
+ chains,
21
+ defaultChain,
22
+ tokens,
23
+ chainImages,
24
+ _sdkVersion,
25
+ ...appKitOptions
26
+ } = options;
27
+ if (!config) {
28
+ throw new Error('appkit:constructor - config is undefined');
29
+ }
30
+ if (!appKitOptions.projectId) {
31
+ throw new Error(ErrorUtil.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED.shortMessage);
32
+ }
33
+ const networkControllerClient = {
34
+ switchCaipNetwork: async caipNetwork => {
35
+ const chainId = NetworkUtil.caipNetworkIdToNumber(caipNetwork?.id);
36
+ if (chainId) {
37
+ try {
38
+ await this.switchNetwork(chainId);
39
+ } catch (error) {
40
+ EthersStoreUtil.setError(error);
41
+ }
42
+ }
43
+ },
44
+ getApprovedCaipNetworksData: async () => new Promise(async resolve => {
45
+ const walletChoice = await StorageUtil.getConnectedConnector();
46
+ const walletConnectType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID];
47
+ const authType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID];
48
+ if (walletChoice?.includes(walletConnectType)) {
49
+ const provider = await this.getWalletConnectProvider();
50
+ const result = getWalletConnectCaipNetworks(provider);
51
+ resolve(result);
52
+ } else if (walletChoice?.includes(authType)) {
53
+ const result = getAuthCaipNetworks();
54
+ resolve(result);
55
+ } else {
56
+ const result = {
57
+ approvedCaipNetworkIds: undefined,
58
+ supportsAllNetworks: true
59
+ };
60
+ resolve(result);
61
+ }
62
+ })
63
+ };
64
+ const connectionControllerClient = {
65
+ connectWalletConnect: async onUri => {
66
+ const WalletConnectProvider = await this.getWalletConnectProvider();
67
+ if (!WalletConnectProvider) {
68
+ throw new Error('connectionControllerClient:getWalletConnectUri - provider is undefined');
69
+ }
70
+ WalletConnectProvider.on('display_uri', uri => {
71
+ onUri(uri);
72
+ });
73
+
74
+ // When connecting through walletconnect, we need to set the clientId in the store
75
+ const clientId = await WalletConnectProvider.signer?.client?.core?.crypto?.getClientId();
76
+ if (clientId) {
77
+ this.setClientId(clientId);
78
+ }
79
+
80
+ // SIWE
81
+ const params = await siweConfig?.getMessageParams?.();
82
+ if (siweConfig?.options?.enabled && params && Object.keys(params).length > 0) {
83
+ const {
84
+ SIWEController,
85
+ getDidChainId,
86
+ getDidAddress
87
+ } = await import('@reown/appkit-siwe-react-native');
88
+ const result = await WalletConnectProvider.authenticate({
89
+ nonce: await siweConfig.getNonce(),
90
+ methods: OPTIONAL_METHODS,
91
+ ...params
92
+ });
93
+ // Auths is an array of signed CACAO objects https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-74.md
94
+ const signedCacao = result?.auths?.[0];
95
+ if (signedCacao) {
96
+ const {
97
+ p,
98
+ s
99
+ } = signedCacao;
100
+ const chainId = getDidChainId(p.iss);
101
+ const address = getDidAddress(p.iss);
102
+ try {
103
+ // Kicks off verifyMessage and populates external states
104
+ const message = WalletConnectProvider.signer.client.formatAuthMessage({
105
+ request: p,
106
+ iss: p.iss
107
+ });
108
+ await SIWEController.verifyMessage({
109
+ message,
110
+ signature: s.s,
111
+ cacao: signedCacao
112
+ });
113
+ if (address && chainId) {
114
+ const session = {
115
+ address,
116
+ chainId: parseInt(chainId, 10)
117
+ };
118
+ SIWEController.setSession(session);
119
+ SIWEController.onSignIn?.(session);
120
+ }
121
+ } catch (error) {
122
+ // eslint-disable-next-line no-console
123
+ console.error('Error verifying message', error);
124
+ // eslint-disable-next-line no-console
125
+ await WalletConnectProvider.disconnect().catch(console.error);
126
+ // eslint-disable-next-line no-console
127
+ await SIWEController.signOut().catch(console.error);
128
+ throw error;
129
+ }
130
+ }
131
+ } else {
132
+ await WalletConnectProvider.connect();
133
+ }
134
+ await this.setWalletConnectProvider();
135
+ },
136
+ // @ts-expect-error TODO expected types in arguments are incomplete
137
+ connectExternal: async ({
138
+ id
139
+ }) => {
140
+ // If connecting with something else than walletconnect, we need to clear the clientId in the store
141
+ this.setClientId(null);
142
+ if (id === ConstantsUtil.COINBASE_CONNECTOR_ID) {
143
+ const coinbaseProvider = config.extraConnectors?.find(connector => connector.id === id);
144
+ if (!coinbaseProvider) {
145
+ throw new Error('connectionControllerClient:connectCoinbase - connector is undefined');
146
+ }
147
+ try {
148
+ await coinbaseProvider.request({
149
+ method: 'eth_requestAccounts'
150
+ });
151
+ await this.setCoinbaseProvider(coinbaseProvider);
152
+ } catch (error) {
153
+ EthersStoreUtil.setError(error);
154
+ }
155
+ } else if (id === ConstantsUtil.AUTH_CONNECTOR_ID) {
156
+ await this.setAuthProvider();
157
+ }
158
+ },
159
+ disconnect: async () => {
160
+ const provider = EthersStoreUtil.state.provider;
161
+ const providerType = EthersStoreUtil.state.providerType;
162
+ const walletConnectType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID];
163
+ const authType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID];
164
+ if (siweConfig?.options?.signOutOnDisconnect) {
165
+ const {
166
+ SIWEController
167
+ } = await import('@reown/appkit-siwe-react-native');
168
+ await SIWEController.signOut();
169
+ }
170
+ if (providerType === walletConnectType) {
171
+ const WalletConnectProvider = provider;
172
+ await WalletConnectProvider.disconnect();
173
+ } else if (providerType === authType) {
174
+ await this.authProvider?.disconnect();
175
+ } else if (provider) {
176
+ provider.emit('disconnect');
177
+ }
178
+ StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
179
+ EthersStoreUtil.reset();
180
+ this.setClientId(null);
181
+ },
182
+ signMessage: async message => {
183
+ const provider = EthersStoreUtil.state.provider;
184
+ if (!provider) {
185
+ throw new Error('connectionControllerClient:signMessage - provider is undefined');
186
+ }
187
+ const hexMessage = isHexString(message) ? message : hexlify(toUtf8Bytes(message));
188
+ const signature = await provider.request({
189
+ method: 'personal_sign',
190
+ params: [hexMessage, this.getAddress()]
191
+ });
192
+ return signature;
193
+ },
194
+ parseUnits: (value, decimals) => parseUnits(value, decimals),
195
+ formatUnits: (value, decimals) => formatUnits(value, decimals),
196
+ sendTransaction: async data => {
197
+ const {
198
+ chainId,
199
+ provider,
200
+ address
201
+ } = EthersStoreUtil.state;
202
+ if (!provider) {
203
+ throw new Error('ethersClient:sendTransaction - provider is undefined');
204
+ }
205
+ if (!address) {
206
+ throw new Error('ethersClient:sendTransaction - address is undefined');
207
+ }
208
+ const txParams = {
209
+ to: data.to,
210
+ value: data.value,
211
+ gasLimit: data.gas,
212
+ gasPrice: data.gasPrice,
213
+ data: data.data,
214
+ type: 0
215
+ };
216
+ const browserProvider = new BrowserProvider(provider, chainId);
217
+ const signer = new JsonRpcSigner(browserProvider, address);
218
+ const txResponse = await signer.sendTransaction(txParams);
219
+ const txReceipt = await txResponse.wait();
220
+ return txReceipt?.hash || null;
221
+ },
222
+ writeContract: async data => {
223
+ const {
224
+ chainId,
225
+ provider,
226
+ address
227
+ } = EthersStoreUtil.state;
228
+ if (!provider) {
229
+ throw new Error('ethersClient:writeContract - provider is undefined');
230
+ }
231
+ if (!address) {
232
+ throw new Error('ethersClient:writeContract - address is undefined');
233
+ }
234
+ const browserProvider = new BrowserProvider(provider, chainId);
235
+ const signer = new JsonRpcSigner(browserProvider, address);
236
+ const contract = new Contract(data.tokenAddress, data.abi, signer);
237
+ if (!contract || !data.method) {
238
+ throw new Error('Contract method is undefined');
239
+ }
240
+ const method = contract[data.method];
241
+ if (method) {
242
+ const tx = await method(data.receiverAddress, data.tokenAmount);
243
+ return tx;
244
+ }
245
+ throw new Error('Contract method is undefined');
246
+ },
247
+ getEnsAddress: async value => {
248
+ try {
249
+ const chainId = Number(this.getCaipNetwork()?.id);
250
+ let ensName = null;
251
+ let wcName = false;
252
+ if (NamesUtil.isReownName(value)) {
253
+ wcName = (await this?.resolveReownName(value)) || false;
254
+ }
255
+
256
+ // If on mainnet, fetch from ENS
257
+ if (chainId === 1) {
258
+ const ensProvider = new InfuraProvider('mainnet');
259
+ ensName = await ensProvider.resolveName(value);
260
+ }
261
+ return ensName || wcName || false;
262
+ } catch {
263
+ return false;
264
+ }
265
+ },
266
+ getEnsAvatar: async value => {
267
+ const chainId = Number(NetworkUtil.caipNetworkIdToNumber(this.getCaipNetwork()?.id));
268
+ if (chainId === 1) {
269
+ const ensProvider = new InfuraProvider('mainnet');
270
+ const avatar = await ensProvider.getAvatar(value);
271
+ return avatar || false;
272
+ }
273
+ return false;
274
+ }
275
+ };
276
+ super({
277
+ networkControllerClient,
278
+ connectionControllerClient,
279
+ siweControllerClient: siweConfig,
280
+ defaultChain: EthersHelpersUtil.getCaipDefaultChain(defaultChain),
281
+ tokens: HelpersUtil.getCaipTokens(tokens),
282
+ _sdkVersion: _sdkVersion ?? `react-native-ethers-${ConstantsUtil.VERSION}`,
283
+ ...appKitOptions
284
+ });
285
+ this.options = options;
286
+ this.metadata = config.metadata;
287
+ this.projectId = appKitOptions.projectId;
288
+ this.chains = chains;
289
+ this.createProvider();
290
+ EthersStoreUtil.subscribeKey('address', address => {
291
+ this.syncAccount({
292
+ address
293
+ });
294
+ });
295
+ EthersStoreUtil.subscribeKey('chainId', () => {
296
+ this.syncNetwork(chainImages);
297
+ });
298
+ this.syncRequestedNetworks(chains, chainImages);
299
+ this.syncConnectors(config);
300
+ this.syncAuthConnector(config);
301
+ }
302
+
303
+ // -- Public ------------------------------------------------------------------
304
+
305
+ // @ts-expect-error: Overriden state type is correct
306
+ getState() {
307
+ const state = super.getState();
308
+ return {
309
+ ...state,
310
+ selectedNetworkId: NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId)
311
+ };
312
+ }
313
+
314
+ // @ts-expect-error: Overriden state type is correct
315
+ subscribeState(callback) {
316
+ return super.subscribeState(state => callback({
317
+ ...state,
318
+ selectedNetworkId: NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId)
319
+ }));
320
+ }
321
+ setAddress(address) {
322
+ const originalAddress = address ? getAddress(address) : undefined;
323
+ EthersStoreUtil.setAddress(originalAddress);
324
+ }
325
+ getAddress() {
326
+ const {
327
+ address
328
+ } = EthersStoreUtil.state;
329
+ return address ? getAddress(address) : address;
330
+ }
331
+ getError() {
332
+ return EthersStoreUtil.state.error;
333
+ }
334
+ getChainId() {
335
+ return EthersStoreUtil.state.chainId;
336
+ }
337
+ getIsConnected() {
338
+ return EthersStoreUtil.state.isConnected;
339
+ }
340
+ getWalletProvider() {
341
+ return EthersStoreUtil.state.provider;
342
+ }
343
+ getWalletProviderType() {
344
+ return EthersStoreUtil.state.providerType;
345
+ }
346
+ subscribeProvider(callback) {
347
+ return EthersStoreUtil.subscribe(callback);
348
+ }
349
+ async disconnect() {
350
+ const {
351
+ provider
352
+ } = EthersStoreUtil.state;
353
+ StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
354
+ EthersStoreUtil.reset();
355
+ this.setClientId(null);
356
+ await provider.disconnect();
357
+ }
358
+
359
+ // -- Private -----------------------------------------------------------------
360
+ createProvider() {
361
+ if (!this.walletConnectProviderInitPromise) {
362
+ this.walletConnectProviderInitPromise = this.initWalletConnectProvider();
363
+ }
364
+ return this.walletConnectProviderInitPromise;
365
+ }
366
+ async initWalletConnectProvider() {
367
+ const rpcMap = this.chains ? this.chains.reduce((map, chain) => {
368
+ map[chain.chainId] = chain.rpcUrl;
369
+ return map;
370
+ }, {}) : {};
371
+ const walletConnectProviderOptions = {
372
+ projectId: this.projectId,
373
+ showQrModal: false,
374
+ rpcMap,
375
+ optionalChains: [...this.chains.map(chain => chain.chainId)],
376
+ metadata: this.metadata
377
+ };
378
+ this.walletConnectProvider = await EthereumProvider.init(walletConnectProviderOptions);
379
+ this.addWalletConnectListeners(this.walletConnectProvider);
380
+ await this.checkActiveWalletConnectProvider();
381
+ }
382
+ async getWalletConnectProvider() {
383
+ if (!this.walletConnectProvider) {
384
+ try {
385
+ await this.createProvider();
386
+ } catch (error) {
387
+ EthersStoreUtil.setError(error);
388
+ }
389
+ }
390
+ return this.walletConnectProvider;
391
+ }
392
+ syncRequestedNetworks(chains, chainImages) {
393
+ const requestedCaipNetworks = chains?.map(chain => ({
394
+ id: `${ConstantsUtil.EIP155}:${chain.chainId}`,
395
+ name: chain.name,
396
+ imageId: PresetsUtil.EIP155NetworkImageIds[chain.chainId],
397
+ imageUrl: chainImages?.[chain.chainId]
398
+ }));
399
+ this.setRequestedCaipNetworks(requestedCaipNetworks ?? []);
400
+ }
401
+ async checkActiveWalletConnectProvider() {
402
+ const WalletConnectProvider = await this.getWalletConnectProvider();
403
+ const walletId = await StorageUtil.getItem(EthersConstantsUtil.WALLET_ID);
404
+ if (WalletConnectProvider) {
405
+ if (walletId === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID) {
406
+ await this.setWalletConnectProvider();
407
+ }
408
+ }
409
+ }
410
+ async checkActiveCoinbaseProvider(provider) {
411
+ const CoinbaseProvider = provider;
412
+ const walletId = await StorageUtil.getItem(EthersConstantsUtil.WALLET_ID);
413
+ if (CoinbaseProvider) {
414
+ if (walletId === ConstantsUtil.COINBASE_CONNECTOR_ID) {
415
+ if (CoinbaseProvider.address) {
416
+ await this.setCoinbaseProvider(provider);
417
+ await this.watchCoinbase(provider);
418
+ } else {
419
+ await StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
420
+ EthersStoreUtil.reset();
421
+ }
422
+ }
423
+ }
424
+ }
425
+ async setWalletConnectProvider() {
426
+ StorageUtil.setItem(EthersConstantsUtil.WALLET_ID, ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID);
427
+ const WalletConnectProvider = await this.getWalletConnectProvider();
428
+ if (WalletConnectProvider) {
429
+ const providerType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID];
430
+ EthersStoreUtil.setChainId(WalletConnectProvider.chainId);
431
+ EthersStoreUtil.setProviderType(providerType);
432
+ EthersStoreUtil.setProvider(WalletConnectProvider);
433
+ EthersStoreUtil.setIsConnected(true);
434
+ this.setAddress(WalletConnectProvider.accounts?.[0]);
435
+ await this.watchWalletConnect();
436
+ }
437
+ }
438
+ async setCoinbaseProvider(provider) {
439
+ await StorageUtil.setItem(EthersConstantsUtil.WALLET_ID, ConstantsUtil.COINBASE_CONNECTOR_ID);
440
+ if (provider) {
441
+ const {
442
+ address,
443
+ chainId
444
+ } = await EthersHelpersUtil.getUserInfo(provider);
445
+ if (address && chainId) {
446
+ const providerType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.COINBASE_CONNECTOR_ID];
447
+ EthersStoreUtil.setChainId(chainId);
448
+ EthersStoreUtil.setProviderType(providerType);
449
+ EthersStoreUtil.setProvider(provider);
450
+ EthersStoreUtil.setIsConnected(true);
451
+ this.setAddress(address);
452
+ await this.watchCoinbase(provider);
453
+ }
454
+ }
455
+ }
456
+ async setAuthProvider() {
457
+ StorageUtil.setItem(EthersConstantsUtil.WALLET_ID, ConstantsUtil.AUTH_CONNECTOR_ID);
458
+ if (this.authProvider) {
459
+ const {
460
+ address,
461
+ chainId
462
+ } = await this.authProvider.connect();
463
+ super.setLoading(false);
464
+ if (address && chainId) {
465
+ EthersStoreUtil.setChainId(chainId);
466
+ EthersStoreUtil.setProviderType(PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID]);
467
+ EthersStoreUtil.setProvider(this.authProvider);
468
+ EthersStoreUtil.setIsConnected(true);
469
+ EthersStoreUtil.setAddress(address);
470
+ }
471
+ }
472
+ }
473
+ async watchWalletConnect() {
474
+ const WalletConnectProvider = await this.getWalletConnectProvider();
475
+ function disconnectHandler() {
476
+ StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
477
+ EthersStoreUtil.reset();
478
+ WalletConnectProvider?.removeListener('disconnect', disconnectHandler);
479
+ WalletConnectProvider?.removeListener('accountsChanged', accountsChangedHandler);
480
+ WalletConnectProvider?.removeListener('chainChanged', chainChangedHandler);
481
+ }
482
+ function chainChangedHandler(chainId) {
483
+ if (chainId) {
484
+ const chain = EthersHelpersUtil.hexStringToNumber(chainId);
485
+ EthersStoreUtil.setChainId(chain);
486
+ }
487
+ }
488
+ const accountsChangedHandler = async accounts => {
489
+ if (accounts.length > 0) {
490
+ await this.setWalletConnectProvider();
491
+ }
492
+ };
493
+ if (WalletConnectProvider) {
494
+ WalletConnectProvider.on('disconnect', disconnectHandler);
495
+ WalletConnectProvider.on('accountsChanged', accountsChangedHandler);
496
+ WalletConnectProvider.on('chainChanged', chainChangedHandler);
497
+ }
498
+ }
499
+ async watchCoinbase(provider) {
500
+ const walletId = await StorageUtil.getItem(EthersConstantsUtil.WALLET_ID);
501
+ function disconnectHandler() {
502
+ StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
503
+ EthersStoreUtil.reset();
504
+ provider?.removeListener('disconnect', disconnectHandler);
505
+ provider?.removeListener('accountsChanged', accountsChangedHandler);
506
+ provider?.removeListener('chainChanged', chainChangedHandler);
507
+ }
508
+ function accountsChangedHandler(accounts) {
509
+ if (accounts.length === 0) {
510
+ StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
511
+ EthersStoreUtil.reset();
512
+ } else {
513
+ EthersStoreUtil.setAddress(accounts[0]);
514
+ }
515
+ }
516
+ function chainChangedHandler(chainId) {
517
+ if (chainId && walletId === ConstantsUtil.COINBASE_CONNECTOR_ID) {
518
+ const chain = Number(chainId);
519
+ EthersStoreUtil.setChainId(chain);
520
+ }
521
+ }
522
+ if (provider) {
523
+ provider.on('disconnect', disconnectHandler);
524
+ provider.on('accountsChanged', accountsChangedHandler);
525
+ provider.on('chainChanged', chainChangedHandler);
526
+ }
527
+ }
528
+ async syncAccount({
529
+ address
530
+ }) {
531
+ const chainId = EthersStoreUtil.state.chainId;
532
+ const isConnected = EthersStoreUtil.state.isConnected;
533
+ if (isConnected && address && chainId) {
534
+ const caipAddress = `${ConstantsUtil.EIP155}:${chainId}:${address}`;
535
+ this.setIsConnected(isConnected);
536
+ this.setCaipAddress(caipAddress);
537
+ await Promise.all([this.syncProfile(address), this.syncBalance(address), this.getApprovedCaipNetworksData()]);
538
+ this.hasSyncedConnectedAccount = true;
539
+ } else if (!isConnected && this.hasSyncedConnectedAccount) {
540
+ this.resetAccount();
541
+ this.resetWcConnection();
542
+ this.resetNetwork();
543
+ }
544
+ }
545
+ async syncNetwork(chainImages) {
546
+ const address = EthersStoreUtil.state.address;
547
+ const chainId = EthersStoreUtil.state.chainId;
548
+ const isConnected = EthersStoreUtil.state.isConnected;
549
+ if (this.chains) {
550
+ const chain = this.chains.find(c => c.chainId === chainId);
551
+ if (chain) {
552
+ const caipChainId = `${ConstantsUtil.EIP155}:${chain.chainId}`;
553
+ this.setCaipNetwork({
554
+ id: caipChainId,
555
+ name: chain.name,
556
+ imageId: PresetsUtil.EIP155NetworkImageIds[chain.chainId],
557
+ imageUrl: chainImages?.[chain.chainId]
558
+ });
559
+ if (isConnected && address) {
560
+ const caipAddress = `${ConstantsUtil.EIP155}:${chainId}:${address}`;
561
+ this.setCaipAddress(caipAddress);
562
+ if (chain.explorerUrl) {
563
+ const url = `${chain.explorerUrl}/address/${address}`;
564
+ this.setAddressExplorerUrl(url);
565
+ } else {
566
+ this.setAddressExplorerUrl(undefined);
567
+ }
568
+ if (this.hasSyncedConnectedAccount) {
569
+ await this.syncBalance(address);
570
+ }
571
+ }
572
+ }
573
+ }
574
+ }
575
+ async syncProfile(address) {
576
+ const chainId = EthersStoreUtil.state.chainId;
577
+ try {
578
+ const response = await this.fetchIdentity({
579
+ address
580
+ });
581
+ if (!response) {
582
+ throw new Error('Couldnt fetch idendity');
583
+ }
584
+ this.setProfileName(response.name);
585
+ this.setProfileImage(response.avatar);
586
+ } catch {
587
+ if (chainId === 1) {
588
+ const ensProvider = new InfuraProvider('mainnet');
589
+ const name = await ensProvider.lookupAddress(address);
590
+ const avatar = await ensProvider.getAvatar(address);
591
+ if (name) {
592
+ this.setProfileName(name);
593
+ }
594
+ if (avatar) {
595
+ this.setProfileImage(avatar);
596
+ }
597
+ } else {
598
+ this.setProfileName(undefined);
599
+ this.setProfileImage(undefined);
600
+ }
601
+ }
602
+ }
603
+ async syncBalance(address) {
604
+ const chainId = EthersStoreUtil.state.chainId;
605
+ if (chainId && this.chains) {
606
+ const chain = this.chains.find(c => c.chainId === chainId);
607
+ const token = this.options?.tokens?.[chainId];
608
+ if (chain) {
609
+ const jsonRpcProvider = new JsonRpcProvider(chain.rpcUrl, {
610
+ chainId,
611
+ name: chain.name
612
+ });
613
+ if (jsonRpcProvider) {
614
+ if (token) {
615
+ // Get balance from custom token address
616
+ const erc20 = new Contract(token.address, erc20ABI, jsonRpcProvider);
617
+ // @ts-expect-error
618
+ const decimals = await erc20.decimals();
619
+ // @ts-expect-error
620
+ const symbol = await erc20.symbol();
621
+ // @ts-expect-error
622
+ const balanceOf = await erc20.balanceOf(address);
623
+ this.setBalance(formatUnits(balanceOf, decimals), symbol);
624
+ } else {
625
+ const balance = await jsonRpcProvider.getBalance(address);
626
+ const formattedBalance = formatEther(balance);
627
+ this.setBalance(formattedBalance, chain.currency);
628
+ }
629
+ }
630
+ }
631
+ }
632
+ }
633
+ async switchNetwork(chainId) {
634
+ const provider = EthersStoreUtil.state.provider;
635
+ const providerType = EthersStoreUtil.state.providerType;
636
+ if (this.chains) {
637
+ const chain = this.chains.find(c => c.chainId === chainId);
638
+ const walletConnectType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID];
639
+ const coinbaseType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.COINBASE_CONNECTOR_ID];
640
+ const authType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID];
641
+ if (providerType === walletConnectType && chain) {
642
+ const WalletConnectProvider = provider;
643
+ if (WalletConnectProvider) {
644
+ try {
645
+ await WalletConnectProvider.request({
646
+ method: 'wallet_switchEthereumChain',
647
+ params: [{
648
+ chainId: EthersHelpersUtil.numberToHexString(chain.chainId)
649
+ }]
650
+ });
651
+ EthersStoreUtil.setChainId(chainId);
652
+ } catch (switchError) {
653
+ const message = switchError?.message;
654
+ if (/(?<temp1>user rejected)/u.test(message?.toLowerCase())) {
655
+ throw new Error('Chain is not supported');
656
+ }
657
+ await EthersHelpersUtil.addEthereumChain(WalletConnectProvider, chain);
658
+ }
659
+ }
660
+ } else if (providerType === coinbaseType && chain) {
661
+ const CoinbaseProvider = provider;
662
+ if (CoinbaseProvider) {
663
+ try {
664
+ await CoinbaseProvider.request({
665
+ method: 'wallet_switchEthereumChain',
666
+ params: [{
667
+ chainId: EthersHelpersUtil.numberToHexString(chain.chainId)
668
+ }]
669
+ });
670
+ EthersStoreUtil.setChainId(chain.chainId);
671
+ } catch (switchError) {
672
+ if (switchError.code === EthersConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID || switchError.code === EthersConstantsUtil.ERROR_CODE_DEFAULT || switchError?.data?.originalError?.code === EthersConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID) {
673
+ await EthersHelpersUtil.addEthereumChain(CoinbaseProvider, chain);
674
+ } else {
675
+ throw new Error('Error switching network');
676
+ }
677
+ }
678
+ }
679
+ } else if (providerType === authType) {
680
+ if (this.authProvider && chain?.chainId) {
681
+ try {
682
+ await this.authProvider?.switchNetwork(chain?.chainId);
683
+ EthersStoreUtil.setChainId(chain.chainId);
684
+ } catch {
685
+ throw new Error('Switching chain failed');
686
+ }
687
+ }
688
+ }
689
+ }
690
+ }
691
+ async handleAuthSetPreferredAccount(address, type) {
692
+ if (!address) {
693
+ return;
694
+ }
695
+ const chainId = this.getCaipNetwork()?.id;
696
+ const caipAddress = `${ConstantsUtil.EIP155}:${chainId}:${address}`;
697
+ this.setCaipAddress(caipAddress);
698
+ this.setPreferredAccountType(type);
699
+ await this.syncAccount({
700
+ address: address
701
+ });
702
+ this.setLoading(false);
703
+ }
704
+ syncConnectors(config) {
705
+ const _connectors = [];
706
+ const EXCLUDED_CONNECTORS = [ConstantsUtil.AUTH_CONNECTOR_ID];
707
+ _connectors.push({
708
+ id: ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID,
709
+ explorerId: PresetsUtil.ConnectorExplorerIds[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
710
+ imageId: PresetsUtil.ConnectorImageIds[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
711
+ imageUrl: this.options?.connectorImages?.[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
712
+ name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
713
+ type: PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID]
714
+ });
715
+ config.extraConnectors?.forEach(connector => {
716
+ if (!EXCLUDED_CONNECTORS.includes(connector.id)) {
717
+ if (connector.id === ConstantsUtil.COINBASE_CONNECTOR_ID) {
718
+ _connectors.push({
719
+ id: ConstantsUtil.COINBASE_CONNECTOR_ID,
720
+ explorerId: PresetsUtil.ConnectorExplorerIds[ConstantsUtil.COINBASE_CONNECTOR_ID],
721
+ imageId: PresetsUtil.ConnectorImageIds[ConstantsUtil.COINBASE_CONNECTOR_ID],
722
+ imageUrl: this.options?.connectorImages?.[ConstantsUtil.COINBASE_CONNECTOR_ID],
723
+ name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.COINBASE_CONNECTOR_ID],
724
+ type: PresetsUtil.ConnectorTypesMap[ConstantsUtil.COINBASE_CONNECTOR_ID]
725
+ });
726
+ this.checkActiveCoinbaseProvider(connector);
727
+ } else {
728
+ _connectors.push({
729
+ id: connector.id,
730
+ name: connector.name,
731
+ type: 'EXTERNAL'
732
+ });
733
+ }
734
+ }
735
+ });
736
+ this.setConnectors(_connectors);
737
+ }
738
+ async syncAuthConnector(config) {
739
+ const authConnector = config.extraConnectors?.find(connector => connector.id === ConstantsUtil.AUTH_CONNECTOR_ID);
740
+ if (!authConnector) {
741
+ return;
742
+ }
743
+ this.authProvider = authConnector;
744
+ this.addConnector({
745
+ id: ConstantsUtil.AUTH_CONNECTOR_ID,
746
+ name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.AUTH_CONNECTOR_ID],
747
+ type: PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID],
748
+ provider: authConnector
749
+ });
750
+ const connectedConnector = await StorageUtil.getItem('@w3m/connected_connector');
751
+ if (connectedConnector === 'AUTH') {
752
+ // Set loader until it reconnects
753
+ this.setLoading(true);
754
+ }
755
+ const {
756
+ isConnected
757
+ } = await this.authProvider.isConnected();
758
+ if (isConnected) {
759
+ this.setAuthProvider();
760
+ }
761
+ this.addAuthListeners(this.authProvider);
762
+ }
763
+ async addAuthListeners(authProvider) {
764
+ authProvider.onSetPreferredAccount(async ({
765
+ address,
766
+ type
767
+ }) => {
768
+ if (address) {
769
+ await this.handleAuthSetPreferredAccount(address, type);
770
+ }
771
+ this.setLoading(false);
772
+ });
773
+ authProvider.setOnTimeout(async () => {
774
+ this.handleAlertError(ErrorUtil.ALERT_ERRORS.SOCIALS_TIMEOUT);
775
+ });
776
+ }
777
+ async addWalletConnectListeners(provider) {
778
+ if (provider) {
779
+ provider.signer.client.core.relayer.provider.on('payload', payload => {
780
+ if (payload?.error) {
781
+ this.handleAlertError(payload?.error.message);
782
+ }
783
+ });
784
+ }
785
+ }
786
+ }
787
+ //# sourceMappingURL=client.js.map