@reown/appkit 1.6.6-basic-test.3.0 → 1.6.6-basic-test.5.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.
@@ -0,0 +1,1490 @@
1
+ import UniversalProvider from '@walletconnect/universal-provider';
2
+ import { ConstantsUtil, NetworkUtil, ParseUtil, getW3mThemeVariables } from '@reown/appkit-common';
3
+ import { ConstantsUtil as CoreConstantsUtil } from '@reown/appkit-core';
4
+ import { AccountController, AlertController, ApiController, AssetUtil, BlockchainApiController, ChainController, ConnectionController, ConnectorController, CoreHelperUtil, EnsController, EventsController, ModalController, OptionsController, PublicStateController, RouterController, SnackController, StorageUtil, ThemeController } from '@reown/appkit-core';
5
+ import { WalletUtil } from '@reown/appkit-scaffold-ui/utils';
6
+ import { setColorTheme, setThemeVariables } from '@reown/appkit-ui';
7
+ import { CaipNetworksUtil, ErrorUtil, HelpersUtil, LoggerUtil, ConstantsUtil as UtilConstantsUtil } from '@reown/appkit-utils';
8
+ import { W3mFrameHelpers, W3mFrameProvider, W3mFrameRpcConstants } from '@reown/appkit-wallet';
9
+ import { W3mFrameProviderSingleton } from './auth-provider/W3MFrameProviderSingleton.js';
10
+ import { ProviderUtil } from './store/ProviderUtil.js';
11
+ import { UniversalAdapter, UniversalAdapter as UniversalAdapterClient } from './universal-adapter/client.js';
12
+ import { WcHelpersUtil } from './utils/HelpersUtil.js';
13
+ // -- Export Controllers -------------------------------------------------------
14
+ export { AccountController };
15
+ // -- Helpers -------------------------------------------------------------------
16
+ let isInitialized = false;
17
+ // -- Client --------------------------------------------------------------------
18
+ export class AppKit {
19
+ constructor(options) {
20
+ this.chainNamespaces = [];
21
+ this.initPromise = undefined;
22
+ this.reportedAlertErrors = {};
23
+ this.setStatus = (status, chain) => {
24
+ StorageUtil.setConnectionStatus(status);
25
+ AccountController.setStatus(status, chain);
26
+ };
27
+ this.getIsConnectedState = () => Boolean(ChainController.state.activeCaipAddress);
28
+ this.setAllAccounts = (addresses, chain) => {
29
+ AccountController.setAllAccounts(addresses, chain);
30
+ OptionsController.setHasMultipleAddresses(addresses?.length > 1);
31
+ };
32
+ this.addAddressLabel = (address, label, chain) => {
33
+ AccountController.addAddressLabel(address, label, chain);
34
+ };
35
+ this.removeAddressLabel = (address, chain) => {
36
+ AccountController.removeAddressLabel(address, chain);
37
+ };
38
+ this.getCaipAddress = (chainNamespace) => {
39
+ if (ChainController.state.activeChain === chainNamespace || !chainNamespace) {
40
+ return ChainController.state.activeCaipAddress;
41
+ }
42
+ return ChainController.getAccountProp('caipAddress', chainNamespace);
43
+ };
44
+ this.getAddressByChainNamespace = (chainNamespace) => ChainController.getAccountProp('address', chainNamespace);
45
+ this.getAddress = (chainNamespace) => {
46
+ if (ChainController.state.activeChain === chainNamespace || !chainNamespace) {
47
+ return AccountController.state.address;
48
+ }
49
+ return ChainController.getAccountProp('address', chainNamespace);
50
+ };
51
+ this.getProvider = (namespace) => ProviderUtil.getProvider(namespace);
52
+ this.getProviderType = (namespace) => ProviderUtil.state.providerIds[namespace];
53
+ this.getPreferredAccountType = () => AccountController.state.preferredAccountType;
54
+ this.setCaipAddress = (caipAddress, chain) => {
55
+ AccountController.setCaipAddress(caipAddress, chain);
56
+ };
57
+ this.setBalance = (balance, balanceSymbol, chain) => {
58
+ AccountController.setBalance(balance, balanceSymbol, chain);
59
+ };
60
+ this.setProfileName = (profileName, chain) => {
61
+ AccountController.setProfileName(profileName, chain);
62
+ };
63
+ this.setProfileImage = (profileImage, chain) => {
64
+ AccountController.setProfileImage(profileImage, chain);
65
+ };
66
+ this.setUser = user => {
67
+ AccountController.setUser(user);
68
+ };
69
+ this.resetAccount = (chain) => {
70
+ AccountController.resetAccount(chain);
71
+ };
72
+ this.setCaipNetwork = caipNetwork => {
73
+ ChainController.setActiveCaipNetwork(caipNetwork);
74
+ };
75
+ this.getCaipNetwork = (chainNamespace) => {
76
+ if (chainNamespace) {
77
+ return ChainController.getRequestedCaipNetworks(chainNamespace).filter(c => c.chainNamespace === chainNamespace)?.[0];
78
+ }
79
+ return ChainController.state.activeCaipNetwork || this.defaultCaipNetwork;
80
+ };
81
+ this.getCaipNetworkId = () => {
82
+ const network = this.getCaipNetwork();
83
+ if (network) {
84
+ return network.id;
85
+ }
86
+ return undefined;
87
+ };
88
+ this.getCaipNetworks = (namespace) => ChainController.getRequestedCaipNetworks(namespace);
89
+ this.getActiveChainNamespace = () => ChainController.state.activeChain;
90
+ this.setRequestedCaipNetworks = (requestedCaipNetworks, chain) => {
91
+ ChainController.setRequestedCaipNetworks(requestedCaipNetworks, chain);
92
+ };
93
+ this.getApprovedCaipNetworkIds = () => ChainController.getAllApprovedCaipNetworkIds();
94
+ this.setApprovedCaipNetworksData = namespace => ChainController.setApprovedCaipNetworksData(namespace);
95
+ this.resetNetwork = (namespace) => {
96
+ ChainController.resetNetwork(namespace);
97
+ };
98
+ this.setConnectors = connectors => {
99
+ const allConnectors = [...ConnectorController.getConnectors(), ...connectors];
100
+ ConnectorController.setConnectors(allConnectors);
101
+ };
102
+ this.addConnector = connector => {
103
+ ConnectorController.addConnector(connector);
104
+ };
105
+ this.getConnectors = () => ConnectorController.getConnectors();
106
+ this.resetWcConnection = () => {
107
+ ConnectionController.resetWcConnection();
108
+ };
109
+ this.fetchIdentity = request => BlockchainApiController.fetchIdentity(request);
110
+ this.setAddressExplorerUrl = (addressExplorerUrl, chain) => {
111
+ AccountController.setAddressExplorerUrl(addressExplorerUrl, chain);
112
+ };
113
+ this.setSmartAccountDeployed = (isDeployed, chain) => {
114
+ AccountController.setSmartAccountDeployed(isDeployed, chain);
115
+ };
116
+ this.setConnectedWalletInfo = (connectedWalletInfo, chain) => {
117
+ AccountController.setConnectedWalletInfo(connectedWalletInfo, chain);
118
+ };
119
+ this.setSmartAccountEnabledNetworks = (smartAccountEnabledNetworks, chain) => {
120
+ ChainController.setSmartAccountEnabledNetworks(smartAccountEnabledNetworks, chain);
121
+ };
122
+ this.setPreferredAccountType = (preferredAccountType, chain) => {
123
+ AccountController.setPreferredAccountType(preferredAccountType, chain);
124
+ };
125
+ this.getReownName = address => EnsController.getNamesForAddress(address);
126
+ this.setEIP6963Enabled = enabled => {
127
+ OptionsController.setEIP6963Enabled(enabled);
128
+ };
129
+ this.setClientId = clientId => {
130
+ BlockchainApiController.setClientId(clientId);
131
+ };
132
+ this.getConnectorImage = connector => AssetUtil.getConnectorImage(connector);
133
+ this.handleUnsafeRPCRequest = () => {
134
+ if (this.isOpen()) {
135
+ // If we are on the modal but there is no transaction stack, close the modal
136
+ if (this.isTransactionStackEmpty()) {
137
+ return;
138
+ }
139
+ // Check if we need to replace or redirect
140
+ this.redirect('ApproveTransaction');
141
+ }
142
+ else {
143
+ // If called from outside the modal, open ApproveTransaction
144
+ this.open({ view: 'ApproveTransaction' });
145
+ }
146
+ };
147
+ this.options = options;
148
+ this.version = options.sdkVersion;
149
+ this.caipNetworks = this.extendCaipNetworks(options);
150
+ this.chainNamespaces = [
151
+ ...new Set(this.caipNetworks?.map(caipNetwork => caipNetwork.chainNamespace))
152
+ ];
153
+ this.defaultCaipNetwork = this.extendDefaultCaipNetwork(options);
154
+ this.chainAdapters = this.createAdapters(options.adapters);
155
+ this.initialize(options);
156
+ }
157
+ static getInstance() {
158
+ return this.instance;
159
+ }
160
+ async initialize(options) {
161
+ this.initControllers(options);
162
+ await this.initChainAdapters();
163
+ await this.injectModalUi();
164
+ await this.syncExistingConnection();
165
+ const { ...optionsCopy } = options;
166
+ delete optionsCopy.adapters;
167
+ EventsController.sendEvent({
168
+ type: 'track',
169
+ event: 'INITIALIZE',
170
+ properties: {
171
+ ...optionsCopy,
172
+ networks: options.networks.map(n => n.id),
173
+ siweConfig: {
174
+ options: options.siweConfig?.options || {}
175
+ }
176
+ }
177
+ });
178
+ PublicStateController.set({ initialized: true });
179
+ }
180
+ // -- Public -------------------------------------------------------------------
181
+ async open(options) {
182
+ await this.injectModalUi();
183
+ if (options?.uri && this.universalProvider) {
184
+ ConnectionController.setUri(options.uri);
185
+ }
186
+ ModalController.open(options);
187
+ }
188
+ async close() {
189
+ await this.injectModalUi();
190
+ ModalController.close();
191
+ }
192
+ setLoading(loading) {
193
+ ModalController.setLoading(loading);
194
+ }
195
+ // -- Adapter Methods ----------------------------------------------------------
196
+ getError() {
197
+ return '';
198
+ }
199
+ getChainId() {
200
+ return ChainController.state.activeCaipNetwork?.id;
201
+ }
202
+ switchNetwork(appKitNetwork) {
203
+ const network = this.caipNetworks?.find(n => n.id === appKitNetwork.id);
204
+ if (!network) {
205
+ AlertController.open(ErrorUtil.ALERT_ERRORS.SWITCH_NETWORK_NOT_FOUND, 'error');
206
+ return;
207
+ }
208
+ ChainController.switchActiveNetwork(network);
209
+ }
210
+ getWalletProvider() {
211
+ return ChainController.state.activeChain
212
+ ? ProviderUtil.state.providers[ChainController.state.activeChain]
213
+ : null;
214
+ }
215
+ getWalletProviderType() {
216
+ return ChainController.state.activeChain
217
+ ? ProviderUtil.state.providerIds[ChainController.state.activeChain]
218
+ : null;
219
+ }
220
+ subscribeProviders(callback) {
221
+ return ProviderUtil.subscribeProviders(callback);
222
+ }
223
+ getThemeMode() {
224
+ return ThemeController.state.themeMode;
225
+ }
226
+ getThemeVariables() {
227
+ return ThemeController.state.themeVariables;
228
+ }
229
+ setThemeMode(themeMode) {
230
+ ThemeController.setThemeMode(themeMode);
231
+ setColorTheme(ThemeController.state.themeMode);
232
+ }
233
+ setTermsConditionsUrl(termsConditionsUrl) {
234
+ OptionsController.setTermsConditionsUrl(termsConditionsUrl);
235
+ }
236
+ setPrivacyPolicyUrl(privacyPolicyUrl) {
237
+ OptionsController.setPrivacyPolicyUrl(privacyPolicyUrl);
238
+ }
239
+ setThemeVariables(themeVariables) {
240
+ ThemeController.setThemeVariables(themeVariables);
241
+ setThemeVariables(ThemeController.state.themeVariables);
242
+ }
243
+ subscribeTheme(callback) {
244
+ return ThemeController.subscribe(callback);
245
+ }
246
+ getWalletInfo() {
247
+ return AccountController.state.connectedWalletInfo;
248
+ }
249
+ subscribeAccount(callback) {
250
+ function updateVal() {
251
+ const authConnector = ConnectorController.getAuthConnector();
252
+ callback({
253
+ allAccounts: AccountController.state.allAccounts,
254
+ caipAddress: ChainController.state.activeCaipAddress,
255
+ address: CoreHelperUtil.getPlainAddress(ChainController.state.activeCaipAddress),
256
+ isConnected: Boolean(ChainController.state.activeCaipAddress),
257
+ status: AccountController.state.status,
258
+ embeddedWalletInfo: authConnector
259
+ ? {
260
+ user: AccountController.state.user,
261
+ authProvider: AccountController.state.socialProvider || 'email',
262
+ accountType: AccountController.state.preferredAccountType,
263
+ isSmartAccountDeployed: Boolean(AccountController.state.smartAccountDeployed)
264
+ }
265
+ : undefined
266
+ });
267
+ }
268
+ ChainController.subscribe(updateVal);
269
+ AccountController.subscribe(updateVal);
270
+ ConnectorController.subscribe(updateVal);
271
+ }
272
+ subscribeNetwork(callback) {
273
+ return ChainController.subscribe(({ activeCaipNetwork }) => {
274
+ callback({
275
+ caipNetwork: activeCaipNetwork,
276
+ chainId: activeCaipNetwork?.id,
277
+ caipNetworkId: activeCaipNetwork?.caipNetworkId
278
+ });
279
+ });
280
+ }
281
+ subscribeWalletInfo(callback) {
282
+ return AccountController.subscribeKey('connectedWalletInfo', callback);
283
+ }
284
+ subscribeShouldUpdateToAddress(callback) {
285
+ AccountController.subscribeKey('shouldUpdateToAddress', callback);
286
+ }
287
+ subscribeCaipNetworkChange(callback) {
288
+ ChainController.subscribeKey('activeCaipNetwork', callback);
289
+ }
290
+ getState() {
291
+ return PublicStateController.state;
292
+ }
293
+ subscribeState(callback) {
294
+ return PublicStateController.subscribe(callback);
295
+ }
296
+ showErrorMessage(message) {
297
+ SnackController.showError(message);
298
+ }
299
+ showSuccessMessage(message) {
300
+ SnackController.showSuccess(message);
301
+ }
302
+ getEvent() {
303
+ return { ...EventsController.state };
304
+ }
305
+ subscribeEvents(callback) {
306
+ return EventsController.subscribe(callback);
307
+ }
308
+ replace(route) {
309
+ RouterController.replace(route);
310
+ }
311
+ redirect(route) {
312
+ RouterController.push(route);
313
+ }
314
+ popTransactionStack(cancel) {
315
+ RouterController.popTransactionStack(cancel);
316
+ }
317
+ isOpen() {
318
+ return ModalController.state.open;
319
+ }
320
+ isTransactionStackEmpty() {
321
+ return RouterController.state.transactionStack.length === 0;
322
+ }
323
+ isTransactionShouldReplaceView() {
324
+ return RouterController.state.transactionStack[RouterController.state.transactionStack.length - 1]?.replace;
325
+ }
326
+ updateFeatures(newFeatures) {
327
+ OptionsController.setFeatures(newFeatures);
328
+ }
329
+ updateOptions(newOptions) {
330
+ const currentOptions = OptionsController.state || {};
331
+ const updatedOptions = { ...currentOptions, ...newOptions };
332
+ OptionsController.setOptions(updatedOptions);
333
+ }
334
+ setConnectMethodsOrder(connectMethodsOrder) {
335
+ OptionsController.setConnectMethodsOrder(connectMethodsOrder);
336
+ }
337
+ setWalletFeaturesOrder(walletFeaturesOrder) {
338
+ OptionsController.setWalletFeaturesOrder(walletFeaturesOrder);
339
+ }
340
+ setCollapseWallets(collapseWallets) {
341
+ OptionsController.setCollapseWallets(collapseWallets);
342
+ }
343
+ setSocialsOrder(socialsOrder) {
344
+ OptionsController.setSocialsOrder(socialsOrder);
345
+ }
346
+ async disconnect() {
347
+ await ConnectionController.disconnect();
348
+ }
349
+ getConnectMethodsOrder() {
350
+ return WalletUtil.getConnectOrderMethod(OptionsController.state.features, ConnectorController.getConnectors());
351
+ }
352
+ /**
353
+ * Removes an adapter from the AppKit.
354
+ * @param namespace - The namespace of the adapter to remove.
355
+ */
356
+ removeAdapter(namespace) {
357
+ const isConnected = this.getIsConnectedState();
358
+ const adapter = this.getAdapter(namespace);
359
+ if (!adapter || !this.chainAdapters || isConnected) {
360
+ return;
361
+ }
362
+ const newCaipNetworks = this.caipNetworks?.filter(network => network.chainNamespace !== namespace);
363
+ ChainController.removeAdapter(namespace);
364
+ ConnectorController.removeAdapter(namespace);
365
+ this.chainNamespaces = this.chainNamespaces.filter(n => n !== namespace);
366
+ this.caipNetworks = newCaipNetworks;
367
+ adapter.removeAllEventListeners();
368
+ Reflect.deleteProperty(this.chainAdapters, namespace);
369
+ }
370
+ /**
371
+ * Adds an adapter to the AppKit.
372
+ * @param adapter - The adapter instance.
373
+ * @param networks - The list of networks that this adapter supports / uses.
374
+ */
375
+ addAdapter(adapter, networks) {
376
+ const namespace = adapter.namespace;
377
+ if (!this.connectionControllerClient || !this.networkControllerClient) {
378
+ return;
379
+ }
380
+ if (!this.chainAdapters || !namespace) {
381
+ return;
382
+ }
383
+ const extendedAdapterNetworks = this.extendCaipNetworks({ ...this.options, networks });
384
+ this.caipNetworks = [...(this.caipNetworks || []), ...extendedAdapterNetworks];
385
+ this.createAdapter(adapter);
386
+ this.initChainAdapter(namespace);
387
+ ChainController.addAdapter(adapter, {
388
+ connectionControllerClient: this.connectionControllerClient,
389
+ networkControllerClient: this.networkControllerClient
390
+ }, extendedAdapterNetworks);
391
+ }
392
+ // -- Private ------------------------------------------------------------------
393
+ initializeOptionsController(options) {
394
+ OptionsController.setDebug(options.debug !== false);
395
+ if (!options.projectId) {
396
+ AlertController.open(ErrorUtil.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED, 'error');
397
+ return;
398
+ }
399
+ // On by default
400
+ OptionsController.setEnableWalletConnect(options.enableWalletConnect !== false);
401
+ OptionsController.setEnableWalletGuide(options.enableWalletGuide !== false);
402
+ OptionsController.setEnableWallets(options.enableWallets !== false);
403
+ OptionsController.setEIP6963Enabled(options.enableEIP6963 !== false);
404
+ OptionsController.setEnableAuthLogger(options.enableAuthLogger !== false);
405
+ OptionsController.setSdkVersion(options.sdkVersion);
406
+ OptionsController.setProjectId(options.projectId);
407
+ OptionsController.setEnableEmbedded(options.enableEmbedded);
408
+ OptionsController.setAllWallets(options.allWallets);
409
+ OptionsController.setIncludeWalletIds(options.includeWalletIds);
410
+ OptionsController.setExcludeWalletIds(options.excludeWalletIds);
411
+ OptionsController.setFeaturedWalletIds(options.featuredWalletIds);
412
+ OptionsController.setTokens(options.tokens);
413
+ OptionsController.setTermsConditionsUrl(options.termsConditionsUrl);
414
+ OptionsController.setPrivacyPolicyUrl(options.privacyPolicyUrl);
415
+ OptionsController.setCustomWallets(options.customWallets);
416
+ OptionsController.setFeatures(options.features);
417
+ OptionsController.setAllowUnsupportedChain(options.allowUnsupportedChain);
418
+ OptionsController.setDefaultAccountTypes(options.defaultAccountTypes);
419
+ const defaultMetaData = this.getDefaultMetaData();
420
+ if (!options.metadata && defaultMetaData) {
421
+ options.metadata = defaultMetaData;
422
+ }
423
+ OptionsController.setMetadata(options.metadata);
424
+ OptionsController.setDisableAppend(options.disableAppend);
425
+ OptionsController.setEnableEmbedded(options.enableEmbedded);
426
+ OptionsController.setSIWX(options.siwx);
427
+ const evmAdapter = options.adapters?.find(adapter => adapter.namespace === ConstantsUtil.CHAIN.EVM);
428
+ // Set the SIWE client for EVM chains
429
+ if (evmAdapter) {
430
+ if (options.siweConfig) {
431
+ if (options.siwx) {
432
+ throw new Error('Cannot set both `siweConfig` and `siwx` options');
433
+ }
434
+ OptionsController.setSIWX(options.siweConfig.mapToSIWX());
435
+ }
436
+ }
437
+ }
438
+ initializeThemeController(options) {
439
+ if (options.themeMode) {
440
+ ThemeController.setThemeMode(options.themeMode);
441
+ }
442
+ if (options.themeVariables) {
443
+ ThemeController.setThemeVariables(options.themeVariables);
444
+ }
445
+ }
446
+ initializeChainController(options) {
447
+ if (!this.connectionControllerClient || !this.networkControllerClient) {
448
+ throw new Error('ConnectionControllerClient and NetworkControllerClient must be set');
449
+ }
450
+ ChainController.initialize(options.adapters ?? [], this.caipNetworks, {
451
+ connectionControllerClient: this.connectionControllerClient,
452
+ networkControllerClient: this.networkControllerClient
453
+ });
454
+ const network = this.getDefaultNetwork();
455
+ if (network) {
456
+ ChainController.setActiveCaipNetwork(network);
457
+ }
458
+ }
459
+ async initializeBlockchainApiController(options) {
460
+ await BlockchainApiController.getSupportedNetworks({
461
+ projectId: options.projectId
462
+ });
463
+ }
464
+ initControllers(options) {
465
+ this.initializeOptionsController(options);
466
+ this.initializeChainController(options);
467
+ this.initializeThemeController(options);
468
+ this.initializeBlockchainApiController(options);
469
+ if (options.excludeWalletIds) {
470
+ ApiController.initializeExcludedWalletRdns({ ids: options.excludeWalletIds });
471
+ }
472
+ }
473
+ getDefaultMetaData() {
474
+ if (typeof window !== 'undefined' && typeof document !== 'undefined') {
475
+ return {
476
+ name: document.getElementsByTagName('title')?.[0]?.textContent || '',
477
+ description: document.querySelector('meta[property="og:description"]')?.content || '',
478
+ url: window.location.origin,
479
+ icons: [document.querySelector('link[rel~="icon"]')?.href || '']
480
+ };
481
+ }
482
+ return null;
483
+ }
484
+ setUnsupportedNetwork(chainId) {
485
+ const namespace = this.getActiveChainNamespace();
486
+ if (namespace) {
487
+ const unsupportedNetwork = this.getUnsupportedNetwork(`${namespace}:${chainId}`);
488
+ ChainController.setActiveCaipNetwork(unsupportedNetwork);
489
+ }
490
+ }
491
+ extendCaipNetworks(options) {
492
+ const extendedNetworks = CaipNetworksUtil.extendCaipNetworks(options.networks, {
493
+ customNetworkImageUrls: options.chainImages,
494
+ projectId: options.projectId
495
+ });
496
+ return extendedNetworks;
497
+ }
498
+ extendDefaultCaipNetwork(options) {
499
+ const defaultNetwork = options.networks.find(n => n.id === options.defaultNetwork?.id);
500
+ const extendedNetwork = defaultNetwork
501
+ ? CaipNetworksUtil.extendCaipNetwork(defaultNetwork, {
502
+ customNetworkImageUrls: options.chainImages,
503
+ projectId: options.projectId
504
+ })
505
+ : undefined;
506
+ return extendedNetwork;
507
+ }
508
+ createClients() {
509
+ this.connectionControllerClient = {
510
+ connectWalletConnect: async () => {
511
+ const adapter = this.getAdapter(ChainController.state.activeChain);
512
+ if (!adapter) {
513
+ throw new Error('Adapter not found');
514
+ }
515
+ const result = await adapter.connectWalletConnect(this.getCaipNetwork()?.id);
516
+ this.close();
517
+ this.setClientId(result?.clientId || null);
518
+ StorageUtil.setConnectedNamespaces([...ChainController.state.chains.keys()]);
519
+ await this.syncWalletConnectAccount();
520
+ },
521
+ connectExternal: async ({ id, info, type, provider, chain, caipNetwork }) => {
522
+ const activeChain = ChainController.state.activeChain;
523
+ if (chain && chain !== activeChain && !caipNetwork) {
524
+ const toConnectNetwork = this.caipNetworks?.find(network => network.chainNamespace === chain);
525
+ if (toConnectNetwork) {
526
+ this.setCaipNetwork(toConnectNetwork);
527
+ }
528
+ }
529
+ const chainToUse = chain || activeChain;
530
+ const adapter = this.getAdapter(chainToUse);
531
+ if (!adapter) {
532
+ throw new Error('Adapter not found');
533
+ }
534
+ const res = await adapter.connect({
535
+ id,
536
+ info,
537
+ type,
538
+ provider,
539
+ chainId: caipNetwork?.id || this.getCaipNetwork()?.id,
540
+ rpcUrl: caipNetwork?.rpcUrls?.default?.http?.[0] ||
541
+ this.getCaipNetwork()?.rpcUrls?.default?.http?.[0]
542
+ });
543
+ if (!res) {
544
+ return;
545
+ }
546
+ StorageUtil.addConnectedNamespace(chainToUse);
547
+ this.syncProvider({ ...res, chainNamespace: chainToUse });
548
+ await this.syncAccount({ ...res, chainNamespace: chainToUse });
549
+ const { accounts } = await adapter.getAccounts({ namespace: chainToUse, id });
550
+ this.setAllAccounts(accounts, chainToUse);
551
+ },
552
+ reconnectExternal: async ({ id, info, type, provider }) => {
553
+ const namespace = ChainController.state.activeChain;
554
+ const adapter = this.getAdapter(namespace);
555
+ if (adapter?.reconnect) {
556
+ await adapter?.reconnect({ id, info, type, provider, chainId: this.getCaipNetwork()?.id });
557
+ StorageUtil.addConnectedNamespace(namespace);
558
+ }
559
+ },
560
+ disconnect: async () => {
561
+ const namespace = ChainController.state.activeChain;
562
+ const adapter = this.getAdapter(namespace);
563
+ const provider = ProviderUtil.getProvider(namespace);
564
+ const providerType = ProviderUtil.state.providerIds[namespace];
565
+ await adapter?.disconnect({ provider, providerType });
566
+ StorageUtil.removeConnectedNamespace(namespace);
567
+ ProviderUtil.resetChain(namespace);
568
+ this.setUser(undefined);
569
+ this.setStatus('disconnected', namespace);
570
+ },
571
+ checkInstalled: (ids) => {
572
+ if (!ids) {
573
+ return Boolean(window.ethereum);
574
+ }
575
+ return ids.some(id => Boolean(window.ethereum?.[String(id)]));
576
+ },
577
+ signMessage: async (message) => {
578
+ const adapter = this.getAdapter(ChainController.state.activeChain);
579
+ const result = await adapter?.signMessage({
580
+ message,
581
+ address: AccountController.state.address,
582
+ provider: ProviderUtil.getProvider(ChainController.state.activeChain)
583
+ });
584
+ return result?.signature || '';
585
+ },
586
+ sendTransaction: async (args) => {
587
+ if (args.chainNamespace === ConstantsUtil.CHAIN.EVM) {
588
+ const adapter = this.getAdapter(ChainController.state.activeChain);
589
+ const provider = ProviderUtil.getProvider(ChainController.state.activeChain);
590
+ const result = await adapter?.sendTransaction({ ...args, provider });
591
+ return result?.hash || '';
592
+ }
593
+ return '';
594
+ },
595
+ estimateGas: async (args) => {
596
+ if (args.chainNamespace === ConstantsUtil.CHAIN.EVM) {
597
+ const adapter = this.getAdapter(ChainController.state.activeChain);
598
+ const provider = ProviderUtil.getProvider(ChainController.state.activeChain);
599
+ const caipNetwork = this.getCaipNetwork();
600
+ if (!caipNetwork) {
601
+ throw new Error('CaipNetwork is undefined');
602
+ }
603
+ const result = await adapter?.estimateGas({
604
+ ...args,
605
+ provider,
606
+ caipNetwork
607
+ });
608
+ return result?.gas || 0n;
609
+ }
610
+ return 0n;
611
+ },
612
+ getEnsAvatar: async () => {
613
+ const adapter = this.getAdapter(ChainController.state.activeChain);
614
+ const result = await adapter?.getProfile({
615
+ address: AccountController.state.address,
616
+ chainId: Number(this.getCaipNetwork()?.id)
617
+ });
618
+ return result?.profileImage || false;
619
+ },
620
+ getEnsAddress: async (name) => {
621
+ const adapter = this.getAdapter(ChainController.state.activeChain);
622
+ const caipNetwork = this.getCaipNetwork();
623
+ if (!caipNetwork) {
624
+ return false;
625
+ }
626
+ const result = await adapter?.getEnsAddress({
627
+ name,
628
+ caipNetwork
629
+ });
630
+ return result?.address || false;
631
+ },
632
+ writeContract: async (args) => {
633
+ const adapter = this.getAdapter(ChainController.state.activeChain);
634
+ const caipNetwork = this.getCaipNetwork();
635
+ const caipAddress = this.getCaipAddress();
636
+ const provider = ProviderUtil.getProvider(ChainController.state.activeChain);
637
+ if (!caipNetwork || !caipAddress) {
638
+ throw new Error('CaipNetwork or CaipAddress is undefined');
639
+ }
640
+ const result = await adapter?.writeContract({ ...args, caipNetwork, provider, caipAddress });
641
+ return result?.hash;
642
+ },
643
+ parseUnits: (value, decimals) => {
644
+ const adapter = this.getAdapter(ChainController.state.activeChain);
645
+ return adapter?.parseUnits({ value, decimals }) ?? 0n;
646
+ },
647
+ formatUnits: (value, decimals) => {
648
+ const adapter = this.getAdapter(ChainController.state.activeChain);
649
+ return adapter?.formatUnits({ value, decimals }) ?? '0';
650
+ },
651
+ getCapabilities: async (params) => {
652
+ const adapter = this.getAdapter(ChainController.state.activeChain);
653
+ await adapter?.getCapabilities(params);
654
+ },
655
+ grantPermissions: async (params) => {
656
+ const adapter = this.getAdapter(ChainController.state.activeChain);
657
+ return await adapter?.grantPermissions(params);
658
+ },
659
+ revokePermissions: async (params) => {
660
+ const adapter = this.getAdapter(ChainController.state.activeChain);
661
+ if (adapter?.revokePermissions) {
662
+ return await adapter.revokePermissions(params);
663
+ }
664
+ return '0x';
665
+ }
666
+ };
667
+ this.networkControllerClient = {
668
+ switchCaipNetwork: async (caipNetwork) => {
669
+ if (!caipNetwork) {
670
+ return;
671
+ }
672
+ if (AccountController.state.address &&
673
+ caipNetwork.chainNamespace === ChainController.state.activeChain) {
674
+ const adapter = this.getAdapter(ChainController.state.activeChain);
675
+ const provider = ProviderUtil.getProvider(ChainController.state.activeChain);
676
+ const providerType = ProviderUtil.state.providerIds[ChainController.state.activeChain];
677
+ await adapter?.switchNetwork({ caipNetwork, provider, providerType });
678
+ this.setCaipNetwork(caipNetwork);
679
+ await this.syncAccount({
680
+ address: AccountController.state.address,
681
+ chainId: caipNetwork.id,
682
+ chainNamespace: caipNetwork.chainNamespace
683
+ });
684
+ }
685
+ else if (AccountController.state.address) {
686
+ const providerType = ProviderUtil.state.providerIds[ChainController.state.activeChain];
687
+ if (providerType === UtilConstantsUtil.CONNECTOR_TYPE_AUTH) {
688
+ try {
689
+ ChainController.state.activeChain = caipNetwork.chainNamespace;
690
+ await this.connectionControllerClient?.connectExternal?.({
691
+ id: ConstantsUtil.CONNECTOR_ID.AUTH,
692
+ provider: this.authProvider,
693
+ chain: caipNetwork.chainNamespace,
694
+ chainId: caipNetwork.id,
695
+ type: UtilConstantsUtil.CONNECTOR_TYPE_AUTH,
696
+ caipNetwork
697
+ });
698
+ this.setCaipNetwork(caipNetwork);
699
+ }
700
+ catch (error) {
701
+ const adapter = this.getAdapter(caipNetwork.chainNamespace);
702
+ await adapter?.switchNetwork({
703
+ caipNetwork,
704
+ provider: this.authProvider,
705
+ providerType
706
+ });
707
+ }
708
+ }
709
+ else if (providerType === 'WALLET_CONNECT') {
710
+ this.setCaipNetwork(caipNetwork);
711
+ this.syncWalletConnectAccount();
712
+ }
713
+ else {
714
+ this.setCaipNetwork(caipNetwork);
715
+ const address = this.getAddressByChainNamespace(caipNetwork.chainNamespace);
716
+ if (address) {
717
+ this.syncAccount({
718
+ address,
719
+ chainId: caipNetwork.id,
720
+ chainNamespace: caipNetwork.chainNamespace
721
+ });
722
+ }
723
+ }
724
+ }
725
+ else {
726
+ this.setCaipNetwork(caipNetwork);
727
+ }
728
+ },
729
+ // eslint-disable-next-line @typescript-eslint/require-await
730
+ getApprovedCaipNetworksData: async () => {
731
+ const providerType = ProviderUtil.state.providerIds[ChainController.state.activeChain];
732
+ if (providerType === UtilConstantsUtil.CONNECTOR_TYPE_WALLET_CONNECT) {
733
+ const namespaces = this.universalProvider?.session?.namespaces;
734
+ return {
735
+ /*
736
+ * MetaMask Wallet only returns 1 namespace in the session object. This makes it imposible
737
+ * to switch to other networks. Setting supportsAllNetworks to true for MetaMask Wallet
738
+ * will make it possible to switch to other networks.
739
+ */
740
+ supportsAllNetworks: this.universalProvider?.session?.peer?.metadata.name === 'MetaMask Wallet',
741
+ approvedCaipNetworkIds: this.getChainsFromNamespaces(namespaces)
742
+ };
743
+ }
744
+ return { supportsAllNetworks: true, approvedCaipNetworkIds: [] };
745
+ }
746
+ };
747
+ ConnectionController.setClient(this.connectionControllerClient);
748
+ }
749
+ setupAuthConnectorListeners(provider) {
750
+ provider.onRpcRequest((request) => {
751
+ if (W3mFrameHelpers.checkIfRequestExists(request)) {
752
+ if (!W3mFrameHelpers.checkIfRequestIsSafe(request)) {
753
+ this.handleUnsafeRPCRequest();
754
+ }
755
+ }
756
+ else {
757
+ this.open();
758
+ // eslint-disable-next-line no-console
759
+ console.error(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_MESSAGE, {
760
+ method: request.method
761
+ });
762
+ setTimeout(() => {
763
+ this.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE);
764
+ }, 300);
765
+ provider.rejectRpcRequests();
766
+ }
767
+ });
768
+ provider.onRpcError(() => {
769
+ const isModalOpen = this.isOpen();
770
+ if (isModalOpen) {
771
+ if (this.isTransactionStackEmpty()) {
772
+ this.close();
773
+ }
774
+ else {
775
+ this.popTransactionStack(true);
776
+ }
777
+ }
778
+ });
779
+ provider.onRpcSuccess((_, request) => {
780
+ const isSafeRequest = W3mFrameHelpers.checkIfRequestIsSafe(request);
781
+ if (isSafeRequest) {
782
+ return;
783
+ }
784
+ if (this.isTransactionStackEmpty()) {
785
+ this.close();
786
+ if (AccountController.state.address && ChainController.state.activeCaipNetwork?.id) {
787
+ this.updateNativeBalance();
788
+ }
789
+ }
790
+ else {
791
+ this.popTransactionStack();
792
+ if (AccountController.state.address && ChainController.state.activeCaipNetwork?.id) {
793
+ this.updateNativeBalance();
794
+ }
795
+ }
796
+ });
797
+ provider.onNotConnected(() => {
798
+ const namespace = ChainController.state.activeChain;
799
+ const connectorId = StorageUtil.getConnectedConnectorId(namespace);
800
+ const isConnectedWithAuth = connectorId === ConstantsUtil.CONNECTOR_ID.AUTH;
801
+ if (isConnectedWithAuth) {
802
+ this.setCaipAddress(undefined, namespace);
803
+ this.setLoading(false);
804
+ }
805
+ });
806
+ provider.onConnect(async (user) => {
807
+ const namespace = ChainController.state.activeChain;
808
+ // To keep backwards compatibility, eip155 chainIds are numbers and not actual caipChainIds
809
+ const caipAddress = namespace === ConstantsUtil.CHAIN.EVM
810
+ ? `eip155:${user.chainId}:${user.address}`
811
+ : `${user.chainId}:${user.address}`;
812
+ this.setSmartAccountDeployed(Boolean(user.smartAccountDeployed), namespace);
813
+ if (!HelpersUtil.isLowerCaseMatch(user.address, AccountController.state.address)) {
814
+ this.syncIdentity({
815
+ address: user.address,
816
+ chainId: user.chainId,
817
+ chainNamespace: namespace
818
+ });
819
+ }
820
+ this.setCaipAddress(caipAddress, namespace);
821
+ this.setUser({ ...(AccountController.state.user || {}), email: user.email });
822
+ const preferredAccountType = (user.preferredAccountType ||
823
+ OptionsController.state.defaultAccountTypes[namespace]);
824
+ this.setPreferredAccountType(preferredAccountType, namespace);
825
+ const userAccounts = user.accounts?.map(account => CoreHelperUtil.createAccount(namespace, account.address, account.type || OptionsController.state.defaultAccountTypes[namespace]));
826
+ this.setAllAccounts(userAccounts || [
827
+ CoreHelperUtil.createAccount(namespace, user.address, preferredAccountType)
828
+ ], namespace);
829
+ await provider.getSmartAccountEnabledNetworks();
830
+ this.setLoading(false);
831
+ });
832
+ provider.onSocialConnected(({ userName }) => {
833
+ this.setUser({ ...(AccountController.state.user || {}), username: userName });
834
+ });
835
+ provider.onGetSmartAccountEnabledNetworks(networks => {
836
+ this.setSmartAccountEnabledNetworks(networks, ChainController.state.activeChain);
837
+ });
838
+ provider.onSetPreferredAccount(({ address, type }) => {
839
+ if (!address) {
840
+ return;
841
+ }
842
+ this.setPreferredAccountType(type, ChainController.state.activeChain);
843
+ });
844
+ }
845
+ async syncAuthConnector(provider) {
846
+ this.setLoading(true);
847
+ const isLoginEmailUsed = provider.getLoginEmailUsed();
848
+ this.setLoading(isLoginEmailUsed);
849
+ if (isLoginEmailUsed) {
850
+ this.setStatus('connecting', ChainController.state.activeChain);
851
+ }
852
+ const email = provider.getEmail();
853
+ const username = provider.getUsername();
854
+ this.setUser({ ...(AccountController.state?.user || {}), username, email });
855
+ this.setupAuthConnectorListeners(provider);
856
+ const { isConnected } = await provider.isConnected();
857
+ const theme = ThemeController.getSnapshot();
858
+ const options = OptionsController.getSnapshot();
859
+ provider.syncDappData({
860
+ metadata: options.metadata,
861
+ sdkVersion: options.sdkVersion,
862
+ projectId: options.projectId,
863
+ sdkType: options.sdkType
864
+ });
865
+ provider.syncTheme({
866
+ themeMode: theme.themeMode,
867
+ themeVariables: theme.themeVariables,
868
+ w3mThemeVariables: getW3mThemeVariables(theme.themeVariables, theme.themeMode)
869
+ });
870
+ const namespace = StorageUtil.getActiveNamespace();
871
+ if (namespace) {
872
+ if (isConnected && this.connectionControllerClient?.connectExternal) {
873
+ await this.connectionControllerClient?.connectExternal({
874
+ id: ConstantsUtil.CONNECTOR_ID.AUTH,
875
+ info: { name: ConstantsUtil.CONNECTOR_ID.AUTH },
876
+ type: UtilConstantsUtil.CONNECTOR_TYPE_AUTH,
877
+ provider,
878
+ chainId: ChainController.state.activeCaipNetwork?.id,
879
+ chain: namespace
880
+ });
881
+ this.setStatus('connected', namespace);
882
+ }
883
+ else if (StorageUtil.getConnectedConnectorId(namespace) === ConstantsUtil.CONNECTOR_ID.AUTH) {
884
+ this.setStatus('disconnected', namespace);
885
+ StorageUtil.removeConnectedNamespace(namespace);
886
+ }
887
+ }
888
+ this.setLoading(false);
889
+ }
890
+ listenWalletConnect() {
891
+ if (this.universalProvider) {
892
+ this.universalProvider.on('display_uri', ConnectionController.setUri.bind(ConnectionController));
893
+ this.universalProvider.on('disconnect', () => {
894
+ this.chainNamespaces.forEach(namespace => {
895
+ this.resetAccount(namespace);
896
+ });
897
+ ConnectionController.resetWcConnection();
898
+ });
899
+ this.universalProvider.on('chainChanged', (chainId) => {
900
+ // eslint-disable-next-line eqeqeq
901
+ const caipNetwork = this.caipNetworks?.find(c => c.id == chainId);
902
+ const currentCaipNetwork = this.getCaipNetwork();
903
+ if (!caipNetwork) {
904
+ this.setUnsupportedNetwork(chainId);
905
+ return;
906
+ }
907
+ if (currentCaipNetwork?.id !== caipNetwork?.id) {
908
+ this.setCaipNetwork(caipNetwork);
909
+ }
910
+ });
911
+ this.universalProvider.on('session_event', (callbackData) => {
912
+ if (WcHelpersUtil.isSessionEventData(callbackData)) {
913
+ const { name, data } = callbackData.params.event;
914
+ if (name === 'accountsChanged' &&
915
+ Array.isArray(data) &&
916
+ CoreHelperUtil.isCaipAddress(data[0])) {
917
+ this.syncAccount(ParseUtil.parseCaipAddress(data[0]));
918
+ }
919
+ }
920
+ });
921
+ }
922
+ }
923
+ listenAdapter(chainNamespace) {
924
+ const adapter = this.getAdapter(chainNamespace);
925
+ if (!adapter) {
926
+ return;
927
+ }
928
+ const connectionStatus = StorageUtil.getConnectionStatus();
929
+ if (connectionStatus === 'connected') {
930
+ this.setStatus('connecting', chainNamespace);
931
+ }
932
+ else {
933
+ this.setStatus(connectionStatus, chainNamespace);
934
+ }
935
+ adapter.on('switchNetwork', ({ address, chainId }) => {
936
+ if (chainId &&
937
+ this.caipNetworks?.find(n => n.id === chainId || n.caipNetworkId === chainId)) {
938
+ if (ChainController.state.activeChain === chainNamespace && address) {
939
+ this.syncAccount({ address, chainId, chainNamespace });
940
+ }
941
+ else if (ChainController.state.activeChain === chainNamespace &&
942
+ AccountController.state.address) {
943
+ this.syncAccount({
944
+ address: AccountController.state.address,
945
+ chainId,
946
+ chainNamespace
947
+ });
948
+ }
949
+ }
950
+ else {
951
+ this.setUnsupportedNetwork(chainId);
952
+ }
953
+ });
954
+ adapter.on('disconnect', this.disconnect.bind(this));
955
+ adapter.on('pendingTransactions', () => {
956
+ const address = AccountController.state.address;
957
+ const activeCaipNetwork = ChainController.state.activeCaipNetwork;
958
+ if (!address || !activeCaipNetwork?.id) {
959
+ return;
960
+ }
961
+ this.updateNativeBalance();
962
+ });
963
+ adapter.on('accountChanged', ({ address, chainId }) => {
964
+ if (ChainController.state.activeChain === chainNamespace && chainId) {
965
+ this.syncAccount({
966
+ address,
967
+ chainId,
968
+ chainNamespace
969
+ });
970
+ }
971
+ else if (ChainController.state.activeChain === chainNamespace &&
972
+ ChainController.state.activeCaipNetwork?.id) {
973
+ this.syncAccount({
974
+ address,
975
+ chainId: ChainController.state.activeCaipNetwork?.id,
976
+ chainNamespace
977
+ });
978
+ }
979
+ });
980
+ }
981
+ async updateNativeBalance() {
982
+ const adapter = this.getAdapter(ChainController.state.activeChain);
983
+ if (adapter && ChainController.state.activeChain && AccountController.state.address) {
984
+ const balance = await adapter.getBalance({
985
+ address: AccountController.state.address,
986
+ chainId: ChainController.state.activeCaipNetwork?.id,
987
+ caipNetwork: this.getCaipNetwork(),
988
+ tokens: this.options.tokens
989
+ });
990
+ this.setBalance(balance.balance, balance.symbol, ChainController.state.activeChain);
991
+ }
992
+ }
993
+ getChainsFromNamespaces(namespaces = {}) {
994
+ return Object.values(namespaces).flatMap((namespace) => {
995
+ const chains = (namespace.chains || []);
996
+ const accountsChains = namespace.accounts.map(account => {
997
+ const { chainId, chainNamespace } = ParseUtil.parseCaipAddress(account);
998
+ return `${chainNamespace}:${chainId}`;
999
+ });
1000
+ return Array.from(new Set([...chains, ...accountsChains]));
1001
+ });
1002
+ }
1003
+ async syncWalletConnectAccount() {
1004
+ const adapter = this.getAdapter(ChainController.state.activeChain);
1005
+ this.chainNamespaces.forEach(async (chainNamespace) => {
1006
+ const namespaceAccounts = this.universalProvider?.session?.namespaces?.[chainNamespace]?.accounts || [];
1007
+ // We try and find the address for this network in the session object.
1008
+ const activeChainId = ChainController.state.activeCaipNetwork?.id;
1009
+ const sessionAddress = namespaceAccounts.find(account => {
1010
+ const { chainId } = ParseUtil.parseCaipAddress(account);
1011
+ return chainId === activeChainId?.toString();
1012
+ }) || namespaceAccounts[0];
1013
+ if (sessionAddress) {
1014
+ const caipAddress = ParseUtil.validateCaipAddress(sessionAddress);
1015
+ const { chainId, address } = ParseUtil.parseCaipAddress(caipAddress);
1016
+ ProviderUtil.setProviderId(chainNamespace, UtilConstantsUtil.CONNECTOR_TYPE_WALLET_CONNECT);
1017
+ if (this.caipNetworks &&
1018
+ ChainController.state.activeCaipNetwork &&
1019
+ adapter?.namespace !== ConstantsUtil.CHAIN.EVM) {
1020
+ const provider = adapter?.getWalletConnectProvider({
1021
+ caipNetworks: this.caipNetworks,
1022
+ provider: this.universalProvider,
1023
+ activeCaipNetwork: ChainController.state.activeCaipNetwork
1024
+ });
1025
+ ProviderUtil.setProvider(chainNamespace, provider);
1026
+ }
1027
+ else {
1028
+ ProviderUtil.setProvider(chainNamespace, this.universalProvider);
1029
+ }
1030
+ StorageUtil.setConnectedConnectorId(chainNamespace, ConstantsUtil.CONNECTOR_ID.WALLET_CONNECT);
1031
+ StorageUtil.addConnectedNamespace(chainNamespace);
1032
+ if (adapter?.adapterType === 'wagmi') {
1033
+ try {
1034
+ await adapter?.connect({
1035
+ id: 'walletConnect',
1036
+ type: 'WALLET_CONNECT',
1037
+ chainId: ChainController.state.activeCaipNetwork?.id
1038
+ });
1039
+ }
1040
+ catch (error) {
1041
+ /**
1042
+ * Handle edge case where wagmi detects existing connection but lacks to complete UniversalProvider instance.
1043
+ * Connection attempt fails due to already connected state - reconnect to restore provider state.
1044
+ */
1045
+ if (adapter?.reconnect) {
1046
+ adapter?.reconnect({
1047
+ id: 'walletConnect',
1048
+ type: 'WALLET_CONNECT'
1049
+ });
1050
+ }
1051
+ }
1052
+ }
1053
+ this.syncWalletConnectAccounts(chainNamespace);
1054
+ await this.syncAccount({
1055
+ address,
1056
+ chainId,
1057
+ chainNamespace
1058
+ });
1059
+ }
1060
+ });
1061
+ await ChainController.setApprovedCaipNetworksData(ChainController.state.activeChain);
1062
+ }
1063
+ syncWalletConnectAccounts(chainNamespace) {
1064
+ const addresses = this.universalProvider?.session?.namespaces?.[chainNamespace]?.accounts
1065
+ ?.map(account => {
1066
+ const { address } = ParseUtil.parseCaipAddress(account);
1067
+ return address;
1068
+ })
1069
+ .filter((address, index, self) => self.indexOf(address) === index);
1070
+ if (addresses) {
1071
+ this.setAllAccounts(addresses.map(address => CoreHelperUtil.createAccount(chainNamespace, address, chainNamespace === 'bip122' ? 'payment' : 'eoa')), chainNamespace);
1072
+ }
1073
+ }
1074
+ syncProvider({ type, provider, id, chainNamespace }) {
1075
+ ProviderUtil.setProviderId(chainNamespace, type);
1076
+ ProviderUtil.setProvider(chainNamespace, provider);
1077
+ StorageUtil.setConnectedConnectorId(chainNamespace, id);
1078
+ }
1079
+ async syncAccount(params) {
1080
+ const { address, chainId, chainNamespace } = params;
1081
+ const { chainId: activeChainId } = StorageUtil.getActiveNetworkProps();
1082
+ const chainIdToUse = chainId || activeChainId;
1083
+ const isUnsupportedNetwork = ChainController.state.activeCaipNetwork?.name === ConstantsUtil.UNSUPPORTED_NETWORK_NAME;
1084
+ const shouldSupportAllNetworks = ChainController.getNetworkProp('supportsAllNetworks', chainNamespace);
1085
+ // Only update state when needed
1086
+ if (!HelpersUtil.isLowerCaseMatch(address, AccountController.state.address)) {
1087
+ this.setCaipAddress(`${chainNamespace}:${chainId}:${address}`, chainNamespace);
1088
+ await this.syncIdentity({ address, chainId, chainNamespace });
1089
+ }
1090
+ this.setStatus('connected', chainNamespace);
1091
+ if (isUnsupportedNetwork && !shouldSupportAllNetworks) {
1092
+ return;
1093
+ }
1094
+ if (chainIdToUse) {
1095
+ let caipNetwork = this.caipNetworks?.find(n => n.id.toString() === chainIdToUse.toString());
1096
+ let fallbackCaipNetwork = this.caipNetworks?.find(n => n.chainNamespace === chainNamespace);
1097
+ // If doesn't support all networks, we need to use approved networks
1098
+ if (!shouldSupportAllNetworks) {
1099
+ // Connection can be requested for a chain that is not supported by the wallet so we need to use approved networks here
1100
+ const caipNetworkIds = this.getApprovedCaipNetworkIds() || [];
1101
+ const caipNetworkId = caipNetworkIds.find(id => ParseUtil.parseCaipNetworkId(id)?.chainId === chainIdToUse.toString());
1102
+ const fallBackCaipNetworkId = caipNetworkIds.find(id => ParseUtil.parseCaipNetworkId(id)?.chainNamespace === chainNamespace);
1103
+ caipNetwork = this.caipNetworks?.find(n => n.caipNetworkId === caipNetworkId);
1104
+ fallbackCaipNetwork = this.caipNetworks?.find(n => n.caipNetworkId === fallBackCaipNetworkId ||
1105
+ // This is a workaround used in Solana network to support deprecated caipNetworkId
1106
+ ('deprecatedCaipNetworkId' in n && n.deprecatedCaipNetworkId === fallBackCaipNetworkId));
1107
+ }
1108
+ const network = caipNetwork || fallbackCaipNetwork;
1109
+ if (network?.chainNamespace === ChainController.state.activeChain) {
1110
+ this.setCaipNetwork(network);
1111
+ }
1112
+ this.syncConnectedWalletInfo(chainNamespace);
1113
+ await this.syncBalance({ address, chainId: network?.id, chainNamespace });
1114
+ }
1115
+ }
1116
+ async syncBalance(params) {
1117
+ const caipNetwork = NetworkUtil.getNetworksByNamespace(this.caipNetworks, params.chainNamespace).find(n => n.id.toString() === params.chainId?.toString());
1118
+ if (!caipNetwork) {
1119
+ return;
1120
+ }
1121
+ const isApiBalanceSupported = CoreConstantsUtil.BALANCE_SUPPORTED_CHAINS.includes(caipNetwork?.chainNamespace);
1122
+ if (caipNetwork.testnet || !isApiBalanceSupported) {
1123
+ await this.updateNativeBalance();
1124
+ return;
1125
+ }
1126
+ const balances = await AccountController.fetchTokenBalance(() => this.setBalance('0.00', caipNetwork.nativeCurrency.symbol, caipNetwork.chainNamespace));
1127
+ const balance = balances.find(b => b.chainId === `${params.chainNamespace}:${params.chainId}` &&
1128
+ b.symbol === caipNetwork.nativeCurrency.symbol);
1129
+ this.setBalance(balance?.quantity?.numeric || '0.00', caipNetwork.nativeCurrency.symbol, params.chainNamespace);
1130
+ }
1131
+ syncConnectedWalletInfo(chainNamespace) {
1132
+ const connectorId = StorageUtil.getConnectedConnectorId(chainNamespace);
1133
+ const providerType = ProviderUtil.getProviderId(chainNamespace);
1134
+ if (providerType === UtilConstantsUtil.CONNECTOR_TYPE_ANNOUNCED ||
1135
+ providerType === UtilConstantsUtil.CONNECTOR_TYPE_INJECTED) {
1136
+ if (connectorId) {
1137
+ const connector = this.getConnectors().find(c => c.id === connectorId);
1138
+ if (connector) {
1139
+ const { info, name, imageUrl } = connector;
1140
+ const icon = imageUrl || this.getConnectorImage(connector);
1141
+ this.setConnectedWalletInfo({ name, icon, ...info }, chainNamespace);
1142
+ }
1143
+ }
1144
+ }
1145
+ else if (providerType === UtilConstantsUtil.CONNECTOR_TYPE_WALLET_CONNECT) {
1146
+ const provider = ProviderUtil.getProvider(chainNamespace);
1147
+ if (provider?.session) {
1148
+ this.setConnectedWalletInfo({
1149
+ ...provider.session.peer.metadata,
1150
+ name: provider.session.peer.metadata.name,
1151
+ icon: provider.session.peer.metadata.icons?.[0]
1152
+ }, chainNamespace);
1153
+ }
1154
+ }
1155
+ else if (connectorId) {
1156
+ if (connectorId === ConstantsUtil.CONNECTOR_ID.COINBASE) {
1157
+ const connector = this.getConnectors().find(c => c.id === ConstantsUtil.CONNECTOR_ID.COINBASE);
1158
+ this.setConnectedWalletInfo({ name: 'Coinbase Wallet', icon: this.getConnectorImage(connector) }, chainNamespace);
1159
+ }
1160
+ this.setConnectedWalletInfo({ name: connectorId }, chainNamespace);
1161
+ }
1162
+ }
1163
+ async syncIdentity({ address, chainId, chainNamespace }) {
1164
+ const activeCaipNetwork = this.caipNetworks?.find(n => n.caipNetworkId === `${chainNamespace}:${chainId}`);
1165
+ if (chainNamespace !== ConstantsUtil.CHAIN.EVM || activeCaipNetwork?.testnet) {
1166
+ return;
1167
+ }
1168
+ try {
1169
+ const { name, avatar } = await this.fetchIdentity({
1170
+ address
1171
+ });
1172
+ this.setProfileName(name, chainNamespace);
1173
+ this.setProfileImage(avatar, chainNamespace);
1174
+ if (!name) {
1175
+ await this.syncReownName(address, chainNamespace);
1176
+ const adapter = this.getAdapter(chainNamespace);
1177
+ const result = await adapter?.getProfile({
1178
+ address,
1179
+ chainId: Number(chainId)
1180
+ });
1181
+ if (result?.profileName) {
1182
+ this.setProfileName(result.profileName, chainNamespace);
1183
+ if (result.profileImage) {
1184
+ this.setProfileImage(result.profileImage, chainNamespace);
1185
+ }
1186
+ }
1187
+ else {
1188
+ await this.syncReownName(address, chainNamespace);
1189
+ this.setProfileImage(null, chainNamespace);
1190
+ }
1191
+ }
1192
+ }
1193
+ catch {
1194
+ if (chainId === 1) {
1195
+ await this.syncReownName(address, chainNamespace);
1196
+ }
1197
+ else {
1198
+ await this.syncReownName(address, chainNamespace);
1199
+ this.setProfileImage(null, chainNamespace);
1200
+ }
1201
+ }
1202
+ }
1203
+ async syncReownName(address, chainNamespace) {
1204
+ try {
1205
+ const registeredWcNames = await this.getReownName(address);
1206
+ if (registeredWcNames[0]) {
1207
+ const wcName = registeredWcNames[0];
1208
+ this.setProfileName(wcName.name, chainNamespace);
1209
+ }
1210
+ else {
1211
+ this.setProfileName(null, chainNamespace);
1212
+ }
1213
+ }
1214
+ catch {
1215
+ this.setProfileName(null, chainNamespace);
1216
+ }
1217
+ }
1218
+ async syncAdapterConnection(namespace) {
1219
+ const adapter = this.getAdapter(namespace);
1220
+ const connectorId = StorageUtil.getConnectedConnectorId(namespace);
1221
+ const caipNetwork = this.getCaipNetwork();
1222
+ try {
1223
+ if (!adapter || !connectorId) {
1224
+ throw new Error(`Adapter or connectorId not found for namespace ${namespace}`);
1225
+ }
1226
+ const connection = await adapter?.syncConnection({
1227
+ namespace,
1228
+ id: connectorId,
1229
+ chainId: caipNetwork?.id,
1230
+ rpcUrl: caipNetwork?.rpcUrls?.default?.http?.[0]
1231
+ });
1232
+ if (connection) {
1233
+ const accounts = await adapter?.getAccounts({
1234
+ namespace,
1235
+ id: connectorId
1236
+ });
1237
+ if (accounts && accounts.accounts.length > 0) {
1238
+ this.setAllAccounts(accounts.accounts, namespace);
1239
+ }
1240
+ else {
1241
+ this.setAllAccounts([CoreHelperUtil.createAccount(namespace, connection.address, 'eoa')], namespace);
1242
+ }
1243
+ this.syncProvider({ ...connection, chainNamespace: namespace });
1244
+ await this.syncAccount({ ...connection, chainNamespace: namespace });
1245
+ this.setStatus('connected', namespace);
1246
+ }
1247
+ else {
1248
+ this.setStatus('disconnected', namespace);
1249
+ }
1250
+ }
1251
+ catch (e) {
1252
+ StorageUtil.deleteConnectedConnectorId(namespace);
1253
+ this.setStatus('disconnected', namespace);
1254
+ }
1255
+ }
1256
+ async syncNamespaceConnection(namespace) {
1257
+ try {
1258
+ const connectorId = StorageUtil.getConnectedConnectorId(namespace);
1259
+ const isEmailUsed = this.authProvider?.getLoginEmailUsed();
1260
+ if (isEmailUsed) {
1261
+ return;
1262
+ }
1263
+ this.setStatus('connecting', namespace);
1264
+ switch (connectorId) {
1265
+ case ConstantsUtil.CONNECTOR_ID.WALLET_CONNECT:
1266
+ await this.syncWalletConnectAccount();
1267
+ break;
1268
+ case ConstantsUtil.CONNECTOR_ID.AUTH:
1269
+ // Handled during initialization of adapters' auth provider
1270
+ break;
1271
+ default:
1272
+ await this.syncAdapterConnection(namespace);
1273
+ }
1274
+ }
1275
+ catch (err) {
1276
+ console.warn("AppKit couldn't sync existing connection", err);
1277
+ StorageUtil.deleteConnectedConnectorId(namespace);
1278
+ this.setStatus('disconnected', namespace);
1279
+ }
1280
+ }
1281
+ async syncExistingConnection() {
1282
+ await Promise.allSettled(this.chainNamespaces.map(namespace => this.syncNamespaceConnection(namespace)));
1283
+ }
1284
+ getAdapter(namespace) {
1285
+ if (!namespace) {
1286
+ return undefined;
1287
+ }
1288
+ return this.chainAdapters?.[namespace];
1289
+ }
1290
+ createUniversalProvider() {
1291
+ if (!this.universalProviderInitPromise &&
1292
+ CoreHelperUtil.isClient() &&
1293
+ this.options?.projectId) {
1294
+ this.universalProviderInitPromise = this.initializeUniversalAdapter();
1295
+ }
1296
+ return this.universalProviderInitPromise;
1297
+ }
1298
+ handleAlertError(error) {
1299
+ const matchedUniversalProviderError = Object.entries(ErrorUtil.UniversalProviderErrors).find(([, { message }]) => error.message.includes(message));
1300
+ const [errorKey, errorValue] = matchedUniversalProviderError ?? [];
1301
+ const { message, alertErrorKey } = errorValue ?? {};
1302
+ if (errorKey && message && !this.reportedAlertErrors[errorKey]) {
1303
+ const alertError = ErrorUtil.ALERT_ERRORS[alertErrorKey];
1304
+ if (alertError) {
1305
+ AlertController.open(alertError, 'error');
1306
+ this.reportedAlertErrors[errorKey] = true;
1307
+ }
1308
+ }
1309
+ }
1310
+ async initializeUniversalAdapter() {
1311
+ const logger = LoggerUtil.createLogger((error, ...args) => {
1312
+ if (error) {
1313
+ this.handleAlertError(error);
1314
+ }
1315
+ // eslint-disable-next-line no-console
1316
+ console.error(...args);
1317
+ });
1318
+ const universalProviderOptions = {
1319
+ projectId: this.options?.projectId,
1320
+ metadata: {
1321
+ name: this.options?.metadata ? this.options?.metadata.name : '',
1322
+ description: this.options?.metadata ? this.options?.metadata.description : '',
1323
+ url: this.options?.metadata ? this.options?.metadata.url : '',
1324
+ icons: this.options?.metadata ? this.options?.metadata.icons : ['']
1325
+ },
1326
+ logger
1327
+ };
1328
+ OptionsController.setUsingInjectedUniversalProvider(Boolean(this.options?.universalProvider));
1329
+ this.universalProvider =
1330
+ this.options.universalProvider ?? (await UniversalProvider.init(universalProviderOptions));
1331
+ this.listenWalletConnect();
1332
+ }
1333
+ async getUniversalProvider() {
1334
+ if (!this.universalProvider) {
1335
+ try {
1336
+ await this.createUniversalProvider();
1337
+ }
1338
+ catch (error) {
1339
+ throw new Error('AppKit:getUniversalProvider - Cannot create provider');
1340
+ }
1341
+ }
1342
+ return this.universalProvider;
1343
+ }
1344
+ createAuthProvider() {
1345
+ const isEmailEnabled = this.options?.features?.email === undefined
1346
+ ? CoreConstantsUtil.DEFAULT_FEATURES.email
1347
+ : this.options?.features?.email;
1348
+ const isSocialsEnabled = this.options?.features?.socials
1349
+ ? this.options?.features?.socials?.length > 0
1350
+ : CoreConstantsUtil.DEFAULT_FEATURES.socials;
1351
+ const isAuthEnabled = isEmailEnabled || isSocialsEnabled;
1352
+ if (!this.authProvider && this.options?.projectId && isAuthEnabled) {
1353
+ this.authProvider = W3mFrameProviderSingleton.getInstance({
1354
+ projectId: this.options.projectId,
1355
+ enableLogger: this.options.enableAuthLogger,
1356
+ chainId: this.getCaipNetwork()?.caipNetworkId,
1357
+ onTimeout: () => {
1358
+ AlertController.open(ErrorUtil.ALERT_ERRORS.SOCIALS_TIMEOUT, 'error');
1359
+ }
1360
+ });
1361
+ this.subscribeState(val => {
1362
+ if (!val.open) {
1363
+ this.authProvider?.rejectRpcRequests();
1364
+ }
1365
+ });
1366
+ this.syncAuthConnector(this.authProvider);
1367
+ }
1368
+ }
1369
+ async createUniversalProviderForAdapter(chainNamespace) {
1370
+ await this.getUniversalProvider();
1371
+ if (this.universalProvider) {
1372
+ this.chainAdapters?.[chainNamespace]?.setUniversalProvider?.(this.universalProvider);
1373
+ }
1374
+ }
1375
+ createAuthProviderForAdapter(chainNamespace) {
1376
+ this.createAuthProvider();
1377
+ if (this.authProvider) {
1378
+ this.chainAdapters?.[chainNamespace]?.setAuthProvider?.(this.authProvider);
1379
+ }
1380
+ }
1381
+ createAdapter(blueprint) {
1382
+ if (!blueprint) {
1383
+ return;
1384
+ }
1385
+ const namespace = blueprint.namespace;
1386
+ if (!namespace) {
1387
+ return;
1388
+ }
1389
+ this.createClients();
1390
+ const adapterBlueprint = blueprint;
1391
+ adapterBlueprint.namespace = namespace;
1392
+ adapterBlueprint.construct({
1393
+ namespace,
1394
+ projectId: this.options?.projectId,
1395
+ networks: this.caipNetworks
1396
+ });
1397
+ if (!this.chainNamespaces.includes(namespace)) {
1398
+ this.chainNamespaces.push(namespace);
1399
+ }
1400
+ if (this.chainAdapters) {
1401
+ this.chainAdapters[namespace] = adapterBlueprint;
1402
+ }
1403
+ }
1404
+ createAdapters(blueprints) {
1405
+ this.createClients();
1406
+ return this.chainNamespaces.reduce((adapters, namespace) => {
1407
+ const blueprint = blueprints?.find(b => b.namespace === namespace);
1408
+ if (blueprint) {
1409
+ adapters[namespace] = blueprint;
1410
+ adapters[namespace].namespace = namespace;
1411
+ adapters[namespace].construct({
1412
+ namespace,
1413
+ projectId: this.options?.projectId,
1414
+ networks: this.caipNetworks
1415
+ });
1416
+ }
1417
+ else {
1418
+ adapters[namespace] = new UniversalAdapter({
1419
+ namespace,
1420
+ networks: this.caipNetworks
1421
+ });
1422
+ }
1423
+ return adapters;
1424
+ // eslint-disable-next-line @typescript-eslint/prefer-reduce-type-parameter
1425
+ }, {});
1426
+ }
1427
+ onConnectors(chainNamespace) {
1428
+ const adapter = this.getAdapter(chainNamespace);
1429
+ adapter?.on('connectors', this.setConnectors.bind(this));
1430
+ }
1431
+ async initChainAdapter(namespace) {
1432
+ this.onConnectors(namespace);
1433
+ this.listenAdapter(namespace);
1434
+ this.chainAdapters?.[namespace].syncConnectors(this.options, this);
1435
+ await this.createUniversalProviderForAdapter(namespace);
1436
+ this.createAuthProviderForAdapter(namespace);
1437
+ }
1438
+ async initChainAdapters() {
1439
+ await Promise.all(this.chainNamespaces.map(async (namespace) => {
1440
+ await this.initChainAdapter(namespace);
1441
+ }));
1442
+ }
1443
+ getUnsupportedNetwork(caipNetworkId) {
1444
+ return {
1445
+ id: caipNetworkId.split(':')[1],
1446
+ caipNetworkId,
1447
+ name: ConstantsUtil.UNSUPPORTED_NETWORK_NAME,
1448
+ chainNamespace: caipNetworkId.split(':')[0],
1449
+ nativeCurrency: {
1450
+ name: '',
1451
+ decimals: 0,
1452
+ symbol: ''
1453
+ },
1454
+ rpcUrls: {
1455
+ default: {
1456
+ http: []
1457
+ }
1458
+ }
1459
+ };
1460
+ }
1461
+ getDefaultNetwork() {
1462
+ const caipNetworkId = StorageUtil.getActiveCaipNetworkId();
1463
+ if (caipNetworkId) {
1464
+ const caipNetwork = this.caipNetworks?.find(n => n.caipNetworkId === caipNetworkId);
1465
+ if (caipNetwork) {
1466
+ return caipNetwork;
1467
+ }
1468
+ return this.getUnsupportedNetwork(caipNetworkId);
1469
+ }
1470
+ return this.caipNetworks?.[0];
1471
+ }
1472
+ async injectModalUi() {
1473
+ if (!this.initPromise && !isInitialized && CoreHelperUtil.isClient()) {
1474
+ isInitialized = true;
1475
+ this.initPromise = new Promise(async (resolve) => {
1476
+ await Promise.all([
1477
+ import('@reown/appkit-ui'),
1478
+ import('@reown/appkit-scaffold-ui/w3m-modal')
1479
+ ]);
1480
+ const modal = document.createElement('w3m-modal');
1481
+ if (!OptionsController.state.disableAppend && !OptionsController.state.enableEmbedded) {
1482
+ document.body.insertAdjacentElement('beforeend', modal);
1483
+ }
1484
+ resolve();
1485
+ });
1486
+ }
1487
+ return this.initPromise;
1488
+ }
1489
+ }
1490
+ //# sourceMappingURL=client.js.map