@reown/appkit 1.6.6-8edd53b.0 → 1.6.6-basic-test.2.0

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