@reown/appkit-wagmi-react-native 0.0.0-fix-approved-networks-20250822000414 → 0.0.0-fix-ui-changes-20250828183750

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 (51) hide show
  1. package/lib/commonjs/adapter.js +160 -0
  2. package/lib/commonjs/adapter.js.map +1 -0
  3. package/lib/commonjs/connectors/UniversalConnector.js +204 -0
  4. package/lib/commonjs/connectors/UniversalConnector.js.map +1 -0
  5. package/lib/commonjs/index.js +8 -121
  6. package/lib/commonjs/index.js.map +1 -1
  7. package/lib/commonjs/package.json +1 -0
  8. package/lib/commonjs/utils/helpers.js +16 -45
  9. package/lib/commonjs/utils/helpers.js.map +1 -1
  10. package/lib/module/adapter.js +155 -0
  11. package/lib/module/adapter.js.map +1 -0
  12. package/lib/module/connectors/UniversalConnector.js +200 -0
  13. package/lib/module/connectors/UniversalConnector.js.map +1 -0
  14. package/lib/module/index.js +4 -91
  15. package/lib/module/index.js.map +1 -1
  16. package/lib/module/utils/helpers.js +16 -41
  17. package/lib/module/utils/helpers.js.map +1 -1
  18. package/lib/typescript/adapter.d.ts +25 -0
  19. package/lib/typescript/adapter.d.ts.map +1 -0
  20. package/lib/typescript/connectors/UniversalConnector.d.ts +5 -0
  21. package/lib/typescript/connectors/UniversalConnector.d.ts.map +1 -0
  22. package/lib/typescript/index.d.ts +3 -24
  23. package/lib/typescript/index.d.ts.map +1 -1
  24. package/lib/typescript/utils/helpers.d.ts +3 -13
  25. package/lib/typescript/utils/helpers.d.ts.map +1 -1
  26. package/package.json +8 -24
  27. package/src/adapter.ts +197 -0
  28. package/src/connectors/UniversalConnector.ts +214 -0
  29. package/src/index.tsx +3 -121
  30. package/src/utils/helpers.ts +17 -57
  31. package/lib/commonjs/client.js +0 -516
  32. package/lib/commonjs/client.js.map +0 -1
  33. package/lib/commonjs/connectors/WalletConnectConnector.js +0 -355
  34. package/lib/commonjs/connectors/WalletConnectConnector.js.map +0 -1
  35. package/lib/commonjs/utils/defaultWagmiConfig.js +0 -46
  36. package/lib/commonjs/utils/defaultWagmiConfig.js.map +0 -1
  37. package/lib/module/client.js +0 -510
  38. package/lib/module/client.js.map +0 -1
  39. package/lib/module/connectors/WalletConnectConnector.js +0 -350
  40. package/lib/module/connectors/WalletConnectConnector.js.map +0 -1
  41. package/lib/module/utils/defaultWagmiConfig.js +0 -40
  42. package/lib/module/utils/defaultWagmiConfig.js.map +0 -1
  43. package/lib/typescript/client.d.ts +0 -40
  44. package/lib/typescript/client.d.ts.map +0 -1
  45. package/lib/typescript/connectors/WalletConnectConnector.d.ts +0 -74
  46. package/lib/typescript/connectors/WalletConnectConnector.d.ts.map +0 -1
  47. package/lib/typescript/utils/defaultWagmiConfig.d.ts +0 -11
  48. package/lib/typescript/utils/defaultWagmiConfig.d.ts.map +0 -1
  49. package/src/client.ts +0 -644
  50. package/src/connectors/WalletConnectConnector.ts +0 -472
  51. package/src/utils/defaultWagmiConfig.ts +0 -53
package/src/client.ts DELETED
@@ -1,644 +0,0 @@
1
- import { formatUnits, type Hex, parseUnits } from 'viem';
2
- import {
3
- type GetAccountReturnType,
4
- type GetEnsAddressReturnType,
5
- type Connector as WagmiConnector,
6
- connect,
7
- reconnect,
8
- disconnect,
9
- signMessage,
10
- getAccount,
11
- switchChain,
12
- watchAccount,
13
- watchConnectors,
14
- getEnsName,
15
- getEnsAvatar as wagmiGetEnsAvatar,
16
- getEnsAddress as wagmiGetEnsAddress,
17
- getBalance,
18
- prepareTransactionRequest,
19
- estimateGas as wagmiEstimateGas,
20
- sendTransaction as wagmiSendTransaction,
21
- waitForTransactionReceipt,
22
- writeContract as wagmiWriteContract
23
- } from '@wagmi/core';
24
- import { normalize } from 'viem/ens';
25
- import { mainnet, type Chain } from '@wagmi/core/chains';
26
- import EthereumProvider, { OPTIONAL_METHODS } from '@walletconnect/ethereum-provider';
27
- import { type JsonRpcError } from '@walletconnect/jsonrpc-types';
28
- import {
29
- type CaipAddress,
30
- type CaipNetwork,
31
- type CaipNetworkId,
32
- type ConnectionControllerClient,
33
- type Connector,
34
- type LibraryOptions,
35
- type NetworkControllerClient,
36
- type PublicStateControllerState,
37
- type SendTransactionArgs,
38
- type Token,
39
- AppKitScaffold,
40
- type WriteContractArgs,
41
- type AppKitFrameProvider,
42
- type EstimateGasTransactionArgs
43
- } from '@reown/appkit-scaffold-react-native';
44
- import { HelpersUtil, StorageUtil } from '@reown/appkit-scaffold-utils-react-native';
45
- import {
46
- NetworkUtil,
47
- NamesUtil,
48
- ErrorUtil,
49
- ConstantsUtil,
50
- PresetsUtil,
51
- type ConnectorType
52
- } from '@reown/appkit-common-react-native';
53
- import {
54
- SIWEController,
55
- getDidChainId,
56
- getDidAddress,
57
- type AppKitSIWEClient
58
- } from '@reown/appkit-siwe-react-native';
59
- import {
60
- getCaipDefaultChain,
61
- getAuthCaipNetworks,
62
- getWalletConnectCaipNetworks,
63
- requireCaipAddress
64
- } from './utils/helpers';
65
- import { defaultWagmiConfig } from './utils/defaultWagmiConfig';
66
-
67
- // -- Types ---------------------------------------------------------------------
68
- type WagmiConfig = ReturnType<typeof defaultWagmiConfig>;
69
-
70
- export interface AppKitClientOptions extends Omit<LibraryOptions, 'defaultChain' | 'tokens'> {
71
- wagmiConfig: WagmiConfig;
72
- siweConfig?: AppKitSIWEClient;
73
- defaultChain?: Chain;
74
- chainImages?: Record<number, string>;
75
- connectorImages?: Record<string, string>;
76
- tokens?: Record<number, Token>;
77
- }
78
-
79
- export type AppKitOptions = Omit<AppKitClientOptions, '_sdkVersion'>;
80
-
81
- // @ts-expect-error: Overriden state type is correct
82
- interface AppKitState extends PublicStateControllerState {
83
- selectedNetworkId: number | undefined;
84
- }
85
-
86
- // -- Client --------------------------------------------------------------------
87
- export class AppKit extends AppKitScaffold {
88
- private hasSyncedConnectedAccount = false;
89
-
90
- private options: AppKitClientOptions | undefined = undefined;
91
-
92
- private wagmiConfig: WagmiConfig;
93
-
94
- public constructor(options: AppKitClientOptions) {
95
- const { wagmiConfig, siweConfig, defaultChain, tokens, _sdkVersion, ...appKitOptions } =
96
- options;
97
-
98
- if (!wagmiConfig) {
99
- throw new Error('appkit:constructor - wagmiConfig is undefined');
100
- }
101
-
102
- if (!appKitOptions.projectId) {
103
- throw new Error(ErrorUtil.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED.shortMessage);
104
- }
105
-
106
- const networkControllerClient: NetworkControllerClient = {
107
- switchCaipNetwork: async caipNetwork => {
108
- const chainId = NetworkUtil.caipNetworkIdToNumber(caipNetwork?.id);
109
- if (chainId) {
110
- await switchChain(wagmiConfig, { chainId });
111
- }
112
- },
113
-
114
- async getApprovedCaipNetworksData(connectorType?: ConnectorType) {
115
- const walletConnectType =
116
- PresetsUtil.ConnectorTypesMap[ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID]!;
117
-
118
- const authType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID]!;
119
-
120
- if (connectorType?.includes(walletConnectType)) {
121
- const connector = wagmiConfig.connectors.find(
122
- c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID
123
- );
124
-
125
- return getWalletConnectCaipNetworks(connector);
126
- } else if (connectorType?.includes(authType)) {
127
- return getAuthCaipNetworks();
128
- }
129
-
130
- return { approvedCaipNetworkIds: undefined, supportsAllNetworks: true };
131
- }
132
- };
133
-
134
- const connectionControllerClient: ConnectionControllerClient = {
135
- connectWalletConnect: async (onUri, walletUniversalLink) => {
136
- const connector = wagmiConfig.connectors.find(
137
- c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID
138
- );
139
- if (!connector) {
140
- throw new Error(
141
- 'connectionControllerClient:getWalletConnectUri - connector is undefined'
142
- );
143
- }
144
-
145
- const provider = (await connector.getProvider()) as Awaited<
146
- ReturnType<(typeof EthereumProvider)['init']>
147
- >;
148
-
149
- provider.on('display_uri', data => {
150
- onUri(data);
151
- });
152
-
153
- // When connecting through walletconnect, we need to set the clientId in the store
154
- const clientId = await provider.signer?.client?.core?.crypto?.getClientId();
155
- if (clientId) {
156
- this.setClientId(clientId);
157
- }
158
-
159
- const chainId = NetworkUtil.caipNetworkIdToNumber(this.getCaipNetwork()?.id);
160
-
161
- // SIWE
162
- const siweParams = await siweConfig?.getMessageParams?.();
163
- // Make sure client uses ethereum provider version that supports `authenticate`
164
- if (
165
- siweConfig?.options?.enabled &&
166
- typeof provider?.authenticate === 'function' &&
167
- siweParams &&
168
- Object.keys(siweParams || {}).length > 0
169
- ) {
170
- // @ts-expect-error - setting requested chains beforehand avoids wagmi auto disconnecting the session when `connect` is called because it things chains are stale
171
- await connector.setRequestedChainsIds(siweParams.chains);
172
- const result = await provider.authenticate(
173
- {
174
- nonce: await siweConfig.getNonce(),
175
- methods: [...OPTIONAL_METHODS],
176
- ...siweParams
177
- },
178
- walletUniversalLink
179
- );
180
-
181
- // Auths is an array of signed CACAO objects https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-74.md
182
- const signedCacao = result?.auths?.[0];
183
- if (signedCacao) {
184
- const { p, s } = signedCacao;
185
- const cacaoChainId = getDidChainId(p.iss) || '';
186
- const address = getDidAddress(p.iss);
187
- try {
188
- // Kicks off verifyMessage and populates external states
189
- const message = provider.signer.client.formatAuthMessage({
190
- request: p,
191
- iss: p.iss
192
- });
193
-
194
- await SIWEController.verifyMessage({
195
- message,
196
- signature: s.s,
197
- cacao: signedCacao
198
- });
199
-
200
- if (address && chainId) {
201
- const session = {
202
- address,
203
- chainId: parseInt(cacaoChainId, 10)
204
- };
205
-
206
- SIWEController.setSession(session);
207
- SIWEController.onSignIn?.(session);
208
- }
209
- } catch (error) {
210
- // eslint-disable-next-line no-console
211
- console.error('Error verifying message', error);
212
- // eslint-disable-next-line no-console
213
- await provider.disconnect().catch(console.error);
214
- // eslint-disable-next-line no-console
215
- await SIWEController.signOut().catch(console.error);
216
- throw error;
217
- }
218
- /*
219
- * Unassign the connector from the wagmiConfig and allow connect() to reassign it in the next step
220
- * this avoids case where wagmi throws because the connector is already connected
221
- * what we need connect() to do is to only setup internal event listeners
222
- */
223
- this.wagmiConfig.state.current = '';
224
- }
225
- }
226
-
227
- await connect(this.wagmiConfig, { connector, chainId });
228
- },
229
-
230
- connectExternal: async ({ id }) => {
231
- const connector = wagmiConfig.connectors.find(c => c.id === id);
232
- if (!connector) {
233
- throw new Error('connectionControllerClient:connectExternal - connector is undefined');
234
- }
235
-
236
- // If connecting with something else than walletconnect, we need to clear the clientId in the store
237
- this.setClientId(null);
238
-
239
- const chainId = NetworkUtil.caipNetworkIdToNumber(this.getCaipNetwork()?.id);
240
- await connect(this.wagmiConfig, { connector, chainId });
241
- },
242
-
243
- signMessage: async message => signMessage(this.wagmiConfig, { message }),
244
-
245
- disconnect: async () => {
246
- await disconnect(this.wagmiConfig);
247
- this.setClientId(null);
248
-
249
- if (siweConfig?.options?.signOutOnDisconnect) {
250
- await SIWEController.signOut();
251
- }
252
- },
253
-
254
- sendTransaction: async (data: SendTransactionArgs) => {
255
- const { chainId } = getAccount(this.wagmiConfig);
256
-
257
- const txParams = {
258
- account: data.address,
259
- to: data.to,
260
- value: data.value,
261
- gas: data.gas,
262
- gasPrice: data.gasPrice,
263
- data: data.data,
264
- chainId,
265
- type: 'legacy' as const
266
- };
267
-
268
- await prepareTransactionRequest(this.wagmiConfig, txParams);
269
- const tx = await wagmiSendTransaction(this.wagmiConfig, txParams);
270
-
271
- await waitForTransactionReceipt(this.wagmiConfig, { hash: tx, timeout: 25000 });
272
-
273
- return tx;
274
- },
275
-
276
- writeContract: async (data: WriteContractArgs) => {
277
- const caipAddress = this.getCaipAddress() || '';
278
- const account = requireCaipAddress(caipAddress);
279
- const chainId = NetworkUtil.caipNetworkIdToNumber(this.getCaipNetwork()?.id);
280
-
281
- const tx = await wagmiWriteContract(wagmiConfig, {
282
- chainId,
283
- address: data.tokenAddress,
284
- account,
285
- abi: data.abi,
286
- functionName: data.method,
287
- args: [data.receiverAddress, data.tokenAmount]
288
- });
289
-
290
- return tx;
291
- },
292
-
293
- estimateGas: async ({
294
- address,
295
- to,
296
- data,
297
- chainNamespace
298
- }: EstimateGasTransactionArgs): Promise<bigint> => {
299
- if (chainNamespace && chainNamespace !== 'eip155') {
300
- throw new Error('estimateGas - chainNamespace is not eip155');
301
- }
302
-
303
- try {
304
- const result = await wagmiEstimateGas(this.wagmiConfig, {
305
- account: address as Hex,
306
- to: to as Hex,
307
- data: data as Hex,
308
- type: 'legacy'
309
- });
310
-
311
- return result;
312
- } catch (error) {
313
- throw new Error('WagmiAdapter:estimateGas - error estimating gas');
314
- }
315
- },
316
-
317
- parseUnits,
318
-
319
- formatUnits,
320
-
321
- getEnsAddress: async (value: string) => {
322
- try {
323
- if (!this.wagmiConfig) {
324
- throw new Error(
325
- 'networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined'
326
- );
327
- }
328
- const chainId = Number(NetworkUtil.caipNetworkIdToNumber(this.getCaipNetwork()?.id));
329
- let ensName: boolean | GetEnsAddressReturnType = false;
330
- let wcName: boolean | string = false;
331
- if (NamesUtil.isReownName(value)) {
332
- wcName = (await this.resolveReownName(value)) || false;
333
- }
334
- if (chainId === 1) {
335
- ensName = await wagmiGetEnsAddress(this.wagmiConfig, {
336
- name: normalize(value),
337
- chainId
338
- });
339
- }
340
-
341
- return ensName || wcName || false;
342
- } catch {
343
- return false;
344
- }
345
- },
346
- getEnsAvatar: async (value: string) => {
347
- const chainId = Number(NetworkUtil.caipNetworkIdToNumber(this.getCaipNetwork()?.id));
348
- if (chainId !== mainnet.id) {
349
- return false;
350
- }
351
- const avatar = await wagmiGetEnsAvatar(this.wagmiConfig, {
352
- name: normalize(value),
353
- chainId
354
- });
355
-
356
- return avatar || false;
357
- }
358
- };
359
-
360
- super({
361
- networkControllerClient,
362
- connectionControllerClient,
363
- siweControllerClient: siweConfig,
364
- defaultChain: getCaipDefaultChain(defaultChain),
365
- tokens: HelpersUtil.getCaipTokens(tokens),
366
- _sdkVersion: _sdkVersion ?? `react-native-wagmi-${ConstantsUtil.VERSION}`,
367
- ...appKitOptions
368
- });
369
-
370
- this.options = options;
371
- this.wagmiConfig = wagmiConfig;
372
-
373
- this.syncRequestedNetworks([...wagmiConfig.chains]);
374
- this.syncConnectors([...wagmiConfig.connectors]);
375
-
376
- watchConnectors(wagmiConfig, {
377
- onChange: connectors => this.syncConnectors([...connectors])
378
- });
379
-
380
- watchAccount(wagmiConfig, {
381
- onChange: (accountData, prevAccountData) => {
382
- this.syncAccount({ ...accountData });
383
-
384
- if (accountData.status === 'disconnected' && prevAccountData.status === 'connected') {
385
- this.close();
386
- }
387
- }
388
- });
389
- }
390
-
391
- // -- Public ------------------------------------------------------------------
392
-
393
- // @ts-expect-error: Overriden state type is correct
394
- public override getState() {
395
- const state = super.getState();
396
-
397
- return {
398
- ...state,
399
- selectedNetworkId: NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId)
400
- };
401
- }
402
-
403
- // @ts-expect-error: Overriden state type is correct
404
- public override subscribeState(callback: (state: AppKitState) => void) {
405
- return super.subscribeState(state =>
406
- callback({
407
- ...state,
408
- selectedNetworkId: NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId)
409
- })
410
- );
411
- }
412
-
413
- // -- Private -----------------------------------------------------------------
414
- private syncRequestedNetworks(chains: Chain[]) {
415
- const requestedCaipNetworks = chains?.map(
416
- chain =>
417
- ({
418
- id: `${ConstantsUtil.EIP155}:${chain.id}`,
419
- name: chain.name,
420
- imageId: PresetsUtil.EIP155NetworkImageIds[chain.id],
421
- imageUrl: this.options?.chainImages?.[chain.id]
422
- }) as CaipNetwork
423
- );
424
- this.setRequestedCaipNetworks(requestedCaipNetworks ?? []);
425
- }
426
-
427
- private async syncAccount({
428
- address,
429
- isConnected,
430
- chainId,
431
- connector,
432
- isConnecting,
433
- isReconnecting
434
- }: Pick<
435
- GetAccountReturnType,
436
- 'address' | 'isConnected' | 'chainId' | 'connector' | 'isConnecting' | 'isReconnecting'
437
- >) {
438
- this.syncNetwork(address, chainId, isConnected);
439
- this.setLoading(!!connector && (isConnecting || isReconnecting));
440
-
441
- if (isConnected && address && chainId) {
442
- const caipAddress: CaipAddress = `${ConstantsUtil.EIP155}:${chainId}:${address}`;
443
- this.setIsConnected(isConnected);
444
- this.setCaipAddress(caipAddress);
445
- const connectorType = PresetsUtil.ConnectorTypesMap[connector?.id ?? ''];
446
- await Promise.all([
447
- this.syncProfile(address, chainId),
448
- this.syncBalance(address, chainId),
449
- this.syncConnectedWalletInfo(connector),
450
- this.getApprovedCaipNetworksData(connectorType)
451
- ]);
452
- this.hasSyncedConnectedAccount = true;
453
- } else if (!isConnected && !isConnecting && !isReconnecting && this.hasSyncedConnectedAccount) {
454
- this.resetAccount();
455
- this.resetWcConnection();
456
- this.resetNetwork();
457
- }
458
- }
459
-
460
- private async syncNetwork(address?: Hex, chainId?: number, isConnected?: boolean) {
461
- const chain = this.wagmiConfig.chains.find((c: Chain) => c.id === chainId);
462
-
463
- if (chain || chainId) {
464
- const name = chain?.name ?? chainId?.toString();
465
- const id = Number(chain?.id ?? chainId);
466
- const caipChainId: CaipNetworkId = `${ConstantsUtil.EIP155}:${id}`;
467
- this.setCaipNetwork({
468
- id: caipChainId,
469
- name,
470
- imageId: PresetsUtil.EIP155NetworkImageIds[id],
471
- imageUrl: this.options?.chainImages?.[id]
472
- });
473
- if (isConnected && address && chainId) {
474
- const caipAddress: CaipAddress = `${ConstantsUtil.EIP155}:${id}:${address}`;
475
- this.setCaipAddress(caipAddress);
476
- if (chain?.blockExplorers?.default?.url) {
477
- const url = `${chain.blockExplorers.default.url}/address/${address}`;
478
- this.setAddressExplorerUrl(url);
479
- } else {
480
- this.setAddressExplorerUrl(undefined);
481
- }
482
- if (this.hasSyncedConnectedAccount) {
483
- await this.syncProfile(address, chainId);
484
- await this.syncBalance(address, chainId);
485
- }
486
- }
487
- }
488
- }
489
-
490
- private async syncProfile(address: Hex, chainId: number) {
491
- try {
492
- const response = await this.fetchIdentity({ address });
493
-
494
- if (!response) {
495
- throw new Error('Couldnt fetch idendity');
496
- }
497
-
498
- this.setProfileName(response.name);
499
- this.setProfileImage(response.avatar);
500
- } catch {
501
- if (chainId === mainnet.id) {
502
- const profileName = await getEnsName(this.wagmiConfig, { address, chainId });
503
- if (profileName) {
504
- this.setProfileName(profileName);
505
- const profileImage = await wagmiGetEnsAvatar(this.wagmiConfig, {
506
- name: profileName,
507
- chainId
508
- });
509
- if (profileImage) {
510
- this.setProfileImage(profileImage);
511
- }
512
- }
513
- } else {
514
- this.setProfileName(undefined);
515
- this.setProfileImage(undefined);
516
- }
517
- }
518
- }
519
-
520
- private async syncBalance(address: Hex, chainId: number) {
521
- const chain = this.wagmiConfig.chains.find((c: Chain) => c.id === chainId);
522
- try {
523
- if (chain) {
524
- const balance = await getBalance(this.wagmiConfig, {
525
- address,
526
- chainId: chain.id,
527
- token: this.options?.tokens?.[chainId]?.address as Hex
528
- });
529
- const formattedBalance = formatUnits(balance.value, balance.decimals);
530
- this.setBalance(formattedBalance, balance.symbol);
531
-
532
- return;
533
- }
534
- this.setBalance(undefined, undefined);
535
- } catch {
536
- this.setBalance(undefined, undefined);
537
- }
538
- }
539
-
540
- private async syncConnectedWalletInfo(connector: GetAccountReturnType['connector']) {
541
- if (!connector) {
542
- throw Error('syncConnectedWalletInfo - connector is undefined');
543
- }
544
-
545
- if (connector.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID && connector.getProvider) {
546
- const walletConnectProvider = (await connector.getProvider()) as Awaited<
547
- ReturnType<(typeof EthereumProvider)['init']>
548
- >;
549
- if (walletConnectProvider.session) {
550
- this.setConnectedWalletInfo({
551
- ...walletConnectProvider.session.peer.metadata,
552
- name: walletConnectProvider.session.peer.metadata.name,
553
- icon: walletConnectProvider.session.peer.metadata.icons?.[0]
554
- });
555
- }
556
- } else {
557
- this.setConnectedWalletInfo({
558
- id: connector.id,
559
- name: connector.name,
560
- icon: this.options?.connectorImages?.[connector.id] ?? connector.icon
561
- });
562
- }
563
- }
564
-
565
- private syncConnectors(connectors: AppKitClientOptions['wagmiConfig']['connectors']) {
566
- const uniqueIds = new Set();
567
- const filteredConnectors = connectors.filter(
568
- item => !uniqueIds.has(item.id) && uniqueIds.add(item.id)
569
- );
570
-
571
- const excludedConnectors = [ConstantsUtil.AUTH_CONNECTOR_ID];
572
-
573
- const _connectors: Connector[] = [];
574
- filteredConnectors.forEach(({ id, name, icon }) => {
575
- if (!excludedConnectors.includes(id)) {
576
- _connectors.push({
577
- id,
578
- explorerId: PresetsUtil.ConnectorExplorerIds[id],
579
- imageId: PresetsUtil.ConnectorImageIds[id] ?? icon,
580
- imageUrl: this.options?.connectorImages?.[id],
581
- name: PresetsUtil.ConnectorNamesMap[id] ?? name,
582
- type: PresetsUtil.ConnectorTypesMap[id] ?? 'EXTERNAL'
583
- });
584
- }
585
- });
586
-
587
- this.setConnectors(_connectors);
588
- this.syncWalletConnectListeners(filteredConnectors);
589
- this.syncAuthConnector(filteredConnectors);
590
- }
591
-
592
- private async syncWalletConnectListeners(
593
- connectors: AppKitClientOptions['wagmiConfig']['connectors']
594
- ) {
595
- const connector = connectors.find(({ id }) => id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID);
596
- if (connector) {
597
- const provider = (await connector.getProvider()) as EthereumProvider;
598
-
599
- provider.signer.client.core.relayer.on('relayer_connect', () => {
600
- provider.signer.client.core.relayer?.provider?.on('payload', (payload: JsonRpcError) => {
601
- if (payload?.error) {
602
- this.handleAlertError(payload?.error.message);
603
- }
604
- });
605
- });
606
- }
607
- }
608
-
609
- private async syncAuthConnector(connectors: AppKitClientOptions['wagmiConfig']['connectors']) {
610
- const authConnector = connectors.find(({ id }) => id === ConstantsUtil.AUTH_CONNECTOR_ID);
611
- if (authConnector) {
612
- const provider = await authConnector.getProvider();
613
- this.addConnector({
614
- id: ConstantsUtil.AUTH_CONNECTOR_ID,
615
- type: PresetsUtil.ConnectorTypesMap[ConstantsUtil.AUTH_CONNECTOR_ID]!,
616
- name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.AUTH_CONNECTOR_ID],
617
- provider
618
- });
619
- this.addAuthListeners(authConnector);
620
- }
621
- }
622
-
623
- private async addAuthListeners(connector: WagmiConnector) {
624
- const connectedConnector: ConnectorType | undefined = await StorageUtil.getItem(
625
- '@w3m/connected_connector'
626
- );
627
-
628
- if (connectedConnector === 'AUTH') {
629
- // Set loader until it reconnects
630
- super.setLoading(true);
631
- }
632
-
633
- const provider = (await connector.getProvider()) as AppKitFrameProvider;
634
-
635
- provider.onSetPreferredAccount(async () => {
636
- await reconnect(this.wagmiConfig, { connectors: [connector] });
637
- });
638
-
639
- provider.setOnTimeout(async () => {
640
- this.handleAlertError(ErrorUtil.ALERT_ERRORS.SOCIALS_TIMEOUT);
641
- this.setLoading(false);
642
- });
643
- }
644
- }