@reown/appkit 1.6.2 → 1.6.3-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/esm/exports/constants.js +1 -1
  2. package/dist/esm/exports/constants.js.map +1 -1
  3. package/dist/esm/package.json +1 -1
  4. package/dist/esm/src/auth-provider/W3MFrameProviderSingleton.js +7 -2
  5. package/dist/esm/src/auth-provider/W3MFrameProviderSingleton.js.map +1 -1
  6. package/dist/esm/src/client.js +117 -66
  7. package/dist/esm/src/client.js.map +1 -1
  8. package/dist/esm/src/library/vue/index.js +3 -3
  9. package/dist/esm/src/library/vue/index.js.map +1 -1
  10. package/dist/esm/src/networks/bitcoin.js +2 -1
  11. package/dist/esm/src/networks/bitcoin.js.map +1 -1
  12. package/dist/esm/src/tests/appkit.test.js +948 -0
  13. package/dist/esm/src/tests/appkit.test.js.map +1 -0
  14. package/dist/esm/src/tests/mocks/Adapter.js +30 -0
  15. package/dist/esm/src/tests/mocks/Adapter.js.map +1 -0
  16. package/dist/esm/src/tests/mocks/AppKit.js +24 -0
  17. package/dist/esm/src/tests/mocks/AppKit.js.map +1 -0
  18. package/dist/esm/src/tests/mocks/Emitter.js +29 -0
  19. package/dist/esm/src/tests/mocks/Emitter.js.map +1 -0
  20. package/dist/esm/src/tests/mocks/Options.js +23 -0
  21. package/dist/esm/src/tests/mocks/Options.js.map +1 -0
  22. package/dist/esm/src/tests/mocks/UniversalProvider.js +137 -0
  23. package/dist/esm/src/tests/mocks/UniversalProvider.js.map +1 -0
  24. package/dist/esm/src/tests/siwe.test.js +240 -0
  25. package/dist/esm/src/tests/siwe.test.js.map +1 -0
  26. package/dist/esm/src/tests/universal-adapter.test.js +115 -0
  27. package/dist/esm/src/tests/universal-adapter.test.js.map +1 -0
  28. package/dist/esm/src/tests/utils/HelpersUtil.test.js +217 -0
  29. package/dist/esm/src/tests/utils/HelpersUtil.test.js.map +1 -0
  30. package/dist/esm/tests/appkit.test.js +1084 -0
  31. package/dist/esm/tests/appkit.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 +32 -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 +115 -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/constants.d.ts +1 -1
  49. package/dist/types/src/auth-provider/W3MFrameProviderSingleton.d.ts +2 -1
  50. package/dist/types/src/client.d.ts +4 -2
  51. package/dist/types/src/library/react/index.d.ts +1 -1
  52. package/dist/types/src/library/vue/index.d.ts +6 -6
  53. package/dist/types/src/networks/bitcoin.d.ts +1 -1
  54. package/dist/types/src/tests/appkit.test.d.ts +1 -0
  55. package/dist/types/src/tests/mocks/Adapter.d.ts +3 -0
  56. package/dist/types/src/tests/mocks/AppKit.d.ts +3 -0
  57. package/dist/types/src/tests/mocks/Emitter.d.ts +12 -0
  58. package/dist/types/src/tests/mocks/Options.d.ts +19 -0
  59. package/dist/types/src/tests/mocks/UniversalProvider.d.ts +3 -0
  60. package/dist/types/src/tests/siwe.test.d.ts +1 -0
  61. package/dist/types/src/tests/universal-adapter.test.d.ts +1 -0
  62. package/dist/types/src/tests/utils/HelpersUtil.test.d.ts +1 -0
  63. package/dist/types/tests/appkit.test.d.ts +1 -0
  64. package/dist/types/tests/mocks/Adapter.d.ts +3 -0
  65. package/dist/types/tests/mocks/AppKit.d.ts +3 -0
  66. package/dist/types/tests/mocks/Options.d.ts +19 -0
  67. package/dist/types/tests/mocks/UniversalProvider.d.ts +3 -0
  68. package/dist/types/tests/siwe.test.d.ts +1 -0
  69. package/dist/types/tests/universal-adapter.test.d.ts +1 -0
  70. package/dist/types/tests/utils/HelpersUtil.test.d.ts +1 -0
  71. package/package.json +9 -9
@@ -0,0 +1,948 @@
1
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
2
+ import { AppKit } from '../client';
3
+ import { base, mainnet, polygon, solana } from '../networks/index.js';
4
+ import { AccountController, ModalController, ThemeController, PublicStateController, SnackController, RouterController, OptionsController, BlockchainApiController, ConnectionController, EnsController, EventsController, AssetUtil, ConnectorController, ChainController, CoreHelperUtil, AlertController, StorageUtil } from '@reown/appkit-core';
5
+ import { SafeLocalStorage, SafeLocalStorageKeys } from '@reown/appkit-common';
6
+ import { mockOptions } from './mocks/Options';
7
+ import { UniversalAdapter } from '../universal-adapter/client';
8
+ import { ProviderUtil } from '../store';
9
+ import { CaipNetworksUtil, ErrorUtil } from '@reown/appkit-utils';
10
+ import mockUniversalAdapter from './mocks/Adapter';
11
+ import { UniversalProvider } from '@walletconnect/universal-provider';
12
+ import mockProvider from './mocks/UniversalProvider';
13
+ import { MockEmitter } from './mocks/Emitter';
14
+ // Mock all controllers and UniversalAdapterClient
15
+ vi.mock('@reown/appkit-core');
16
+ vi.mock('../universal-adapter/client');
17
+ vi.mock('../client.ts', async () => {
18
+ const actual = await vi.importActual('../client.ts');
19
+ return {
20
+ ...actual,
21
+ initOrContinue: vi.fn(),
22
+ syncExistingConnection: vi.fn()
23
+ };
24
+ });
25
+ vi.mocked(global).window = { location: { origin: '' } };
26
+ vi.mocked(global).document = {
27
+ body: {
28
+ injectAdjacentElement: vi.fn()
29
+ },
30
+ createElement: vi.fn().mockReturnValue({ appendChild: vi.fn() }),
31
+ getElementsByTagName: vi.fn().mockReturnValue([{ textContent: '' }]),
32
+ querySelector: vi.fn()
33
+ };
34
+ describe('Base', () => {
35
+ let appKit;
36
+ beforeEach(() => {
37
+ vi.resetAllMocks();
38
+ vi.mocked(ChainController).state = {
39
+ chains: new Map(),
40
+ activeChain: 'eip155'
41
+ };
42
+ vi.mocked(ConnectorController).getConnectors = vi.fn().mockReturnValue([]);
43
+ vi.mocked(CaipNetworksUtil).extendCaipNetworks = vi.fn().mockReturnValue([]);
44
+ appKit = new AppKit(mockOptions);
45
+ });
46
+ describe('Base Initialization', () => {
47
+ it('should initialize controllers', () => {
48
+ const copyMockOptions = { ...mockOptions };
49
+ delete copyMockOptions.adapters;
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
+ });
65
+ it('should set EIP6963 enabled by default', () => {
66
+ new AppKit({
67
+ ...mockOptions
68
+ });
69
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(true);
70
+ });
71
+ it('should set EIP6963 disabled when option is disabled in config', () => {
72
+ new AppKit({
73
+ ...mockOptions,
74
+ enableEIP6963: false
75
+ });
76
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(false);
77
+ });
78
+ });
79
+ describe('Base Public methods', () => {
80
+ it('should open modal', async () => {
81
+ await appKit.open();
82
+ expect(ModalController.open).toHaveBeenCalled();
83
+ });
84
+ it('should close modal', async () => {
85
+ await appKit.close();
86
+ expect(ModalController.close).toHaveBeenCalled();
87
+ });
88
+ it('should set loading state', () => {
89
+ appKit.setLoading(true);
90
+ expect(ModalController.setLoading).toHaveBeenCalledWith(true);
91
+ });
92
+ it('should get theme mode', () => {
93
+ vi.mocked(ThemeController).state = { themeMode: 'dark' };
94
+ expect(appKit.getThemeMode()).toBe('dark');
95
+ });
96
+ it('should set theme mode', () => {
97
+ appKit.setThemeMode('light');
98
+ expect(ThemeController.setThemeMode).toHaveBeenCalledWith('light');
99
+ });
100
+ it('should get theme variables', () => {
101
+ vi.mocked(ThemeController).state = {
102
+ themeVariables: { '--w3m-accent': '#000' }
103
+ };
104
+ expect(appKit.getThemeVariables()).toEqual({ '--w3m-accent': '#000' });
105
+ });
106
+ it('should set theme variables', () => {
107
+ const themeVariables = { '--w3m-accent': '#fff' };
108
+ appKit.setThemeVariables(themeVariables);
109
+ expect(ThemeController.setThemeVariables).toHaveBeenCalledWith(themeVariables);
110
+ });
111
+ it('should subscribe to theme changes', () => {
112
+ const callback = vi.fn();
113
+ appKit.subscribeTheme(callback);
114
+ expect(ThemeController.subscribe).toHaveBeenCalledWith(callback);
115
+ });
116
+ it('should get wallet info', () => {
117
+ vi.mocked(AccountController).state = { connectedWalletInfo: { name: 'Test Wallet' } };
118
+ expect(appKit.getWalletInfo()).toEqual({ name: 'Test Wallet' });
119
+ });
120
+ it('should subscribe to wallet info changes', () => {
121
+ const callback = vi.fn();
122
+ appKit.subscribeWalletInfo(callback);
123
+ expect(AccountController.subscribeKey).toHaveBeenCalledWith('connectedWalletInfo', callback);
124
+ });
125
+ it('should subscribe to address updates', () => {
126
+ const callback = vi.fn();
127
+ appKit.subscribeShouldUpdateToAddress(callback);
128
+ expect(AccountController.subscribeKey).toHaveBeenCalledWith('shouldUpdateToAddress', callback);
129
+ });
130
+ it('should subscribe to CAIP network changes', () => {
131
+ const callback = vi.fn();
132
+ appKit.subscribeCaipNetworkChange(callback);
133
+ expect(ChainController.subscribeKey).toHaveBeenCalledWith('activeCaipNetwork', callback);
134
+ });
135
+ it('should get state', () => {
136
+ vi.mocked(PublicStateController).state = { isConnected: true };
137
+ expect(appKit.getState()).toEqual({ isConnected: true });
138
+ });
139
+ it('should subscribe to state changes', () => {
140
+ const callback = vi.fn();
141
+ appKit.subscribeState(callback);
142
+ expect(PublicStateController.subscribe).toHaveBeenCalledWith(callback);
143
+ });
144
+ it('should show error message', () => {
145
+ appKit.showErrorMessage('Test error');
146
+ expect(SnackController.showError).toHaveBeenCalledWith('Test error');
147
+ });
148
+ it('should show success message', () => {
149
+ appKit.showSuccessMessage('Test success');
150
+ expect(SnackController.showSuccess).toHaveBeenCalledWith('Test success');
151
+ });
152
+ it('should get event', () => {
153
+ vi.mocked(EventsController).state = { name: 'test_event' };
154
+ expect(appKit.getEvent()).toEqual({ name: 'test_event' });
155
+ });
156
+ it('should subscribe to events', () => {
157
+ const callback = vi.fn();
158
+ appKit.subscribeEvents(callback);
159
+ expect(EventsController.subscribe).toHaveBeenCalledWith(callback);
160
+ });
161
+ it('should replace route', () => {
162
+ appKit.replace('Connect');
163
+ expect(RouterController.replace).toHaveBeenCalledWith('Connect');
164
+ });
165
+ it('should redirect to route', () => {
166
+ appKit.redirect('Networks');
167
+ expect(RouterController.push).toHaveBeenCalledWith('Networks');
168
+ });
169
+ it('should pop transaction stack', () => {
170
+ appKit.popTransactionStack(true);
171
+ expect(RouterController.popTransactionStack).toHaveBeenCalledWith(true);
172
+ });
173
+ it('should check if modal is open', () => {
174
+ vi.mocked(ModalController).state = { open: true };
175
+ expect(appKit.isOpen()).toBe(true);
176
+ });
177
+ it('should check if transaction stack is empty', () => {
178
+ vi.mocked(RouterController).state = { transactionStack: [] };
179
+ expect(appKit.isTransactionStackEmpty()).toBe(true);
180
+ });
181
+ it('should check if transaction should replace view', () => {
182
+ vi.mocked(RouterController).state = { transactionStack: [{ replace: true }] };
183
+ expect(appKit.isTransactionShouldReplaceView()).toBe(true);
184
+ });
185
+ it('should set status', () => {
186
+ appKit.setStatus('connected', 'eip155');
187
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connected', 'eip155');
188
+ });
189
+ it('should set all accounts', () => {
190
+ const evmAddresses = [
191
+ { address: '0x1', namespace: 'eip155', type: 'eoa' },
192
+ { address: '0x2', namespace: 'eip155', type: 'smartAccount' }
193
+ ];
194
+ const solanaAddresses = [{ address: 'asdbjk', namespace: 'solana', type: 'eoa' }];
195
+ const bip122Addresses = [
196
+ { address: 'asdasd1', namespace: 'bip122', type: 'payment' },
197
+ { address: 'asdasd2', namespace: 'bip122', type: 'ordinal' },
198
+ { address: 'ASDASD3', namespace: 'bip122', type: 'stx' }
199
+ ];
200
+ appKit.setAllAccounts(evmAddresses, 'eip155');
201
+ appKit.setAllAccounts(solanaAddresses, 'solana');
202
+ appKit.setAllAccounts(bip122Addresses, 'bip122');
203
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(evmAddresses, 'eip155');
204
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(solanaAddresses, 'solana');
205
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(bip122Addresses, 'bip122');
206
+ expect(OptionsController.setHasMultipleAddresses).toHaveBeenCalledWith(true);
207
+ });
208
+ it('should add address label', () => {
209
+ appKit.addAddressLabel('0x123', 'eip155 Address', 'eip155');
210
+ expect(AccountController.addAddressLabel).toHaveBeenCalledWith('0x123', 'eip155 Address', 'eip155');
211
+ });
212
+ it('should remove address label', () => {
213
+ appKit.removeAddressLabel('0x123', 'eip155');
214
+ expect(AccountController.removeAddressLabel).toHaveBeenCalledWith('0x123', 'eip155');
215
+ });
216
+ it('should get CAIP address', () => {
217
+ vi.mocked(ChainController).state = {
218
+ activeChain: 'eip155',
219
+ activeCaipAddress: 'eip155:1:0x123',
220
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
221
+ };
222
+ expect(appKit.getCaipAddress()).toBe('eip155:1:0x123');
223
+ });
224
+ it('should get address', () => {
225
+ vi.mocked(AccountController).state = { address: '0x123' };
226
+ expect(appKit.getAddress()).toBe('0x123');
227
+ });
228
+ it('should get provider', () => {
229
+ const mockProvider = { request: vi.fn() };
230
+ vi.mocked(AccountController).state = { provider: mockProvider };
231
+ expect(appKit.getProvider()).toBe(mockProvider);
232
+ });
233
+ it('should get preferred account type', () => {
234
+ vi.mocked(AccountController).state = { preferredAccountType: 'eoa' };
235
+ expect(appKit.getPreferredAccountType()).toBe('eoa');
236
+ });
237
+ it('should set CAIP address', () => {
238
+ // First mock AccountController.setCaipAddress to update ChainController state
239
+ vi.mocked(AccountController.setCaipAddress).mockImplementation(() => {
240
+ vi.mocked(ChainController).state = {
241
+ ...vi.mocked(ChainController).state,
242
+ activeCaipAddress: 'eip155:1:0x123',
243
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
244
+ };
245
+ });
246
+ appKit.setCaipAddress('eip155:1:0x123', 'eip155');
247
+ expect(AccountController.setCaipAddress).toHaveBeenCalledWith('eip155:1:0x123', 'eip155');
248
+ expect(appKit.getIsConnectedState()).toBe(true);
249
+ });
250
+ it('should set provider', () => {
251
+ const mockProvider = {
252
+ request: vi.fn()
253
+ };
254
+ appKit.setProvider(mockProvider, 'eip155');
255
+ expect(AccountController.setProvider).toHaveBeenCalledWith(mockProvider, 'eip155');
256
+ });
257
+ it('should set balance', () => {
258
+ appKit.setBalance('1.5', 'ETH', 'eip155');
259
+ expect(AccountController.setBalance).toHaveBeenCalledWith('1.5', 'ETH', 'eip155');
260
+ });
261
+ it('should set profile name', () => {
262
+ appKit.setProfileName('John Doe', 'eip155');
263
+ expect(AccountController.setProfileName).toHaveBeenCalledWith('John Doe', 'eip155');
264
+ });
265
+ it('should set profile image', () => {
266
+ appKit.setProfileImage('https://example.com/image.png', 'eip155');
267
+ expect(AccountController.setProfileImage).toHaveBeenCalledWith('https://example.com/image.png', 'eip155');
268
+ });
269
+ it('should reset account', () => {
270
+ appKit.resetAccount('eip155');
271
+ expect(AccountController.resetAccount).toHaveBeenCalledWith('eip155');
272
+ });
273
+ it('should set CAIP network', () => {
274
+ const caipNetwork = { id: 'eip155:1', name: 'Ethereum' };
275
+ appKit.setCaipNetwork(caipNetwork);
276
+ expect(ChainController.setActiveCaipNetwork).toHaveBeenCalledWith(caipNetwork);
277
+ });
278
+ it('should get CAIP network', () => {
279
+ vi.mocked(ChainController).state = {
280
+ activeCaipNetwork: { id: 'eip155:1', name: 'Ethereum' },
281
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
282
+ };
283
+ expect(appKit.getCaipNetwork()).toEqual({ id: 'eip155:1', name: 'Ethereum' });
284
+ });
285
+ it('should set requested CAIP networks', () => {
286
+ const requestedNetworks = [{ id: 'eip155:1', name: 'Ethereum' }];
287
+ appKit.setRequestedCaipNetworks(requestedNetworks, 'eip155');
288
+ expect(ChainController.setRequestedCaipNetworks).toHaveBeenCalledWith(requestedNetworks, 'eip155');
289
+ });
290
+ it('should set connectors', () => {
291
+ const existingConnectors = [
292
+ { id: 'phantom', name: 'Phantom', chain: 'eip155', type: 'INJECTED' }
293
+ ];
294
+ // Mock getConnectors to return existing connectors
295
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue(existingConnectors);
296
+ const newConnectors = [
297
+ { id: 'metamask', name: 'MetaMask', chain: 'eip155', type: 'INJECTED' }
298
+ ];
299
+ appKit.setConnectors(newConnectors);
300
+ // Verify that setConnectors was called with combined array
301
+ expect(ConnectorController.setConnectors).toHaveBeenCalledWith([
302
+ ...existingConnectors,
303
+ ...newConnectors
304
+ ]);
305
+ });
306
+ it('should add connector', () => {
307
+ const connector = {
308
+ id: 'metamask',
309
+ name: 'MetaMask',
310
+ chain: 'eip155',
311
+ type: 'INJECTED'
312
+ };
313
+ appKit.addConnector(connector);
314
+ expect(ConnectorController.addConnector).toHaveBeenCalledWith(connector);
315
+ });
316
+ it('should get connectors', () => {
317
+ const mockConnectors = [
318
+ { id: 'metamask', name: 'MetaMask', chain: 'eip155:1', type: 'INJECTED' }
319
+ ];
320
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue(mockConnectors);
321
+ expect(appKit.getConnectors()).toEqual(mockConnectors);
322
+ });
323
+ it('should get approved CAIP network IDs', () => {
324
+ vi.mocked(ChainController.getAllApprovedCaipNetworkIds).mockReturnValue(['eip155:1']);
325
+ expect(appKit.getApprovedCaipNetworkIds()).toEqual(['eip155:1']);
326
+ });
327
+ it('should set approved CAIP networks data', () => {
328
+ appKit.setApprovedCaipNetworksData('eip155');
329
+ expect(ChainController.setApprovedCaipNetworksData).toHaveBeenCalledWith('eip155');
330
+ });
331
+ it('should reset network', () => {
332
+ appKit.resetNetwork('eip155');
333
+ expect(ChainController.resetNetwork).toHaveBeenCalled();
334
+ });
335
+ it('should reset WC connection', () => {
336
+ appKit.resetWcConnection();
337
+ expect(ConnectionController.resetWcConnection).toHaveBeenCalled();
338
+ });
339
+ it('should fetch identity', async () => {
340
+ const mockRequest = { caipChainId: 'eip155:1', address: '0x123' };
341
+ vi.mocked(BlockchainApiController.fetchIdentity).mockResolvedValue({
342
+ name: 'John Doe',
343
+ avatar: null
344
+ });
345
+ const result = await appKit.fetchIdentity(mockRequest);
346
+ expect(BlockchainApiController.fetchIdentity).toHaveBeenCalledWith(mockRequest);
347
+ expect(result).toEqual({ name: 'John Doe', avatar: null });
348
+ });
349
+ it('should set address explorer URL', () => {
350
+ appKit.setAddressExplorerUrl('https://etherscan.io/address/0x123', 'eip155');
351
+ expect(AccountController.setAddressExplorerUrl).toHaveBeenCalledWith('https://etherscan.io/address/0x123', 'eip155');
352
+ });
353
+ it('should set smart account deployed', () => {
354
+ appKit.setSmartAccountDeployed(true, 'eip155');
355
+ expect(AccountController.setSmartAccountDeployed).toHaveBeenCalledWith(true, 'eip155');
356
+ });
357
+ it('should set connected wallet info', () => {
358
+ const walletInfo = { name: 'MetaMask', icon: 'icon-url' };
359
+ appKit.setConnectedWalletInfo(walletInfo, 'eip155');
360
+ expect(AccountController.setConnectedWalletInfo).toHaveBeenCalledWith(walletInfo, 'eip155');
361
+ });
362
+ it('should set smart account enabled networks', () => {
363
+ const networks = [1, 137];
364
+ appKit.setSmartAccountEnabledNetworks(networks, 'eip155');
365
+ expect(ChainController.setSmartAccountEnabledNetworks).toHaveBeenCalledWith(networks, 'eip155');
366
+ });
367
+ it('should set preferred account type', () => {
368
+ appKit.setPreferredAccountType('eoa', 'eip155');
369
+ expect(AccountController.setPreferredAccountType).toHaveBeenCalledWith('eoa', 'eip155');
370
+ });
371
+ it('should create accounts with correct account types from user accounts', async () => {
372
+ const mockUser = {
373
+ address: '0x123',
374
+ accounts: [
375
+ { address: '0x1', type: 'eoa' },
376
+ { address: '0x2', type: 'smartAccount' }
377
+ ],
378
+ preferredAccountType: 'eoa'
379
+ };
380
+ vi.mocked(ChainController).state = {
381
+ activeChain: 'eip155',
382
+ chains: new Map([['eip155', { namespace: 'eip155' }]])
383
+ };
384
+ vi.mocked(CoreHelperUtil.createAccount).mockImplementation((namespace, address, type) => {
385
+ if (namespace === 'eip155') {
386
+ return {
387
+ address,
388
+ type: type,
389
+ namespace: 'eip155'
390
+ };
391
+ }
392
+ throw new Error('Unexpected namespace');
393
+ });
394
+ const mockAuthProvider = {
395
+ onConnect: vi.fn(callback => callback(mockUser)),
396
+ connect: vi.fn(),
397
+ getSmartAccountEnabledNetworks: vi.fn(),
398
+ onGetSmartAccountEnabledNetworks: vi.fn(),
399
+ onSetPreferredAccount: vi.fn(),
400
+ onRpcRequest: vi.fn(),
401
+ onRpcError: vi.fn(),
402
+ onRpcSuccess: vi.fn(),
403
+ onNotConnected: vi.fn(),
404
+ onIsConnected: vi.fn(),
405
+ getLoginEmailUsed: vi.fn().mockReturnValue(false),
406
+ isConnected: vi.fn().mockResolvedValue({ isConnected: false })
407
+ };
408
+ const appKitWithAuth = new AppKit({
409
+ ...mockOptions,
410
+ features: {
411
+ email: true
412
+ }
413
+ });
414
+ appKitWithAuth.authProvider = mockAuthProvider;
415
+ await appKitWithAuth.listenAuthConnector(mockAuthProvider);
416
+ expect(CoreHelperUtil.createAccount).toHaveBeenCalledWith('eip155', '0x1', 'eoa');
417
+ expect(CoreHelperUtil.createAccount).toHaveBeenCalledWith('eip155', '0x2', 'smartAccount');
418
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith([
419
+ { address: '0x1', type: 'eoa', namespace: 'eip155' },
420
+ { address: '0x2', type: 'smartAccount', namespace: 'eip155' }
421
+ ], 'eip155');
422
+ expect(AccountController.setPreferredAccountType).toHaveBeenCalledWith('eoa', 'eip155');
423
+ });
424
+ it('should get Reown name', async () => {
425
+ vi.mocked(EnsController.getNamesForAddress).mockResolvedValue([
426
+ {
427
+ name: 'john.reown.id',
428
+ addresses: { eip155: { address: '0x123', created: '0' } },
429
+ attributes: [],
430
+ registered: 0,
431
+ updated: 0
432
+ }
433
+ ]);
434
+ const result = await appKit.getReownName('john.reown.id');
435
+ expect(EnsController.getNamesForAddress).toHaveBeenCalledWith('john.reown.id');
436
+ expect(result).toEqual([
437
+ {
438
+ name: 'john.reown.id',
439
+ addresses: { eip155: { address: '0x123', created: '0' } },
440
+ attributes: [],
441
+ registered: 0,
442
+ updated: 0
443
+ }
444
+ ]);
445
+ });
446
+ it('should set EIP6963 enabled', () => {
447
+ appKit.setEIP6963Enabled(true);
448
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(true);
449
+ });
450
+ it('should set client ID', () => {
451
+ appKit.setClientId('client-123');
452
+ expect(BlockchainApiController.setClientId).toHaveBeenCalledWith('client-123');
453
+ });
454
+ it('should get connector image', () => {
455
+ vi.mocked(AssetUtil.getConnectorImage).mockReturnValue('connector-image-url');
456
+ const result = appKit.getConnectorImage({ id: 'metamask', type: 'INJECTED', chain: 'eip155' });
457
+ expect(AssetUtil.getConnectorImage).toHaveBeenCalledWith({
458
+ id: 'metamask',
459
+ type: 'INJECTED',
460
+ chain: 'eip155'
461
+ });
462
+ expect(result).toBe('connector-image-url');
463
+ });
464
+ it('should switch network when requested', async () => {
465
+ vi.mocked(CaipNetworksUtil).extendCaipNetworks = vi
466
+ .fn()
467
+ .mockReturnValue([{ id: mainnet.id, name: mainnet.name }]);
468
+ const mockAppKit = new AppKit(mockOptions);
469
+ vi.mocked(ChainController.switchActiveNetwork).mockResolvedValue(undefined);
470
+ await mockAppKit.switchNetwork(mainnet);
471
+ expect(ChainController.switchActiveNetwork).toHaveBeenCalledWith(expect.objectContaining({
472
+ id: mainnet.id,
473
+ name: mainnet.name
474
+ }));
475
+ await mockAppKit.switchNetwork(polygon);
476
+ expect(ChainController.switchActiveNetwork).toHaveBeenCalledTimes(1);
477
+ });
478
+ it('should set connected wallet info when syncing account', async () => {
479
+ // Mock the connector data
480
+ const mockConnector = {
481
+ id: 'test-wallet'
482
+ };
483
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue([mockConnector]);
484
+ vi.mocked(StorageUtil.getActiveNetworkProps).mockReturnValue({
485
+ namespace: 'eip155',
486
+ chainId: '1',
487
+ caipNetworkId: '1'
488
+ });
489
+ const mockAccountData = {
490
+ address: '0x123',
491
+ chainId: '1',
492
+ chainNamespace: 'eip155'
493
+ };
494
+ vi.spyOn(StorageUtil, 'getConnectedConnectorId').mockReturnValue(mockConnector.id);
495
+ await appKit['syncAccount'](mockAccountData);
496
+ expect(AccountController.setConnectedWalletInfo).toHaveBeenCalledWith(expect.objectContaining({
497
+ name: mockConnector.id
498
+ }), 'eip155');
499
+ });
500
+ it('should sync identity only if address changed', async () => {
501
+ const mockAccountData = {
502
+ address: '0x123',
503
+ chainId: '1',
504
+ chainNamespace: 'eip155'
505
+ };
506
+ vi.mocked(StorageUtil.getActiveNetworkProps).mockReturnValue({
507
+ namespace: 'eip155',
508
+ chainId: '1',
509
+ caipNetworkId: '1'
510
+ });
511
+ vi.mocked(BlockchainApiController.fetchIdentity).mockResolvedValue({
512
+ name: 'John Doe',
513
+ avatar: null
514
+ });
515
+ vi.mocked(AccountController).state = { address: '0x123' };
516
+ await appKit['syncAccount'](mockAccountData);
517
+ expect(BlockchainApiController.fetchIdentity).not.toHaveBeenCalled();
518
+ await appKit['syncAccount']({ ...mockAccountData, address: '0x456' });
519
+ expect(BlockchainApiController.fetchIdentity).toHaveBeenCalledOnce();
520
+ });
521
+ it('should disconnect correctly', async () => {
522
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
523
+ { id: 'eip155:1', chainNamespace: 'eip155' }
524
+ ]);
525
+ vi.mocked(ChainController).state = {
526
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
527
+ activeChain: 'eip155'
528
+ };
529
+ const mockRemoveItem = vi.fn();
530
+ vi.spyOn(SafeLocalStorage, 'removeItem').mockImplementation(mockRemoveItem);
531
+ const appKit = new AppKit({
532
+ ...mockOptions,
533
+ networks: [base],
534
+ projectId: 'YOUR_PROJECT_ID',
535
+ adapters: [mockUniversalAdapter]
536
+ });
537
+ await appKit.disconnect();
538
+ expect(mockUniversalAdapter.disconnect).toHaveBeenCalled();
539
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
540
+ });
541
+ it('should set unsupported chain when synced chainId is not supported', async () => {
542
+ vi.mocked(StorageUtil.getConnectedConnectorId).mockReturnValue('EXTERNAL');
543
+ vi.mocked(StorageUtil.getActiveNamespace).mockReturnValue('eip155');
544
+ vi.mocked(ChainController).state = {
545
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
546
+ activeChain: 'eip155'
547
+ };
548
+ appKit.caipNetworks = [{ id: 'eip155:1', chainNamespace: 'eip155' }];
549
+ const mockAdapter = {
550
+ getAccounts: vi.fn().mockResolvedValue([]),
551
+ syncConnection: vi.fn().mockResolvedValue({
552
+ chainId: 'eip155:999', // Unsupported chain
553
+ address: '0x123'
554
+ }),
555
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' }),
556
+ getProfile: vi.fn().mockResolvedValue({}),
557
+ on: vi.fn(),
558
+ off: vi.fn(),
559
+ emit: vi.fn()
560
+ };
561
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
562
+ vi.spyOn(StorageUtil, 'setConnectedConnectorId').mockImplementation(vi.fn());
563
+ vi.spyOn(appKit, 'syncAccount').mockImplementation(vi.fn());
564
+ vi.spyOn(appKit, 'setUnsupportedNetwork').mockImplementation(vi.fn());
565
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation((key) => {
566
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR_ID) {
567
+ return 'test-wallet';
568
+ }
569
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
570
+ return 'eip155:1';
571
+ }
572
+ return undefined;
573
+ });
574
+ vi.mocked(ChainController.showUnsupportedChainUI).mockImplementation(vi.fn());
575
+ await appKit.syncExistingConnection();
576
+ expect(appKit.setUnsupportedNetwork).toHaveBeenCalled();
577
+ });
578
+ it('should not show unsupported chain UI when allowUnsupportedChain is true', async () => {
579
+ vi.mocked(ChainController).state = {
580
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
581
+ activeChain: 'eip155'
582
+ };
583
+ appKit.caipNetworks = [{ id: 'eip155:1', chainNamespace: 'eip155' }];
584
+ vi.mocked(OptionsController).state = {
585
+ allowUnsupportedChain: true
586
+ };
587
+ const mockAdapter = {
588
+ getAccounts: vi.fn().mockResolvedValue([]),
589
+ syncConnection: vi.fn().mockResolvedValue({
590
+ chainId: 'eip155:999', // Unsupported chain
591
+ address: '0x123'
592
+ }),
593
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' }),
594
+ getProfile: vi.fn().mockResolvedValue({}),
595
+ on: vi.fn(),
596
+ off: vi.fn(),
597
+ emit: vi.fn()
598
+ };
599
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
600
+ vi.spyOn(appKit, 'setUnsupportedNetwork').mockImplementation(vi.fn());
601
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation((key) => {
602
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR_ID) {
603
+ return 'test-wallet';
604
+ }
605
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
606
+ return 'eip155:1';
607
+ }
608
+ return undefined;
609
+ });
610
+ vi.mocked(ChainController.showUnsupportedChainUI).mockImplementation(vi.fn());
611
+ await appKit.syncExistingConnection();
612
+ expect(ChainController.showUnsupportedChainUI).not.toHaveBeenCalled();
613
+ });
614
+ it('should subscribe to providers', () => {
615
+ const callback = vi.fn();
616
+ const providers = {
617
+ eip155: { provider: {} },
618
+ solana: {},
619
+ polkadot: {},
620
+ bip122: {}
621
+ };
622
+ const mockSubscribeProviders = vi.fn().mockImplementation(cb => {
623
+ cb(providers);
624
+ return () => { };
625
+ });
626
+ // Mock the entire ProviderUtil
627
+ vi.mocked(ProviderUtil).subscribeProviders = mockSubscribeProviders;
628
+ appKit.subscribeProviders(callback);
629
+ expect(mockSubscribeProviders).toHaveBeenCalled();
630
+ expect(callback).toHaveBeenCalledWith(providers);
631
+ });
632
+ });
633
+ describe('syncExistingConnection', () => {
634
+ it('should set status to "connecting" and sync the connection when a connector and namespace are present', async () => {
635
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
636
+ vi.spyOn(StorageUtil, 'getActiveNamespace').mockReturnValue('eip155');
637
+ vi.spyOn(StorageUtil, 'getConnectedConnectorId').mockReturnValue('test-connector');
638
+ vi.mocked(StorageUtil.getActiveNetworkProps).mockReturnValue({
639
+ namespace: 'eip155',
640
+ chainId: '1',
641
+ caipNetworkId: '1'
642
+ });
643
+ const mockAdapter = {
644
+ getAccounts: vi.fn().mockResolvedValue([]),
645
+ syncConnection: vi.fn().mockResolvedValue({
646
+ address: '0x123',
647
+ chainId: '1',
648
+ chainNamespace: 'eip155'
649
+ }),
650
+ on: vi.fn(),
651
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' })
652
+ };
653
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
654
+ await appKit['syncExistingConnection']();
655
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connecting', 'eip155');
656
+ expect(mockAdapter.syncConnection).toHaveBeenCalled();
657
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connected', 'eip155');
658
+ });
659
+ it('should set status to "disconnected" when no connector is present', async () => {
660
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
661
+ vi.spyOn(SafeLocalStorage, 'getItem').mockReturnValueOnce(undefined);
662
+ await appKit['syncExistingConnection']();
663
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
664
+ });
665
+ it('should set status to "disconnected" if the connector is set to "AUTH" and the adapter fails to sync', async () => {
666
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
667
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation(key => {
668
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR_ID) {
669
+ return 'AUTH';
670
+ }
671
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
672
+ return 'eip155:1';
673
+ }
674
+ return undefined;
675
+ });
676
+ const mockAdapter = {
677
+ getAccounts: vi.fn().mockResolvedValue([]),
678
+ syncConnection: vi.fn().mockResolvedValue(null),
679
+ on: vi.fn()
680
+ };
681
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
682
+ await appKit['syncExistingConnection']();
683
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
684
+ });
685
+ });
686
+ describe('Base Initialization', () => {
687
+ let appKit;
688
+ let mockAdapter;
689
+ let mockUniversalAdapter;
690
+ beforeEach(() => {
691
+ vi.resetAllMocks();
692
+ vi.mocked(ChainController).state = {
693
+ chains: new Map(),
694
+ activeChain: 'eip155'
695
+ };
696
+ vi.mocked(ConnectorController).getConnectors = vi.fn().mockReturnValue([]);
697
+ mockAdapter = {
698
+ getAccounts: vi.fn().mockResolvedValue([]),
699
+ namespace: 'eip155',
700
+ construct: vi.fn(),
701
+ setUniversalProvider: vi.fn(),
702
+ setAuthProvider: vi.fn(),
703
+ syncConnectors: vi.fn(),
704
+ connectors: [],
705
+ on: vi.fn(),
706
+ off: vi.fn(),
707
+ emit: vi.fn()
708
+ };
709
+ vi.mocked(UniversalAdapter).mockImplementation(() => mockUniversalAdapter);
710
+ appKit = new AppKit({
711
+ ...mockOptions,
712
+ adapters: [mockAdapter]
713
+ });
714
+ vi.spyOn(appKit, 'getUniversalProvider').mockResolvedValue({
715
+ on: vi.fn(),
716
+ off: vi.fn(),
717
+ emit: vi.fn()
718
+ });
719
+ });
720
+ it('should call syncConnectors when initializing adapters', async () => {
721
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
722
+ { id: 'eip155:1', chainNamespace: 'eip155' }
723
+ ]);
724
+ const appKit = new AppKit({
725
+ ...mockOptions,
726
+ networks: [base],
727
+ projectId: 'YOUR_PROJECT_ID',
728
+ adapters: [mockAdapter]
729
+ });
730
+ const initChainAdapters = appKit.initChainAdapters.bind(appKit);
731
+ vi.spyOn(appKit, 'createConnectorsForAdapter').mockResolvedValue(undefined);
732
+ await initChainAdapters([mockAdapter]);
733
+ expect(mockAdapter.syncConnectors).toHaveBeenCalled();
734
+ });
735
+ it('should create UniversalAdapter when no blueprint is provided for namespace', async () => {
736
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
737
+ { id: 'eip155:1', chainNamespace: 'eip155' }
738
+ ]);
739
+ const appKit = new AppKit({
740
+ ...mockOptions,
741
+ networks: [mainnet],
742
+ projectId: 'YOUR_PROJECT_ID',
743
+ adapters: [mockAdapter]
744
+ });
745
+ const createAdapters = appKit.createAdapters.bind(appKit);
746
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
747
+ const mockUniversalAdapter = {
748
+ setUniversalProvider: vi.fn(),
749
+ setAuthProvider: vi.fn()
750
+ };
751
+ vi.mocked(UniversalAdapter).mockImplementation(() => mockUniversalAdapter);
752
+ const adapters = await createAdapters([]);
753
+ expect(adapters.eip155).toBeDefined();
754
+ expect(UniversalAdapter).toHaveBeenCalledWith({
755
+ namespace: 'eip155',
756
+ networks: [{ id: 'eip155:1', chainNamespace: 'eip155' }]
757
+ });
758
+ });
759
+ it('should initialize UniversalProvider when not provided in options', () => {
760
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
761
+ { id: 'eip155:1', chainNamespace: 'eip155' }
762
+ ]);
763
+ vi.spyOn(CoreHelperUtil, 'isClient').mockReturnValue(true);
764
+ const upSpy = vi.spyOn(UniversalProvider, 'init');
765
+ new AppKit({
766
+ ...mockOptions,
767
+ projectId: '123',
768
+ networks: [mainnet],
769
+ adapters: [mockAdapter]
770
+ });
771
+ expect(OptionsController.setUsingInjectedUniversalProvider).toHaveBeenCalled();
772
+ expect(upSpy).toHaveBeenCalled();
773
+ });
774
+ it('should not initialize UniversalProvider when provided in options', async () => {
775
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
776
+ { id: 'eip155:1', chainNamespace: 'eip155' }
777
+ ]);
778
+ vi.spyOn(CoreHelperUtil, 'isClient').mockReturnValue(true);
779
+ const upSpy = vi.spyOn(UniversalProvider, 'init');
780
+ new AppKit({
781
+ ...mockOptions,
782
+ projectId: 'test',
783
+ networks: [mainnet],
784
+ universalProvider: mockProvider,
785
+ adapters: [mockAdapter]
786
+ });
787
+ expect(upSpy).not.toHaveBeenCalled();
788
+ expect(OptionsController.setUsingInjectedUniversalProvider).toHaveBeenCalled();
789
+ });
790
+ it('should initialize multiple adapters for different namespaces', async () => {
791
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
792
+ { id: '1', chainNamespace: 'eip155' },
793
+ { id: 'solana', chainNamespace: 'solana' }
794
+ ]);
795
+ const mockSolanaAdapter = {
796
+ namespace: 'solana',
797
+ construct: vi.fn(),
798
+ setUniversalProvider: vi.fn(),
799
+ setAuthProvider: vi.fn(),
800
+ syncConnectors: vi.fn(),
801
+ connectors: [],
802
+ on: vi.fn(),
803
+ off: vi.fn(),
804
+ emit: vi.fn()
805
+ };
806
+ const appKit = new AppKit({
807
+ ...mockOptions,
808
+ networks: [mainnet, solana],
809
+ projectId: 'YOUR_PROJECT_ID',
810
+ adapters: [mockSolanaAdapter, mockAdapter]
811
+ });
812
+ const createAdapters = appKit.createAdapters.bind(appKit);
813
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
814
+ const adapters = await createAdapters([mockAdapter, mockSolanaAdapter]);
815
+ expect(mockAdapter.syncConnectors).toHaveBeenCalled();
816
+ expect(mockSolanaAdapter.syncConnectors).toHaveBeenCalled();
817
+ expect(adapters.eip155).toBeDefined();
818
+ expect(adapters.solana).toBeDefined();
819
+ });
820
+ it('should set universal provider and auth provider for each adapter', async () => {
821
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
822
+ { id: '1', chainNamespace: 'eip155' }
823
+ ]);
824
+ const appKit = new AppKit({
825
+ ...mockOptions,
826
+ networks: [mainnet],
827
+ projectId: 'YOUR_PROJECT_ID',
828
+ adapters: [mockAdapter]
829
+ });
830
+ const mockUniversalProvider = {
831
+ on: vi.fn(),
832
+ off: vi.fn(),
833
+ emit: vi.fn()
834
+ };
835
+ vi.spyOn(appKit, 'initialize').mockResolvedValue(undefined);
836
+ vi.spyOn(CoreHelperUtil, 'isClient').mockReturnValue(true);
837
+ vi.spyOn(UniversalProvider, 'init').mockResolvedValue(mockUniversalProvider);
838
+ const initChainAdapters = appKit.initChainAdapters.bind(appKit);
839
+ await initChainAdapters([mockAdapter]);
840
+ expect(mockAdapter.setUniversalProvider).toHaveBeenCalled();
841
+ expect(mockAdapter.setAuthProvider).toHaveBeenCalled();
842
+ });
843
+ it('should update ChainController state with initialized adapters', async () => {
844
+ vi.mocked(CaipNetworksUtil.extendCaipNetworks).mockReturnValue([
845
+ { id: '1', chainNamespace: 'eip155' }
846
+ ]);
847
+ const appKit = new AppKit({
848
+ ...mockOptions,
849
+ networks: [mainnet],
850
+ projectId: 'YOUR_PROJECT_ID',
851
+ adapters: [mockAdapter]
852
+ });
853
+ const createAdapters = appKit.createAdapters.bind(appKit);
854
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
855
+ await createAdapters([mockAdapter]);
856
+ expect(ChainController.state.chains.get('eip155')).toEqual(expect.objectContaining({
857
+ namespace: 'eip155',
858
+ connectionControllerClient: expect.any(Object),
859
+ networkControllerClient: expect.any(Object),
860
+ networkState: expect.any(Object),
861
+ accountState: expect.any(Object),
862
+ caipNetworks: expect.any(Array)
863
+ }));
864
+ });
865
+ });
866
+ describe('Alert Errors', () => {
867
+ it('should handle alert errors based on error messages', () => {
868
+ const errors = [
869
+ {
870
+ alert: ErrorUtil.ALERT_ERRORS.INVALID_APP_CONFIGURATION,
871
+ message: 'Error: WebSocket connection closed abnormally with code: 3000 (Unauthorized: origin not allowed)'
872
+ },
873
+ {
874
+ alert: ErrorUtil.ALERT_ERRORS.JWT_TOKEN_NOT_VALID,
875
+ message: 'WebSocket connection closed abnormally with code: 3000 (JWT validation error: JWT Token is not yet valid:)'
876
+ }
877
+ ];
878
+ for (const { alert, message } of errors) {
879
+ // @ts-expect-error
880
+ appKit.handleAlertError(new Error(message));
881
+ expect(AlertController.open).toHaveBeenCalledWith(alert, 'error');
882
+ }
883
+ });
884
+ });
885
+ });
886
+ describe('Listeners', () => {
887
+ it('should set caip address, profile name and profile image on accountChanged event', async () => {
888
+ vi.spyOn(AccountController, 'state', 'get').mockReturnValue({
889
+ address: '0x'
890
+ });
891
+ vi.spyOn(CaipNetworksUtil, 'extendCaipNetworks').mockReturnValueOnce([
892
+ { id: '1', chainNamespace: 'eip155' }
893
+ ]);
894
+ vi.spyOn(StorageUtil, 'getActiveNetworkProps').mockReturnValueOnce({
895
+ namespace: 'eip155',
896
+ chainId: '1',
897
+ caipNetworkId: '1'
898
+ });
899
+ const mockAccount = {
900
+ address: '0x123',
901
+ chainId: '1',
902
+ chainNamespace: 'eip155'
903
+ };
904
+ vi.spyOn(ChainController, 'state', 'get').mockReturnValue({
905
+ activeChain: mockAccount.chainNamespace,
906
+ activeCaipAddress: `${mockAccount.chainNamespace}:${mockAccount.chainId}:${mockAccount.address}`,
907
+ chains: new Map([])
908
+ });
909
+ const emitter = new MockEmitter();
910
+ const mockAdapter = {
911
+ namespace: 'eip155',
912
+ construct: vi.fn(),
913
+ syncConnectors: vi.fn(),
914
+ getAccounts: vi.fn().mockResolvedValue([]),
915
+ syncConnection: vi.fn(),
916
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' }),
917
+ getProfile: vi.fn(),
918
+ on: emitter.on,
919
+ emit: emitter.emit
920
+ };
921
+ // Initialize AppKit
922
+ const appKit = new AppKit({
923
+ ...mockOptions,
924
+ networks: [mainnet],
925
+ projectId: 'YOUR_PROJECT_ID',
926
+ features: {
927
+ email: false,
928
+ socials: []
929
+ },
930
+ adapters: [mockAdapter]
931
+ });
932
+ const identity = { name: 'vitalik.eth', avatar: null };
933
+ const setCaipAddressSpy = vi.spyOn(AccountController, 'setCaipAddress');
934
+ const fetchIdentitySpy = vi
935
+ .spyOn(BlockchainApiController, 'fetchIdentity')
936
+ .mockResolvedValueOnce(identity);
937
+ const setProfileNameSpy = vi.spyOn(appKit, 'setProfileName');
938
+ const setProfileImageSpy = vi.spyOn(appKit, 'setProfileImage');
939
+ emitter.emit('accountChanged', mockAccount);
940
+ expect(setCaipAddressSpy).toHaveBeenCalledWith(`${mockAccount.chainNamespace}:${mockAccount.chainId}:${mockAccount.address}`, 'eip155');
941
+ // Wait for the promise to fetchIdentity to resolve
942
+ await new Promise(resolve => setTimeout(resolve, 10));
943
+ expect(fetchIdentitySpy).toHaveBeenCalledWith({ address: mockAccount.address });
944
+ expect(setProfileNameSpy).toHaveBeenCalledWith(identity.name, 'eip155');
945
+ expect(setProfileImageSpy).toHaveBeenCalledWith(identity.avatar, 'eip155');
946
+ });
947
+ });
948
+ //# sourceMappingURL=appkit.test.js.map