@reown/appkit-ethers-react-native 0.0.0-fix-approved-networks-20250822000414 → 0.0.0-fix-improvements-20250827190629

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