@reown/appkit-ethers-react-native 1.2.4 → 2.0.0

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