@reown/appkit 1.6.6-rc.3.0 → 1.6.6

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