@reown/appkit-adapter-wagmi 0.0.3

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.
@@ -0,0 +1,711 @@
1
+ import { connect, disconnect, signMessage, getBalance, getEnsAvatar as wagmiGetEnsAvatar, getEnsName, watchAccount, watchConnectors, estimateGas as wagmiEstimateGas, writeContract as wagmiWriteContract, getAccount, getEnsAddress as wagmiGetEnsAddress, reconnect, switchChain, waitForTransactionReceipt, getConnections, switchAccount, injected, createConfig, getConnectors } from '@wagmi/core';
2
+ import { ChainController, ConstantsUtil as CoreConstantsUtil } from '@reown/appkit-core';
3
+ import { prepareTransactionRequest, sendTransaction as wagmiSendTransaction } from '@wagmi/core';
4
+ import { mainnet } from 'viem/chains';
5
+ import { formatUnits, parseUnits } from 'viem';
6
+ import { ConstantsUtil, PresetsUtil, HelpersUtil } from '@reown/appkit-utils';
7
+ import { ConstantsUtil as CommonConstants, SafeLocalStorage, SafeLocalStorageKeys } from '@reown/appkit-common';
8
+ import { convertToAppKitChains, getEmailCaipNetworks, getTransport, getWalletConnectCaipNetworks, requireCaipAddress } from './utils/helpers.js';
9
+ import { W3mFrameHelpers, W3mFrameRpcConstants } from '@reown/appkit-wallet';
10
+ import { NetworkUtil } from '@reown/appkit-common';
11
+ import { normalize } from 'viem/ens';
12
+ import { ConstantsUtil as CommonConstantsUtil } from '@reown/appkit-common';
13
+ import { walletConnect } from './connectors/UniversalConnector.js';
14
+ import { coinbaseWallet } from '@wagmi/connectors';
15
+ import { authConnector } from './connectors/AuthConnector.js';
16
+ import { ProviderUtil } from '@reown/appkit/store';
17
+ const OPTIONAL_METHODS = [
18
+ 'eth_accounts',
19
+ 'eth_requestAccounts',
20
+ 'eth_sendRawTransaction',
21
+ 'eth_sign',
22
+ 'eth_signTransaction',
23
+ 'eth_signTypedData',
24
+ 'eth_signTypedData_v3',
25
+ 'eth_signTypedData_v4',
26
+ 'eth_sendTransaction',
27
+ 'personal_sign',
28
+ 'wallet_switchEthereumChain',
29
+ 'wallet_addEthereumChain',
30
+ 'wallet_getPermissions',
31
+ 'wallet_requestPermissions',
32
+ 'wallet_registerOnboarding',
33
+ 'wallet_watchAsset',
34
+ 'wallet_scanQRCode'
35
+ ];
36
+ export class EVMWagmiClient {
37
+ constructor(configParams) {
38
+ this.appKit = undefined;
39
+ this.options = undefined;
40
+ this.chainNamespace = CommonConstantsUtil.CHAIN.EVM;
41
+ this.defaultCaipNetwork = undefined;
42
+ this.tokens = HelpersUtil.getCaipTokens(this.options?.tokens);
43
+ this.getCaipDefaultNetwork = this.options?.defaultCaipNetwork;
44
+ this.siweControllerClient = this.options?.siweConfig;
45
+ this.adapterType = 'wagmi';
46
+ this.wagmiChains = convertToAppKitChains(configParams.caipNetworks.filter(caipNetwork => caipNetwork.chainNamespace === CommonConstantsUtil.CHAIN.EVM));
47
+ this.caipNetworks = configParams.caipNetworks;
48
+ const transportsArr = this.wagmiChains.map(chain => [
49
+ chain.id,
50
+ getTransport({ chain, projectId: configParams.projectId })
51
+ ]);
52
+ const transports = Object.fromEntries(transportsArr);
53
+ const connectors = [...(configParams.connectors ?? [])];
54
+ this.wagmiConfig = createConfig({
55
+ ...this.createConfigParams,
56
+ chains: this.wagmiChains,
57
+ transports,
58
+ connectors: [...connectors, ...(this.createConfigParams?.connectors ?? [])]
59
+ });
60
+ }
61
+ setCustomConnectors(options, appKit) {
62
+ const customConnectors = [];
63
+ if (options.enableWalletConnect !== false) {
64
+ customConnectors.push(walletConnect(options, appKit));
65
+ }
66
+ if (options.enableInjected !== false) {
67
+ customConnectors.push(injected({ shimDisconnect: true }));
68
+ }
69
+ if (options.enableCoinbase !== false) {
70
+ customConnectors.push(coinbaseWallet({
71
+ version: '4',
72
+ appName: options.metadata?.name ?? 'Unknown',
73
+ appLogoUrl: options.metadata?.icons[0] ?? 'Unknown',
74
+ preference: options.coinbasePreference ?? 'all'
75
+ }));
76
+ }
77
+ const emailEnabled = options.features?.email === undefined
78
+ ? CoreConstantsUtil.DEFAULT_FEATURES.email
79
+ : options.features?.email;
80
+ const socialsEnabled = options.features?.socials === undefined
81
+ ? CoreConstantsUtil.DEFAULT_FEATURES.socials
82
+ : options.features?.socials?.length > 0;
83
+ if (emailEnabled || socialsEnabled) {
84
+ customConnectors.push(authConnector({
85
+ chains: this.wagmiChains,
86
+ options: { projectId: options.projectId }
87
+ }));
88
+ }
89
+ customConnectors.forEach(connector => {
90
+ const cnctr = this.wagmiConfig._internal.connectors.setup(connector);
91
+ this.wagmiConfig._internal.connectors.setState(prev => [...prev, cnctr]);
92
+ });
93
+ }
94
+ construct(appKit, options) {
95
+ if (!options.projectId) {
96
+ throw new Error('web3modal:initialize - projectId is undefined');
97
+ }
98
+ this.appKit = appKit;
99
+ this.options = options;
100
+ this.caipNetworks = options.caipNetworks;
101
+ this.defaultCaipNetwork = options.defaultCaipNetwork || options.caipNetworks[0];
102
+ this.tokens = HelpersUtil.getCaipTokens(options.tokens);
103
+ this.setCustomConnectors(options, appKit);
104
+ if (!this.wagmiConfig) {
105
+ throw new Error('web3modal:wagmiConfig - is undefined');
106
+ }
107
+ this.networkControllerClient = {
108
+ switchCaipNetwork: async (caipNetwork) => {
109
+ SafeLocalStorage.setItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK, JSON.stringify(caipNetwork));
110
+ const chainId = Number(NetworkUtil.caipNetworkIdToNumber(caipNetwork?.id));
111
+ if (chainId && this.wagmiConfig) {
112
+ await switchChain(this.wagmiConfig, { chainId });
113
+ }
114
+ },
115
+ getApprovedCaipNetworksData: async () => {
116
+ if (!this.wagmiConfig) {
117
+ throw new Error('networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined');
118
+ }
119
+ return new Promise(resolve => {
120
+ const connections = new Map(this.wagmiConfig.state.connections);
121
+ const connection = connections.get(this.wagmiConfig.state.current || '');
122
+ if (connection?.connector?.id === ConstantsUtil.AUTH_CONNECTOR_ID) {
123
+ resolve(getEmailCaipNetworks());
124
+ }
125
+ else if (connection?.connector?.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID) {
126
+ const connector = this.wagmiConfig.connectors.find(c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID);
127
+ resolve(getWalletConnectCaipNetworks(connector));
128
+ }
129
+ resolve({ approvedCaipNetworkIds: undefined, supportsAllNetworks: true });
130
+ });
131
+ }
132
+ };
133
+ this.connectionControllerClient = {
134
+ connectWalletConnect: async () => {
135
+ if (!this.wagmiConfig) {
136
+ throw new Error('connectionControllerClient:getWalletConnectUri - wagmiConfig is undefined');
137
+ }
138
+ const connector = this.wagmiConfig.connectors.find(c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID);
139
+ if (!connector) {
140
+ throw new Error('connectionControllerClient:getWalletConnectUri - connector is undefined');
141
+ }
142
+ const provider = (await connector.getProvider());
143
+ const siweParams = await this.options?.siweConfig?.getMessageParams?.();
144
+ const isSiweEnabled = this.options?.siweConfig?.options?.enabled;
145
+ const isProviderSupported = typeof provider?.authenticate === 'function';
146
+ const isSiweParamsValid = siweParams && Object.keys(siweParams || {}).length > 0;
147
+ if (isSiweEnabled && isProviderSupported && isSiweParamsValid) {
148
+ await connector.setRequestedChainsIds(siweParams.chains);
149
+ const siweConfig = this.options?.siweConfig;
150
+ const params = await siweConfig?.getMessageParams?.();
151
+ if (siweConfig?.options?.enabled && params && Object.keys(params || {}).length > 0) {
152
+ const { SIWEController, getDidChainId, getDidAddress } = await import('@reown/appkit-siwe');
153
+ const chains = this.options?.caipNetworks.map(network => network.id);
154
+ const result = await provider.authenticate({
155
+ nonce: await siweConfig.getNonce(),
156
+ methods: [...OPTIONAL_METHODS],
157
+ ...params,
158
+ chains
159
+ });
160
+ const signedCacao = result?.auths?.[0];
161
+ if (signedCacao) {
162
+ const { p, s } = signedCacao;
163
+ const cacaoChainId = getDidChainId(p.iss);
164
+ const address = getDidAddress(p.iss);
165
+ if (address && cacaoChainId) {
166
+ SIWEController.setSession({
167
+ address,
168
+ chainId: parseInt(cacaoChainId, 10)
169
+ });
170
+ }
171
+ try {
172
+ const message = provider.client.formatAuthMessage({
173
+ request: p,
174
+ iss: p.iss
175
+ });
176
+ await SIWEController.verifyMessage({
177
+ message,
178
+ signature: s.s,
179
+ cacao: signedCacao
180
+ });
181
+ }
182
+ catch (error) {
183
+ console.error('Error verifying message', error);
184
+ await provider.disconnect().catch(console.error);
185
+ await SIWEController.signOut().catch(console.error);
186
+ throw error;
187
+ }
188
+ }
189
+ this.wagmiConfig.state.current = '';
190
+ }
191
+ }
192
+ await connect(this.wagmiConfig, { connector });
193
+ },
194
+ connectExternal: async ({ id, provider, info }) => {
195
+ if (!this.wagmiConfig) {
196
+ throw new Error('networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined');
197
+ }
198
+ const connector = this.wagmiConfig.connectors.find(c => c.id === id);
199
+ if (!connector) {
200
+ throw new Error('connectionControllerClient:connectExternal - connector is undefined');
201
+ }
202
+ this.appKit?.setClientId(null);
203
+ if (provider && info && connector.id === ConstantsUtil.EIP6963_CONNECTOR_ID) {
204
+ connector.setEip6963Wallet?.({ provider, info });
205
+ }
206
+ const chainId = Number(NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id));
207
+ await connect(this.wagmiConfig, { connector, chainId });
208
+ },
209
+ checkInstalled: ids => {
210
+ const injectedConnector = this.appKit
211
+ ?.getConnectors()
212
+ .find((c) => c.type === 'INJECTED');
213
+ if (!ids) {
214
+ return Boolean(window.ethereum);
215
+ }
216
+ if (injectedConnector) {
217
+ if (!window?.ethereum) {
218
+ return false;
219
+ }
220
+ return ids.some(id => Boolean(window.ethereum?.[String(id)]));
221
+ }
222
+ return false;
223
+ },
224
+ disconnect: async () => {
225
+ await disconnect(this.wagmiConfig);
226
+ SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
227
+ SafeLocalStorage.removeItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK);
228
+ this.appKit?.setClientId(null);
229
+ this.appKit?.resetAccount('eip155');
230
+ this.appKit?.resetAccount('solana');
231
+ if (this.options?.siweConfig?.options?.signOutOnDisconnect) {
232
+ const { SIWEController } = await import('@reown/appkit-siwe');
233
+ await SIWEController.signOut();
234
+ }
235
+ },
236
+ signMessage: async (message) => {
237
+ const caipAddress = this.appKit?.getCaipAddress() || '';
238
+ const account = requireCaipAddress(caipAddress);
239
+ return signMessage(this.wagmiConfig, { message, account });
240
+ },
241
+ estimateGas: async (args) => {
242
+ if (args.chainNamespace && args.chainNamespace !== 'eip155') {
243
+ throw new Error(`Invalid chain namespace - Expected eip155, got ${args.chainNamespace}`);
244
+ }
245
+ try {
246
+ return await wagmiEstimateGas(this.wagmiConfig, {
247
+ account: args.address,
248
+ to: args.to,
249
+ data: args.data,
250
+ type: 'legacy'
251
+ });
252
+ }
253
+ catch (error) {
254
+ return BigInt(0);
255
+ }
256
+ },
257
+ sendTransaction: async (data) => {
258
+ if (data.chainNamespace && data.chainNamespace !== 'eip155') {
259
+ throw new Error(`Invalid chain namespace - Expected eip155, got ${data.chainNamespace}`);
260
+ }
261
+ const { chainId } = getAccount(this.wagmiConfig);
262
+ const txParams = {
263
+ account: data.address,
264
+ to: data.to,
265
+ value: data.value,
266
+ gas: data.gas,
267
+ gasPrice: data.gasPrice,
268
+ data: data.data,
269
+ chainId,
270
+ type: 'legacy'
271
+ };
272
+ await prepareTransactionRequest(this.wagmiConfig, txParams);
273
+ const tx = await wagmiSendTransaction(this.wagmiConfig, txParams);
274
+ await waitForTransactionReceipt(this.wagmiConfig, { hash: tx, timeout: 25000 });
275
+ return tx;
276
+ },
277
+ writeContract: async (data) => {
278
+ const caipAddress = this.appKit?.getCaipAddress() || '';
279
+ const account = requireCaipAddress(caipAddress);
280
+ const chainId = Number(NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id));
281
+ const tx = await wagmiWriteContract(this.wagmiConfig, {
282
+ chain: this.wagmiChains?.[chainId],
283
+ chainId,
284
+ address: data.tokenAddress,
285
+ account,
286
+ abi: data.abi,
287
+ functionName: data.method,
288
+ args: [data.receiverAddress, data.tokenAmount]
289
+ });
290
+ return tx;
291
+ },
292
+ getEnsAddress: async (value) => {
293
+ try {
294
+ if (!this.wagmiConfig) {
295
+ throw new Error('networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined');
296
+ }
297
+ const chainId = Number(NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id));
298
+ let ensName = false;
299
+ let wcName = false;
300
+ if (value?.endsWith(CommonConstants.WC_NAME_SUFFIX)) {
301
+ wcName = (await this.appKit?.resolveWalletConnectName(value)) || false;
302
+ }
303
+ if (chainId === 1) {
304
+ ensName = await wagmiGetEnsAddress(this.wagmiConfig, {
305
+ name: normalize(value),
306
+ chainId
307
+ });
308
+ }
309
+ return ensName || wcName || false;
310
+ }
311
+ catch {
312
+ return false;
313
+ }
314
+ },
315
+ getEnsAvatar: async (value) => {
316
+ const chainId = Number(NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id));
317
+ if (chainId !== mainnet.id) {
318
+ return false;
319
+ }
320
+ const avatar = await wagmiGetEnsAvatar(this.wagmiConfig, {
321
+ name: normalize(value),
322
+ chainId
323
+ });
324
+ return avatar || false;
325
+ },
326
+ parseUnits,
327
+ formatUnits
328
+ };
329
+ ChainController.state.chains.set(this.chainNamespace, {
330
+ chainNamespace: this.chainNamespace,
331
+ connectionControllerClient: this.connectionControllerClient,
332
+ networkControllerClient: this.networkControllerClient,
333
+ adapterType: this.adapterType
334
+ });
335
+ this.syncConnectors(this.wagmiConfig.connectors);
336
+ this.syncAuthConnector(this.wagmiConfig?.connectors.find(c => c.id === ConstantsUtil.AUTH_CONNECTOR_ID));
337
+ this.syncRequestedNetworks(options.caipNetworks);
338
+ watchConnectors(this.wagmiConfig, {
339
+ onChange: _connectors => {
340
+ this.syncConnectors(_connectors);
341
+ this.syncAuthConnector(_connectors.find(c => c.id === ConstantsUtil.AUTH_CONNECTOR_ID));
342
+ }
343
+ });
344
+ watchAccount(this.wagmiConfig, {
345
+ onChange: accountData => {
346
+ this.syncAccount(accountData);
347
+ }
348
+ });
349
+ this.appKit?.setEIP6963Enabled(options.enableEIP6963 !== false);
350
+ this.appKit?.subscribeShouldUpdateToAddress((newAddress) => {
351
+ if (newAddress) {
352
+ const connections = getConnections(this.wagmiConfig);
353
+ const connector = connections[0]?.connector;
354
+ if (connector) {
355
+ switchAccount(this.wagmiConfig, {
356
+ connector
357
+ }).then(response => this.syncAccount({
358
+ address: newAddress,
359
+ isConnected: true,
360
+ addresses: response.accounts,
361
+ connector,
362
+ chainId: response.chainId,
363
+ status: 'connected'
364
+ }));
365
+ }
366
+ }
367
+ });
368
+ }
369
+ subscribeState(callback) {
370
+ return this.appKit?.subscribeState((state) => callback({
371
+ ...state,
372
+ selectedNetworkId: Number(NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId))
373
+ }));
374
+ }
375
+ syncRequestedNetworks(caipNetworks) {
376
+ const uniqueChainNamespaces = Array.from(new Set(caipNetworks.map(caipNetwork => caipNetwork.chainNamespace)));
377
+ uniqueChainNamespaces
378
+ .filter(c => Boolean(c))
379
+ .forEach(chainNamespace => {
380
+ this.appKit?.setRequestedCaipNetworks(caipNetworks.filter(caipNetwork => caipNetwork.chainNamespace === chainNamespace), chainNamespace);
381
+ });
382
+ }
383
+ async syncAccount({ address, chainId, connector, addresses, status }) {
384
+ if (this.wagmiConfig) {
385
+ if (connector) {
386
+ if (connector && connector.name === 'WalletConnect' && connector.getProvider && address) {
387
+ const currentChainId = chainId || Number(NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id));
388
+ const provider = (await connector.getProvider());
389
+ const namespaces = provider?.session?.namespaces || {};
390
+ const namespaceKeys = namespaces ? Object.keys(namespaces) : [];
391
+ const preferredAccountType = this.appKit?.getPreferredAccountType();
392
+ namespaceKeys.forEach(key => {
393
+ const chainNamespace = key;
394
+ const caipAddress = namespaces?.[key]?.accounts[0];
395
+ ProviderUtil.setProvider(chainNamespace, provider);
396
+ ProviderUtil.setProviderId(chainNamespace, 'walletConnect');
397
+ this.appKit?.setIsConnected(true, chainNamespace);
398
+ this.appKit?.setPreferredAccountType(preferredAccountType, chainNamespace);
399
+ this.appKit?.setCaipAddress(caipAddress, chainNamespace);
400
+ });
401
+ if (this.appKit?.getCaipNetwork()?.chainNamespace !== 'solana') {
402
+ this.syncNetwork(address, currentChainId, true);
403
+ await Promise.all([
404
+ this.syncProfile(address, currentChainId),
405
+ this.syncBalance(address, currentChainId),
406
+ this.syncConnectedWalletInfo(connector),
407
+ this.appKit?.setApprovedCaipNetworksData(this.chainNamespace)
408
+ ]);
409
+ }
410
+ }
411
+ else if (status === 'connected' && address && chainId) {
412
+ const caipAddress = `eip155:${chainId}:${address}`;
413
+ this.appKit?.resetAccount(this.chainNamespace);
414
+ this.syncNetwork(address, chainId, true);
415
+ this.appKit?.setIsConnected(true, this.chainNamespace);
416
+ this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
417
+ await Promise.all([
418
+ this.syncProfile(address, chainId),
419
+ this.syncBalance(address, chainId),
420
+ this.syncConnectedWalletInfo(connector),
421
+ this.appKit?.setApprovedCaipNetworksData(this.chainNamespace)
422
+ ]);
423
+ if (connector) {
424
+ this.syncConnectedWalletInfo(connector);
425
+ }
426
+ const isAuthConnector = connector?.id === ConstantsUtil.AUTH_CONNECTOR_ID;
427
+ if (!isAuthConnector && addresses?.length) {
428
+ this.appKit?.setAllAccounts(addresses.map(addr => ({ address: addr, type: 'eoa' })), this.chainNamespace);
429
+ }
430
+ }
431
+ else if (status === 'disconnected') {
432
+ this.appKit?.resetAccount(this.chainNamespace);
433
+ this.appKit?.resetWcConnection();
434
+ this.appKit?.resetNetwork();
435
+ this.appKit?.setAllAccounts([], this.chainNamespace);
436
+ SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
437
+ SafeLocalStorage.removeItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK);
438
+ }
439
+ else if (status === 'reconnecting') {
440
+ this.appKit?.setLoading(true);
441
+ const connectors = getConnectors(this.wagmiConfig);
442
+ const currentConnector = connectors.find(c => c.id === connector.id);
443
+ if (currentConnector) {
444
+ await reconnect(this.wagmiConfig, {
445
+ connectors: [currentConnector]
446
+ });
447
+ this.appKit?.setLoading(false);
448
+ }
449
+ }
450
+ }
451
+ }
452
+ }
453
+ async syncNetwork(address, chainId, isConnected) {
454
+ const chain = this.options?.caipNetworks.find((c) => c.chainId === chainId);
455
+ if (chain && chainId) {
456
+ this.appKit?.setCaipNetwork({
457
+ chainId: chain.chainId,
458
+ id: chain.id,
459
+ name: chain.name || '',
460
+ imageId: PresetsUtil.NetworkImageIds[chain.chainId],
461
+ imageUrl: this.options?.chainImages?.[chain.chainId],
462
+ chainNamespace: this.chainNamespace,
463
+ currency: chain?.currency || '',
464
+ explorerUrl: chain?.explorerUrl || '',
465
+ rpcUrl: chain?.rpcUrl || ''
466
+ });
467
+ if (isConnected && address && chainId) {
468
+ const caipAddress = `eip155:${chainId}:${address}`;
469
+ this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
470
+ if (chain?.explorerUrl) {
471
+ const url = `${chain.explorerUrl}/address/${address}`;
472
+ this.appKit?.setAddressExplorerUrl(url, this.chainNamespace);
473
+ }
474
+ else {
475
+ this.appKit?.setAddressExplorerUrl(undefined, this.chainNamespace);
476
+ }
477
+ await this.syncBalance(address, chainId);
478
+ }
479
+ }
480
+ }
481
+ async syncWalletConnectName(address) {
482
+ if (!this.appKit) {
483
+ throw new Error('syncWalletConnectName - appKit is undefined');
484
+ }
485
+ try {
486
+ const registeredWcNames = await this.appKit.getWalletConnectName(address);
487
+ if (registeredWcNames[0]) {
488
+ const wcName = registeredWcNames[0];
489
+ this.appKit?.setProfileName(wcName.name, this.chainNamespace);
490
+ }
491
+ else {
492
+ this.appKit?.setProfileName(null, this.chainNamespace);
493
+ }
494
+ }
495
+ catch {
496
+ this.appKit?.setProfileName(null, this.chainNamespace);
497
+ }
498
+ }
499
+ async syncProfile(address, chainId) {
500
+ if (!this.appKit) {
501
+ throw new Error('syncProfile - appKit is undefined');
502
+ }
503
+ try {
504
+ const { name, avatar } = await this.appKit.fetchIdentity({
505
+ address
506
+ });
507
+ this.appKit?.setProfileName(name, this.chainNamespace);
508
+ this.appKit?.setProfileImage(avatar, this.chainNamespace);
509
+ if (!name) {
510
+ await this.syncWalletConnectName(address);
511
+ }
512
+ }
513
+ catch {
514
+ if (chainId === mainnet.id) {
515
+ const profileName = await getEnsName(this.wagmiConfig, { address, chainId });
516
+ if (profileName) {
517
+ this.appKit?.setProfileName(profileName, this.chainNamespace);
518
+ const profileImage = await wagmiGetEnsAvatar(this.wagmiConfig, {
519
+ name: profileName,
520
+ chainId
521
+ });
522
+ if (profileImage) {
523
+ this.appKit?.setProfileImage(profileImage, this.chainNamespace);
524
+ }
525
+ }
526
+ else {
527
+ await this.syncWalletConnectName(address);
528
+ this.appKit?.setProfileImage(null, this.chainNamespace);
529
+ }
530
+ }
531
+ else {
532
+ await this.syncWalletConnectName(address);
533
+ this.appKit?.setProfileImage(null, this.chainNamespace);
534
+ }
535
+ }
536
+ }
537
+ async syncBalance(address, chainId) {
538
+ const chain = this.options?.caipNetworks.find((c) => c.chainId === chainId);
539
+ if (chain && this.wagmiConfig) {
540
+ const balance = await getBalance(this.wagmiConfig, {
541
+ address,
542
+ chainId,
543
+ token: this.options?.tokens?.[chain.id]?.address
544
+ });
545
+ this.appKit?.setBalance(balance.formatted, balance.symbol, this.chainNamespace);
546
+ return;
547
+ }
548
+ this.appKit?.setBalance(undefined, undefined, this.chainNamespace);
549
+ }
550
+ async syncConnectedWalletInfo(connector) {
551
+ if (!connector) {
552
+ throw Error('syncConnectedWalletInfo - connector is undefined');
553
+ }
554
+ if (connector.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID && connector.getProvider) {
555
+ const walletConnectProvider = (await connector.getProvider());
556
+ if (walletConnectProvider.session) {
557
+ this.appKit?.setConnectedWalletInfo({
558
+ ...walletConnectProvider.session.peer.metadata,
559
+ name: walletConnectProvider.session.peer.metadata.name,
560
+ icon: walletConnectProvider.session.peer.metadata.icons?.[0]
561
+ }, this.chainNamespace);
562
+ }
563
+ }
564
+ else {
565
+ const wagmiConnector = this.appKit?.getConnectors().find(c => c.id === connector.id);
566
+ this.appKit?.setConnectedWalletInfo({
567
+ name: connector.name,
568
+ icon: connector.icon || this.appKit.getConnectorImage(wagmiConnector)
569
+ }, this.chainNamespace);
570
+ }
571
+ }
572
+ syncConnectors(_connectors) {
573
+ const connectors = _connectors.map(connector => ({ ...connector, chain: this.chainNamespace }));
574
+ const uniqueIds = new Set();
575
+ const filteredConnectors = connectors.filter(item => {
576
+ const isDuplicate = uniqueIds.has(item.id);
577
+ uniqueIds.add(item.id);
578
+ return !isDuplicate;
579
+ });
580
+ const w3mConnectors = [];
581
+ filteredConnectors.forEach(({ id, name, type, icon }) => {
582
+ const shouldSkip = ConstantsUtil.AUTH_CONNECTOR_ID === id;
583
+ if (!shouldSkip) {
584
+ w3mConnectors.push({
585
+ id,
586
+ explorerId: PresetsUtil.ConnectorExplorerIds[id],
587
+ imageUrl: this.options?.connectorImages?.[id] ?? icon,
588
+ name: PresetsUtil.ConnectorNamesMap[id] ?? name,
589
+ imageId: PresetsUtil.ConnectorImageIds[id],
590
+ type: PresetsUtil.ConnectorTypesMap[type] ?? 'EXTERNAL',
591
+ info: {
592
+ rdns: id
593
+ },
594
+ chain: this.chainNamespace
595
+ });
596
+ }
597
+ });
598
+ this.appKit?.setConnectors(w3mConnectors);
599
+ }
600
+ async syncAuthConnector(_authConnector) {
601
+ const connector = _authConnector;
602
+ if (connector) {
603
+ const provider = await connector.getProvider();
604
+ this.appKit?.addConnector({
605
+ id: ConstantsUtil.AUTH_CONNECTOR_ID,
606
+ type: 'AUTH',
607
+ name: 'Auth',
608
+ provider,
609
+ chain: this.chainNamespace
610
+ });
611
+ this.initAuthConnectorListeners(_authConnector);
612
+ }
613
+ }
614
+ async initAuthConnectorListeners(_authConnector) {
615
+ if (_authConnector) {
616
+ await this.listenAuthConnector(_authConnector);
617
+ await this.listenModal(_authConnector);
618
+ }
619
+ }
620
+ async listenAuthConnector(connector, bypassWindowCheck = false) {
621
+ if (bypassWindowCheck || (typeof window !== 'undefined' && connector)) {
622
+ this.appKit?.setLoading(true);
623
+ const provider = (await connector.getProvider());
624
+ const isLoginEmailUsed = provider.getLoginEmailUsed();
625
+ this.appKit?.setLoading(isLoginEmailUsed);
626
+ if (isLoginEmailUsed) {
627
+ this.appKit?.setIsConnected(false, this.chainNamespace);
628
+ }
629
+ provider.onRpcRequest((request) => {
630
+ if (W3mFrameHelpers.checkIfRequestExists(request)) {
631
+ if (!W3mFrameHelpers.checkIfRequestIsSafe(request)) {
632
+ this.appKit?.handleUnsafeRPCRequest();
633
+ }
634
+ }
635
+ else {
636
+ this.appKit?.open();
637
+ console.error(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_MESSAGE, {
638
+ method: request.method
639
+ });
640
+ setTimeout(() => {
641
+ this.appKit?.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE);
642
+ }, 300);
643
+ provider.rejectRpcRequests();
644
+ }
645
+ });
646
+ provider.onRpcError(() => {
647
+ const isModalOpen = this.appKit?.isOpen();
648
+ if (isModalOpen) {
649
+ if (this.appKit?.isTransactionStackEmpty()) {
650
+ this.appKit?.close();
651
+ }
652
+ else {
653
+ this.appKit?.popTransactionStack(true);
654
+ }
655
+ }
656
+ });
657
+ provider.onRpcSuccess((_, request) => {
658
+ const isSafeRequest = W3mFrameHelpers.checkIfRequestIsSafe(request);
659
+ if (isSafeRequest) {
660
+ return;
661
+ }
662
+ if (this.appKit?.isTransactionStackEmpty()) {
663
+ this.appKit?.close();
664
+ }
665
+ else {
666
+ this.appKit?.popTransactionStack();
667
+ }
668
+ });
669
+ provider.onNotConnected(() => {
670
+ const isConnected = this.appKit?.getIsConnectedState();
671
+ if (!isConnected) {
672
+ this.appKit?.setIsConnected(false, this.chainNamespace);
673
+ this.appKit?.setLoading(false);
674
+ }
675
+ });
676
+ provider.onIsConnected(req => {
677
+ this.appKit?.setIsConnected(true, this.chainNamespace);
678
+ this.appKit?.setSmartAccountDeployed(Boolean(req.smartAccountDeployed), this.chainNamespace);
679
+ this.appKit?.setPreferredAccountType(req.preferredAccountType, this.chainNamespace);
680
+ this.appKit?.setLoading(false);
681
+ this.appKit?.setAllAccounts(req.accounts || [
682
+ {
683
+ address: req.address,
684
+ type: (req.preferredAccountType || 'eoa')
685
+ }
686
+ ], this.chainNamespace);
687
+ });
688
+ provider.onGetSmartAccountEnabledNetworks(networks => {
689
+ this.appKit?.setSmartAccountEnabledNetworks(networks, this.chainNamespace);
690
+ });
691
+ provider.onSetPreferredAccount(({ address, type }) => {
692
+ if (!address) {
693
+ return;
694
+ }
695
+ this.appKit?.setPreferredAccountType(type, this.chainNamespace);
696
+ if (this.wagmiConfig) {
697
+ reconnect(this.wagmiConfig, { connectors: [connector] });
698
+ }
699
+ });
700
+ }
701
+ }
702
+ async listenModal(connector) {
703
+ const provider = (await connector.getProvider());
704
+ this.subscribeState(val => {
705
+ if (!val.open) {
706
+ provider.rejectRpcRequests();
707
+ }
708
+ });
709
+ }
710
+ }
711
+ //# sourceMappingURL=client.js.map