@reown/appkit 1.6.0 → 1.6.1-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 (41) 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 +5 -5
  4. package/dist/esm/src/adapters/ChainAdapterBlueprint.js.map +1 -1
  5. package/dist/esm/src/client.js +17 -7
  6. package/dist/esm/src/client.js.map +1 -1
  7. package/dist/esm/src/networks/solana/eclipseDevnet.js +17 -0
  8. package/dist/esm/src/networks/solana/eclipseDevnet.js.map +1 -0
  9. package/dist/esm/src/tests/appkit.test.js +714 -0
  10. package/dist/esm/src/tests/appkit.test.js.map +1 -0
  11. package/dist/esm/src/tests/mocks/Adapter.js +30 -0
  12. package/dist/esm/src/tests/mocks/Adapter.js.map +1 -0
  13. package/dist/esm/src/tests/mocks/AppKit.js +24 -0
  14. package/dist/esm/src/tests/mocks/AppKit.js.map +1 -0
  15. package/dist/esm/src/tests/mocks/Options.js +14 -0
  16. package/dist/esm/src/tests/mocks/Options.js.map +1 -0
  17. package/dist/esm/src/tests/mocks/UniversalProvider.js +137 -0
  18. package/dist/esm/src/tests/mocks/UniversalProvider.js.map +1 -0
  19. package/dist/esm/src/tests/siwe.test.js +205 -0
  20. package/dist/esm/src/tests/siwe.test.js.map +1 -0
  21. package/dist/esm/src/tests/universal-adapter.test.js +115 -0
  22. package/dist/esm/src/tests/universal-adapter.test.js.map +1 -0
  23. package/dist/esm/src/tests/utils/HelpersUtil.test.js +195 -0
  24. package/dist/esm/src/tests/utils/HelpersUtil.test.js.map +1 -0
  25. package/dist/esm/src/utils/HelpersUtil.js +13 -0
  26. package/dist/esm/src/utils/HelpersUtil.js.map +1 -1
  27. package/dist/esm/tsconfig.build.tsbuildinfo +1 -1
  28. package/dist/esm/tsconfig.tsbuildinfo +1 -0
  29. package/dist/types/exports/constants.d.ts +1 -1
  30. package/dist/types/src/adapters/ChainAdapterBlueprint.d.ts +2 -8
  31. package/dist/types/src/networks/solana/eclipseDevnet.d.ts +42 -0
  32. package/dist/types/src/tests/appkit.test.d.ts +1 -0
  33. package/dist/types/src/tests/mocks/Adapter.d.ts +3 -0
  34. package/dist/types/src/tests/mocks/AppKit.d.ts +3 -0
  35. package/dist/types/src/tests/mocks/Options.d.ts +18 -0
  36. package/dist/types/src/tests/mocks/UniversalProvider.d.ts +3 -0
  37. package/dist/types/src/tests/siwe.test.d.ts +1 -0
  38. package/dist/types/src/tests/universal-adapter.test.d.ts +1 -0
  39. package/dist/types/src/tests/utils/HelpersUtil.test.d.ts +1 -0
  40. package/dist/types/src/utils/HelpersUtil.d.ts +14 -0
  41. package/package.json +13 -13
@@ -0,0 +1,714 @@
1
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
2
+ import { AppKit } from '../client';
3
+ import { mainnet, polygon } from '../networks/index.js';
4
+ import { AccountController, ModalController, ThemeController, PublicStateController, SnackController, RouterController, OptionsController, BlockchainApiController, ConnectionController, EnsController, EventsController, AssetUtil, ConnectorController, ChainController, StorageUtil, CoreHelperUtil, AlertController } 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 { ErrorUtil } from '@reown/appkit-utils';
10
+ // Mock all controllers and UniversalAdapterClient
11
+ vi.mock('@reown/appkit-core');
12
+ vi.mock('../universal-adapter/client');
13
+ describe('Base', () => {
14
+ let appKit;
15
+ beforeEach(() => {
16
+ vi.resetAllMocks();
17
+ vi.mocked(ChainController).state = {
18
+ chains: new Map(),
19
+ activeChain: 'eip155'
20
+ };
21
+ vi.mocked(ConnectorController).getConnectors = vi.fn().mockReturnValue([]);
22
+ appKit = new AppKit(mockOptions);
23
+ });
24
+ describe('Base Initialization', () => {
25
+ it('should initialize controllers with required provided options', () => {
26
+ expect(OptionsController.setSdkVersion).toHaveBeenCalledWith(mockOptions.sdkVersion);
27
+ expect(OptionsController.setProjectId).toHaveBeenCalledWith(mockOptions.projectId);
28
+ expect(OptionsController.setMetadata).toHaveBeenCalledWith(mockOptions.metadata);
29
+ const copyMockOptions = { ...mockOptions };
30
+ delete copyMockOptions.adapters;
31
+ expect(EventsController.sendEvent).toHaveBeenCalledWith(mockOptions);
32
+ });
33
+ it('should initialize adapters in ChainController', () => {
34
+ expect(ChainController.initialize).toHaveBeenCalledWith(mockOptions.adapters);
35
+ });
36
+ it('should set EIP6963 enabled by default', () => {
37
+ new AppKit({
38
+ ...mockOptions
39
+ });
40
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(true);
41
+ });
42
+ it('should set EIP6963 disabled when option is disabled in config', () => {
43
+ new AppKit({
44
+ ...mockOptions,
45
+ enableEIP6963: false
46
+ });
47
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(false);
48
+ });
49
+ });
50
+ describe('Base Public methods', () => {
51
+ it('should open modal', async () => {
52
+ await appKit.open();
53
+ expect(ModalController.open).toHaveBeenCalled();
54
+ });
55
+ it('should close modal', async () => {
56
+ await appKit.close();
57
+ expect(ModalController.close).toHaveBeenCalled();
58
+ });
59
+ it('should set loading state', () => {
60
+ appKit.setLoading(true);
61
+ expect(ModalController.setLoading).toHaveBeenCalledWith(true);
62
+ });
63
+ it('should get theme mode', () => {
64
+ vi.mocked(ThemeController).state = { themeMode: 'dark' };
65
+ expect(appKit.getThemeMode()).toBe('dark');
66
+ });
67
+ it('should set theme mode', () => {
68
+ appKit.setThemeMode('light');
69
+ expect(ThemeController.setThemeMode).toHaveBeenCalledWith('light');
70
+ });
71
+ it('should get theme variables', () => {
72
+ vi.mocked(ThemeController).state = {
73
+ themeVariables: { '--w3m-accent': '#000' }
74
+ };
75
+ expect(appKit.getThemeVariables()).toEqual({ '--w3m-accent': '#000' });
76
+ });
77
+ it('should set theme variables', () => {
78
+ const themeVariables = { '--w3m-accent': '#fff' };
79
+ appKit.setThemeVariables(themeVariables);
80
+ expect(ThemeController.setThemeVariables).toHaveBeenCalledWith(themeVariables);
81
+ });
82
+ it('should subscribe to theme changes', () => {
83
+ const callback = vi.fn();
84
+ appKit.subscribeTheme(callback);
85
+ expect(ThemeController.subscribe).toHaveBeenCalledWith(callback);
86
+ });
87
+ it('should get wallet info', () => {
88
+ vi.mocked(AccountController).state = { connectedWalletInfo: { name: 'Test Wallet' } };
89
+ expect(appKit.getWalletInfo()).toEqual({ name: 'Test Wallet' });
90
+ });
91
+ it('should subscribe to wallet info changes', () => {
92
+ const callback = vi.fn();
93
+ appKit.subscribeWalletInfo(callback);
94
+ expect(AccountController.subscribeKey).toHaveBeenCalledWith('connectedWalletInfo', callback);
95
+ });
96
+ it('should subscribe to address updates', () => {
97
+ const callback = vi.fn();
98
+ appKit.subscribeShouldUpdateToAddress(callback);
99
+ expect(AccountController.subscribeKey).toHaveBeenCalledWith('shouldUpdateToAddress', callback);
100
+ });
101
+ it('should subscribe to CAIP network changes', () => {
102
+ const callback = vi.fn();
103
+ appKit.subscribeCaipNetworkChange(callback);
104
+ expect(ChainController.subscribeKey).toHaveBeenCalledWith('activeCaipNetwork', callback);
105
+ });
106
+ it('should get state', () => {
107
+ vi.mocked(PublicStateController).state = { isConnected: true };
108
+ expect(appKit.getState()).toEqual({ isConnected: true });
109
+ });
110
+ it('should subscribe to state changes', () => {
111
+ const callback = vi.fn();
112
+ appKit.subscribeState(callback);
113
+ expect(PublicStateController.subscribe).toHaveBeenCalledWith(callback);
114
+ });
115
+ it('should show error message', () => {
116
+ appKit.showErrorMessage('Test error');
117
+ expect(SnackController.showError).toHaveBeenCalledWith('Test error');
118
+ });
119
+ it('should show success message', () => {
120
+ appKit.showSuccessMessage('Test success');
121
+ expect(SnackController.showSuccess).toHaveBeenCalledWith('Test success');
122
+ });
123
+ it('should get event', () => {
124
+ vi.mocked(EventsController).state = { name: 'test_event' };
125
+ expect(appKit.getEvent()).toEqual({ name: 'test_event' });
126
+ });
127
+ it('should subscribe to events', () => {
128
+ const callback = vi.fn();
129
+ appKit.subscribeEvents(callback);
130
+ expect(EventsController.subscribe).toHaveBeenCalledWith(callback);
131
+ });
132
+ it('should replace route', () => {
133
+ appKit.replace('Connect');
134
+ expect(RouterController.replace).toHaveBeenCalledWith('Connect');
135
+ });
136
+ it('should redirect to route', () => {
137
+ appKit.redirect('Networks');
138
+ expect(RouterController.push).toHaveBeenCalledWith('Networks');
139
+ });
140
+ it('should pop transaction stack', () => {
141
+ appKit.popTransactionStack(true);
142
+ expect(RouterController.popTransactionStack).toHaveBeenCalledWith(true);
143
+ });
144
+ it('should check if modal is open', () => {
145
+ vi.mocked(ModalController).state = { open: true };
146
+ expect(appKit.isOpen()).toBe(true);
147
+ });
148
+ it('should check if transaction stack is empty', () => {
149
+ vi.mocked(RouterController).state = { transactionStack: [] };
150
+ expect(appKit.isTransactionStackEmpty()).toBe(true);
151
+ });
152
+ it('should check if transaction should replace view', () => {
153
+ vi.mocked(RouterController).state = { transactionStack: [{ replace: true }] };
154
+ expect(appKit.isTransactionShouldReplaceView()).toBe(true);
155
+ });
156
+ it('should set status', () => {
157
+ appKit.setStatus('connected', 'eip155');
158
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connected', 'eip155');
159
+ });
160
+ it('should set all accounts', () => {
161
+ const evmAddresses = [
162
+ { address: '0x1', namespace: 'eip155', type: 'eoa' },
163
+ { address: '0x2', namespace: 'eip155', type: 'smartAccount' }
164
+ ];
165
+ const solanaAddresses = [{ address: 'asdbjk', namespace: 'solana', type: 'eoa' }];
166
+ const bip122Addresses = [
167
+ { address: 'asdasd1', namespace: 'bip122', type: 'payment' },
168
+ { address: 'asdasd2', namespace: 'bip122', type: 'ordinal' },
169
+ { address: 'ASDASD3', namespace: 'bip122', type: 'stx' }
170
+ ];
171
+ appKit.setAllAccounts(evmAddresses, 'eip155');
172
+ appKit.setAllAccounts(solanaAddresses, 'solana');
173
+ appKit.setAllAccounts(bip122Addresses, 'bip122');
174
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(evmAddresses, 'eip155');
175
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(solanaAddresses, 'solana');
176
+ expect(AccountController.setAllAccounts).toHaveBeenCalledWith(bip122Addresses, 'bip122');
177
+ expect(OptionsController.setHasMultipleAddresses).toHaveBeenCalledWith(true);
178
+ });
179
+ it('should add address label', () => {
180
+ appKit.addAddressLabel('0x123', 'eip155 Address', 'eip155');
181
+ expect(AccountController.addAddressLabel).toHaveBeenCalledWith('0x123', 'eip155 Address', 'eip155');
182
+ });
183
+ it('should remove address label', () => {
184
+ appKit.removeAddressLabel('0x123', 'eip155');
185
+ expect(AccountController.removeAddressLabel).toHaveBeenCalledWith('0x123', 'eip155');
186
+ });
187
+ it('should get CAIP address', () => {
188
+ vi.mocked(ChainController).state = {
189
+ activeChain: 'eip155',
190
+ activeCaipAddress: 'eip155:1:0x123'
191
+ };
192
+ expect(appKit.getCaipAddress()).toBe('eip155:1:0x123');
193
+ });
194
+ it('should get address', () => {
195
+ vi.mocked(AccountController).state = { address: '0x123' };
196
+ expect(appKit.getAddress()).toBe('0x123');
197
+ });
198
+ it('should get provider', () => {
199
+ const mockProvider = { request: vi.fn() };
200
+ vi.mocked(AccountController).state = { provider: mockProvider };
201
+ expect(appKit.getProvider()).toBe(mockProvider);
202
+ });
203
+ it('should get preferred account type', () => {
204
+ vi.mocked(AccountController).state = { preferredAccountType: 'eoa' };
205
+ expect(appKit.getPreferredAccountType()).toBe('eoa');
206
+ });
207
+ it('should set CAIP address', () => {
208
+ // First mock AccountController.setCaipAddress to update ChainController state
209
+ vi.mocked(AccountController.setCaipAddress).mockImplementation(() => {
210
+ vi.mocked(ChainController).state = {
211
+ ...vi.mocked(ChainController).state,
212
+ activeCaipAddress: 'eip155:1:0x123'
213
+ };
214
+ });
215
+ appKit.setCaipAddress('eip155:1:0x123', 'eip155');
216
+ expect(AccountController.setCaipAddress).toHaveBeenCalledWith('eip155:1:0x123', 'eip155');
217
+ expect(appKit.getIsConnectedState()).toBe(true);
218
+ });
219
+ it('should set provider', () => {
220
+ const mockProvider = {
221
+ request: vi.fn()
222
+ };
223
+ appKit.setProvider(mockProvider, 'eip155');
224
+ expect(AccountController.setProvider).toHaveBeenCalledWith(mockProvider, 'eip155');
225
+ });
226
+ it('should set balance', () => {
227
+ appKit.setBalance('1.5', 'ETH', 'eip155');
228
+ expect(AccountController.setBalance).toHaveBeenCalledWith('1.5', 'ETH', 'eip155');
229
+ });
230
+ it('should set profile name', () => {
231
+ appKit.setProfileName('John Doe', 'eip155');
232
+ expect(AccountController.setProfileName).toHaveBeenCalledWith('John Doe', 'eip155');
233
+ });
234
+ it('should set profile image', () => {
235
+ appKit.setProfileImage('https://example.com/image.png', 'eip155');
236
+ expect(AccountController.setProfileImage).toHaveBeenCalledWith('https://example.com/image.png', 'eip155');
237
+ });
238
+ it('should reset account', () => {
239
+ appKit.resetAccount('eip155');
240
+ expect(AccountController.resetAccount).toHaveBeenCalledWith('eip155');
241
+ });
242
+ it('should set CAIP network', () => {
243
+ const caipNetwork = { id: 'eip155:1', name: 'Ethereum' };
244
+ appKit.setCaipNetwork(caipNetwork);
245
+ expect(ChainController.setActiveCaipNetwork).toHaveBeenCalledWith(caipNetwork);
246
+ });
247
+ it('should get CAIP network', () => {
248
+ vi.mocked(ChainController).state = {
249
+ activeCaipNetwork: { id: 'eip155:1', name: 'Ethereum' }
250
+ };
251
+ expect(appKit.getCaipNetwork()).toEqual({ id: 'eip155:1', name: 'Ethereum' });
252
+ });
253
+ it('should set requested CAIP networks', () => {
254
+ const requestedNetworks = [{ id: 'eip155:1', name: 'Ethereum' }];
255
+ appKit.setRequestedCaipNetworks(requestedNetworks, 'eip155');
256
+ expect(ChainController.setRequestedCaipNetworks).toHaveBeenCalledWith(requestedNetworks, 'eip155');
257
+ });
258
+ it('should set connectors', () => {
259
+ const existingConnectors = [
260
+ { id: 'phantom', name: 'Phantom', chain: 'eip155', type: 'INJECTED' }
261
+ ];
262
+ // Mock getConnectors to return existing connectors
263
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue(existingConnectors);
264
+ const newConnectors = [
265
+ { id: 'metamask', name: 'MetaMask', chain: 'eip155', type: 'INJECTED' }
266
+ ];
267
+ appKit.setConnectors(newConnectors);
268
+ // Verify that setConnectors was called with combined array
269
+ expect(ConnectorController.setConnectors).toHaveBeenCalledWith([
270
+ ...existingConnectors,
271
+ ...newConnectors
272
+ ]);
273
+ });
274
+ it('should add connector', () => {
275
+ const connector = {
276
+ id: 'metamask',
277
+ name: 'MetaMask',
278
+ chain: 'eip155',
279
+ type: 'INJECTED'
280
+ };
281
+ appKit.addConnector(connector);
282
+ expect(ConnectorController.addConnector).toHaveBeenCalledWith(connector);
283
+ });
284
+ it('should get connectors', () => {
285
+ const mockConnectors = [
286
+ { id: 'metamask', name: 'MetaMask', chain: 'eip155:1', type: 'INJECTED' }
287
+ ];
288
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue(mockConnectors);
289
+ expect(appKit.getConnectors()).toEqual(mockConnectors);
290
+ });
291
+ it('should get approved CAIP network IDs', () => {
292
+ vi.mocked(ChainController.getAllApprovedCaipNetworkIds).mockReturnValue(['eip155:1']);
293
+ expect(appKit.getApprovedCaipNetworkIds()).toEqual(['eip155:1']);
294
+ });
295
+ it('should set approved CAIP networks data', () => {
296
+ appKit.setApprovedCaipNetworksData('eip155');
297
+ expect(ChainController.setApprovedCaipNetworksData).toHaveBeenCalledWith('eip155');
298
+ });
299
+ it('should reset network', () => {
300
+ appKit.resetNetwork('eip155');
301
+ expect(ChainController.resetNetwork).toHaveBeenCalled();
302
+ });
303
+ it('should reset WC connection', () => {
304
+ appKit.resetWcConnection();
305
+ expect(ConnectionController.resetWcConnection).toHaveBeenCalled();
306
+ });
307
+ it('should fetch identity', async () => {
308
+ const mockRequest = { caipChainId: 'eip155:1', address: '0x123' };
309
+ vi.mocked(BlockchainApiController.fetchIdentity).mockResolvedValue({
310
+ name: 'John Doe',
311
+ avatar: null
312
+ });
313
+ const result = await appKit.fetchIdentity(mockRequest);
314
+ expect(BlockchainApiController.fetchIdentity).toHaveBeenCalledWith(mockRequest);
315
+ expect(result).toEqual({ name: 'John Doe', avatar: null });
316
+ });
317
+ it('should set address explorer URL', () => {
318
+ appKit.setAddressExplorerUrl('https://etherscan.io/address/0x123', 'eip155');
319
+ expect(AccountController.setAddressExplorerUrl).toHaveBeenCalledWith('https://etherscan.io/address/0x123', 'eip155');
320
+ });
321
+ it('should set smart account deployed', () => {
322
+ appKit.setSmartAccountDeployed(true, 'eip155');
323
+ expect(AccountController.setSmartAccountDeployed).toHaveBeenCalledWith(true, 'eip155');
324
+ });
325
+ it('should set connected wallet info', () => {
326
+ const walletInfo = { name: 'MetaMask', icon: 'icon-url' };
327
+ appKit.setConnectedWalletInfo(walletInfo, 'eip155');
328
+ expect(AccountController.setConnectedWalletInfo).toHaveBeenCalledWith(walletInfo, 'eip155');
329
+ });
330
+ it('should set smart account enabled networks', () => {
331
+ const networks = [1, 137];
332
+ appKit.setSmartAccountEnabledNetworks(networks, 'eip155');
333
+ expect(ChainController.setSmartAccountEnabledNetworks).toHaveBeenCalledWith(networks, 'eip155');
334
+ });
335
+ it('should set preferred account type', () => {
336
+ appKit.setPreferredAccountType('eoa', 'eip155');
337
+ expect(AccountController.setPreferredAccountType).toHaveBeenCalledWith('eoa', 'eip155');
338
+ });
339
+ it('should get Reown name', async () => {
340
+ vi.mocked(EnsController.getNamesForAddress).mockResolvedValue([
341
+ {
342
+ name: 'john.reown.id',
343
+ addresses: { eip155: { address: '0x123', created: '0' } },
344
+ attributes: [],
345
+ registered: 0,
346
+ updated: 0
347
+ }
348
+ ]);
349
+ const result = await appKit.getReownName('john.reown.id');
350
+ expect(EnsController.getNamesForAddress).toHaveBeenCalledWith('john.reown.id');
351
+ expect(result).toEqual([
352
+ {
353
+ name: 'john.reown.id',
354
+ addresses: { eip155: { address: '0x123', created: '0' } },
355
+ attributes: [],
356
+ registered: 0,
357
+ updated: 0
358
+ }
359
+ ]);
360
+ });
361
+ it('should set EIP6963 enabled', () => {
362
+ appKit.setEIP6963Enabled(true);
363
+ expect(OptionsController.setEIP6963Enabled).toHaveBeenCalledWith(true);
364
+ });
365
+ it('should set client ID', () => {
366
+ appKit.setClientId('client-123');
367
+ expect(BlockchainApiController.setClientId).toHaveBeenCalledWith('client-123');
368
+ });
369
+ it('should get connector image', () => {
370
+ vi.mocked(AssetUtil.getConnectorImage).mockReturnValue('connector-image-url');
371
+ const result = appKit.getConnectorImage({ id: 'metamask', type: 'INJECTED', chain: 'eip155' });
372
+ expect(AssetUtil.getConnectorImage).toHaveBeenCalledWith({
373
+ id: 'metamask',
374
+ type: 'INJECTED',
375
+ chain: 'eip155'
376
+ });
377
+ expect(result).toBe('connector-image-url');
378
+ });
379
+ it('should switch network when requested', async () => {
380
+ vi.mocked(ChainController.switchActiveNetwork).mockResolvedValue(undefined);
381
+ await appKit.switchNetwork(mainnet);
382
+ expect(ChainController.switchActiveNetwork).toHaveBeenCalledWith(expect.objectContaining({
383
+ id: mainnet.id,
384
+ name: mainnet.name
385
+ }));
386
+ await appKit.switchNetwork(polygon);
387
+ expect(ChainController.switchActiveNetwork).toHaveBeenCalledTimes(1);
388
+ });
389
+ it('should set connected wallet info when syncing account', async () => {
390
+ // Mock the connector data
391
+ const mockConnector = {
392
+ id: 'test-wallet'
393
+ };
394
+ vi.mocked(ConnectorController.getConnectors).mockReturnValue([mockConnector]);
395
+ const mockAccountData = {
396
+ address: '0x123',
397
+ chainId: '1',
398
+ chainNamespace: 'eip155'
399
+ };
400
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation((key) => {
401
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR) {
402
+ return mockConnector.id;
403
+ }
404
+ return undefined;
405
+ });
406
+ await appKit['syncAccount'](mockAccountData);
407
+ expect(AccountController.setConnectedWalletInfo).toHaveBeenCalledWith(expect.objectContaining({
408
+ name: mockConnector.id
409
+ }), 'eip155');
410
+ });
411
+ it('should sync identity only if address changed', async () => {
412
+ const mockAccountData = {
413
+ address: '0x123',
414
+ chainId: '1',
415
+ chainNamespace: 'eip155'
416
+ };
417
+ vi.mocked(BlockchainApiController.fetchIdentity).mockResolvedValue({
418
+ name: 'John Doe',
419
+ avatar: null
420
+ });
421
+ vi.mocked(AccountController).state = { address: '0x123' };
422
+ await appKit['syncAccount'](mockAccountData);
423
+ expect(BlockchainApiController.fetchIdentity).not.toHaveBeenCalled();
424
+ await appKit['syncAccount']({ ...mockAccountData, address: '0x456' });
425
+ expect(BlockchainApiController.fetchIdentity).toHaveBeenCalledOnce();
426
+ });
427
+ it('should disconnect correctly', async () => {
428
+ vi.mocked(ChainController).state = {
429
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
430
+ activeChain: 'eip155'
431
+ };
432
+ const mockRemoveItem = vi.fn();
433
+ vi.spyOn(SafeLocalStorage, 'removeItem').mockImplementation(mockRemoveItem);
434
+ await appKit.disconnect();
435
+ expect(mockRemoveItem).toHaveBeenCalledWith(SafeLocalStorageKeys.CONNECTED_CONNECTOR);
436
+ expect(mockRemoveItem).toHaveBeenCalledWith(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID);
437
+ expect(AccountController.resetAccount).toHaveBeenCalledWith('eip155');
438
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
439
+ expect(AccountController.resetAccount).toHaveBeenCalledWith('eip155');
440
+ });
441
+ it('should set unsupported chain when synced chainId is not supported', async () => {
442
+ const isClientSpy = vi.spyOn(CoreHelperUtil, 'isClient').mockReturnValue(true);
443
+ vi.mocked(ChainController).state = {
444
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
445
+ activeChain: 'eip155'
446
+ };
447
+ appKit.caipNetworks = [{ id: 'eip155:1', chainNamespace: 'eip155' }];
448
+ const mockAdapter = {
449
+ getAccounts: vi.fn().mockResolvedValue([]),
450
+ syncConnection: vi.fn().mockResolvedValue({
451
+ chainId: 'eip155:999', // Unsupported chain
452
+ address: '0x123'
453
+ }),
454
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' }),
455
+ getProfile: vi.fn().mockResolvedValue({}),
456
+ on: vi.fn(),
457
+ off: vi.fn(),
458
+ emit: vi.fn()
459
+ };
460
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
461
+ vi.spyOn(StorageUtil, 'setConnectedConnector').mockImplementation(vi.fn());
462
+ vi.spyOn(appKit, 'setUnsupportedNetwork').mockImplementation(vi.fn());
463
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation((key) => {
464
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR) {
465
+ return 'test-wallet';
466
+ }
467
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
468
+ return 'eip155:1';
469
+ }
470
+ return undefined;
471
+ });
472
+ vi.mocked(ChainController.showUnsupportedChainUI).mockImplementation(vi.fn());
473
+ await appKit.syncExistingConnection();
474
+ expect(appKit.setUnsupportedNetwork).toHaveBeenCalled();
475
+ expect(isClientSpy).toHaveBeenCalled();
476
+ });
477
+ it('should not show unsupported chain UI when allowUnsupportedChain is true', async () => {
478
+ vi.mocked(ChainController).state = {
479
+ chains: new Map([['eip155', { namespace: 'eip155' }]]),
480
+ activeChain: 'eip155'
481
+ };
482
+ appKit.caipNetworks = [{ id: 'eip155:1', chainNamespace: 'eip155' }];
483
+ vi.mocked(OptionsController).state = {
484
+ allowUnsupportedChain: true
485
+ };
486
+ const mockAdapter = {
487
+ getAccounts: vi.fn().mockResolvedValue([]),
488
+ syncConnection: vi.fn().mockResolvedValue({
489
+ chainId: 'eip155:999', // Unsupported chain
490
+ address: '0x123'
491
+ }),
492
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' }),
493
+ getProfile: vi.fn().mockResolvedValue({}),
494
+ on: vi.fn(),
495
+ off: vi.fn(),
496
+ emit: vi.fn()
497
+ };
498
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
499
+ vi.spyOn(StorageUtil, 'setConnectedConnector').mockImplementation(vi.fn());
500
+ vi.spyOn(appKit, 'setUnsupportedNetwork').mockImplementation(vi.fn());
501
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation((key) => {
502
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR) {
503
+ return 'test-wallet';
504
+ }
505
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
506
+ return 'eip155:1';
507
+ }
508
+ return undefined;
509
+ });
510
+ vi.mocked(ChainController.showUnsupportedChainUI).mockImplementation(vi.fn());
511
+ await appKit.syncExistingConnection();
512
+ expect(ChainController.showUnsupportedChainUI).not.toHaveBeenCalled();
513
+ });
514
+ it('should subscribe to providers', () => {
515
+ const callback = vi.fn();
516
+ const providers = {
517
+ eip155: { provider: {} },
518
+ solana: {},
519
+ polkadot: {},
520
+ bip122: {}
521
+ };
522
+ const mockSubscribeProviders = vi.fn().mockImplementation(cb => {
523
+ cb(providers);
524
+ return () => { };
525
+ });
526
+ // Mock the entire ProviderUtil
527
+ vi.mocked(ProviderUtil).subscribeProviders = mockSubscribeProviders;
528
+ appKit.subscribeProviders(callback);
529
+ expect(mockSubscribeProviders).toHaveBeenCalled();
530
+ expect(callback).toHaveBeenCalledWith(providers);
531
+ });
532
+ });
533
+ describe('syncExistingConnection', () => {
534
+ it('should set status to "connecting" and sync the connection when a connector and namespace are present', async () => {
535
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
536
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation(key => {
537
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR) {
538
+ return 'test-wallet';
539
+ }
540
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
541
+ return 'eip155:1';
542
+ }
543
+ return undefined;
544
+ });
545
+ const mockAdapter = {
546
+ getAccounts: vi.fn().mockResolvedValue([]),
547
+ syncConnection: vi.fn().mockResolvedValue({
548
+ address: '0x123',
549
+ chainId: '1',
550
+ chainNamespace: 'eip155'
551
+ }),
552
+ on: vi.fn(),
553
+ getBalance: vi.fn().mockResolvedValue({ balance: '0', symbol: 'ETH' })
554
+ };
555
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
556
+ await appKit['syncExistingConnection']();
557
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connecting', 'eip155');
558
+ expect(mockAdapter.syncConnection).toHaveBeenCalled();
559
+ expect(AccountController.setStatus).toHaveBeenCalledWith('connected', 'eip155');
560
+ });
561
+ it('should set status to "disconnected" when no connector is present', async () => {
562
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
563
+ vi.spyOn(SafeLocalStorage, 'getItem').mockReturnValueOnce(undefined);
564
+ await appKit['syncExistingConnection']();
565
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
566
+ });
567
+ it('should set status to "disconnected" if the connector is set to "AUTH" and the adapter fails to sync', async () => {
568
+ vi.mocked(CoreHelperUtil.isClient).mockReturnValueOnce(true);
569
+ vi.spyOn(SafeLocalStorage, 'getItem').mockImplementation(key => {
570
+ if (key === SafeLocalStorageKeys.CONNECTED_CONNECTOR) {
571
+ return 'AUTH';
572
+ }
573
+ if (key === SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID) {
574
+ return 'eip155:1';
575
+ }
576
+ return undefined;
577
+ });
578
+ const mockAdapter = {
579
+ getAccounts: vi.fn().mockResolvedValue([]),
580
+ syncConnection: vi.fn().mockResolvedValue(null),
581
+ on: vi.fn()
582
+ };
583
+ vi.spyOn(appKit, 'getAdapter').mockReturnValue(mockAdapter);
584
+ await appKit['syncExistingConnection']();
585
+ expect(AccountController.setStatus).toHaveBeenCalledWith('disconnected', 'eip155');
586
+ });
587
+ });
588
+ describe('Base Initialization', () => {
589
+ let appKit;
590
+ let mockAdapter;
591
+ let mockUniversalAdapter;
592
+ beforeEach(() => {
593
+ vi.resetAllMocks();
594
+ vi.mocked(ChainController).state = {
595
+ chains: new Map(),
596
+ activeChain: 'eip155'
597
+ };
598
+ vi.mocked(ConnectorController).getConnectors = vi.fn().mockReturnValue([]);
599
+ mockAdapter = {
600
+ getAccounts: vi.fn().mockResolvedValue([]),
601
+ namespace: 'eip155',
602
+ construct: vi.fn(),
603
+ setUniversalProvider: vi.fn(),
604
+ setAuthProvider: vi.fn(),
605
+ syncConnectors: vi.fn(),
606
+ connectors: [],
607
+ on: vi.fn(),
608
+ off: vi.fn(),
609
+ emit: vi.fn()
610
+ };
611
+ vi.mocked(UniversalAdapter).mockImplementation(() => mockUniversalAdapter);
612
+ appKit = new AppKit({
613
+ ...mockOptions,
614
+ adapters: [mockAdapter]
615
+ });
616
+ vi.spyOn(appKit, 'getUniversalProvider').mockResolvedValue({
617
+ on: vi.fn(),
618
+ off: vi.fn(),
619
+ emit: vi.fn()
620
+ });
621
+ });
622
+ it('should call syncConnectors when initializing adapters', async () => {
623
+ const createAdapters = appKit.createAdapters.bind(appKit);
624
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
625
+ await createAdapters([mockAdapter]);
626
+ expect(mockAdapter.syncConnectors).toHaveBeenCalledWith(expect.objectContaining({
627
+ projectId: mockOptions.projectId,
628
+ metadata: mockOptions.metadata
629
+ }), expect.any(Object));
630
+ });
631
+ it('should create UniversalAdapter when no blueprint is provided for namespace', async () => {
632
+ const createAdapters = appKit.createAdapters.bind(appKit);
633
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
634
+ const mockUniversalAdapter = {
635
+ setUniversalProvider: vi.fn(),
636
+ setAuthProvider: vi.fn()
637
+ };
638
+ vi.mocked(UniversalAdapter).mockImplementation(() => mockUniversalAdapter);
639
+ const adapters = await createAdapters([]);
640
+ expect(adapters.eip155).toBeDefined();
641
+ expect(mockUniversalAdapter.setUniversalProvider).toHaveBeenCalled();
642
+ });
643
+ it('should initialize multiple adapters for different namespaces', async () => {
644
+ const createAdapters = appKit.createAdapters.bind(appKit);
645
+ const mockSolanaAdapter = {
646
+ namespace: 'solana',
647
+ construct: vi.fn(),
648
+ setUniversalProvider: vi.fn(),
649
+ setAuthProvider: vi.fn(),
650
+ syncConnectors: vi.fn(),
651
+ connectors: [],
652
+ on: vi.fn(),
653
+ off: vi.fn(),
654
+ emit: vi.fn()
655
+ };
656
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
657
+ const adapters = await createAdapters([mockAdapter, mockSolanaAdapter]);
658
+ expect(mockAdapter.syncConnectors).toHaveBeenCalled();
659
+ expect(mockSolanaAdapter.syncConnectors).toHaveBeenCalled();
660
+ expect(adapters.eip155).toBeDefined();
661
+ expect(adapters.solana).toBeDefined();
662
+ });
663
+ it('should set universal provider and auth provider for each adapter', async () => {
664
+ const createAdapters = appKit.createAdapters.bind(appKit);
665
+ const mockUniversalProvider = {
666
+ on: vi.fn(),
667
+ off: vi.fn(),
668
+ emit: vi.fn()
669
+ };
670
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
671
+ vi.spyOn(appKit, 'getUniversalProvider').mockResolvedValue(mockUniversalProvider);
672
+ await createAdapters([mockAdapter]);
673
+ expect(mockAdapter.setUniversalProvider).toHaveBeenCalledWith(expect.objectContaining({
674
+ on: expect.any(Function),
675
+ off: expect.any(Function),
676
+ emit: expect.any(Function)
677
+ }));
678
+ expect(mockAdapter.setAuthProvider).toHaveBeenCalled();
679
+ });
680
+ it('should update ChainController state with initialized adapters', async () => {
681
+ const createAdapters = appKit.createAdapters.bind(appKit);
682
+ vi.spyOn(appKit, 'createUniversalProvider').mockResolvedValue(undefined);
683
+ await createAdapters([mockAdapter]);
684
+ expect(ChainController.state.chains.get('eip155')).toEqual(expect.objectContaining({
685
+ namespace: 'eip155',
686
+ connectionControllerClient: expect.any(Object),
687
+ networkControllerClient: expect.any(Object),
688
+ networkState: expect.any(Object),
689
+ accountState: expect.any(Object),
690
+ caipNetworks: expect.any(Array)
691
+ }));
692
+ });
693
+ });
694
+ describe('Alert Errors', () => {
695
+ it('should handle alert errors based on error messages', () => {
696
+ const errors = [
697
+ {
698
+ alert: ErrorUtil.ALERT_ERRORS.INVALID_APP_CONFIGURATION,
699
+ message: 'Error: WebSocket connection closed abnormally with code: 3000 (Unauthorized: origin not allowed)'
700
+ },
701
+ {
702
+ alert: ErrorUtil.ALERT_ERRORS.JWT_TOKEN_NOT_VALID,
703
+ message: 'WebSocket connection closed abnormally with code: 3000 (JWT validation error: JWT Token is not yet valid:)'
704
+ }
705
+ ];
706
+ for (const { alert, message } of errors) {
707
+ // @ts-expect-error
708
+ appKit.handleAlertError(new Error(message));
709
+ expect(AlertController.open).toHaveBeenCalledWith(alert, 'error');
710
+ }
711
+ });
712
+ });
713
+ });
714
+ //# sourceMappingURL=appkit.test.js.map