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