@reown/appkit-adapter-solana 1.3.2 → 1.4.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.
@@ -1,478 +1,322 @@
1
- import { Connection } from '@solana/web3.js';
2
- import { AccountController, ApiController, ChainController, CoreHelperUtil, EventsController, AlertController } from '@reown/appkit-core';
3
- import { ConstantsUtil as CommonConstantsUtil, SafeLocalStorage, SafeLocalStorageKeys } from '@reown/appkit-common';
1
+ import { AdapterBlueprint } from '@reown/appkit/adapters';
2
+ import { ConstantsUtil as CommonConstantsUtil } from '@reown/appkit-common';
3
+ import { AlertController, CoreHelperUtil, EventsController } from '@reown/appkit-core';
4
+ import { ConstantsUtil, ErrorUtil } from '@reown/appkit-utils';
5
+ import { Connection, PublicKey } from '@solana/web3.js';
4
6
  import { SolConstantsUtil } from '@reown/appkit-utils/solana';
5
7
  import { SolStoreUtil } from './utils/SolanaStoreUtil.js';
6
- import { PublicKey } from '@solana/web3.js';
7
- import UniversalProvider, {} from '@walletconnect/universal-provider';
8
8
  import { watchStandard } from './utils/watchStandard.js';
9
- import { WalletConnectProvider } from './providers/WalletConnectProvider.js';
10
9
  import { AuthProvider } from './providers/AuthProvider.js';
11
- import { W3mFrameHelpers, W3mFrameProvider, W3mFrameRpcConstants } from '@reown/appkit-wallet';
12
- import { ConstantsUtil as CoreConstantsUtil } from '@reown/appkit-core';
13
- import { withSolanaNamespace } from './utils/withSolanaNamespace.js';
14
- import { ProviderUtil } from '@reown/appkit/store';
10
+ import { CoinbaseWalletProvider } from './providers/CoinbaseWalletProvider.js';
11
+ import { WcHelpersUtil } from '@reown/appkit';
15
12
  import { W3mFrameProviderSingleton } from '@reown/appkit/auth-provider';
16
- import { ConstantsUtil, ErrorUtil } from '@reown/appkit-utils';
13
+ import { withSolanaNamespace } from './utils/withSolanaNamespace.js';
14
+ import UniversalProvider from '@walletconnect/universal-provider';
17
15
  import { createSendTransaction } from './utils/createSendTransaction.js';
18
- import { CoinbaseWalletProvider } from './providers/CoinbaseWalletProvider.js';
19
- import base58 from 'bs58';
20
- export class SolanaAdapter {
21
- constructor(options) {
22
- this.appKit = undefined;
23
- this.options = undefined;
24
- this.caipNetworks = [];
25
- this.chainNamespace = CommonConstantsUtil.CHAIN.SOLANA;
26
- this.availableProviders = [];
27
- this.defaultCaipNetwork = undefined;
16
+ import { handleMobileWalletRedirection } from './utils/handleMobileWalletRedirection.js';
17
+ import { WalletConnectProvider } from './providers/WalletConnectProvider.js';
18
+ export class SolanaAdapter extends AdapterBlueprint {
19
+ constructor(options = {}) {
20
+ super({});
28
21
  this.adapterType = 'solana';
29
- const { wallets, connectionSettings = 'confirmed' } = options;
30
- this.wallets = wallets;
31
- this.connectionSettings = connectionSettings;
32
- ChainController.subscribeKey('activeCaipNetwork', caipNetwork => {
33
- const caipAddress = this.appKit?.getCaipAddress(this.chainNamespace);
34
- const isSolanaAddress = caipAddress?.startsWith('solana:');
35
- const isSolanaNetwork = caipNetwork?.chainNamespace === this.chainNamespace;
36
- if (caipAddress && isSolanaAddress && isSolanaNetwork) {
37
- this.syncAccount({
38
- address: CoreHelperUtil.getPlainAddress(caipAddress),
39
- caipNetwork
40
- });
41
- }
42
- });
43
- AccountController.subscribeKey('caipAddress', caipAddress => {
44
- const isSolanaAddress = caipAddress?.startsWith('solana:');
45
- const caipNetwork = ChainController.state.activeCaipNetwork;
46
- const isSolanaNetwork = caipNetwork?.chainNamespace === this.chainNamespace;
47
- if (caipAddress && isSolanaAddress && isSolanaNetwork) {
48
- this.syncAccount({
49
- address: CoreHelperUtil.getPlainAddress(caipAddress),
50
- caipNetwork
51
- });
52
- }
53
- }, this.chainNamespace);
54
- }
55
- construct(appKit, options) {
56
- const { projectId } = options;
57
- this.appKit = appKit;
58
- this.options = options;
59
- this.caipNetworks = options.networks;
60
- this.defaultCaipNetwork = options.defaultNetwork;
61
- if (!projectId) {
62
- throw new Error('Solana:construct - projectId is undefined');
63
- }
64
- this.networkControllerClient = {
65
- switchCaipNetwork: async (caipNetwork) => {
66
- if (caipNetwork) {
67
- try {
68
- await this.switchNetwork(caipNetwork);
69
- }
70
- catch (error) {
71
- console.warn('Error switching network', error);
72
- }
73
- }
74
- },
75
- getApprovedCaipNetworksData: async () => {
76
- if (this.provider) {
77
- return Promise.resolve({
78
- supportsAllNetworks: false,
79
- approvedCaipNetworkIds: this.provider.chains.map(chain => chain.caipNetworkId)
80
- });
81
- }
82
- return Promise.resolve({
83
- supportsAllNetworks: false,
84
- approvedCaipNetworkIds: []
85
- });
86
- }
87
- };
88
- this.connectionControllerClient = {
89
- connectExternal: async ({ id }) => {
90
- const externalProvider = this.availableProviders.find(provider => provider.name.toLocaleLowerCase() === id.toLocaleLowerCase());
91
- const isAuthProvider = id.toLocaleLowerCase() === ConstantsUtil.AUTH_CONNECTOR_ID.toLocaleLowerCase();
92
- if (!externalProvider) {
93
- throw Error('connectionControllerClient:connectExternal - adapter was undefined');
94
- }
95
- const chainNamespace = this.appKit?.getActiveChainNamespace();
96
- if (chainNamespace === this.chainNamespace || !isAuthProvider) {
97
- await this.setProvider(externalProvider);
98
- }
99
- },
100
- disconnect: async () => {
101
- await ProviderUtil.getProvider('solana')?.disconnect();
102
- this.appKit?.resetAccount(this.chainNamespace);
103
- },
104
- signMessage: async (message) => {
105
- const provider = ProviderUtil.state.providers['solana'];
106
- if (!provider) {
107
- throw new Error('connectionControllerClient:signMessage - provider is undefined');
108
- }
109
- const signature = await provider.signMessage(new TextEncoder().encode(message));
110
- return base58.encode(signature);
111
- },
112
- estimateGas: async (params) => {
113
- if (params.chainNamespace !== CommonConstantsUtil.CHAIN.SOLANA) {
114
- throw new Error('Chain namespace is not supported');
115
- }
116
- const connection = SolStoreUtil.state.connection;
117
- if (!connection || !this.provider) {
118
- throw new Error('Connection is not set');
119
- }
120
- const transaction = await createSendTransaction({
121
- provider: this.provider,
122
- connection,
123
- to: '11111111111111111111111111111111',
124
- value: 1
125
- });
126
- const fee = await transaction.getEstimatedFee(connection);
127
- return BigInt(fee || 0);
128
- },
129
- getEnsAvatar: async (value) => await Promise.resolve(value),
130
- getEnsAddress: async (value) => await Promise.resolve(value),
131
- writeContract: async () => await Promise.resolve('0x'),
132
- getCapabilities: async () => await Promise.resolve('0x'),
133
- grantPermissions: async () => await Promise.resolve('0x'),
134
- revokePermissions: async () => await Promise.resolve('0x'),
135
- sendTransaction: async (params) => {
136
- if (params.chainNamespace !== CommonConstantsUtil.CHAIN.SOLANA) {
137
- throw new Error('Chain namespace is not supported');
138
- }
139
- const connection = SolStoreUtil.state.connection;
140
- const address = this.appKit?.getAddress(this.chainNamespace);
141
- if (!connection || !address || !this.provider) {
142
- throw new Error('Connection is not set');
143
- }
144
- const transaction = await createSendTransaction({
145
- provider: this.provider,
146
- connection,
147
- to: params.to,
148
- value: params.value
149
- });
150
- const result = await this.provider.sendTransaction(transaction, connection);
151
- await new Promise(resolve => {
152
- const interval = setInterval(async () => {
153
- const status = await connection.getSignatureStatus(result);
154
- if (status?.value) {
155
- clearInterval(interval);
156
- resolve();
157
- }
158
- }, 1000);
159
- });
160
- await this.syncBalance(address);
161
- return result;
162
- },
163
- parseUnits: () => BigInt(0),
164
- formatUnits: () => '',
165
- checkInstalled: (ids = []) => {
166
- const availableIds = new Set(this.availableProviders.map(provider => provider.name));
167
- return ids.some(id => availableIds.has(id));
168
- }
169
- };
170
- ChainController.state.chains.set(this.chainNamespace, {
171
- chainNamespace: this.chainNamespace,
172
- connectionControllerClient: this.connectionControllerClient,
173
- networkControllerClient: this.networkControllerClient,
174
- adapterType: this.adapterType,
175
- caipNetworks: this.caipNetworks
176
- });
177
- ProviderUtil.subscribeProviders(providers => {
178
- if (providers['solana'] && providers['solana'] instanceof UniversalProvider) {
179
- const walletConnectProvider = this.getSolanaWalletConnectProvider(providers['solana']);
180
- ProviderUtil.setProvider(this.chainNamespace, walletConnectProvider);
181
- }
182
- });
183
- this.syncRequestedNetworks(this.caipNetworks);
184
- this.initializeProviders({
185
- relayUrl: 'wss://relay.walletconnect.com',
186
- metadata: options.metadata,
187
- projectId: options.projectId
188
- });
189
- this.syncRequestedNetworks(this.caipNetworks);
190
- ChainController.subscribeKey('activeCaipNetwork', (newCaipNetwork) => {
191
- const newChain = this.caipNetworks.find(_chain => _chain.id === newCaipNetwork?.id);
192
- if (!newChain) {
193
- return;
194
- }
195
- if (ChainController.state.activeCaipNetwork && this.appKit?.getIsConnectedState()) {
196
- ApiController.reFetchWallets();
197
- }
198
- });
22
+ this.providerHandlers = null;
23
+ this.namespace = CommonConstantsUtil.CHAIN.SOLANA;
24
+ this.connectionSettings = options.connectionSettings || 'confirmed';
25
+ this.wallets = options.wallets;
199
26
  EventsController.subscribe(state => {
200
27
  if (state.data.event === 'SELECT_WALLET') {
201
28
  const isMobile = CoreHelperUtil.isMobile();
202
29
  const isClient = CoreHelperUtil.isClient();
203
30
  if (isMobile && isClient) {
204
- if (state.data.properties?.name === 'Phantom' && !('phantom' in window)) {
205
- const href = window.location.href;
206
- const protocol = href.startsWith('https') ? 'https' : 'http';
207
- const host = href.split('/')[2];
208
- const ref = `${protocol}://${host}`;
209
- window.location.href = `https://phantom.app/ul/browse/${href}?ref=${ref}`;
210
- }
211
- if (state.data.properties?.name === 'Coinbase Wallet' && !('coinbaseSolana' in window)) {
212
- const href = window.location.href;
213
- window.location.href = `https://go.cb-w.com/dapp?cb_url=${href}`;
214
- }
31
+ handleMobileWalletRedirection(state.data.properties);
215
32
  }
216
33
  }
217
34
  });
218
35
  }
219
- getWalletConnection() {
220
- return SolStoreUtil.state.connection;
221
- }
222
- async syncAccount({ address, caipNetwork }) {
223
- if (address && caipNetwork) {
224
- SolStoreUtil.setConnection(new Connection(caipNetwork.rpcUrls.default.http?.[0], this.connectionSettings));
225
- this.appKit?.setAllAccounts([{ address, type: 'eoa' }], this.chainNamespace);
226
- this.appKit?.setCaipAddress(`${this.chainNamespace}:${caipNetwork.id}:${address}`, this.chainNamespace);
227
- await this.syncNetwork(address);
36
+ syncConnectors(options, appKit) {
37
+ if (!options.projectId) {
38
+ AlertController.open(ErrorUtil.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED, 'error');
228
39
  }
229
- else {
230
- this.appKit?.resetWcConnection();
231
- this.appKit?.resetNetwork(this.chainNamespace);
232
- this.appKit?.resetAccount(this.chainNamespace);
40
+ const emailEnabled = options.features?.email !== false;
41
+ const socialsEnabled = options.features?.socials !== false &&
42
+ Array.isArray(options.features?.socials) &&
43
+ options.features.socials.length > 0;
44
+ if (emailEnabled || socialsEnabled) {
45
+ this.w3mFrameProvider = W3mFrameProviderSingleton.getInstance({
46
+ projectId: options.projectId,
47
+ chainId: withSolanaNamespace(appKit?.getCaipNetwork(this.namespace)?.id),
48
+ onTimeout: () => {
49
+ AlertController.open(ErrorUtil.ALERT_ERRORS.INVALID_APP_CONFIGURATION, 'error');
50
+ }
51
+ });
52
+ this.authProvider = new AuthProvider({
53
+ getProvider: () => this.w3mFrameProvider,
54
+ getActiveChain: () => appKit.getCaipNetwork(this.namespace),
55
+ getActiveNamespace: () => appKit.getActiveChainNamespace(),
56
+ getSession: () => this.authSession,
57
+ setSession: session => {
58
+ this.authSession = session;
59
+ },
60
+ chains: this.caipNetworks
61
+ });
62
+ this.addConnector({
63
+ id: ConstantsUtil.AUTH_CONNECTOR_ID,
64
+ type: 'AUTH',
65
+ provider: this.authProvider,
66
+ name: 'Auth',
67
+ chain: this.namespace,
68
+ chains: []
69
+ });
233
70
  }
71
+ if ('coinbaseSolana' in window) {
72
+ this.addConnector({
73
+ id: 'coinbaseWallet',
74
+ type: 'EXTERNAL',
75
+ provider: new CoinbaseWalletProvider({
76
+ provider: window.coinbaseSolana,
77
+ chains: this.caipNetworks,
78
+ getActiveChain: () => appKit.getCaipNetwork(this.namespace)
79
+ }),
80
+ name: 'Coinbase Wallet',
81
+ chain: this.namespace,
82
+ chains: []
83
+ });
84
+ }
85
+ watchStandard(this.caipNetworks, () => appKit.getCaipNetwork(this.namespace), (...providers) => {
86
+ providers.forEach(provider => {
87
+ this.addConnector({
88
+ id: provider.name,
89
+ type: 'ANNOUNCED',
90
+ provider: provider,
91
+ imageUrl: provider.icon,
92
+ name: provider.name,
93
+ chain: CommonConstantsUtil.CHAIN.SOLANA,
94
+ chains: []
95
+ });
96
+ });
97
+ });
234
98
  }
235
- async syncBalance(address = this.appKit?.getAddress(this.chainNamespace)) {
236
- if (!address) {
237
- return;
99
+ async getEnsAddress(params) {
100
+ return { address: params.name };
101
+ }
102
+ async writeContract() {
103
+ return Promise.resolve({
104
+ hash: ''
105
+ });
106
+ }
107
+ async getCapabilities() {
108
+ return Promise.resolve({});
109
+ }
110
+ async grantPermissions() {
111
+ return Promise.resolve({});
112
+ }
113
+ async revokePermissions() {
114
+ return Promise.resolve('0x');
115
+ }
116
+ async signMessage(params) {
117
+ const walletStandardProvider = params.provider;
118
+ if (!walletStandardProvider) {
119
+ throw new Error('connectionControllerClient:signMessage - provider is undefined');
238
120
  }
239
- if (!SolStoreUtil.state.connection) {
121
+ const signature = await walletStandardProvider.signMessage(new TextEncoder().encode(params.message));
122
+ return {
123
+ signature: new TextDecoder().decode(signature)
124
+ };
125
+ }
126
+ async estimateGas(params) {
127
+ const connection = SolStoreUtil.state.connection;
128
+ if (!connection || !params.provider) {
240
129
  throw new Error('Connection is not set');
241
130
  }
242
- if (!this.appKit?.getCaipNetwork()) {
243
- this.appKit?.setCaipNetwork(this.defaultCaipNetwork);
244
- }
245
- const balance = (await SolStoreUtil.state.connection.getBalance(new PublicKey(address))) /
246
- SolConstantsUtil.LAMPORTS_PER_SOL;
247
- this.appKit?.setBalance(balance.toString(), this.appKit?.getCaipNetwork()?.nativeCurrency.symbol, this.chainNamespace);
131
+ const transaction = await createSendTransaction({
132
+ provider: params.provider,
133
+ connection,
134
+ to: '11111111111111111111111111111111',
135
+ value: 1
136
+ });
137
+ const fee = await transaction.getEstimatedFee(connection);
138
+ return {
139
+ gas: BigInt(fee || 0)
140
+ };
248
141
  }
249
- syncRequestedNetworks(caipNetworks) {
250
- const uniqueChainNamespaces = Array.from(new Set(caipNetworks.map(caipNetwork => caipNetwork.chainNamespace)));
251
- uniqueChainNamespaces.forEach(chainNamespace => {
252
- this.appKit?.setRequestedCaipNetworks(caipNetworks.filter(caipNetwork => caipNetwork.chainNamespace === chainNamespace), chainNamespace);
142
+ async sendTransaction(params) {
143
+ const connection = SolStoreUtil.state.connection;
144
+ if (!connection || !params.address || !params.provider) {
145
+ throw new Error('Connection is not set');
146
+ }
147
+ const walletStandardProvider = params.provider;
148
+ const transaction = await createSendTransaction({
149
+ provider: walletStandardProvider,
150
+ connection,
151
+ to: params.to,
152
+ value: params.value
253
153
  });
154
+ const result = await walletStandardProvider.sendTransaction(transaction, connection);
155
+ await new Promise(resolve => {
156
+ const interval = setInterval(async () => {
157
+ const status = await connection.getSignatureStatus(result);
158
+ if (status?.value) {
159
+ clearInterval(interval);
160
+ resolve();
161
+ }
162
+ }, 1000);
163
+ });
164
+ return {
165
+ hash: result
166
+ };
254
167
  }
255
- getAuthSession() {
256
- return this.authSession;
168
+ parseUnits() {
169
+ return 0n;
257
170
  }
258
- async switchNetwork(caipNetwork) {
259
- const connectedConnector = SafeLocalStorage.getItem(SafeLocalStorageKeys.CONNECTED_CONNECTOR);
260
- const isConnectedWithAuth = connectedConnector === 'AUTH';
261
- if (isConnectedWithAuth) {
262
- await this.w3mFrameProvider?.switchNetwork(caipNetwork.caipNetworkId);
263
- const user = await this.w3mFrameProvider?.getUser({
264
- chainId: caipNetwork?.caipNetworkId
265
- });
266
- this.authSession = user;
267
- if (user) {
268
- const caipAddress = `${caipNetwork.caipNetworkId}:${user.address}`;
269
- ProviderUtil.setProvider(this.chainNamespace, this.authProvider);
270
- ProviderUtil.setProviderId(this.chainNamespace, 'walletConnect');
271
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
272
- this.syncAccount({
273
- address: user.address,
274
- caipNetwork
275
- });
171
+ formatUnits() {
172
+ return '';
173
+ }
174
+ async connect(params) {
175
+ const { id, type, rpcUrl } = params;
176
+ const selectedProvider = this.connectors.find(c => c.id === id)?.provider;
177
+ if (!selectedProvider) {
178
+ throw new Error('Provider not found');
179
+ }
180
+ let address;
181
+ if (type === 'AUTH') {
182
+ const data = await this.authProvider?.connect();
183
+ if (!data) {
184
+ throw new Error('No address found');
276
185
  }
186
+ address = data;
277
187
  }
278
188
  else {
279
- this.appKit?.setCaipNetwork(caipNetwork);
280
- const address = this.appKit?.getAddress(this.chainNamespace);
281
- await this.syncAccount({
282
- address,
283
- caipNetwork
284
- });
189
+ address = await selectedProvider.connect();
285
190
  }
191
+ this.listenProviderEvents(selectedProvider);
192
+ SolStoreUtil.setConnection(new Connection(rpcUrl, 'confirmed'));
193
+ return {
194
+ address,
195
+ chainId: params.chainId,
196
+ provider: selectedProvider,
197
+ type: type,
198
+ id
199
+ };
286
200
  }
287
- async syncNetwork(address) {
288
- const caipNetwork = this.appKit?.getCaipNetwork(this.chainNamespace);
289
- const connection = SolStoreUtil.state.connection;
290
- if (!address || !caipNetwork || !connection) {
291
- return;
201
+ async getBalance(params) {
202
+ const connection = new Connection(params.caipNetwork?.rpcUrls?.default?.http?.[0], this.connectionSettings);
203
+ const balance = await connection.getBalance(new PublicKey(params.address));
204
+ const formattedBalance = (balance / SolConstantsUtil.LAMPORTS_PER_SOL).toString();
205
+ if (!params.caipNetwork) {
206
+ throw new Error('caipNetwork is required');
292
207
  }
293
- this.appKit?.setAddressExplorerUrl(caipNetwork.blockExplorers?.default.url
294
- ? `${caipNetwork.blockExplorers.default.url}/account/${address}`
295
- : undefined, this.chainNamespace);
296
- await this.syncBalance(address);
208
+ return {
209
+ balance: formattedBalance,
210
+ symbol: params.caipNetwork?.nativeCurrency.symbol
211
+ };
297
212
  }
298
- async setProvider(provider) {
299
- try {
300
- this.appKit?.setLoading(true);
301
- const address = await provider.connect();
302
- const caipNetworkId = SafeLocalStorage.getItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID);
303
- const connectionChain = provider.chains.find(chain => chain.caipNetworkId === caipNetworkId) || provider.chains[0];
304
- if (connectionChain) {
305
- const caipAddress = `${connectionChain.caipNetworkId}:${address}`;
306
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
307
- await this.switchNetwork(connectionChain);
308
- ProviderUtil.setProvider(this.chainNamespace, provider);
309
- this.provider = provider;
310
- switch (provider.type) {
311
- case 'WALLET_CONNECT':
312
- ProviderUtil.setProviderId(this.chainNamespace, 'walletConnect');
313
- break;
314
- case 'AUTH':
315
- ProviderUtil.setProviderId(this.chainNamespace, 'w3mAuth');
316
- break;
317
- default:
318
- ProviderUtil.setProviderId(this.chainNamespace, 'injected');
319
- }
320
- SafeLocalStorage.setItem(SafeLocalStorageKeys.WALLET_ID, provider.name);
321
- await this.appKit?.setApprovedCaipNetworksData(this.chainNamespace);
322
- this.watchProvider(provider);
323
- }
213
+ async switchNetwork(params) {
214
+ const { caipNetwork, provider, providerType } = params;
215
+ if (providerType === 'ID_AUTH') {
216
+ await provider.switchNetwork(caipNetwork.id);
217
+ const user = await provider.getUser({
218
+ chainId: caipNetwork.id
219
+ });
220
+ this.authSession = user;
221
+ this.emit('switchNetwork', { chainId: caipNetwork.id, address: user.address });
324
222
  }
325
- finally {
326
- this.appKit?.setLoading(false);
223
+ if (caipNetwork?.rpcUrls?.default?.http?.[0]) {
224
+ SolStoreUtil.setConnection(new Connection(caipNetwork.rpcUrls.default.http[0], this.connectionSettings));
327
225
  }
328
226
  }
329
- watchProvider(provider) {
330
- const rpcRequestHandler = (request) => {
331
- if (!this.appKit) {
332
- return;
333
- }
334
- if (W3mFrameHelpers.checkIfRequestExists(request)) {
335
- if (!W3mFrameHelpers.checkIfRequestIsSafe(request)) {
336
- this.appKit?.handleUnsafeRPCRequest();
337
- }
338
- }
339
- else {
340
- this.appKit.open();
341
- console.error(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_MESSAGE, {
342
- method: request.method
343
- });
344
- setTimeout(() => {
345
- this.appKit?.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE);
346
- }, 300);
347
- }
227
+ listenProviderEvents(provider) {
228
+ const disconnectHandler = () => {
229
+ this.removeProviderListeners(provider);
230
+ this.emit('disconnect');
348
231
  };
349
- const rpcSuccessHandler = (_response) => {
350
- if (!this.appKit) {
351
- return;
352
- }
353
- if (this.appKit.isTransactionStackEmpty()) {
354
- this.appKit.close();
355
- }
356
- else {
357
- this.appKit.popTransactionStack();
232
+ const accountsChangedHandler = (publicKey) => {
233
+ const address = publicKey.toBase58();
234
+ if (address) {
235
+ this.emit('accountChanged', { address });
358
236
  }
359
237
  };
360
- const rpcErrorHandler = (_error) => {
361
- if (!this.appKit) {
362
- return;
363
- }
364
- if (this.appKit.isOpen()) {
365
- if (this.appKit.isTransactionStackEmpty()) {
366
- this.appKit.close();
367
- }
368
- else {
369
- this.appKit.popTransactionStack(true);
370
- }
371
- }
238
+ provider.on('disconnect', disconnectHandler);
239
+ provider.on('accountsChanged', accountsChangedHandler);
240
+ provider.on('connect', accountsChangedHandler);
241
+ this.providerHandlers = {
242
+ disconnect: disconnectHandler,
243
+ accountsChanged: accountsChangedHandler
372
244
  };
373
- function disconnectHandler(appKit) {
374
- appKit?.resetAccount('solana');
375
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
376
- provider.removeListener('disconnect', disconnectHandler);
377
- provider.removeListener('accountsChanged', accountsChangedHandler);
378
- provider.removeListener('connect', accountsChangedHandler);
379
- provider.removeListener('auth_rpcRequest', rpcRequestHandler);
380
- provider.removeListener('auth_rpcSuccess', rpcSuccessHandler);
381
- provider.removeListener('auth_rpcError', rpcErrorHandler);
382
- }
383
- function accountsChangedHandler(publicKey, appKit) {
384
- const currentAccount = publicKey.toBase58();
385
- const caipNetworkId = SafeLocalStorage.getItem(SafeLocalStorageKeys.ACTIVE_CAIP_NETWORK_ID);
386
- const chainId = caipNetworkId?.split(':')[1];
387
- if (currentAccount && chainId) {
388
- appKit?.setCaipAddress(`solana:${chainId}:${currentAccount}`, 'solana');
389
- }
390
- else {
391
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
392
- appKit?.resetAccount('solana');
393
- }
245
+ }
246
+ removeProviderListeners(provider) {
247
+ if (this.providerHandlers) {
248
+ provider.removeListener('disconnect', this.providerHandlers.disconnect);
249
+ provider.removeListener('accountsChanged', this.providerHandlers.accountsChanged);
250
+ provider.removeListener('connect', this.providerHandlers.accountsChanged);
251
+ this.providerHandlers = null;
394
252
  }
395
- provider.on('disconnect', () => disconnectHandler(this.appKit));
396
- provider.on('accountsChanged', (publicKey) => accountsChangedHandler(publicKey, this.appKit));
397
- provider.on('connect', accountsChangedHandler);
398
- provider.on('auth_rpcRequest', rpcRequestHandler);
399
- provider.on('auth_rpcSuccess', rpcSuccessHandler);
400
- provider.on('auth_rpcError', rpcErrorHandler);
401
253
  }
402
- getSolanaWalletConnectProvider(provider) {
403
- const walletConnectProvider = new WalletConnectProvider({
404
- provider,
405
- chains: this.caipNetworks,
406
- getActiveChain: () => this.appKit?.getCaipNetwork()
254
+ async connectWalletConnect(onUri) {
255
+ const connector = this.connectors.find(c => c.type === 'WALLET_CONNECT');
256
+ const provider = connector?.provider;
257
+ if (!this.caipNetworks || !provider) {
258
+ throw new Error('UniversalAdapter:connectWalletConnect - caipNetworks or provider is undefined');
259
+ }
260
+ provider.on('display_uri', (uri) => {
261
+ onUri(uri);
407
262
  });
408
- this.addProvider(walletConnectProvider);
409
- return walletConnectProvider;
263
+ const namespaces = WcHelpersUtil.createNamespaces(this.caipNetworks);
264
+ await provider.connect({ optionalNamespaces: namespaces });
410
265
  }
411
- initializeProviders(opts) {
412
- if (CoreHelperUtil.isClient()) {
413
- if (!opts.projectId) {
414
- throw new Error('projectId is required for AuthProvider');
415
- }
416
- const getActiveChain = () => this.appKit?.getCaipNetwork(this.chainNamespace);
417
- const emailEnabled = this.options?.features?.email === undefined
418
- ? CoreConstantsUtil.DEFAULT_FEATURES.email
419
- : this.options?.features?.email;
420
- const socialsEnabled = this.options?.features?.socials
421
- ? this.options?.features?.socials?.length > 0
422
- : CoreConstantsUtil.DEFAULT_FEATURES.socials;
423
- if (emailEnabled || socialsEnabled) {
424
- this.w3mFrameProvider = W3mFrameProviderSingleton.getInstance({
425
- projectId: opts.projectId,
426
- chainId: withSolanaNamespace(this.appKit?.getCaipNetwork(this.chainNamespace)?.id),
427
- onTimeout: () => {
428
- AlertController.open(ErrorUtil.ALERT_ERRORS.SOCIALS_TIMEOUT, 'error');
429
- }
430
- });
431
- this.authProvider = new AuthProvider({
432
- getProvider: () => this.w3mFrameProvider,
433
- getActiveChain,
434
- getActiveNamespace: () => this.appKit?.getActiveChainNamespace(),
435
- getSession: () => this.getAuthSession(),
436
- setSession: (session) => {
437
- this.authSession = session;
438
- },
439
- chains: this.caipNetworks
440
- });
441
- this.addProvider(this.authProvider);
442
- }
443
- if ('coinbaseSolana' in window) {
444
- this.addProvider(new CoinbaseWalletProvider({
445
- provider: window.coinbaseSolana,
446
- chains: this.caipNetworks,
447
- getActiveChain
448
- }));
449
- }
450
- watchStandard(this.caipNetworks, getActiveChain, this.addProvider.bind(this));
266
+ async disconnect(params) {
267
+ if (!params.provider || !params.providerType) {
268
+ throw new Error('Provider or providerType not provided');
451
269
  }
270
+ await params.provider.disconnect();
271
+ }
272
+ async getProfile() {
273
+ return Promise.resolve({
274
+ profileName: undefined,
275
+ profileImage: undefined
276
+ });
452
277
  }
453
- addProvider(...providers) {
454
- const activeProviderName = SafeLocalStorage.getItem(SafeLocalStorageKeys.WALLET_ID);
455
- const activeNamespace = this.appKit?.getActiveChainNamespace();
456
- const isSolana = activeNamespace === this.chainNamespace;
457
- for (const provider of providers) {
458
- this.availableProviders = this.availableProviders.filter(p => p.name !== provider.name);
459
- this.availableProviders.push(provider);
460
- if (provider.name === activeProviderName && isSolana) {
461
- this.setProvider(provider);
278
+ async syncConnection(params) {
279
+ const { id, rpcUrl } = params;
280
+ const connector = this.connectors.find(c => c.id === id);
281
+ const selectedProvider = connector?.provider;
282
+ if (!selectedProvider) {
283
+ throw new Error('Provider not found');
284
+ }
285
+ if (connector?.type === 'AUTH') {
286
+ const authProvider = selectedProvider;
287
+ const user = await authProvider.getUser({
288
+ chainId: Number(this.caipNetworks?.[0]?.id)
289
+ });
290
+ if (!user?.address) {
291
+ throw new Error('No address found');
462
292
  }
293
+ return {
294
+ address: user.address,
295
+ chainId: typeof user.chainId === 'string' ? Number(user.chainId.split(':')[1]) : 1,
296
+ provider: selectedProvider,
297
+ type: connector.type,
298
+ id
299
+ };
463
300
  }
464
- this.syncConnectors();
301
+ const address = await selectedProvider.connect();
302
+ const chainId = this.caipNetworks?.[0]?.id || 1;
303
+ this.listenProviderEvents(selectedProvider);
304
+ SolStoreUtil.setConnection(new Connection(rpcUrl, 'confirmed'));
305
+ return {
306
+ address,
307
+ chainId,
308
+ provider: selectedProvider,
309
+ type: connector?.type,
310
+ id
311
+ };
465
312
  }
466
- syncConnectors() {
467
- const connectors = this.availableProviders.map(provider => ({
468
- id: provider.name,
469
- type: provider.type,
470
- imageUrl: provider.icon,
471
- name: provider.name,
472
- provider: provider.type === 'AUTH' ? provider : undefined,
473
- chain: CommonConstantsUtil.CHAIN.SOLANA
474
- }));
475
- this.appKit?.setConnectors(connectors);
313
+ getWalletConnectProvider(params) {
314
+ const walletConnectProvider = new WalletConnectProvider({
315
+ provider: params.provider,
316
+ chains: params.caipNetworks,
317
+ getActiveChain: () => params.activeCaipNetwork
318
+ });
319
+ return walletConnectProvider;
476
320
  }
477
321
  }
478
322
  //# sourceMappingURL=client.js.map