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