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