@reown/appkit-ethers-react-native 0.0.0-develop-20240925193922 → 0.0.0-refactor-modal-migration-20241003185737

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,732 +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 { 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('appkit:constructor - projectId is undefined');
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', () => {
291
- this.syncAccount();
292
- });
293
- EthersStoreUtil.subscribeKey('chainId', () => {
294
- this.syncNetwork(chainImages);
295
- });
296
- this.syncRequestedNetworks(chains, chainImages);
297
- this.syncConnectors(config);
298
- this.syncAuthConnector(config);
299
- }
300
-
301
- // -- Public ------------------------------------------------------------------
302
-
303
- // @ts-expect-error: Overriden state type is correct
304
- getState() {
305
- const state = super.getState();
306
- return {
307
- ...state,
308
- selectedNetworkId: NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId)
309
- };
310
- }
311
-
312
- // @ts-expect-error: Overriden state type is correct
313
- subscribeState(callback) {
314
- return super.subscribeState(state => callback({
315
- ...state,
316
- selectedNetworkId: NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId)
317
- }));
318
- }
319
- setAddress(address) {
320
- const originalAddress = address ? getAddress(address) : undefined;
321
- EthersStoreUtil.setAddress(originalAddress);
322
- }
323
- getAddress() {
324
- const {
325
- address
326
- } = EthersStoreUtil.state;
327
- return address ? getAddress(address) : address;
328
- }
329
- getError() {
330
- return EthersStoreUtil.state.error;
331
- }
332
- getChainId() {
333
- return EthersStoreUtil.state.chainId;
334
- }
335
- getIsConnected() {
336
- return EthersStoreUtil.state.isConnected;
337
- }
338
- getWalletProvider() {
339
- return EthersStoreUtil.state.provider;
340
- }
341
- getWalletProviderType() {
342
- return EthersStoreUtil.state.providerType;
343
- }
344
- subscribeProvider(callback) {
345
- return EthersStoreUtil.subscribe(callback);
346
- }
347
- async disconnect() {
348
- const {
349
- provider
350
- } = EthersStoreUtil.state;
351
- StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
352
- EthersStoreUtil.reset();
353
- this.setClientId(null);
354
- await provider.disconnect();
355
- }
356
-
357
- // -- Private -----------------------------------------------------------------
358
- createProvider() {
359
- if (!this.walletConnectProviderInitPromise) {
360
- this.walletConnectProviderInitPromise = this.initWalletConnectProvider();
361
- }
362
- return this.walletConnectProviderInitPromise;
363
- }
364
- async initWalletConnectProvider() {
365
- const rpcMap = this.chains ? this.chains.reduce((map, chain) => {
366
- map[chain.chainId] = chain.rpcUrl;
367
- return map;
368
- }, {}) : {};
369
- const walletConnectProviderOptions = {
370
- projectId: this.projectId,
371
- showQrModal: false,
372
- rpcMap,
373
- optionalChains: [...this.chains.map(chain => chain.chainId)],
374
- metadata: this.metadata
375
- };
376
- this.walletConnectProvider = await EthereumProvider.init(walletConnectProviderOptions);
377
- await this.checkActiveWalletConnectProvider();
378
- }
379
- async getWalletConnectProvider() {
380
- if (!this.walletConnectProvider) {
381
- try {
382
- await this.createProvider();
383
- } catch (error) {
384
- EthersStoreUtil.setError(error);
385
- }
386
- }
387
- return this.walletConnectProvider;
388
- }
389
- syncRequestedNetworks(chains, chainImages) {
390
- const requestedCaipNetworks = chains?.map(chain => ({
391
- id: `${ConstantsUtil.EIP155}:${chain.chainId}`,
392
- name: chain.name,
393
- imageId: PresetsUtil.EIP155NetworkImageIds[chain.chainId],
394
- imageUrl: chainImages?.[chain.chainId]
395
- }));
396
- this.setRequestedCaipNetworks(requestedCaipNetworks ?? []);
397
- }
398
- async checkActiveWalletConnectProvider() {
399
- const WalletConnectProvider = await this.getWalletConnectProvider();
400
- const walletId = await StorageUtil.getItem(EthersConstantsUtil.WALLET_ID);
401
- if (WalletConnectProvider) {
402
- if (walletId === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID) {
403
- await this.setWalletConnectProvider();
404
- }
405
- }
406
- }
407
- async checkActiveCoinbaseProvider(provider) {
408
- const CoinbaseProvider = provider;
409
- const walletId = await StorageUtil.getItem(EthersConstantsUtil.WALLET_ID);
410
- if (CoinbaseProvider) {
411
- if (walletId === ConstantsUtil.COINBASE_CONNECTOR_ID) {
412
- if (CoinbaseProvider.address) {
413
- await this.setCoinbaseProvider(provider);
414
- await this.watchCoinbase(provider);
415
- } else {
416
- await StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
417
- EthersStoreUtil.reset();
418
- }
419
- }
420
- }
421
- }
422
- async setWalletConnectProvider() {
423
- StorageUtil.setItem(EthersConstantsUtil.WALLET_ID, ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID);
424
- const WalletConnectProvider = await this.getWalletConnectProvider();
425
- if (WalletConnectProvider) {
426
- const providerType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID];
427
- EthersStoreUtil.setChainId(WalletConnectProvider.chainId);
428
- EthersStoreUtil.setProviderType(providerType);
429
- EthersStoreUtil.setProvider(WalletConnectProvider);
430
- EthersStoreUtil.setIsConnected(true);
431
- this.setAddress(WalletConnectProvider.accounts?.[0]);
432
- await this.watchWalletConnect();
433
- }
434
- }
435
- async setCoinbaseProvider(provider) {
436
- await StorageUtil.setItem(EthersConstantsUtil.WALLET_ID, ConstantsUtil.COINBASE_CONNECTOR_ID);
437
- if (provider) {
438
- const {
439
- address,
440
- chainId
441
- } = await EthersHelpersUtil.getUserInfo(provider);
442
- if (address && chainId) {
443
- const providerType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.COINBASE_CONNECTOR_ID];
444
- EthersStoreUtil.setChainId(chainId);
445
- EthersStoreUtil.setProviderType(providerType);
446
- EthersStoreUtil.setProvider(provider);
447
- EthersStoreUtil.setIsConnected(true);
448
- this.setAddress(address);
449
- await this.watchCoinbase(provider);
450
- }
451
- }
452
- }
453
- async setAuthProvider() {
454
- StorageUtil.setItem(EthersConstantsUtil.WALLET_ID, ConstantsUtil.AUTH_CONNECTOR_ID);
455
- if (this.authProvider) {
456
- const {
457
- address,
458
- chainId
459
- } = await this.authProvider.connect();
460
- super.setLoading(false);
461
- if (address && chainId) {
462
- EthersStoreUtil.setChainId(chainId);
463
- EthersStoreUtil.setProviderType(PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID]);
464
- EthersStoreUtil.setProvider(this.authProvider);
465
- EthersStoreUtil.setIsConnected(true);
466
- EthersStoreUtil.setAddress(address);
467
- }
468
- }
469
- }
470
- async watchWalletConnect() {
471
- const WalletConnectProvider = await this.getWalletConnectProvider();
472
- function disconnectHandler() {
473
- StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
474
- EthersStoreUtil.reset();
475
- WalletConnectProvider?.removeListener('disconnect', disconnectHandler);
476
- WalletConnectProvider?.removeListener('accountsChanged', accountsChangedHandler);
477
- WalletConnectProvider?.removeListener('chainChanged', chainChangedHandler);
478
- }
479
- function chainChangedHandler(chainId) {
480
- if (chainId) {
481
- const chain = EthersHelpersUtil.hexStringToNumber(chainId);
482
- EthersStoreUtil.setChainId(chain);
483
- }
484
- }
485
- const accountsChangedHandler = async accounts => {
486
- if (accounts.length > 0) {
487
- await this.setWalletConnectProvider();
488
- }
489
- };
490
- if (WalletConnectProvider) {
491
- WalletConnectProvider.on('disconnect', disconnectHandler);
492
- WalletConnectProvider.on('accountsChanged', accountsChangedHandler);
493
- WalletConnectProvider.on('chainChanged', chainChangedHandler);
494
- }
495
- }
496
- async watchCoinbase(provider) {
497
- const walletId = await StorageUtil.getItem(EthersConstantsUtil.WALLET_ID);
498
- function disconnectHandler() {
499
- StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
500
- EthersStoreUtil.reset();
501
- provider?.removeListener('disconnect', disconnectHandler);
502
- provider?.removeListener('accountsChanged', accountsChangedHandler);
503
- provider?.removeListener('chainChanged', chainChangedHandler);
504
- }
505
- function accountsChangedHandler(accounts) {
506
- if (accounts.length === 0) {
507
- StorageUtil.removeItem(EthersConstantsUtil.WALLET_ID);
508
- EthersStoreUtil.reset();
509
- } else {
510
- EthersStoreUtil.setAddress(accounts[0]);
511
- }
512
- }
513
- function chainChangedHandler(chainId) {
514
- if (chainId && walletId === ConstantsUtil.COINBASE_CONNECTOR_ID) {
515
- const chain = Number(chainId);
516
- EthersStoreUtil.setChainId(chain);
517
- }
518
- }
519
- if (provider) {
520
- provider.on('disconnect', disconnectHandler);
521
- provider.on('accountsChanged', accountsChangedHandler);
522
- provider.on('chainChanged', chainChangedHandler);
523
- }
524
- }
525
- async syncAccount() {
526
- const address = EthersStoreUtil.state.address;
527
- const chainId = EthersStoreUtil.state.chainId;
528
- const isConnected = EthersStoreUtil.state.isConnected;
529
- this.resetAccount();
530
- if (isConnected && address && chainId) {
531
- const caipAddress = `${ConstantsUtil.EIP155}:${chainId}:${address}`;
532
- this.setIsConnected(isConnected);
533
- this.setCaipAddress(caipAddress);
534
- await Promise.all([this.syncProfile(address), this.syncBalance(address), this.getApprovedCaipNetworksData()]);
535
- this.hasSyncedConnectedAccount = true;
536
- } else if (!isConnected && this.hasSyncedConnectedAccount) {
537
- this.resetWcConnection();
538
- this.resetNetwork();
539
- }
540
- }
541
- async syncNetwork(chainImages) {
542
- const address = EthersStoreUtil.state.address;
543
- const chainId = EthersStoreUtil.state.chainId;
544
- const isConnected = EthersStoreUtil.state.isConnected;
545
- if (this.chains) {
546
- const chain = this.chains.find(c => c.chainId === chainId);
547
- if (chain) {
548
- const caipChainId = `${ConstantsUtil.EIP155}:${chain.chainId}`;
549
- this.setCaipNetwork({
550
- id: caipChainId,
551
- name: chain.name,
552
- imageId: PresetsUtil.EIP155NetworkImageIds[chain.chainId],
553
- imageUrl: chainImages?.[chain.chainId]
554
- });
555
- if (isConnected && address) {
556
- const caipAddress = `${ConstantsUtil.EIP155}:${chainId}:${address}`;
557
- this.setCaipAddress(caipAddress);
558
- if (chain.explorerUrl) {
559
- const url = `${chain.explorerUrl}/address/${address}`;
560
- this.setAddressExplorerUrl(url);
561
- } else {
562
- this.setAddressExplorerUrl(undefined);
563
- }
564
- if (this.hasSyncedConnectedAccount) {
565
- await this.syncBalance(address);
566
- }
567
- }
568
- }
569
- }
570
- }
571
- async syncProfile(address) {
572
- const chainId = EthersStoreUtil.state.chainId;
573
- try {
574
- const response = await this.fetchIdentity({
575
- address
576
- });
577
- if (!response) {
578
- throw new Error('Couldnt fetch idendity');
579
- }
580
- this.setProfileName(response.name);
581
- this.setProfileImage(response.avatar);
582
- } catch {
583
- if (chainId === 1) {
584
- const ensProvider = new InfuraProvider('mainnet');
585
- const name = await ensProvider.lookupAddress(address);
586
- const avatar = await ensProvider.getAvatar(address);
587
- if (name) {
588
- this.setProfileName(name);
589
- }
590
- if (avatar) {
591
- this.setProfileImage(avatar);
592
- }
593
- } else {
594
- this.setProfileName(undefined);
595
- this.setProfileImage(undefined);
596
- }
597
- }
598
- }
599
- async syncBalance(address) {
600
- const chainId = EthersStoreUtil.state.chainId;
601
- if (chainId && this.chains) {
602
- const chain = this.chains.find(c => c.chainId === chainId);
603
- if (chain) {
604
- const jsonRpcProvider = new JsonRpcProvider(chain.rpcUrl, {
605
- chainId,
606
- name: chain.name
607
- });
608
- if (jsonRpcProvider) {
609
- const balance = await jsonRpcProvider.getBalance(address);
610
- const formattedBalance = formatEther(balance);
611
- this.setBalance(formattedBalance, chain.currency);
612
- }
613
- }
614
- }
615
- }
616
- async switchNetwork(chainId) {
617
- const provider = EthersStoreUtil.state.provider;
618
- const providerType = EthersStoreUtil.state.providerType;
619
- if (this.chains) {
620
- const chain = this.chains.find(c => c.chainId === chainId);
621
- const walletConnectType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID];
622
- const coinbaseType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.COINBASE_CONNECTOR_ID];
623
- const authType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID];
624
- if (providerType === walletConnectType && chain) {
625
- const WalletConnectProvider = provider;
626
- if (WalletConnectProvider) {
627
- try {
628
- await WalletConnectProvider.request({
629
- method: 'wallet_switchEthereumChain',
630
- params: [{
631
- chainId: EthersHelpersUtil.numberToHexString(chain.chainId)
632
- }]
633
- });
634
- EthersStoreUtil.setChainId(chainId);
635
- } catch (switchError) {
636
- const message = switchError?.message;
637
- if (/(?<temp1>user rejected)/u.test(message?.toLowerCase())) {
638
- throw new Error('Chain is not supported');
639
- }
640
- await EthersHelpersUtil.addEthereumChain(WalletConnectProvider, chain);
641
- }
642
- }
643
- } else if (providerType === coinbaseType && chain) {
644
- const CoinbaseProvider = provider;
645
- if (CoinbaseProvider) {
646
- try {
647
- await CoinbaseProvider.request({
648
- method: 'wallet_switchEthereumChain',
649
- params: [{
650
- chainId: EthersHelpersUtil.numberToHexString(chain.chainId)
651
- }]
652
- });
653
- EthersStoreUtil.setChainId(chain.chainId);
654
- } catch (switchError) {
655
- 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) {
656
- await EthersHelpersUtil.addEthereumChain(CoinbaseProvider, chain);
657
- } else {
658
- throw new Error('Error switching network');
659
- }
660
- }
661
- }
662
- } else if (providerType === authType) {
663
- if (this.authProvider && chain?.chainId) {
664
- try {
665
- await this.authProvider?.switchNetwork(chain?.chainId);
666
- EthersStoreUtil.setChainId(chain.chainId);
667
- } catch {
668
- throw new Error('Switching chain failed');
669
- }
670
- }
671
- }
672
- }
673
- }
674
- syncConnectors(config) {
675
- const _connectors = [];
676
- const EXCLUDED_CONNECTORS = [ConstantsUtil.AUTH_CONNECTOR_ID];
677
- _connectors.push({
678
- id: ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID,
679
- explorerId: PresetsUtil.ConnectorExplorerIds[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
680
- imageId: PresetsUtil.ConnectorImageIds[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
681
- imageUrl: this.options?.connectorImages?.[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
682
- name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID],
683
- type: PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID]
684
- });
685
- config.extraConnectors?.forEach(connector => {
686
- if (!EXCLUDED_CONNECTORS.includes(connector.id)) {
687
- if (connector.id === ConstantsUtil.COINBASE_CONNECTOR_ID) {
688
- _connectors.push({
689
- id: ConstantsUtil.COINBASE_CONNECTOR_ID,
690
- explorerId: PresetsUtil.ConnectorExplorerIds[ConstantsUtil.COINBASE_CONNECTOR_ID],
691
- imageId: PresetsUtil.ConnectorImageIds[ConstantsUtil.COINBASE_CONNECTOR_ID],
692
- imageUrl: this.options?.connectorImages?.[ConstantsUtil.COINBASE_CONNECTOR_ID],
693
- name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.COINBASE_CONNECTOR_ID],
694
- type: PresetsUtil.ConnectorTypesMap[ConstantsUtil.COINBASE_CONNECTOR_ID]
695
- });
696
- this.checkActiveCoinbaseProvider(connector);
697
- } else {
698
- _connectors.push({
699
- id: connector.id,
700
- name: connector.name,
701
- type: 'EXTERNAL'
702
- });
703
- }
704
- }
705
- });
706
- this.setConnectors(_connectors);
707
- }
708
- async syncAuthConnector(config) {
709
- const authConnector = config.extraConnectors?.find(connector => connector.id === ConstantsUtil.AUTH_CONNECTOR_ID);
710
- if (!authConnector) {
711
- return;
712
- }
713
- this.authProvider = authConnector;
714
- this.addConnector({
715
- id: ConstantsUtil.AUTH_CONNECTOR_ID,
716
- name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.AUTH_CONNECTOR_ID],
717
- type: PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID],
718
- provider: authConnector
719
- });
720
- const connectedConnector = await StorageUtil.getItem('@w3m/connected_connector');
721
- if (connectedConnector === 'AUTH') {
722
- this.setLoading(true);
723
- }
724
- const {
725
- isConnected
726
- } = await this.authProvider.isConnected();
727
- if (isConnected) {
728
- this.setAuthProvider();
729
- }
730
- }
731
- }
732
- //# sourceMappingURL=client.js.map