@reown/appkit-ethers-react-native 0.0.0-fix-duplicated-wallets-20250320212046 → 0.0.0-fix-cover-screen-20250328152136

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