@reown/appkit-ethers-react-native 0.0.0-canary-20240912195440

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