@reown/appkit 1.6.5 → 1.6.6-basic-test.1.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 (55) hide show
  1. package/dist/esm/exports/basic.js +15 -0
  2. package/dist/esm/exports/basic.js.map +1 -0
  3. package/dist/esm/exports/constants.js +1 -1
  4. package/dist/esm/exports/constants.js.map +1 -1
  5. package/dist/esm/exports/index.js +0 -2
  6. package/dist/esm/exports/index.js.map +1 -1
  7. package/dist/esm/exports/react copy.js +38 -0
  8. package/dist/esm/exports/react copy.js.map +1 -0
  9. package/dist/esm/exports/react.js +0 -2
  10. package/dist/esm/exports/react.js.map +1 -1
  11. package/dist/esm/exports/vue.js +0 -2
  12. package/dist/esm/exports/vue.js.map +1 -1
  13. package/dist/esm/package.json +6 -1
  14. package/dist/esm/src/client.js +40 -4
  15. package/dist/esm/src/client.js.map +1 -1
  16. package/dist/esm/src/networks/solana/eclipseDevnet.js +17 -0
  17. package/dist/esm/src/networks/solana/eclipseDevnet.js.map +1 -0
  18. package/dist/esm/tests/appkit.test.js +1459 -0
  19. package/dist/esm/tests/appkit.test.js.map +1 -0
  20. package/dist/esm/tests/connectors/WalletConnectConnector.test.js +63 -0
  21. package/dist/esm/tests/connectors/WalletConnectConnector.test.js.map +1 -0
  22. package/dist/esm/tests/mocks/Adapter.js +30 -0
  23. package/dist/esm/tests/mocks/Adapter.js.map +1 -0
  24. package/dist/esm/tests/mocks/AppKit.js +24 -0
  25. package/dist/esm/tests/mocks/AppKit.js.map +1 -0
  26. package/dist/esm/tests/mocks/Options.js +33 -0
  27. package/dist/esm/tests/mocks/Options.js.map +1 -0
  28. package/dist/esm/tests/mocks/UniversalProvider.js +137 -0
  29. package/dist/esm/tests/mocks/UniversalProvider.js.map +1 -0
  30. package/dist/esm/tests/siwe.test.js +258 -0
  31. package/dist/esm/tests/siwe.test.js.map +1 -0
  32. package/dist/esm/tests/universal-adapter.test.js +152 -0
  33. package/dist/esm/tests/universal-adapter.test.js.map +1 -0
  34. package/dist/esm/tests/utils/HelpersUtil.test.js +217 -0
  35. package/dist/esm/tests/utils/HelpersUtil.test.js.map +1 -0
  36. package/dist/esm/tsconfig.build.tsbuildinfo +1 -1
  37. package/dist/esm/tsconfig.tsbuildinfo +1 -0
  38. package/dist/types/exports/basic.d.ts +10 -0
  39. package/dist/types/exports/constants.d.ts +1 -1
  40. package/dist/types/exports/index.d.ts +0 -1
  41. package/dist/types/exports/react copy.d.ts +16 -0
  42. package/dist/types/exports/react.d.ts +0 -1
  43. package/dist/types/exports/vue.d.ts +0 -1
  44. package/dist/types/src/client.d.ts +2 -2
  45. package/dist/types/src/networks/solana/eclipseDevnet.d.ts +42 -0
  46. package/dist/types/tests/appkit.test.d.ts +1 -0
  47. package/dist/types/tests/connectors/WalletConnectConnector.test.d.ts +1 -0
  48. package/dist/types/tests/mocks/Adapter.d.ts +3 -0
  49. package/dist/types/tests/mocks/AppKit.d.ts +3 -0
  50. package/dist/types/tests/mocks/Options.d.ts +6 -0
  51. package/dist/types/tests/mocks/UniversalProvider.d.ts +3 -0
  52. package/dist/types/tests/siwe.test.d.ts +1 -0
  53. package/dist/types/tests/universal-adapter.test.d.ts +1 -0
  54. package/dist/types/tests/utils/HelpersUtil.test.d.ts +1 -0
  55. package/package.json +14 -9
@@ -0,0 +1,1459 @@
1
+ import UniversalProvider from '@walletconnect/universal-provider';
2
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
3
+ import { Emitter, NetworkUtil, SafeLocalStorage, SafeLocalStorageKeys, getSafeConnectorIdKey } from '@reown/appkit-common';
4
+ import { AccountController, AlertController, AssetUtil, BlockchainApiController, ChainController, ConnectionController, ConnectorController, ConstantsUtil, CoreHelperUtil, EnsController, EventsController, ModalController, OptionsController, PublicStateController, RouterController, SnackController, StorageUtil, ThemeController } from '@reown/appkit-core';
5
+ import { CaipNetworksUtil, ErrorUtil } from '@reown/appkit-utils';
6
+ import { AppKit } from '../src/client';
7
+ import { base as baseNetwork, mainnet as mainnetNetwork, polygon as polygonNetwork, sepolia as sepoliaNetwork, solana as solanaNetwork } from '../src/networks/index.js';
8
+ import { ProviderUtil } from '../src/store';
9
+ import { UniversalAdapter } from '../src/universal-adapter/client';
10
+ import mockUniversalAdapter from './mocks/Adapter';
11
+ import { mockOptions } from './mocks/Options';
12
+ import mockProvider from './mocks/UniversalProvider';
13
+ // Extend networks as CAIP networks
14
+ const [base, mainnet, polygon, sepolia, solana] = CaipNetworksUtil.extendCaipNetworks([baseNetwork, mainnetNetwork, polygonNetwork, sepoliaNetwork, solanaNetwork], { customNetworkImageUrls: {}, projectId: 'test-project-id' });
15
+ // Mock all controllers and UniversalAdapterClient
16
+ vi.mock('@reown/appkit-core');
17
+ vi.mock('../src/universal-adapter/client');
18
+ vi.mock('../src/client.ts', async () => {
19
+ const actual = await vi.importActual('../src/client.ts');
20
+ return {
21
+ ...actual,
22
+ injectModalUi: vi.fn(),
23
+ syncExistingConnection: vi.fn()
24
+ };
25
+ });
26
+ vi.mocked(global).window = { location: { origin: '' } };
27
+ vi.mocked(global).document = {
28
+ body: {
29
+ insertAdjacentElement: vi.fn()
30
+ },
31
+ createElement: vi.fn().mockReturnValue({ appendChild: vi.fn() }),
32
+ getElementsByTagName: vi.fn().mockReturnValue([{ textContent: '' }]),
33
+ querySelector: vi.fn()
34
+ };
35
+ describe('Base', () => {
36
+ let appKit;
37
+ beforeEach(() => {
38
+ vi.mocked(ConnectorController).getConnectors = vi.fn().mockReturnValue([]);
39
+ vi.spyOn(ConstantsUtil, 'BALANCE_SUPPORTED_CHAINS', 'get').mockReturnValue(['eip155', 'solana']);
40
+ appKit = new AppKit(mockOptions);
41
+ vi.spyOn(OptionsController, 'getSnapshot').mockReturnValue({ ...OptionsController.state });
42
+ vi.spyOn(ThemeController, 'getSnapshot').mockReturnValue({ ...ThemeController.state });
43
+ });
44
+ afterEach(() => {
45
+ vi.restoreAllMocks();
46
+ });
47
+ describe('Base Initialization', () => {
48
+ it('should initialize controllers', async () => {
49
+ const copyMockOptions = { ...mockOptions };
50
+ delete copyMockOptions.adapters;
51
+ await new Promise(resolve => setTimeout(resolve, 100));
52
+ expect(EventsController.sendEvent).toHaveBeenCalledOnce();
53
+ expect(EventsController.sendEvent).toHaveBeenCalledWith({
54
+ type: 'track',
55
+ event: 'INITIALIZE',
56
+ properties: {
57
+ ...copyMockOptions,
58
+ networks: copyMockOptions.networks.map((n) => n.id),
59
+ siweConfig: {
60
+ options: copyMockOptions.siweConfig?.options || {}
61
+ }
62
+ }
63
+ });
64
+ expect(ChainController.initialize).toHaveBeenCalledOnce();
65
+ expect(ChainController.initialize).toHaveBeenCalledWith(mockOptions.adapters, [mainnet, sepolia, solana], {
66
+ connectionControllerClient: expect.any(Object),
67
+ networkControllerClient: expect.any(Object)
68
+ });
69
+ });
70
+ it('should set EIP6963 enabled by default', () => {
71
+ new AppKit({
72
+ ...mockOptions
73
+ });
74
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(true);
75
+ });
76
+ it('should set EIP6963 disabled when option is disabled in config', () => {
77
+ new AppKit({
78
+ ...mockOptions,
79
+ enableEIP6963: false
80
+ });
81
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(false);
82
+ });
83
+ it('should set partially defaultAccountType', () => {
84
+ new AppKit({
85
+ ...mockOptions,
86
+ defaultAccountTypes: {
87
+ eip155: 'eoa',
88
+ bip122: 'ordinal'
89
+ }
90
+ });
91
+ expect(OptionsController.setDefaultAccountTypes).toHaveBeenCalledWith({
92
+ eip155: 'eoa',
93
+ bip122: 'ordinal'
94
+ });
95
+ });
96
+ });
97
+ describe('Base Public methods', () => {
98
+ it('should open modal', async () => {
99
+ await appKit.open();
100
+ expect(ModalController.open).toHaveBeenCalled();
101
+ });
102
+ it('should close modal', async () => {
103
+ await appKit.close();
104
+ expect(ModalController.close).toHaveBeenCalled();
105
+ });
106
+ it('should set loading state', () => {
107
+ appKit.setLoading(true);
108
+ expect(ModalController.setLoading).toHaveBeenCalledWith(true);
109
+ });
110
+ it('should get theme mode', () => {
111
+ vi.spyOn(ThemeController.state, 'themeMode', 'get').mockReturnValueOnce('dark');
112
+ expect(appKit.getThemeMode()).toBe('dark');
113
+ });
114
+ it('should set theme mode', () => {
115
+ appKit.setThemeMode('light');
116
+ expect(ThemeController.setThemeMode).toHaveBeenCalledWith('light');
117
+ });
118
+ it('should get theme variables', () => {
119
+ vi.spyOn(ThemeController.state, 'themeVariables', 'get').mockReturnValueOnce({
120
+ '--w3m-accent': '#000'
121
+ });
122
+ expect(appKit.getThemeVariables()).toEqual({ '--w3m-accent': '#000' });
123
+ });
124
+ it('should set theme variables', () => {
125
+ const themeVariables = { '--w3m-accent': '#fff' };
126
+ appKit.setThemeVariables(themeVariables);
127
+ expect(ThemeController.setThemeVariables).toHaveBeenCalledWith(themeVariables);
128
+ });
129
+ it('should subscribe to theme changes', () => {
130
+ const callback = vi.fn();
131
+ appKit.subscribeTheme(callback);
132
+ expect(ThemeController.subscribe).toHaveBeenCalledWith(callback);
133
+ });
134
+ it('should get wallet info', () => {
135
+ vi.mocked(AccountController).state = { connectedWalletInfo: { name: 'Test Wallet' } };
136
+ expect(appKit.getWalletInfo()).toEqual({ name: 'Test Wallet' });
137
+ });
138
+ it('should subscribe to wallet info changes', () => {
139
+ const callback = vi.fn();
140
+ appKit.subscribeWalletInfo(callback);
141
+ expect(AccountController.subscribeKey).toHaveBeenCalledWith('connectedWalletInfo', callback);
142
+ });
143
+ it('should subscribe to address updates', () => {
144
+ const callback = vi.fn();
145
+ appKit.subscribeShouldUpdateToAddress(callback);
146
+ expect(AccountController.subscribeKey).toHaveBeenCalledWith('shouldUpdateToAddress', callback);
147
+ });
148
+ it('should subscribe to CAIP network changes', () => {
149
+ const callback = vi.fn();
150
+ appKit.subscribeCaipNetworkChange(callback);
151
+ expect(ChainController.subscribeKey).toHaveBeenCalledWith('activeCaipNetwork', callback);
152
+ });
153
+ it('should get state', () => {
154
+ vi.mocked(PublicStateController).state = { isConnected: true };
155
+ expect(appKit.getState()).toEqual({ isConnected: true });
156
+ });
157
+ it('should subscribe to state changes', () => {
158
+ const callback = vi.fn();
159
+ appKit.subscribeState(callback);
160
+ expect(PublicStateController.subscribe).toHaveBeenCalledWith(callback);
161
+ });
162
+ it('should show error message', () => {
163
+ appKit.showErrorMessage('Test error');
164
+ expect(SnackController.showError).toHaveBeenCalledWith('Test error');
165
+ });
166
+ it('should show success message', () => {
167
+ appKit.showSuccessMessage('Test success');
168
+ expect(SnackController.showSuccess).toHaveBeenCalledWith('Test success');
169
+ });
170
+ it('should get event', () => {
171
+ vi.mocked(EventsController).state = { name: 'test_event' };
172
+ expect(appKit.getEvent()).toEqual({ name: 'test_event' });
173
+ });
174
+ it('should subscribe to events', () => {
175
+ const callback = vi.fn();
176
+ appKit.subscribeEvents(callback);
177
+ expect(EventsController.subscribe).toHaveBeenCalledWith(callback);
178
+ });
179
+ it('should replace route', () => {
180
+ appKit.replace('Connect');
181
+ expect(RouterController.replace).toHaveBeenCalledWith('Connect');
182
+ });
183
+ it('should redirect to route', () => {
184
+ appKit.redirect('Networks');
185
+ expect(RouterController.push).toHaveBeenCalledWith('Networks');
186
+ });
187
+ it('should pop transaction stack', () => {
188
+ appKit.popTransactionStack(true);
189
+ expect(RouterController.popTransactionStack).toHaveBeenCalledWith(true);
190
+ });
191
+ it('should check if modal is open', () => {
192
+ vi.mocked(ModalController).state = { open: true };
193
+ expect(appKit.isOpen()).toBe(true);
194
+ });
195
+ it('should check if transaction stack is empty', () => {
196
+ vi.mocked(RouterController).state = { transactionStack: [] };
197
+ expect(appKit.isTransactionStackEmpty()).toBe(true);
198
+ });
199
+ it('should check if transaction should replace view', () => {
200
+ vi.mocked(RouterController).state = { transactionStack: [{ replace: true }] };
201
+ expect(appKit.isTransactionShouldReplaceView()).toBe(true);
202
+ });
203
+ it('should set status', () => {
204
+ appKit.setStatus('connected', 'eip155');
205
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connected', 'eip155');
206
+ });
207
+ it('should set all accounts', () => {
208
+ const evmAddresses = [
209
+ { address: '0x1', namespace: 'eip155', type: 'eoa' },
210
+ { address: '0x2', namespace: 'eip155', type: 'smartAccount' }
211
+ ];
212
+ const solanaAddresses = [{ address: 'asdbjk', namespace: 'solana', type: 'eoa' }];
213
+ const bip122Addresses = [
214
+ { address: 'asdasd1', namespace: 'bip122', type: 'payment' },
215
+ { address: 'asdasd2', namespace: 'bip122', type: 'ordinal' },
216
+ { address: 'ASDASD3', namespace: 'bip122', type: 'stx' }
217
+ ];
218
+ appKit.setAllAccounts(evmAddresses, 'eip155');
219
+ appKit.setAllAccounts(solanaAddresses, 'solana');
220
+ appKit.setAllAccounts(bip122Addresses, 'bip122');
221
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(evmAddresses, 'eip155');
222
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(solanaAddresses, 'solana');
223
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(bip122Addresses, 'bip122');
224
+ expect(OptionsController.setHasMultipleAddresses).toHaveBeenCalledWith(true);
225
+ });
226
+ it('should add address label', () => {
227
+ appKit.addAddressLabel('0x123', 'eip155 Address', 'eip155');
228
+ expect(AccountController.addAddressLabel).toHaveBeenCalledWith('0x123', 'eip155 Address', 'eip155');
229
+ });
230
+ it('should remove address label', () => {
231
+ appKit.removeAddressLabel('0x123', 'eip155');
232
+ expect(AccountController.removeAddressLabel).toHaveBeenCalledWith('0x123', 'eip155');
233
+ });
234
+ it('should get CAIP address', () => {
235
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
236
+ activeChain: 'eip155',
237
+ activeCaipAddress: 'eip155:1:0x123',
238
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
239
+ });
240
+ expect(appKit.getCaipAddress()).toBe('eip155:1:0x123');
241
+ });
242
+ it('should get address', () => {
243
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
244
+ chains: new Map(),
245
+ activeChain: 'eip155'
246
+ });
247
+ vi.mocked(AccountController).state = { address: '0x123' };
248
+ expect(appKit.getAddress()).toBe('0x123');
249
+ });
250
+ it('should get provider', () => {
251
+ const mockProvider = vi.fn();
252
+ vi.mocked(ProviderUtil.state).providers = { eip155: mockProvider };
253
+ vi.mocked(ProviderUtil.state).providerIds = { eip155: 'INJECTED' };
254
+ expect(appKit.getProvider('eip155')).toBe(mockProvider);
255
+ });
256
+ it('should get preferred account type', () => {
257
+ vi.mocked(AccountController).state = { preferredAccountType: 'eoa' };
258
+ expect(appKit.getPreferredAccountType()).toBe('eoa');
259
+ });
260
+ it('should set CAIP address', () => {
261
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
262
+ ...ChainController.state,
263
+ activeChain: 'eip155',
264
+ activeCaipAddress: 'eip155:1:0x123',
265
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
266
+ });
267
+ appKit.setCaipAddress('eip155:1:0x123', 'eip155');
268
+ expect(AccountController.setCaipAddress).toHaveBeenCalledWith('eip155:1:0x123', 'eip155');
269
+ expect(appKit.getIsConnectedState()).toBe(true);
270
+ });
271
+ it('should set balance', () => {
272
+ appKit.setBalance('1.5', 'ETH', 'eip155');
273
+ expect(AccountController.setBalance).toHaveBeenCalledWith('1.5', 'ETH', 'eip155');
274
+ });
275
+ it('should set profile name', () => {
276
+ appKit.setProfileName('John Doe', 'eip155');
277
+ expect(AccountController.setProfileName).toHaveBeenCalledWith('John Doe', 'eip155');
278
+ });
279
+ it('should set profile image', () => {
280
+ appKit.setProfileImage('https://example.com/image.png', 'eip155');
281
+ expect(AccountController.setProfileImage).toHaveBeenCalledWith('https://example.com/image.png', 'eip155');
282
+ });
283
+ it('should reset account', () => {
284
+ appKit.resetAccount('eip155');
285
+ expect(AccountController.resetAccount).toHaveBeenCalledWith('eip155');
286
+ });
287
+ it('should set CAIP network', () => {
288
+ const caipNetwork = mainnet;
289
+ appKit.setCaipNetwork(caipNetwork);
290
+ expect(ChainController.setActiveCaipNetwork).toHaveBeenCalledWith(caipNetwork);
291
+ });
292
+ it('should get CAIP network', () => {
293
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
294
+ activeCaipNetwork: mainnet,
295
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
296
+ });
297
+ expect(appKit.getCaipNetwork()).toEqual(mainnet);
298
+ });
299
+ it('should set requested CAIP networks', () => {
300
+ const requestedNetworks = [mainnet];
301
+ appKit.setRequestedCaipNetworks(requestedNetworks, 'eip155');
302
+ expect(ChainController.setRequestedCaipNetworks).toHaveBeenCalledWith(requestedNetworks, 'eip155');
303
+ });
304
+ it('should set connectors', () => {
305
+ const existingConnectors = [
306
+ { id: 'phantom', name: 'Phantom', chain: 'eip155', type: 'INJECTED' }
307
+ ];
308
+ // Mock getConnectors to return existing connectors
309
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue(existingConnectors);
310
+ const newConnectors = [
311
+ { id: 'metamask', name: 'MetaMask', chain: 'eip155', type: 'INJECTED' }
312
+ ];
313
+ appKit.setConnectors(newConnectors);
314
+ // Verify that setConnectors was called with combined array
315
+ expect(ConnectorController.setConnectors).toHaveBeenCalledWith([
316
+ ...existingConnectors,
317
+ ...newConnectors
318
+ ]);
319
+ });
320
+ it('should add connector', () => {
321
+ const connector = {
322
+ id: 'metamask',
323
+ name: 'MetaMask',
324
+ chain: 'eip155',
325
+ type: 'INJECTED'
326
+ };
327
+ appKit.addConnector(connector);
328
+ expect(ConnectorController.addConnector).toHaveBeenCalledWith(connector);
329
+ });
330
+ it('should get connectors', () => {
331
+ const mockConnectors = [
332
+ { id: 'metamask', name: 'MetaMask', chain: 'eip155:1', type: 'INJECTED' }
333
+ ];
334
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue(mockConnectors);
335
+ expect(appKit.getConnectors()).toEqual(mockConnectors);
336
+ });
337
+ it('should get approved CAIP network IDs', () => {
338
+ vi.mocked(ChainController.getAllApprovedCaipNetworkIds).mockReturnValue(['eip155:1']);
339
+ expect(appKit.getApprovedCaipNetworkIds()).toEqual(['eip155:1']);
340
+ });
341
+ it('should set approved CAIP networks data', () => {
342
+ appKit.setApprovedCaipNetworksData('eip155');
343
+ expect(ChainController.setApprovedCaipNetworksData).toHaveBeenCalledWith('eip155');
344
+ });
345
+ it('should reset network', () => {
346
+ appKit.resetNetwork('eip155');
347
+ expect(ChainController.resetNetwork).toHaveBeenCalled();
348
+ });
349
+ it('should reset WC connection', () => {
350
+ appKit.resetWcConnection();
351
+ expect(ConnectionController.resetWcConnection).toHaveBeenCalled();
352
+ });
353
+ it('should fetch identity', async () => {
354
+ const mockRequest = { caipChainId: 'eip155:1', address: '0x123' };
355
+ vi.mocked(BlockchainApiController.fetchIdentity).mockResolvedValue({
356
+ name: 'John Doe',
357
+ avatar: null
358
+ });
359
+ const result = await appKit.fetchIdentity(mockRequest);
360
+ expect(BlockchainApiController.fetchIdentity).toHaveBeenCalledWith(mockRequest);
361
+ expect(result).toEqual({ name: 'John Doe', avatar: null });
362
+ });
363
+ it('should set address explorer URL', () => {
364
+ appKit.setAddressExplorerUrl('https://etherscan.io/address/0x123', 'eip155');
365
+ expect(AccountController.setAddressExplorerUrl).toHaveBeenCalledWith('https://etherscan.io/address/0x123', 'eip155');
366
+ });
367
+ it('should set smart account deployed', () => {
368
+ appKit.setSmartAccountDeployed(true, 'eip155');
369
+ expect(AccountController.setSmartAccountDeployed).toHaveBeenCalledWith(true, 'eip155');
370
+ });
371
+ it('should set connected wallet info', () => {
372
+ const walletInfo = { name: 'MetaMask', icon: 'icon-url' };
373
+ appKit.setConnectedWalletInfo(walletInfo, 'eip155');
374
+ expect(AccountController.setConnectedWalletInfo).toHaveBeenCalledWith(walletInfo, 'eip155');
375
+ });
376
+ it('should set smart account enabled networks', () => {
377
+ const networks = [1, 137];
378
+ appKit.setSmartAccountEnabledNetworks(networks, 'eip155');
379
+ expect(ChainController.setSmartAccountEnabledNetworks).toHaveBeenCalledWith(networks, 'eip155');
380
+ });
381
+ it('should set preferred account type', () => {
382
+ appKit.setPreferredAccountType('eoa', 'eip155');
383
+ expect(AccountController.setPreferredAccountType).toHaveBeenCalledWith('eoa', 'eip155');
384
+ });
385
+ it('should create accounts with correct account types from user accounts', async () => {
386
+ const mockUser = {
387
+ address: '0x123',
388
+ accounts: [
389
+ { address: '0x1', type: 'eoa' },
390
+ { address: '0x2', type: 'smartAccount' }
391
+ ],
392
+ preferredAccountType: 'eoa',
393
+ user: {
394
+ email: 'email@test.com',
395
+ username: 'test'
396
+ }
397
+ };
398
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
399
+ activeChain: 'eip155',
400
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
401
+ });
402
+ vi.spyOn(CoreHelperUtil, 'createAccount').mockImplementation((namespace, address, type) => {
403
+ if (namespace === 'eip155') {
404
+ return {
405
+ address,
406
+ type: type,
407
+ namespace: 'eip155'
408
+ };
409
+ }
410
+ throw new Error('Unexpected namespace');
411
+ });
412
+ const mockAuthProvider = {
413
+ onConnect: vi.fn(callback => callback(mockUser)),
414
+ connect: vi.fn(),
415
+ getSmartAccountEnabledNetworks: vi.fn(),
416
+ onGetSmartAccountEnabledNetworks: vi.fn(),
417
+ onSetPreferredAccount: vi.fn(),
418
+ onRpcRequest: vi.fn(),
419
+ onRpcError: vi.fn(),
420
+ onRpcSuccess: vi.fn(),
421
+ onNotConnected: vi.fn(),
422
+ onIsConnected: vi.fn(),
423
+ getLoginEmailUsed: vi.fn().mockReturnValue(false),
424
+ isConnected: vi.fn().mockResolvedValue({ isConnected: false }),
425
+ getEmail: vi.fn().mockReturnValue('email@email.com'),
426
+ getUsername: vi.fn().mockReturnValue('test'),
427
+ onSocialConnected: vi.fn(),
428
+ syncDappData: vi.fn(),
429
+ syncTheme: vi.fn()
430
+ };
431
+ const appKitWithAuth = new AppKit({
432
+ ...mockOptions,
433
+ features: {
434
+ email: true
435
+ }
436
+ });
437
+ appKitWithAuth.authProvider = mockAuthProvider;
438
+ await appKitWithAuth.syncAuthConnector(mockAuthProvider);
439
+ expect(CoreHelperUtil.createAccount).toHaveBeenCalledWith('eip155', '0x1', 'eoa');
440
+ expect(CoreHelperUtil.createAccount).toHaveBeenCalledWith('eip155', '0x2', 'smartAccount');
441
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith([
442
+ { address: '0x1', type: 'eoa', namespace: 'eip155' },
443
+ { address: '0x2', type: 'smartAccount', namespace: 'eip155' }
444
+ ], 'eip155');
445
+ expect(AccountController.setPreferredAccountType).toHaveBeenCalledWith('eoa', 'eip155');
446
+ });
447
+ it('should get Reown name', async () => {
448
+ vi.mocked(EnsController.getNamesForAddress).mockResolvedValue([
449
+ {
450
+ name: 'john.reown.id',
451
+ addresses: { eip155: { address: '0x123', created: '0' } },
452
+ attributes: [],
453
+ registered: 0,
454
+ updated: 0
455
+ }
456
+ ]);
457
+ const result = await appKit.getReownName('john.reown.id');
458
+ expect(EnsController.getNamesForAddress).toHaveBeenCalledWith('john.reown.id');
459
+ expect(result).toEqual([
460
+ {
461
+ name: 'john.reown.id',
462
+ addresses: { eip155: { address: '0x123', created: '0' } },
463
+ attributes: [],
464
+ registered: 0,
465
+ updated: 0
466
+ }
467
+ ]);
468
+ });
469
+ it('should set EIP6963 enabled', () => {
470
+ appKit.setEIP6963Enabled(true);
471
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(true);
472
+ });
473
+ it('should set client ID', () => {
474
+ appKit.setClientId('client-123');
475
+ expect(BlockchainApiController.setClientId).toHaveBeenCalledWith('client-123');
476
+ });
477
+ it('should get connector image', () => {
478
+ vi.mocked(AssetUtil.getConnectorImage).mockReturnValue('connector-image-url');
479
+ const result = appKit.getConnectorImage({
480
+ id: 'metamask',
481
+ type: 'INJECTED',
482
+ chain: 'eip155',
483
+ name: 'Metamask'
484
+ });
485
+ expect(AssetUtil.getConnectorImage).toHaveBeenCalledWith({
486
+ id: 'metamask',
487
+ type: 'INJECTED',
488
+ chain: 'eip155',
489
+ name: 'Metamask'
490
+ });
491
+ expect(result).toBe('connector-image-url');
492
+ });
493
+ it('should switch network when requested', async () => {
494
+ const mockAppKit = new AppKit(mockOptions);
495
+ vi.mocked(ChainController.switchActiveNetwork).mockResolvedValue(undefined);
496
+ mockAppKit.switchNetwork(mainnet);
497
+ expect(ChainController.switchActiveNetwork).toHaveBeenCalledWith(expect.objectContaining({
498
+ id: mainnet.id,
499
+ name: mainnet.name
500
+ }));
501
+ mockAppKit.switchNetwork(polygon);
502
+ expect(ChainController.switchActiveNetwork).toHaveBeenCalledTimes(1);
503
+ });
504
+ it('should use the correct network when syncing account if is does not allow all networks and network is not allowed', async () => {
505
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
506
+ {
507
+ quantity: { numeric: '0.00', decimals: '18' },
508
+ chainId: 'eip155:1',
509
+ symbol: 'ETH'
510
+ }
511
+ ]);
512
+ vi.mocked(ChainController.getAllApprovedCaipNetworkIds).mockReturnValue([
513
+ 'eip155:1',
514
+ 'eip155:11155111'
515
+ ]);
516
+ vi.spyOn(ChainController, 'getNetworkProp').mockReturnValue(false);
517
+ vi.spyOn(ChainController.state, 'activeChain', 'get').mockReturnValueOnce('eip155');
518
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValueOnce({
519
+ namespace: mainnet.chainNamespace,
520
+ chainId: mainnet.id,
521
+ caipNetworkId: mainnet.caipNetworkId
522
+ });
523
+ vi.spyOn(OptionsController, 'state', 'get').mockReturnValueOnce({
524
+ allowUnsupportedChain: false
525
+ });
526
+ const mockAccountData = {
527
+ address: '0x123',
528
+ chainId: '2',
529
+ chainNamespace: 'eip155'
530
+ };
531
+ await appKit['syncAccount'](mockAccountData);
532
+ expect(ChainController.getNetworkProp).toHaveBeenCalledWith('supportsAllNetworks', 'eip155');
533
+ expect(ChainController.setActiveCaipNetwork).toHaveBeenCalledWith(mainnet);
534
+ });
535
+ it('should set connected wallet info when syncing account', async () => {
536
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
537
+ {
538
+ ...sepolia,
539
+ nativeCurrency: { symbol: 'ETH' },
540
+ chainNamespace: 'eip155'
541
+ }
542
+ ]);
543
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
544
+ {
545
+ quantity: { numeric: '0.00', decimals: '18' },
546
+ chainId: 'eip155:1',
547
+ symbol: 'ETH'
548
+ }
549
+ ]);
550
+ vi.spyOn(ChainController, 'getAllApprovedCaipNetworkIds').mockReturnValue(['eip155:1']);
551
+ vi.mocked(appKit).caipNetworks = [mainnet];
552
+ // Mock the connector data
553
+ const mockConnector = {
554
+ id: 'test-wallet',
555
+ name: 'Test Wallet',
556
+ imageUrl: 'test-wallet-icon'
557
+ };
558
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue([mockConnector]);
559
+ vi.mocked(StorageUtil.getActiveNetworkProps).mockReturnValue({
560
+ namespace: mainnet.chainNamespace,
561
+ chainId: mainnet.id,
562
+ caipNetworkId: mainnet.caipNetworkId
563
+ });
564
+ const mockAccountData = {
565
+ address: '0x123',
566
+ chainId: mainnet.id,
567
+ chainNamespace: mainnet.chainNamespace
568
+ };
569
+ vi.spyOn(StorageUtil, 'getConnectedConnectorId').mockReturnValue(mockConnector.id);
570
+ await appKit['syncAccount'](mockAccountData);
571
+ expect(AccountController.setConnectedWalletInfo).toHaveBeenCalledWith(expect.objectContaining({
572
+ name: mockConnector.name,
573
+ icon: mockConnector.imageUrl
574
+ }), 'eip155');
575
+ });
576
+ it('should sync identity only if address changed', async () => {
577
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
578
+ {
579
+ ...mainnet,
580
+ nativeCurrency: { symbol: 'ETH' },
581
+ chainNamespace: 'eip155'
582
+ }
583
+ ]);
584
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
585
+ {
586
+ quantity: { numeric: '0.00', decimals: '18' },
587
+ chainId: 'eip155:1',
588
+ symbol: 'ETH'
589
+ }
590
+ ]);
591
+ vi.spyOn(ChainController, 'getAllApprovedCaipNetworkIds').mockReturnValue(['eip155:1']);
592
+ vi.mocked(appKit).caipNetworks = [mainnet];
593
+ const mockAccountData = {
594
+ address: '0x123',
595
+ chainId: mainnet.id,
596
+ chainNamespace: mainnet.chainNamespace
597
+ };
598
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValue({
599
+ namespace: mainnet.chainNamespace,
600
+ chainId: mainnet.id,
601
+ caipNetworkId: mainnet.caipNetworkId
602
+ });
603
+ vi.mocked(BlockchainApiController.fetchIdentity).mockResolvedValue({
604
+ name: 'John Doe',
605
+ avatar: null
606
+ });
607
+ vi.mocked(AccountController).state = { address: '0x123' };
608
+ await appKit['syncAccount'](mockAccountData);
609
+ expect(BlockchainApiController.fetchIdentity).not.toHaveBeenCalled();
610
+ await appKit['syncAccount']({ ...mockAccountData, address: '0x456' });
611
+ expect(BlockchainApiController.fetchIdentity).toHaveBeenCalledOnce();
612
+ });
613
+ it('should not sync identity on non-evm network', async () => {
614
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
615
+ {
616
+ ...solana,
617
+ nativeCurrency: { symbol: 'SOL' },
618
+ chainNamespace: 'solana'
619
+ }
620
+ ]);
621
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
622
+ {
623
+ quantity: { numeric: '0.00', decimals: '18' },
624
+ chainId: 'solana:1',
625
+ symbol: 'SOL'
626
+ }
627
+ ]);
628
+ vi.spyOn(ChainController, 'getAllApprovedCaipNetworkIds').mockReturnValue(['solana:1']);
629
+ vi.mocked(appKit).caipNetworks = [solana];
630
+ const mockAccountData = {
631
+ address: '0x123',
632
+ chainId: solana.id,
633
+ chainNamespace: solana.chainNamespace
634
+ };
635
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValueOnce({
636
+ namespace: solana.chainNamespace,
637
+ chainId: solana.id,
638
+ caipNetworkId: solana.caipNetworkId
639
+ });
640
+ await appKit['syncAccount'](mockAccountData);
641
+ expect(BlockchainApiController.fetchIdentity).not.toHaveBeenCalled();
642
+ });
643
+ it('should not sync identity on a test network', async () => {
644
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
645
+ {
646
+ ...sepolia,
647
+ nativeCurrency: { symbol: 'sETH' },
648
+ chainNamespace: 'eip155'
649
+ }
650
+ ]);
651
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
652
+ {
653
+ quantity: { numeric: '0.00', decimals: '18' },
654
+ chainId: 'eip155:11155111',
655
+ symbol: 'sETH'
656
+ }
657
+ ]);
658
+ vi.spyOn(ChainController, 'getAllApprovedCaipNetworkIds').mockReturnValue(['eip155:11155111']);
659
+ vi.mocked(appKit).caipNetworks = [sepolia];
660
+ const mockAccountData = {
661
+ address: '0x123',
662
+ chainId: '11155111',
663
+ chainNamespace: 'eip155'
664
+ };
665
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValueOnce({
666
+ namespace: 'eip155',
667
+ chainId: '11155111',
668
+ caipNetworkId: 'eip155:11155111'
669
+ });
670
+ await appKit['syncAccount'](mockAccountData);
671
+ expect(BlockchainApiController.fetchIdentity).not.toHaveBeenCalled();
672
+ });
673
+ it('should sync balance correctly', async () => {
674
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
675
+ mainnet
676
+ ]);
677
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
678
+ {
679
+ quantity: { numeric: '0.00', decimals: '18' },
680
+ chainId: 'eip155:1',
681
+ symbol: 'ETH'
682
+ }
683
+ ]);
684
+ vi.spyOn(ChainController, 'getAllApprovedCaipNetworkIds').mockReturnValue(['eip155:1']);
685
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValueOnce({
686
+ namespace: mainnet.chainNamespace,
687
+ chainId: mainnet.id,
688
+ caipNetworkId: mainnet.caipNetworkId
689
+ });
690
+ const mockAccountData = {
691
+ address: '0x123',
692
+ chainId: mainnet.id,
693
+ chainNamespace: mainnet.chainNamespace
694
+ };
695
+ vi.spyOn(AccountController, 'state', 'get').mockReturnValue(mockAccountData);
696
+ appKit = new AppKit({ ...mockOptions });
697
+ await appKit['syncAccount']({ ...mockAccountData, address: '0x1234' });
698
+ expect(AccountController.fetchTokenBalance).toHaveBeenCalled();
699
+ });
700
+ it('should not sync balance on testnets', async () => {
701
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
702
+ {
703
+ ...sepolia,
704
+ nativeCurrency: { symbol: 'sETH' },
705
+ chainNamespace: 'eip155'
706
+ }
707
+ ]);
708
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
709
+ {
710
+ quantity: { numeric: '0.00', decimals: '18' },
711
+ chainId: 'eip155:11155111',
712
+ symbol: 'sETH'
713
+ }
714
+ ]);
715
+ vi.spyOn(ChainController, 'getAllApprovedCaipNetworkIds').mockReturnValue(['eip155:11155111']);
716
+ const mockAccountData = {
717
+ address: '0x123',
718
+ chainId: '11155111',
719
+ chainNamespace: 'eip155'
720
+ };
721
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValueOnce({
722
+ namespace: 'eip155',
723
+ chainId: '11155111',
724
+ caipNetworkId: 'eip155:11155111'
725
+ });
726
+ vi.spyOn(CaipNetworksUtil, 'extendCaipNetworks').mockReturnValueOnce([
727
+ {
728
+ id: '11155111',
729
+ chainNamespace: 'eip155',
730
+ caipNetworkId: 'eip155:11155111',
731
+ testnet: true,
732
+ nativeCurrency: { symbol: 'ETH' }
733
+ }
734
+ ]);
735
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
736
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
737
+ activeChain: 'eip155'
738
+ });
739
+ vi.spyOn(AccountController, 'state', 'get').mockReturnValue(mockAccountData);
740
+ appKit = new AppKit({ ...mockOptions });
741
+ const mockAdapter = {
742
+ getBalance: vi.fn().mockResolvedValue({ balance: '0.00', symbol: 'sETH' })
743
+ };
744
+ vi.mocked(appKit).getAdapter = vi.fn().mockReturnValue(mockAdapter);
745
+ await appKit['syncAccount'](mockAccountData);
746
+ expect(AccountController.fetchTokenBalance).not.toHaveBeenCalled();
747
+ expect(AccountController.setBalance).toHaveBeenCalledWith('0.00', 'sETH', 'eip155');
748
+ });
749
+ it('should disconnect correctly', async () => {
750
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
751
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
752
+ activeChain: 'eip155'
753
+ });
754
+ const mockRemoveItem = vi.fn();
755
+ vi.spyOn(SafeLocalStorage, 'removeItem').mockImplementation(mockRemoveItem);
756
+ const appKit = new AppKit({
757
+ ...mockOptions,
758
+ networks: [base],
759
+ adapters: [mockUniversalAdapter]
760
+ });
761
+ await appKit.disconnect();
762
+ expect(ConnectionController.disconnect).toHaveBeenCalled();
763
+ // TODO: Unmock all of this file and check for AccountController hooks called from ChainController
764
+ });
765
+ it('should not show unsupported chain UI when allowUnsupportedChain is true', async () => {
766
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
767
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
768
+ activeChain: 'eip155'
769
+ });
770
+ appKit.caipNetworks = [mainnet];
771
+ OptionsController.state.allowUnsupportedChain = undefined;
772
+ vi.spyOn(OptionsController.state, 'allowUnsupportedChain', 'get').mockResolvedValueOnce(true);
773
+ const overrideAdapter = {
774
+ getAccounts: vi.fn().mockResolvedValue({ accounts: [] }),
775
+ syncConnection: vi.fn().mockResolvedValue({
776
+ chainId: 'eip155:999', // Unsupported chain
777
+ address: '0x123',
778
+ accounts: [{ address: '0x123', type: 'eoa' }]
779
+ }),
780
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' }),
781
+ getProfile: vi.fn().mockResolvedValue({}),
782
+ on: vi.fn(),
783
+ off: vi.fn(),
784
+ emit: vi.fn()
785
+ };
786
+ vi.spyOn(appKit, 'getAdapter').mockReturnValueOnce(overrideAdapter);
787
+ vi.spyOn(appKit, 'setUnsupportedNetwork').mockImplementation(vi.fn());
788
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation((key) => {
789
+ const connectorKey = getSafeConnectorIdKey('eip155');
790
+ if (key === connectorKey) {
791
+ return 'test-wallet';
792
+ }
793
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
794
+ return 'eip155:1';
795
+ }
796
+ return undefined;
797
+ });
798
+ vi.mocked(ChainController.showUnsupportedChainUI).mockImplementation(vi.fn());
799
+ await appKit.syncExistingConnection();
800
+ expect(ChainController.showUnsupportedChainUI).not.toHaveBeenCalled();
801
+ });
802
+ it('should subscribe to providers', () => {
803
+ const callback = vi.fn();
804
+ const providers = {
805
+ eip155: { provider: {} },
806
+ solana: {},
807
+ polkadot: {},
808
+ bip122: {}
809
+ };
810
+ const mockSubscribeProviders = vi.fn().mockImplementation(cb => {
811
+ cb(providers);
812
+ return () => { };
813
+ });
814
+ // Mock the entire ProviderUtil
815
+ vi.mocked(ProviderUtil).subscribeProviders = mockSubscribeProviders;
816
+ appKit.subscribeProviders(callback);
817
+ expect(mockSubscribeProviders).toHaveBeenCalled();
818
+ expect(callback).toHaveBeenCalledWith(providers);
819
+ });
820
+ });
821
+ describe('syncExistingConnection', () => {
822
+ it('should set status to "connecting" and sync the connection when a connector and namespace are present', async () => {
823
+ vi.spyOn(AccountController, 'state', 'get').mockReturnValueOnce({
824
+ currentTab: 0,
825
+ addressLabels: new Map(),
826
+ allAccounts: []
827
+ });
828
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
829
+ vi.spyOn(StorageUtil, 'getActiveNamespace').mockReturnValue('eip155');
830
+ vi.spyOn(StorageUtil, 'getConnectedConnectorId').mockReturnValue('test-connector');
831
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
832
+ activeCaipNetwork: { id: 'eip155:1', chainNamespace: 'eip155' }
833
+ });
834
+ vi.mocked(StorageUtil.getActiveNetworkProps).mockReturnValue({
835
+ namespace: mainnet.chainNamespace,
836
+ chainId: mainnet.id,
837
+ caipNetworkId: mainnet.caipNetworkId
838
+ });
839
+ const mockAdapter = {
840
+ getAccounts: vi.fn().mockResolvedValue({ accounts: [{ address: '0x123', type: 'eoa' }] }),
841
+ syncConnection: vi.fn().mockResolvedValue({
842
+ address: '0x123',
843
+ chainId: mainnet.id,
844
+ chainNamespace: mainnet.chainNamespace,
845
+ accounts: [{ address: '0x123', type: 'eoa' }]
846
+ }),
847
+ on: vi.fn(),
848
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' })
849
+ };
850
+ vi.spyOn(appKit, 'getAdapter').mockReturnValueOnce(mockAdapter);
851
+ vi.mocked(appKit).chainNamespaces = ['eip155'];
852
+ await appKit['syncExistingConnection']();
853
+ expect(mockAdapter.syncConnection).toHaveBeenCalled();
854
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connecting', 'eip155');
855
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connected', 'eip155');
856
+ });
857
+ it('should set status to "disconnected" when no connector is present', async () => {
858
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
859
+ vi.spyOn(StorageUtil, 'getConnectedConnectorId').mockReturnValueOnce(undefined);
860
+ vi.mocked(appKit).chainNamespaces = ['eip155'];
861
+ await appKit['syncExistingConnection']();
862
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
863
+ });
864
+ it('should set status to "disconnected" if the connector is set to "AUTH" and the adapter fails to sync', async () => {
865
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
866
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation(key => {
867
+ const connectorKey = getSafeConnectorIdKey('eip155');
868
+ if (key === connectorKey) {
869
+ return 'AUTH';
870
+ }
871
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
872
+ return 'eip155:1';
873
+ }
874
+ return undefined;
875
+ });
876
+ vi.mocked(appKit).chainNamespaces = ['eip155'];
877
+ const mockAdapter = {
878
+ getAccounts: vi.fn().mockResolvedValue({ accounts: [] }),
879
+ syncConnection: vi.fn().mockResolvedValue(null),
880
+ on: vi.fn()
881
+ };
882
+ vi.spyOn(appKit, 'getAdapter').mockReturnValueOnce(mockAdapter);
883
+ await appKit['syncExistingConnection']();
884
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
885
+ });
886
+ it('should reconnect to multiple namespaces if previously connected', async () => {
887
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
888
+ chains: new Map(),
889
+ activeChain: 'eip155'
890
+ });
891
+ vi.spyOn(ProviderUtil, 'setProviderId').mockImplementation(vi.fn());
892
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValue({
893
+ namespace: 'eip155',
894
+ chainId: mainnet.id,
895
+ caipNetworkId: mainnet.caipNetworkId
896
+ });
897
+ vi.spyOn(StorageUtil, 'getConnectedNamespaces').mockReturnValueOnce(['eip155', 'solana']);
898
+ vi.spyOn(StorageUtil, 'getConnectedConnectorId').mockImplementation(namespace => {
899
+ if (namespace === 'eip155') {
900
+ return 'evm-connector';
901
+ }
902
+ return 'solana-connector';
903
+ });
904
+ const mockEvmAdapter = {
905
+ getAccounts: vi.fn().mockResolvedValue({ accounts: [{ address: '0x123', type: 'eoa' }] }),
906
+ syncConnection: vi.fn().mockResolvedValue({
907
+ address: '0x123',
908
+ chainId: mainnet.id,
909
+ chainNamespace: mainnet.chainNamespace,
910
+ accounts: [{ address: '0x123', type: 'eoa' }],
911
+ type: 'EXTERNAL',
912
+ id: 'evm-connector'
913
+ }),
914
+ on: vi.fn()
915
+ };
916
+ const mockSolanaAdapter = {
917
+ getAccounts: vi.fn().mockResolvedValue({ accounts: [{ address: 'Hgbsh1', type: 'eoa' }] }),
918
+ syncConnection: vi.fn().mockResolvedValue({
919
+ address: 'Hgbsh1',
920
+ chainId: solana.id,
921
+ chainNamespace: solana.chainNamespace,
922
+ accounts: [{ address: 'Hgbsh1', type: 'eoa' }],
923
+ type: 'EXTERNAL',
924
+ id: 'solana-connector'
925
+ }),
926
+ on: vi.fn()
927
+ };
928
+ vi.spyOn(appKit, 'getAdapter').mockImplementation(namespace => {
929
+ if (namespace === 'eip155') {
930
+ return mockEvmAdapter;
931
+ }
932
+ return mockSolanaAdapter;
933
+ });
934
+ vi.mocked(appKit).chainNamespaces = ['eip155', 'solana'];
935
+ await appKit['syncExistingConnection']();
936
+ expect(mockEvmAdapter.syncConnection).toHaveBeenCalled();
937
+ expect(mockSolanaAdapter.syncConnection).toHaveBeenCalled();
938
+ expect(mockEvmAdapter.getAccounts).toHaveBeenCalled();
939
+ expect(mockSolanaAdapter.getAccounts).toHaveBeenCalled();
940
+ expect(ProviderUtil.setProviderId).toHaveBeenCalledWith('eip155', 'EXTERNAL');
941
+ expect(ProviderUtil.setProviderId).toHaveBeenCalledWith('solana', 'EXTERNAL');
942
+ expect(StorageUtil.setConnectedConnectorId).toHaveBeenCalledWith('eip155', 'evm-connector');
943
+ expect(StorageUtil.setConnectedConnectorId).toHaveBeenCalledWith('solana', 'solana-connector');
944
+ });
945
+ });
946
+ describe('Base Initialization', () => {
947
+ let appKit;
948
+ let mockAdapter;
949
+ let mockUniversalAdapter;
950
+ beforeEach(() => {
951
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
952
+ chains: new Map(),
953
+ activeChain: 'eip155'
954
+ });
955
+ vi.mocked(ConnectorController).getConnectors = vi.fn().mockReturnValue([]);
956
+ mockAdapter = {
957
+ getAccounts: vi.fn().mockResolvedValue({ accounts: [] }),
958
+ namespace: 'eip155',
959
+ construct: vi.fn(),
960
+ setUniversalProvider: vi.fn(),
961
+ setAuthProvider: vi.fn(),
962
+ syncConnectors: vi.fn(),
963
+ connectors: [],
964
+ on: vi.fn(),
965
+ off: vi.fn(),
966
+ emit: vi.fn(),
967
+ removeAllEventListeners: vi.fn()
968
+ };
969
+ vi.mocked(UniversalAdapter).mockImplementation(() => mockUniversalAdapter);
970
+ appKit = new AppKit({
971
+ ...mockOptions,
972
+ adapters: [mockAdapter]
973
+ });
974
+ vi.spyOn(appKit, 'getUniversalProvider').mockResolvedValue({
975
+ on: vi.fn(),
976
+ off: vi.fn(),
977
+ emit: vi.fn()
978
+ });
979
+ });
980
+ it('should call syncConnectors when initializing adapters', async () => {
981
+ const appKit = new AppKit({
982
+ ...mockOptions,
983
+ networks: [base],
984
+ adapters: [mockAdapter]
985
+ });
986
+ const initChainAdapters = appKit.initChainAdapters.bind(appKit);
987
+ vi.spyOn(appKit, 'createUniversalProviderForAdapter').mockResolvedValueOnce(undefined);
988
+ vi.spyOn(appKit, 'createAuthProviderForAdapter').mockReturnValueOnce(undefined);
989
+ await initChainAdapters([mockAdapter]);
990
+ expect(mockAdapter.syncConnectors).toHaveBeenCalled();
991
+ });
992
+ it('should create UniversalAdapter when no blueprint is provided for namespace', async () => {
993
+ const appKit = new AppKit({
994
+ ...mockOptions,
995
+ networks: [mainnetNetwork],
996
+ adapters: [mockAdapter]
997
+ });
998
+ const createAdapters = appKit.createAdapters.bind(appKit);
999
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
1000
+ const mockUniversalAdapter = {
1001
+ setUniversalProvider: vi.fn(),
1002
+ setAuthProvider: vi.fn()
1003
+ };
1004
+ vi.mocked(UniversalAdapter).mockImplementation(() => mockUniversalAdapter);
1005
+ const adapters = await createAdapters([]);
1006
+ expect(adapters.eip155).toBeDefined();
1007
+ expect(UniversalAdapter).toHaveBeenCalledWith({
1008
+ namespace: 'eip155',
1009
+ networks: [mainnet]
1010
+ });
1011
+ });
1012
+ it('should initialize UniversalProvider when not provided in options', () => {
1013
+ vi.spyOn(CoreHelperUtil, 'isClient').mockReturnValue(true);
1014
+ const upSpy = vi.spyOn(UniversalProvider, 'init');
1015
+ new AppKit({
1016
+ ...mockOptions,
1017
+ projectId: '123',
1018
+ networks: [mainnet],
1019
+ adapters: [mockAdapter]
1020
+ });
1021
+ expect(OptionsController.setUsingInjectedUniversalProvider).toHaveBeenCalled();
1022
+ expect(upSpy).toHaveBeenCalled();
1023
+ });
1024
+ it('should not initialize UniversalProvider when provided in options', async () => {
1025
+ vi.spyOn(CoreHelperUtil, 'isClient').mockReturnValue(true);
1026
+ const upSpy = vi.spyOn(UniversalProvider, 'init');
1027
+ new AppKit({
1028
+ ...mockOptions,
1029
+ projectId: 'test',
1030
+ networks: [mainnet],
1031
+ universalProvider: mockProvider,
1032
+ adapters: [mockAdapter]
1033
+ });
1034
+ expect(upSpy).not.toHaveBeenCalled();
1035
+ expect(OptionsController.setUsingInjectedUniversalProvider).toHaveBeenCalled();
1036
+ });
1037
+ it('should initialize multiple adapters for different namespaces', async () => {
1038
+ const mockSolanaAdapter = {
1039
+ namespace: 'solana',
1040
+ construct: vi.fn(),
1041
+ setUniversalProvider: vi.fn(),
1042
+ setAuthProvider: vi.fn(),
1043
+ syncConnectors: vi.fn(),
1044
+ connectors: [],
1045
+ on: vi.fn(),
1046
+ off: vi.fn(),
1047
+ emit: vi.fn()
1048
+ };
1049
+ const appKit = new AppKit({
1050
+ ...mockOptions,
1051
+ networks: [mainnet, solana],
1052
+ adapters: [mockSolanaAdapter, mockAdapter]
1053
+ });
1054
+ const createAdapters = appKit.createAdapters.bind(appKit);
1055
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
1056
+ const adapters = await createAdapters([mockAdapter, mockSolanaAdapter]);
1057
+ expect(mockAdapter.syncConnectors).toHaveBeenCalled();
1058
+ expect(mockSolanaAdapter.syncConnectors).toHaveBeenCalled();
1059
+ expect(adapters.eip155).toBeDefined();
1060
+ expect(adapters.solana).toBeDefined();
1061
+ });
1062
+ it('should set universal provider and auth provider for each adapter', async () => {
1063
+ const appKit = new AppKit({
1064
+ ...mockOptions,
1065
+ networks: [mainnet],
1066
+ adapters: [mockAdapter]
1067
+ });
1068
+ const mockUniversalProvider = {
1069
+ on: vi.fn(),
1070
+ off: vi.fn(),
1071
+ emit: vi.fn()
1072
+ };
1073
+ vi.spyOn(appKit, 'initialize').mockResolvedValue(undefined);
1074
+ vi.spyOn(CoreHelperUtil, 'isClient').mockReturnValue(true);
1075
+ vi.spyOn(UniversalProvider, 'init').mockResolvedValue(mockUniversalProvider);
1076
+ const initChainAdapters = appKit.initChainAdapters.bind(appKit);
1077
+ await initChainAdapters([mockAdapter]);
1078
+ expect(mockAdapter.setUniversalProvider).toHaveBeenCalled();
1079
+ expect(mockAdapter.setAuthProvider).toHaveBeenCalled();
1080
+ });
1081
+ });
1082
+ describe('Alert Errors', () => {
1083
+ it('should handle alert errors based on error messages', () => {
1084
+ const errors = [
1085
+ {
1086
+ alert: ErrorUtil.ALERT_ERRORS.INVALID_APP_CONFIGURATION,
1087
+ message: 'Error: WebSocket connection closed abnormally with code: 3000 (Unauthorized: origin not allowed)'
1088
+ },
1089
+ {
1090
+ alert: ErrorUtil.ALERT_ERRORS.JWT_TOKEN_NOT_VALID,
1091
+ message: 'WebSocket connection closed abnormally with code: 3000 (JWT validation error: JWT Token is not yet valid:)'
1092
+ },
1093
+ {
1094
+ alert: ErrorUtil.ALERT_ERRORS.INVALID_PROJECT_ID,
1095
+ message: 'Uncaught Error: WebSocket connection closed abnormally with code: 3000 (Unauthorized: invalid key)'
1096
+ }
1097
+ ];
1098
+ for (const { alert, message } of errors) {
1099
+ // @ts-expect-error
1100
+ appKit.handleAlertError(new Error(message));
1101
+ expect(AlertController.open).toHaveBeenCalledWith(alert, 'error');
1102
+ }
1103
+ });
1104
+ });
1105
+ });
1106
+ describe('Listeners', () => {
1107
+ it('should set caip address, profile name and profile image on accountChanged event', async () => {
1108
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
1109
+ {
1110
+ ...sepolia,
1111
+ nativeCurrency: { symbol: 'sETH' },
1112
+ chainNamespace: 'eip155'
1113
+ }
1114
+ ]);
1115
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
1116
+ {
1117
+ quantity: { numeric: '0.00', decimals: '18' },
1118
+ chainId: 'eip155:11155111',
1119
+ symbol: 'sETH'
1120
+ }
1121
+ ]);
1122
+ vi.spyOn(AccountController, 'state', 'get').mockReturnValue({
1123
+ address: '0x'
1124
+ });
1125
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValueOnce({
1126
+ namespace: mainnet.chainNamespace,
1127
+ chainId: mainnet.id,
1128
+ caipNetworkId: mainnet.caipNetworkId
1129
+ });
1130
+ const mockAccount = {
1131
+ address: '0x123',
1132
+ chainId: mainnet.id,
1133
+ chainNamespace: mainnet.chainNamespace
1134
+ };
1135
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
1136
+ activeChain: mockAccount.chainNamespace,
1137
+ activeCaipAddress: `${mockAccount.chainNamespace}:${mockAccount.chainId}:${mockAccount.address}`,
1138
+ chains: new Map([])
1139
+ });
1140
+ const emitter = new Emitter();
1141
+ const mockAdapter = {
1142
+ namespace: 'eip155',
1143
+ construct: vi.fn(),
1144
+ syncConnectors: vi.fn(),
1145
+ getAccounts: vi.fn().mockResolvedValue({ accounts: [] }),
1146
+ syncConnection: vi.fn(),
1147
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' }),
1148
+ getProfile: vi.fn(),
1149
+ on: emitter.on,
1150
+ emit: emitter.emit
1151
+ };
1152
+ // Initialize AppKit
1153
+ const appKit = new AppKit({
1154
+ ...mockOptions,
1155
+ networks: [mainnet],
1156
+ features: {
1157
+ email: false,
1158
+ socials: []
1159
+ },
1160
+ adapters: [mockAdapter]
1161
+ });
1162
+ const identity = { name: 'vitalik.eth', avatar: null };
1163
+ const setCaipAddressSpy = vi.spyOn(AccountController, 'setCaipAddress');
1164
+ const fetchIdentitySpy = vi
1165
+ .spyOn(BlockchainApiController, 'fetchIdentity')
1166
+ .mockResolvedValueOnce(identity);
1167
+ const setProfileNameSpy = vi.spyOn(appKit, 'setProfileName');
1168
+ const setProfileImageSpy = vi.spyOn(appKit, 'setProfileImage');
1169
+ emitter.emit('accountChanged', mockAccount);
1170
+ expect(setCaipAddressSpy).toHaveBeenCalledWith(`${mockAccount.chainNamespace}:${mockAccount.chainId}:${mockAccount.address}`, 'eip155');
1171
+ // Wait for the promise to fetchIdentity to resolve
1172
+ await new Promise(resolve => setTimeout(resolve, 10));
1173
+ expect(fetchIdentitySpy).toHaveBeenCalledWith({ address: mockAccount.address });
1174
+ expect(setProfileNameSpy).toHaveBeenCalledWith(identity.name, 'eip155');
1175
+ expect(setProfileImageSpy).toHaveBeenCalledWith(identity.avatar, 'eip155');
1176
+ });
1177
+ });
1178
+ describe('Adapter Management', () => {
1179
+ let appKit;
1180
+ let mockAdapter;
1181
+ beforeEach(() => {
1182
+ vi.spyOn(OptionsController, 'getSnapshot').mockReturnValue({ ...OptionsController.state });
1183
+ vi.spyOn(ThemeController, 'getSnapshot').mockReturnValue({ ...ThemeController.state });
1184
+ mockAdapter = {
1185
+ namespace: 'eip155',
1186
+ construct: vi.fn(),
1187
+ setUniversalProvider: vi.fn(),
1188
+ setAuthProvider: vi.fn(),
1189
+ syncConnectors: vi.fn(),
1190
+ connectors: [],
1191
+ on: vi.fn(),
1192
+ off: vi.fn(),
1193
+ emit: vi.fn(),
1194
+ removeAllEventListeners: vi.fn()
1195
+ };
1196
+ appKit = new AppKit({
1197
+ ...mockOptions,
1198
+ networks: [mainnet],
1199
+ adapters: [mockAdapter]
1200
+ });
1201
+ appKit.connectionControllerClient = {};
1202
+ appKit.networkControllerClient = {};
1203
+ });
1204
+ describe('addAdapter', () => {
1205
+ it('should add a new adapter successfully', () => {
1206
+ const newAdapter = {
1207
+ namespace: 'solana',
1208
+ construct: vi.fn(),
1209
+ setUniversalProvider: vi.fn(),
1210
+ setAuthProvider: vi.fn(),
1211
+ syncConnectors: vi.fn(),
1212
+ connectors: [],
1213
+ on: vi.fn(),
1214
+ off: vi.fn(),
1215
+ emit: vi.fn()
1216
+ };
1217
+ appKit.addAdapter(newAdapter, [solana]);
1218
+ expect(appKit.chainAdapters?.solana).toBeDefined();
1219
+ expect(appKit.chainNamespaces).toContain('solana');
1220
+ expect(ChainController.addAdapter).toHaveBeenCalledWith(newAdapter, {
1221
+ connectionControllerClient: expect.any(Object),
1222
+ networkControllerClient: expect.any(Object)
1223
+ }, expect.any(Array));
1224
+ });
1225
+ it('should not add adapter if clients are not initialized', () => {
1226
+ const newAdapter = {
1227
+ namespace: 'solana'
1228
+ };
1229
+ appKit.connectionControllerClient = undefined;
1230
+ appKit.networkControllerClient = undefined;
1231
+ appKit.addAdapter(newAdapter, [solana]);
1232
+ expect(appKit.chainAdapters?.solana).toBeUndefined();
1233
+ });
1234
+ it('should not add adapter if chainAdapters is not initialized', () => {
1235
+ vi.spyOn(appKit, 'createAdapter').mockImplementation(() => { });
1236
+ vi.spyOn(appKit, 'initChainAdapter').mockImplementation(() => { });
1237
+ vi.spyOn(ChainController, 'addAdapter').mockImplementation(() => { });
1238
+ const newAdapter = {
1239
+ namespace: 'solana'
1240
+ };
1241
+ appKit.chainAdapters = undefined;
1242
+ appKit.addAdapter(newAdapter, [solana]);
1243
+ expect(appKit.createAdapter).not.toHaveBeenCalled();
1244
+ expect(appKit.initChainAdapter).not.toHaveBeenCalled();
1245
+ expect(ChainController.addAdapter).not.toHaveBeenCalled();
1246
+ });
1247
+ });
1248
+ describe('removeAdapter', () => {
1249
+ it('should remove an existing adapter successfully', () => {
1250
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
1251
+ activeCaipAddress: undefined
1252
+ });
1253
+ appKit.removeAdapter('eip155');
1254
+ expect(appKit.chainAdapters?.eip155).toBeUndefined();
1255
+ expect(appKit.chainNamespaces).not.toContain('eip155');
1256
+ expect(mockAdapter.removeAllEventListeners).toHaveBeenCalled();
1257
+ expect(ChainController.removeAdapter).toHaveBeenCalledWith('eip155');
1258
+ expect(ConnectorController.removeAdapter).toHaveBeenCalledWith('eip155');
1259
+ });
1260
+ it('should not remove adapter if user is connected', () => {
1261
+ vi.spyOn(ChainController, 'removeAdapter').mockImplementation(() => { });
1262
+ vi.spyOn(ConnectorController, 'removeAdapter').mockImplementation(() => { });
1263
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
1264
+ activeCaipAddress: 'eip155:1:0x123'
1265
+ });
1266
+ appKit.removeAdapter('eip155');
1267
+ expect(appKit.chainAdapters?.eip155).toBeDefined();
1268
+ expect(appKit.chainNamespaces).toContain('eip155');
1269
+ expect(mockAdapter.removeAllEventListeners).not.toHaveBeenCalled();
1270
+ expect(ChainController.removeAdapter).not.toHaveBeenCalled();
1271
+ expect(ConnectorController.removeAdapter).not.toHaveBeenCalled();
1272
+ });
1273
+ it('should not remove adapter if adapter does not exist', () => {
1274
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
1275
+ activeCaipAddress: undefined
1276
+ });
1277
+ appKit.removeAdapter('polkadot');
1278
+ expect(ChainController.removeAdapter).not.toHaveBeenCalled();
1279
+ expect(ConnectorController.removeAdapter).not.toHaveBeenCalled();
1280
+ });
1281
+ it('should not remove adapter if chainAdapters is not initialized', () => {
1282
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
1283
+ activeCaipAddress: undefined
1284
+ });
1285
+ appKit.chainAdapters = undefined;
1286
+ appKit.removeAdapter('eip155');
1287
+ expect(ChainController.removeAdapter).not.toHaveBeenCalled();
1288
+ expect(ConnectorController.removeAdapter).not.toHaveBeenCalled();
1289
+ });
1290
+ });
1291
+ });
1292
+ describe('Balance sync', () => {
1293
+ beforeEach(() => {
1294
+ vi.resetAllMocks();
1295
+ vi.spyOn(ConstantsUtil, 'BALANCE_SUPPORTED_CHAINS', 'get').mockReturnValue(['eip155', 'solana']);
1296
+ vi.spyOn(OptionsController, 'getSnapshot').mockReturnValue({ ...OptionsController.state });
1297
+ vi.spyOn(ThemeController, 'getSnapshot').mockReturnValue({ ...ThemeController.state });
1298
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({ ...ChainController.state });
1299
+ });
1300
+ it('should not sync balance if theres no matching caipNetwork', async () => {
1301
+ const appKit = new AppKit({
1302
+ ...mockOptions,
1303
+ networks: [mainnet]
1304
+ });
1305
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([]);
1306
+ await appKit['syncBalance']({
1307
+ address: '0x123',
1308
+ chainId: sepolia.id,
1309
+ chainNamespace: sepolia.chainNamespace
1310
+ });
1311
+ expect(NetworkUtil.getNetworksByNamespace).toHaveBeenCalled();
1312
+ expect(AccountController.fetchTokenBalance).not.toHaveBeenCalled();
1313
+ expect(AccountController.setBalance).not.toHaveBeenCalled();
1314
+ });
1315
+ it('should fetch native balance on testnet', async () => {
1316
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
1317
+ { ...sepolia, caipNetworkId: 'eip155:11155111', chainNamespace: 'eip155' }
1318
+ ]);
1319
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
1320
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
1321
+ activeChain: 'eip155'
1322
+ });
1323
+ vi.spyOn(AccountController, 'state', 'get').mockReturnValue({
1324
+ address: '0x123'
1325
+ });
1326
+ const mockAdapter = {
1327
+ ...mockUniversalAdapter,
1328
+ getBalance: vi.fn().mockResolvedValue({ balance: '1.00', symbol: 'sETH' })
1329
+ };
1330
+ const appKit = new AppKit({
1331
+ ...mockOptions,
1332
+ adapters: [mockAdapter],
1333
+ networks: [sepolia]
1334
+ });
1335
+ await appKit['syncBalance']({
1336
+ address: '0x123',
1337
+ chainId: sepolia.id,
1338
+ chainNamespace: 'eip155'
1339
+ });
1340
+ expect(NetworkUtil.getNetworksByNamespace).toHaveBeenCalled();
1341
+ expect(AccountController.fetchTokenBalance).not.toHaveBeenCalled();
1342
+ expect(AccountController.setBalance).toHaveBeenCalledWith('1.00', 'sETH', 'eip155');
1343
+ });
1344
+ it('should set the correct native token balance', async () => {
1345
+ vi.spyOn(NetworkUtil, 'getNetworksByNamespace').mockReturnValue([
1346
+ { ...mainnet, caipNetworkId: 'eip155:1', chainNamespace: 'eip155' }
1347
+ ]);
1348
+ vi.spyOn(AccountController, 'fetchTokenBalance').mockResolvedValue([
1349
+ {
1350
+ quantity: { numeric: '1.00', decimals: '18' },
1351
+ chainId: 'eip155:1',
1352
+ symbol: 'ETH'
1353
+ },
1354
+ {
1355
+ quantity: { numeric: '0.00', decimals: '18' },
1356
+ chainId: 'eip155:137',
1357
+ symbol: 'POL'
1358
+ },
1359
+ {
1360
+ quantity: { numeric: '0.00', decimals: '18' },
1361
+ chainId: 'eip155:1',
1362
+ symbol: 'USDC'
1363
+ }
1364
+ ]);
1365
+ const appKit = new AppKit({
1366
+ ...mockOptions,
1367
+ networks: [mainnet]
1368
+ });
1369
+ await appKit['syncBalance']({
1370
+ address: '0x123',
1371
+ chainId: mainnet.id,
1372
+ chainNamespace: 'eip155'
1373
+ });
1374
+ expect(NetworkUtil.getNetworksByNamespace).toHaveBeenCalled();
1375
+ expect(AccountController.fetchTokenBalance).toHaveBeenCalled();
1376
+ expect(AccountController.setBalance).toHaveBeenCalledWith('1.00', mainnet.nativeCurrency.symbol, 'eip155');
1377
+ });
1378
+ });
1379
+ describe('WalletConnect Events', () => {
1380
+ let appkit;
1381
+ let universalProvider;
1382
+ let chainChangedCallback;
1383
+ let displayUriCallback;
1384
+ beforeEach(async () => {
1385
+ appkit = new AppKit({
1386
+ ...mockOptions,
1387
+ adapters: [],
1388
+ networks: [mainnet]
1389
+ });
1390
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({});
1391
+ universalProvider = { on: vi.fn() };
1392
+ appkit['universalProvider'] = universalProvider;
1393
+ appkit['caipNetworks'] = mockOptions.networks;
1394
+ appkit['listenWalletConnect']();
1395
+ chainChangedCallback = universalProvider.on.mock.calls.find(([event]) => event === 'chainChanged')?.[1];
1396
+ displayUriCallback = universalProvider.on.mock.calls.find(([event]) => event === 'display_uri')?.[1];
1397
+ });
1398
+ describe('chainChanged', () => {
1399
+ it('should call setUnsupportedNetwork', () => {
1400
+ const setUnsupportedNetworkSpy = vi.spyOn(appkit, 'setUnsupportedNetwork');
1401
+ chainChangedCallback('unknown_chain_id');
1402
+ expect(setUnsupportedNetworkSpy).toHaveBeenCalledWith('unknown_chain_id');
1403
+ });
1404
+ it('should call setCaipNetwork', () => {
1405
+ const setCaipNetworkSpy = vi.spyOn(appkit, 'setCaipNetwork');
1406
+ const newChain = mockOptions.networks[0];
1407
+ // should accept as number
1408
+ chainChangedCallback(newChain.id);
1409
+ expect(setCaipNetworkSpy).toHaveBeenNthCalledWith(1, newChain);
1410
+ // should accept as string
1411
+ ChainController.state.activeCaipNetwork = undefined;
1412
+ chainChangedCallback(newChain.id.toString());
1413
+ expect(setCaipNetworkSpy).toHaveBeenNthCalledWith(2, newChain);
1414
+ });
1415
+ });
1416
+ describe('open', () => {
1417
+ beforeEach(() => {
1418
+ vi.clearAllMocks();
1419
+ vi.spyOn(OptionsController, 'getSnapshot').mockReturnValue({ ...OptionsController.state });
1420
+ vi.spyOn(ThemeController, 'getSnapshot').mockReturnValue({ ...ThemeController.state });
1421
+ });
1422
+ it('should open different views', async () => {
1423
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
1424
+ ...ChainController.state,
1425
+ activeCaipNetwork: mainnet
1426
+ });
1427
+ const openSpy = vi.spyOn(ModalController, 'open');
1428
+ const views = [
1429
+ 'Account',
1430
+ 'Connect',
1431
+ 'Networks',
1432
+ 'ApproveTransaction',
1433
+ 'OnRampProviders',
1434
+ 'ConnectingWalletConnectBasic',
1435
+ 'Swap',
1436
+ 'WhatIsAWallet',
1437
+ 'WhatIsANetwork',
1438
+ 'AllWallets',
1439
+ 'WalletSend'
1440
+ ];
1441
+ const appkit = new AppKit({
1442
+ ...mockOptions,
1443
+ adapters: [],
1444
+ networks: [mainnet]
1445
+ });
1446
+ for (const view of views) {
1447
+ await appkit.open({ view });
1448
+ expect(openSpy).toHaveBeenCalledWith({ view });
1449
+ }
1450
+ });
1451
+ });
1452
+ describe('display_uri', () => {
1453
+ it('should call openUri', () => {
1454
+ displayUriCallback('mock_uri');
1455
+ expect(ConnectionController.setUri).toHaveBeenCalledWith('mock_uri');
1456
+ });
1457
+ });
1458
+ });
1459
+ //# sourceMappingURL=appkit.test.js.map