@reown/appkit-adapter-ethers5 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,18 +1,22 @@
1
- import { SafeLocalStorage, SafeLocalStorageKeys } from '@reown/appkit-common';
2
- import { AccountController, ChainController, CoreHelperUtil, AlertController } from '@reown/appkit-core';
3
- import { EthersHelpersUtil } from '@reown/appkit-utils/ethers';
4
- import { W3mFrameHelpers, W3mFrameProvider, W3mFrameRpcConstants } from '@reown/appkit-wallet';
5
- import { ConstantsUtil as CoreConstantsUtil } from '@reown/appkit-core';
1
+ import { AdapterBlueprint } from '@reown/appkit/adapters';
6
2
  import { ConstantsUtil as CommonConstantsUtil } from '@reown/appkit-common';
7
- import { CaipNetworksUtil, ConstantsUtil, ErrorUtil, HelpersUtil, PresetsUtil } from '@reown/appkit-utils';
3
+ import {} from '@reown/appkit-core';
4
+ import { ConstantsUtil, PresetsUtil } from '@reown/appkit-utils';
5
+ import { EthersHelpersUtil } from '@reown/appkit-utils/ethers';
6
+ import { WcConstantsUtil, WcHelpersUtil } from '@reown/appkit';
8
7
  import UniversalProvider from '@walletconnect/universal-provider';
9
- import { WcConstantsUtil } from '@reown/appkit';
8
+ import * as ethers from 'ethers';
9
+ import { CoinbaseWalletSDK } from '@coinbase/wallet-sdk';
10
10
  import { Ethers5Methods } from './utils/Ethers5Methods.js';
11
- import { ethers } from 'ethers';
11
+ import { formatEther } from 'ethers/lib/utils.js';
12
12
  import { ProviderUtil } from '@reown/appkit/store';
13
- import { CoinbaseWalletSDK } from '@coinbase/wallet-sdk';
14
- import { W3mFrameProviderSingleton } from '@reown/appkit/auth-provider';
15
- export class Ethers5Adapter {
13
+ export class Ethers5Adapter extends AdapterBlueprint {
14
+ constructor() {
15
+ super({});
16
+ this.adapterType = 'ethers';
17
+ this.providerHandlers = null;
18
+ this.namespace = CommonConstantsUtil.CHAIN.EVM;
19
+ }
16
20
  createEthersConfig(options) {
17
21
  if (!options.metadata) {
18
22
  return undefined;
@@ -59,457 +63,275 @@ export class Ethers5Adapter {
59
63
  providers.EIP6963 = options.enableEIP6963 !== false;
60
64
  return providers;
61
65
  }
62
- constructor() {
63
- this.appKit = undefined;
64
- this.EIP6963Providers = [];
65
- this.options = undefined;
66
- this.caipNetworks = [];
67
- this.chainNamespace = CommonConstantsUtil.CHAIN.EVM;
68
- this.siweControllerClient = this.options?.siweConfig;
69
- this.tokens = HelpersUtil.getCaipTokens(this.options?.tokens);
70
- this.defaultCaipNetwork = undefined;
71
- this.adapterType = 'ethers';
72
- this.providerHandlers = null;
73
- ChainController.subscribeKey('activeCaipNetwork', val => {
74
- const caipAddress = this.appKit?.getCaipAddress(this.chainNamespace);
75
- const isEVMAddress = caipAddress?.startsWith('eip155:');
76
- const isEVMNetwork = val?.chainNamespace === this.chainNamespace;
77
- if (isEVMAddress && isEVMNetwork && caipAddress) {
78
- this.syncBalance(CoreHelperUtil.getPlainAddress(caipAddress), val);
79
- this.syncAccount({
80
- address: CoreHelperUtil.getPlainAddress(caipAddress),
81
- caipNetwork: val
82
- });
83
- }
84
- });
85
- ChainController.subscribeKey('activeCaipAddress', val => {
86
- const isEVMAddress = val?.startsWith('eip155:');
87
- const caipNetwork = ChainController.state.activeCaipNetwork;
88
- const isEVMNetwork = caipNetwork?.chainNamespace === this.chainNamespace;
89
- if (isEVMAddress) {
90
- if (isEVMNetwork) {
91
- this.syncBalance(CoreHelperUtil.getPlainAddress(val), caipNetwork);
92
- }
93
- this.syncAccount({ address: CoreHelperUtil.getPlainAddress(val) });
94
- }
95
- });
96
- AccountController.subscribeKey('shouldUpdateToAddress', newAddress => {
97
- const isEVMAddress = newAddress?.startsWith('0x');
98
- if (isEVMAddress) {
99
- this.syncAccount({ address: newAddress });
100
- }
101
- }, this.chainNamespace);
102
- }
103
- construct(appKit, options) {
104
- this.appKit = appKit;
105
- this.options = options;
106
- this.caipNetworks = options.networks;
107
- this.defaultCaipNetwork = options.defaultNetwork
108
- ? CaipNetworksUtil.extendCaipNetwork(options.defaultNetwork, {
109
- customNetworkImageUrls: options.chainImages,
110
- projectId: options.projectId
111
- })
112
- : this.caipNetworks[0];
113
- this.tokens = HelpersUtil.getCaipTokens(options.tokens);
114
- this.ethersConfig = this.createEthersConfig(options);
115
- this.networkControllerClient = {
116
- switchCaipNetwork: async (caipNetwork) => {
117
- if (caipNetwork?.id) {
118
- try {
119
- await this.switchNetwork(caipNetwork);
120
- }
121
- catch (error) {
122
- throw new Error('networkControllerClient:switchCaipNetwork - unable to switch chain');
123
- }
124
- }
125
- },
126
- getApprovedCaipNetworksData: async () => this.getApprovedCaipNetworksData()
127
- };
128
- this.connectionControllerClient = {
129
- connectWalletConnect: async (onUri) => {
130
- await this.appKit?.universalAdapter?.connectionControllerClient?.connectWalletConnect?.(onUri);
131
- },
132
- connectExternal: async ({ id, info, provider }) => {
133
- this.appKit?.setClientId(null);
134
- const connectorConfig = {
135
- [ConstantsUtil.INJECTED_CONNECTOR_ID]: {
136
- getProvider: () => this.ethersConfig?.injected,
137
- providerType: 'injected'
138
- },
139
- [ConstantsUtil.EIP6963_CONNECTOR_ID]: {
140
- getProvider: () => provider,
141
- providerType: 'eip6963'
142
- },
143
- [ConstantsUtil.COINBASE_SDK_CONNECTOR_ID]: {
144
- getProvider: () => this.ethersConfig?.coinbase,
145
- providerType: 'coinbaseWalletSDK'
146
- },
147
- [ConstantsUtil.AUTH_CONNECTOR_ID]: {
148
- getProvider: () => this.authProvider,
149
- providerType: 'w3mAuth'
150
- }
151
- };
152
- const selectedConnector = connectorConfig[id];
153
- if (!selectedConnector) {
154
- throw new Error(`Unsupported connector ID: ${id}`);
155
- }
156
- const selectedProvider = selectedConnector.getProvider();
157
- if (!selectedProvider) {
158
- throw new Error(`Provider for connector ${id} is undefined`);
159
- }
160
- try {
161
- if (selectedProvider && id !== ConstantsUtil.AUTH_CONNECTOR_ID) {
162
- await selectedProvider.request({ method: 'eth_requestAccounts' });
163
- }
164
- await this.setProvider(selectedProvider, selectedConnector.providerType, info?.name);
165
- }
166
- catch (error) {
167
- if (id === ConstantsUtil.COINBASE_SDK_CONNECTOR_ID) {
168
- throw new Error(error.message);
169
- }
170
- }
171
- },
172
- checkInstalled: (ids) => {
173
- if (!ids) {
174
- return Boolean(window.ethereum);
175
- }
176
- if (this.ethersConfig?.injected) {
177
- if (!window?.ethereum) {
178
- return false;
179
- }
180
- }
181
- return ids.some(id => Boolean(window.ethereum?.[String(id)]));
182
- },
183
- disconnect: async () => {
184
- const provider = ProviderUtil.getProvider('eip155');
185
- const providerId = ProviderUtil.state.providerIds['eip155'];
186
- this.appKit?.setClientId(null);
187
- if (this.options?.siweConfig?.options?.signOutOnDisconnect) {
188
- const { SIWEController } = await import('@reown/appkit-siwe');
189
- await SIWEController.signOut();
190
- }
191
- const disconnectConfig = {
192
- [ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID]: async () => await this.appKit?.universalAdapter?.connectionControllerClient?.disconnect(),
193
- coinbaseWalletSDK: async () => {
194
- if (provider && 'disconnect' in provider) {
195
- await provider.disconnect();
196
- }
197
- },
198
- [ConstantsUtil.AUTH_CONNECTOR_ID]: async () => {
199
- await this.authProvider?.disconnect();
200
- },
201
- [ConstantsUtil.EIP6963_CONNECTOR_ID]: async () => {
202
- if (provider) {
203
- await this.revokeProviderPermissions(provider);
204
- }
205
- },
206
- [ConstantsUtil.INJECTED_CONNECTOR_ID]: async () => {
207
- if (provider) {
208
- ;
209
- provider.emit('disconnect');
210
- await this.revokeProviderPermissions(provider);
211
- }
212
- }
213
- };
214
- const disconnectFunction = disconnectConfig[providerId];
215
- if (disconnectFunction) {
216
- await disconnectFunction();
217
- }
218
- else {
219
- console.warn(`No disconnect function found for provider type: ${providerId}`);
220
- }
221
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
222
- this.appKit?.resetAccount(this.chainNamespace);
223
- this.removeListeners(provider);
224
- },
225
- signMessage: async (message) => {
226
- const provider = ProviderUtil.getProvider(this.chainNamespace);
227
- const caipAddress = ChainController.state.activeCaipAddress;
228
- const address = CoreHelperUtil.getPlainAddress(caipAddress);
229
- if (!address) {
230
- throw new Error('Address is undefined');
231
- }
232
- if (!provider) {
233
- throw new Error('Provider is undefined');
234
- }
235
- return await Ethers5Methods.signMessage(message, provider, address);
236
- },
237
- parseUnits: Ethers5Methods.parseUnits,
238
- formatUnits: Ethers5Methods.formatUnits,
239
- estimateGas: async (data) => {
240
- if (data.chainNamespace && data.chainNamespace !== 'eip155') {
241
- throw new Error(`Invalid chain namespace - Expected eip155, got ${data.chainNamespace}`);
242
- }
243
- const provider = ProviderUtil.getProvider('eip155');
244
- const caipAddress = ChainController.state.activeCaipAddress;
245
- const address = CoreHelperUtil.getPlainAddress(caipAddress);
246
- const caipNetwork = this.appKit?.getCaipNetwork();
247
- if (!address) {
248
- throw new Error('Address is undefined');
249
- }
250
- if (!provider) {
251
- throw new Error('Provider is undefined');
252
- }
253
- return await Ethers5Methods.estimateGas(data, provider, address, Number(caipNetwork?.id));
254
- },
255
- sendTransaction: async (data) => {
256
- if (data.chainNamespace && data.chainNamespace !== 'eip155') {
257
- throw new Error(`Invalid chain namespace - Expected eip155, got ${data.chainNamespace}`);
258
- }
259
- const provider = ProviderUtil.getProvider('eip155');
260
- const caipAddress = ChainController.state.activeCaipAddress;
261
- const address = CoreHelperUtil.getPlainAddress(caipAddress);
262
- const caipNetwork = this.appKit?.getCaipNetwork();
263
- if (!address) {
264
- throw new Error('Address is undefined');
265
- }
266
- if (!provider) {
267
- throw new Error('Provider is undefined');
268
- }
269
- return await Ethers5Methods.sendTransaction(data, provider, address, Number(caipNetwork?.id));
270
- },
271
- writeContract: async (data) => {
272
- const provider = ProviderUtil.getProvider('eip155');
273
- const caipAddress = ChainController.state.activeCaipAddress;
274
- const address = CoreHelperUtil.getPlainAddress(caipAddress);
275
- const caipNetwork = this.appKit?.getCaipNetwork();
276
- if (!address) {
277
- throw new Error('Address is undefined');
278
- }
279
- if (!provider) {
280
- throw new Error('Provider is undefined');
281
- }
282
- return await Ethers5Methods.writeContract(data, provider, address, Number(caipNetwork?.id));
283
- },
284
- getEnsAddress: async (value) => {
285
- if (this.appKit) {
286
- return await Ethers5Methods.getEnsAddress(value, this.appKit);
287
- }
288
- return false;
289
- },
290
- getEnsAvatar: async (value) => {
291
- const caipNetwork = this.appKit?.getCaipNetwork();
292
- return await Ethers5Methods.getEnsAvatar(value, Number(caipNetwork?.id));
293
- },
294
- grantPermissions: async (params) => {
295
- const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM);
296
- if (!provider) {
297
- throw new Error('Provider is undefined');
298
- }
299
- return await provider.request({ method: 'wallet_grantPermissions', params });
300
- },
301
- revokePermissions: async (session) => {
302
- const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM);
303
- if (!provider) {
304
- throw new Error('Provider is undefined');
305
- }
306
- return await provider.request({ method: 'wallet_revokePermissions', params: [session] });
307
- }
308
- };
309
- ChainController.state.chains.set(this.chainNamespace, {
310
- chainNamespace: this.chainNamespace,
311
- connectionControllerClient: this.connectionControllerClient,
312
- networkControllerClient: this.networkControllerClient,
313
- adapterType: this.adapterType,
314
- caipNetworks: this.caipNetworks
315
- });
316
- if (this.ethersConfig) {
317
- this.syncConnectors(this.ethersConfig);
318
- }
319
- if (typeof window !== 'undefined') {
320
- this.listenConnectors(true);
321
- }
322
- this.appKit?.setEIP6963Enabled(this.ethersConfig?.EIP6963);
323
- const emailEnabled = options.features?.email === undefined
324
- ? CoreConstantsUtil.DEFAULT_FEATURES.email
325
- : options.features?.email;
326
- const socialsEnabled = options.features?.socials
327
- ? options.features?.socials?.length > 0
328
- : CoreConstantsUtil.DEFAULT_FEATURES.socials;
329
- if (emailEnabled || socialsEnabled) {
330
- this.syncAuthConnector(this.options.projectId);
331
- }
332
- if (this.ethersConfig) {
333
- this.checkActiveProviders(this.ethersConfig);
334
- }
335
- this.syncRequestedNetworks(this.caipNetworks);
66
+ async signMessage(params) {
67
+ const { message, address, provider } = params;
68
+ if (!provider) {
69
+ throw new Error('Provider is undefined');
70
+ }
71
+ try {
72
+ const signature = await Ethers5Methods.signMessage(message, provider, address);
73
+ return { signature };
74
+ }
75
+ catch (error) {
76
+ throw new Error('EthersAdapter:signMessage - Sign message failed');
77
+ }
336
78
  }
337
- subscribeState(callback) {
338
- return this.appKit?.subscribeState(state => callback(state));
79
+ async sendTransaction(params) {
80
+ if (!params.provider) {
81
+ throw new Error('Provider is undefined');
82
+ }
83
+ const tx = await Ethers5Methods.sendTransaction({
84
+ value: params.value,
85
+ to: params.to,
86
+ data: params.data,
87
+ gas: params.gas,
88
+ gasPrice: params.gasPrice,
89
+ address: params.address
90
+ }, params.provider, params.address, Number(params.caipNetwork?.id));
91
+ return { hash: tx };
339
92
  }
340
- async disconnect() {
341
- await this.connectionControllerClient?.disconnect();
93
+ async writeContract(params) {
94
+ if (!params.provider) {
95
+ throw new Error('Provider is undefined');
96
+ }
97
+ const result = await Ethers5Methods.writeContract({
98
+ abi: params.abi,
99
+ method: params.method,
100
+ fromAddress: params.caipAddress,
101
+ receiverAddress: params.receiverAddress,
102
+ tokenAmount: params.tokenAmount,
103
+ tokenAddress: params.tokenAddress
104
+ }, params.provider, params.caipAddress, Number(params.caipNetwork?.id));
105
+ return { hash: result };
342
106
  }
343
- async revokeProviderPermissions(provider) {
107
+ async estimateGas(params) {
108
+ const { provider, caipNetwork, address } = params;
109
+ if (!provider) {
110
+ throw new Error('Provider is undefined');
111
+ }
344
112
  try {
345
- const permissions = await provider.request({
346
- method: 'wallet_getPermissions'
347
- });
348
- const ethAccountsPermission = permissions.find(permission => permission.parentCapability === 'eth_accounts');
349
- if (ethAccountsPermission) {
350
- await provider.request({
351
- method: 'wallet_revokePermissions',
352
- params: [{ eth_accounts: {} }]
353
- });
354
- }
113
+ const result = await Ethers5Methods.estimateGas({
114
+ data: params.data,
115
+ to: params.to,
116
+ address: address
117
+ }, provider, address, Number(caipNetwork?.id));
118
+ return { gas: result };
355
119
  }
356
120
  catch (error) {
357
- console.info('Could not revoke permissions from wallet. Disconnecting...', error);
121
+ throw new Error('EthersAdapter:estimateGas - Estimate gas failed');
358
122
  }
359
123
  }
360
- getApprovedCaipNetworksData() {
361
- return new Promise(resolve => {
362
- const walletId = SafeLocalStorage.getItem(SafeLocalStorageKeys.WALLET_ID);
363
- if (!walletId) {
364
- throw new Error('No wallet id found to get approved networks data');
365
- }
366
- const providerConfigs = {
367
- [ConstantsUtil.AUTH_CONNECTOR_ID]: {
368
- supportsAllNetworks: true,
369
- approvedCaipNetworkIds: PresetsUtil.WalletConnectRpcChainIds.map(id => `${ConstantsUtil.EIP155}:${id}`)
370
- }
371
- };
372
- const networkData = providerConfigs[walletId];
373
- if (networkData) {
374
- resolve(networkData);
375
- }
376
- else {
377
- resolve({
378
- supportsAllNetworks: true,
379
- approvedCaipNetworkIds: []
124
+ async getEnsAddress(params) {
125
+ const { name, caipNetwork } = params;
126
+ if (caipNetwork) {
127
+ const result = await Ethers5Methods.getEnsAddress(name, caipNetwork);
128
+ return { address: result };
129
+ }
130
+ return { address: '' };
131
+ }
132
+ parseUnits(params) {
133
+ return Ethers5Methods.parseUnits(params.value, params.decimals);
134
+ }
135
+ formatUnits(params) {
136
+ return Ethers5Methods.formatUnits(params.value, params.decimals);
137
+ }
138
+ async syncConnection(params) {
139
+ const { id, chainId } = params;
140
+ const connector = this.connectors.find(c => c.id === id);
141
+ const selectedProvider = connector?.provider;
142
+ if (!selectedProvider) {
143
+ throw new Error('Provider not found');
144
+ }
145
+ const accounts = await selectedProvider.request({
146
+ method: 'eth_requestAccounts'
147
+ });
148
+ this.listenProviderEvents(selectedProvider);
149
+ if (!accounts[0]) {
150
+ throw new Error('No accounts found');
151
+ }
152
+ if (!connector?.type) {
153
+ throw new Error('Connector type not found');
154
+ }
155
+ return {
156
+ address: accounts[0],
157
+ chainId: Number(chainId),
158
+ provider: selectedProvider,
159
+ type: connector.type,
160
+ id
161
+ };
162
+ }
163
+ syncConnectors(options) {
164
+ this.ethersConfig = this.createEthersConfig(options);
165
+ if (this.ethersConfig?.EIP6963) {
166
+ this.listenInjectedConnector(true);
167
+ }
168
+ const connectors = Object.keys(this.ethersConfig || {}).filter(key => key !== 'metadata' && key !== 'EIP6963');
169
+ connectors.forEach(connector => {
170
+ const key = connector === 'coinbase' ? 'coinbaseWalletSDK' : connector;
171
+ if (this.namespace) {
172
+ this.addConnector({
173
+ id: connector,
174
+ explorerId: PresetsUtil.ConnectorExplorerIds[key],
175
+ imageUrl: options?.connectorImages?.[key],
176
+ name: PresetsUtil.ConnectorNamesMap[key],
177
+ imageId: PresetsUtil.ConnectorImageIds[key],
178
+ type: PresetsUtil.ConnectorTypesMap[key] ?? 'EXTERNAL',
179
+ info: { rdns: key },
180
+ chain: this.namespace,
181
+ chains: [],
182
+ provider: this.ethersConfig?.[connector]
380
183
  });
381
184
  }
382
185
  });
383
186
  }
384
- checkActiveProviders(config) {
385
- const walletId = SafeLocalStorage.getItem(SafeLocalStorageKeys.WALLET_ID);
386
- const walletName = SafeLocalStorage.getItem(SafeLocalStorageKeys.WALLET_NAME);
387
- if (!walletId) {
388
- return;
389
- }
390
- const providerConfigs = {
391
- [ConstantsUtil.INJECTED_CONNECTOR_ID]: {
392
- provider: config.injected
393
- },
394
- [ConstantsUtil.COINBASE_SDK_CONNECTOR_ID]: {
395
- provider: config.coinbase
396
- },
397
- [ConstantsUtil.EIP6963_CONNECTOR_ID]: {
398
- provider: this.EIP6963Providers.find(p => p.info.name === walletName)?.provider
187
+ async connectWalletConnect(onUri) {
188
+ const connector = this.connectors.find(c => c.type === 'WALLET_CONNECT');
189
+ const provider = connector?.provider;
190
+ if (!this.caipNetworks || !provider) {
191
+ throw new Error('UniversalAdapter:connectWalletConnect - caipNetworks or provider is undefined');
192
+ }
193
+ provider.on('display_uri', (uri) => {
194
+ onUri(uri);
195
+ });
196
+ const namespaces = WcHelpersUtil.createNamespaces(this.caipNetworks);
197
+ await provider.connect({ optionalNamespaces: namespaces });
198
+ }
199
+ eip6963EventHandler(event) {
200
+ if (event.detail) {
201
+ const { info, provider } = event.detail;
202
+ const existingConnector = this.connectors?.find(c => c.name === info?.name);
203
+ const coinbaseConnector = this.connectors?.find(c => c.id === ConstantsUtil.COINBASE_SDK_CONNECTOR_ID);
204
+ const isCoinbaseDuplicated = coinbaseConnector &&
205
+ event.detail.info?.rdns ===
206
+ ConstantsUtil.CONNECTOR_RDNS_MAP[ConstantsUtil.COINBASE_SDK_CONNECTOR_ID];
207
+ if (!existingConnector && !isCoinbaseDuplicated) {
208
+ const type = PresetsUtil.ConnectorTypesMap[ConstantsUtil.EIP6963_CONNECTOR_ID];
209
+ if (type && this.namespace) {
210
+ this.addConnector({
211
+ id: info?.rdns || '',
212
+ type,
213
+ imageUrl: info?.icon,
214
+ name: info?.name,
215
+ provider,
216
+ info,
217
+ chain: this.namespace,
218
+ chains: []
219
+ });
220
+ }
399
221
  }
400
- };
401
- const activeConfig = providerConfigs[walletId];
402
- if (activeConfig?.provider) {
403
- this.setProvider(activeConfig.provider, walletId);
404
- this.setupProviderListeners(activeConfig.provider, walletId);
405
222
  }
406
223
  }
407
- async setProvider(provider, providerId, name) {
408
- if (providerId === 'w3mAuth') {
409
- this.setAuthProvider();
224
+ listenInjectedConnector(enableEIP6963) {
225
+ if (typeof window !== 'undefined' && enableEIP6963) {
226
+ const handler = this.eip6963EventHandler.bind(this);
227
+ window.addEventListener(ConstantsUtil.EIP6963_ANNOUNCE_EVENT, handler);
228
+ window.dispatchEvent(new Event(ConstantsUtil.EIP6963_REQUEST_EVENT));
229
+ }
230
+ }
231
+ async connect({ id, type, chainId }) {
232
+ const connector = this.connectors.find(c => c.id === id);
233
+ const selectedProvider = connector?.provider;
234
+ if (!selectedProvider) {
235
+ throw new Error('Provider not found');
236
+ }
237
+ let accounts = [];
238
+ if (type === 'AUTH') {
239
+ const { address } = await selectedProvider.connect({
240
+ chainId
241
+ });
242
+ accounts = [address];
410
243
  }
411
244
  else {
412
- const walletId = providerId;
413
- SafeLocalStorage.setItem(SafeLocalStorageKeys.WALLET_ID, walletId);
414
- if (name) {
415
- SafeLocalStorage.setItem(SafeLocalStorageKeys.WALLET_NAME, name);
416
- }
417
- if (provider) {
418
- const { addresses, chainId } = await EthersHelpersUtil.getUserInfo(provider);
419
- const firstAddress = addresses?.[0];
420
- const caipNetwork = this.caipNetworks.find(c => c.id === chainId) ?? this.caipNetworks[0];
421
- const caipAddress = `${this.chainNamespace}:${caipNetwork?.id}:${firstAddress}`;
422
- if (firstAddress && caipNetwork) {
423
- this.appKit?.setCaipNetwork(caipNetwork);
424
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
425
- ProviderUtil.setProviderId('eip155', providerId);
426
- ProviderUtil.setProvider('eip155', provider);
427
- this.appKit?.setStatus('connected', this.chainNamespace);
428
- this.appKit?.setAllAccounts(addresses.map(address => ({ address, type: 'eoa' })), this.chainNamespace);
429
- }
430
- }
245
+ accounts = await selectedProvider.request({
246
+ method: 'eth_requestAccounts'
247
+ });
248
+ this.listenProviderEvents(selectedProvider);
249
+ }
250
+ return {
251
+ address: accounts[0],
252
+ chainId: Number(chainId),
253
+ provider: selectedProvider,
254
+ type: type,
255
+ id
256
+ };
257
+ }
258
+ async reconnect(params) {
259
+ const { id, chainId } = params;
260
+ const connector = this.connectors.find(c => c.id === id);
261
+ if (connector && connector.type === 'AUTH' && chainId) {
262
+ await connector.provider.connect({ chainId });
431
263
  }
432
264
  }
433
- async setAuthProvider() {
434
- SafeLocalStorage.setItem(SafeLocalStorageKeys.WALLET_ID, ConstantsUtil.AUTH_CONNECTOR_ID);
435
- if (this.authProvider) {
436
- this.appKit?.setLoading(true);
437
- const { address, chainId, smartAccountDeployed, preferredAccountType, accounts = [] } = await this.authProvider.connect({
438
- chainId: Number(this.appKit?.getCaipNetwork()?.id || this.caipNetworks[0]?.id)
439
- });
440
- const { smartAccountEnabledNetworks } = await this.authProvider.getSmartAccountEnabledNetworks();
441
- this.appKit?.setSmartAccountEnabledNetworks(smartAccountEnabledNetworks, this.chainNamespace);
442
- if (address && chainId) {
443
- this.appKit?.setAllAccounts(accounts.length > 0
444
- ? accounts
445
- : [{ address, type: preferredAccountType }], this.chainNamespace);
446
- this.appKit?.setStatus('connected', this.chainNamespace);
447
- this.appKit?.setCaipAddress(`${this.chainNamespace}:${chainId}:${address}`, this.chainNamespace);
448
- this.appKit?.setPreferredAccountType(preferredAccountType, this.chainNamespace);
449
- this.appKit?.setSmartAccountDeployed(Boolean(smartAccountDeployed), this.chainNamespace);
450
- ProviderUtil.setProvider('eip155', this.authProvider);
451
- ProviderUtil.setProviderId('eip155', ConstantsUtil.AUTH_CONNECTOR_ID);
452
- this.setupProviderListeners(this.authProvider, 'w3mAuth');
453
- this.watchModal();
454
- }
455
- this.appKit?.setLoading(false);
265
+ async disconnect(params) {
266
+ if (!params.provider || !params.providerType) {
267
+ throw new Error('Provider or providerType not provided');
268
+ }
269
+ switch (params.providerType) {
270
+ case 'WALLET_CONNECT':
271
+ if (params.provider.session) {
272
+ ;
273
+ params.provider.disconnect();
274
+ }
275
+ break;
276
+ case 'AUTH':
277
+ await params.provider.disconnect();
278
+ break;
279
+ case 'ANNOUNCED':
280
+ case 'EXTERNAL':
281
+ await this.revokeProviderPermissions(params.provider);
282
+ break;
283
+ default:
284
+ throw new Error('Unsupported provider type');
456
285
  }
457
286
  }
458
- watchModal() {
459
- if (this.authProvider) {
460
- this.subscribeState(val => {
461
- if (!val.open) {
462
- this.authProvider?.rejectRpcRequests();
463
- }
287
+ async getBalance(params) {
288
+ const caipNetwork = this.caipNetworks?.find((c) => c.id === params.chainId);
289
+ if (caipNetwork) {
290
+ const jsonRpcProvider = new ethers.providers.JsonRpcProvider(caipNetwork.rpcUrls.default.http[0], {
291
+ chainId: caipNetwork.id,
292
+ name: caipNetwork.name
464
293
  });
294
+ const balance = await jsonRpcProvider.getBalance(params.address);
295
+ const formattedBalance = formatEther(balance);
296
+ return { balance: formattedBalance, symbol: caipNetwork.nativeCurrency.symbol };
465
297
  }
298
+ return { balance: '', symbol: '' };
466
299
  }
467
- setupProviderListeners(provider, providerId) {
300
+ async getProfile(params) {
301
+ if (params.chainId === 1) {
302
+ const ensProvider = new ethers.providers.InfuraProvider('mainnet');
303
+ const name = await ensProvider.lookupAddress(params.address);
304
+ const avatar = await ensProvider.getAvatar(params.address);
305
+ return { profileName: name || undefined, profileImage: avatar || undefined };
306
+ }
307
+ return { profileName: undefined, profileImage: undefined };
308
+ }
309
+ listenProviderEvents(provider) {
468
310
  const disconnectHandler = () => {
469
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
470
- this.removeListeners(provider);
311
+ this.removeProviderListeners(provider);
312
+ this.emit('disconnect');
471
313
  };
472
314
  const accountsChangedHandler = (accounts) => {
473
- const currentAccount = accounts?.[0];
474
- if (currentAccount) {
475
- const chainId = this.appKit?.getCaipNetwork()?.id;
476
- const caipAddress = `${this.chainNamespace}:${chainId}:${currentAccount}`;
477
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
478
- if (providerId === ConstantsUtil.EIP6963_CONNECTOR_ID) {
479
- this.appKit?.setAllAccounts(accounts.map(address => ({ address, type: 'eoa' })), this.chainNamespace);
480
- }
481
- }
482
- else {
483
- if (providerId === ConstantsUtil.EIP6963_CONNECTOR_ID) {
484
- this.appKit?.setAllAccounts([], this.chainNamespace);
485
- }
486
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
487
- this.appKit?.resetAccount(this.chainNamespace);
315
+ if (accounts.length > 0) {
316
+ this.emit('accountChanged', {
317
+ address: accounts[0]
318
+ });
488
319
  }
489
320
  };
490
321
  const chainChangedHandler = (chainId) => {
491
322
  const chainIdNumber = typeof chainId === 'string' ? EthersHelpersUtil.hexStringToNumber(chainId) : Number(chainId);
492
- const caipNetwork = this.caipNetworks.find(c => c.id === chainIdNumber);
493
- const currentCaipNetwork = this.appKit?.getCaipNetwork();
494
- if (!currentCaipNetwork || currentCaipNetwork?.id !== caipNetwork?.id) {
495
- this.appKit?.setCaipNetwork(caipNetwork);
496
- }
323
+ this.emit('switchNetwork', { chainId: chainIdNumber });
497
324
  };
498
- if (providerId === ConstantsUtil.AUTH_CONNECTOR_ID) {
499
- this.setupAuthListeners(provider);
500
- }
501
- else {
502
- provider.on('disconnect', disconnectHandler);
503
- provider.on('accountsChanged', accountsChangedHandler);
504
- provider.on('chainChanged', chainChangedHandler);
505
- }
325
+ provider.on('disconnect', disconnectHandler);
326
+ provider.on('accountsChanged', accountsChangedHandler);
327
+ provider.on('chainChanged', chainChangedHandler);
506
328
  this.providerHandlers = {
507
329
  disconnect: disconnectHandler,
508
330
  accountsChanged: accountsChangedHandler,
509
331
  chainChanged: chainChangedHandler
510
332
  };
511
333
  }
512
- removeListeners(provider) {
334
+ removeProviderListeners(provider) {
513
335
  if (this.providerHandlers) {
514
336
  provider.removeListener('disconnect', this.providerHandlers.disconnect);
515
337
  provider.removeListener('accountsChanged', this.providerHandlers.accountsChanged);
@@ -517,212 +339,20 @@ export class Ethers5Adapter {
517
339
  this.providerHandlers = null;
518
340
  }
519
341
  }
520
- setupAuthListeners(authProvider) {
521
- authProvider.onRpcRequest(request => {
522
- if (W3mFrameHelpers.checkIfRequestExists(request)) {
523
- if (!W3mFrameHelpers.checkIfRequestIsSafe(request)) {
524
- this.appKit?.handleUnsafeRPCRequest();
525
- }
526
- }
527
- else {
528
- this.handleInvalidAuthRequest();
529
- }
530
- });
531
- authProvider.onRpcError(() => this.handleAuthRpcError());
532
- authProvider.onRpcSuccess((_, request) => this.handleAuthRpcSuccess(_, request));
533
- authProvider.onNotConnected(() => this.handleAuthNotConnected());
534
- authProvider.onConnect(({ preferredAccountType }) => this.handleAuthIsConnected(preferredAccountType));
535
- authProvider.onSetPreferredAccount(({ address, type }) => {
536
- if (address) {
537
- this.handleAuthSetPreferredAccount(address, type);
538
- }
539
- });
540
- }
541
- handleInvalidAuthRequest() {
542
- this.appKit?.open();
543
- setTimeout(() => {
544
- this.appKit?.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE);
545
- }, 300);
546
- }
547
- handleAuthRpcError() {
548
- if (this.appKit?.isOpen()) {
549
- if (this.appKit?.isTransactionStackEmpty()) {
550
- this.appKit?.close();
551
- }
552
- else {
553
- this.appKit?.popTransactionStack(true);
554
- }
555
- }
556
- }
557
- handleAuthRpcSuccess(_, request) {
558
- const isSafeRequest = W3mFrameHelpers.checkIfRequestIsSafe(request);
559
- if (isSafeRequest) {
560
- return;
561
- }
562
- if (this.appKit?.isTransactionStackEmpty()) {
563
- this.appKit?.close();
564
- }
565
- else {
566
- this.appKit?.popTransactionStack();
567
- }
568
- }
569
- handleAuthNotConnected() {
570
- this.appKit?.setCaipAddress(undefined, this.chainNamespace);
571
- }
572
- handleAuthIsConnected(preferredAccountType) {
573
- const activeNamespace = this.appKit?.getActiveChainNamespace();
574
- if (activeNamespace !== this.chainNamespace) {
575
- return;
576
- }
577
- this.appKit?.setPreferredAccountType(preferredAccountType, this.chainNamespace);
578
- }
579
- handleAuthSetPreferredAccount(address, type) {
580
- if (!address) {
581
- return;
582
- }
583
- this.appKit?.setLoading(true);
584
- const chainId = this.appKit?.getCaipNetwork()?.id;
585
- this.appKit?.setCaipAddress(`${this.chainNamespace}:${chainId}:${address}`, this.chainNamespace);
586
- this.appKit?.setStatus('connected', this.chainNamespace);
587
- this.appKit?.setPreferredAccountType(type, this.chainNamespace);
588
- this.syncAccount({
589
- address: address
590
- }).then(() => this.appKit?.setLoading(false));
591
- this.appKit?.setLoading(false);
592
- }
593
- async syncReownName(address) {
594
- try {
595
- const registeredWcNames = await this.appKit?.getReownName(address);
596
- if (registeredWcNames?.[0]) {
597
- const wcName = registeredWcNames[0];
598
- this.appKit?.setProfileName(wcName.name, this.chainNamespace);
599
- }
600
- else {
601
- this.appKit?.setProfileName(null, this.chainNamespace);
602
- }
603
- }
604
- catch {
605
- this.appKit?.setProfileName(null, this.chainNamespace);
606
- }
607
- }
608
- async syncAccount({ address, caipNetwork }) {
609
- const currentCaipNetwork = caipNetwork || this.appKit?.getCaipNetwork();
610
- const preferredAccountType = this.appKit?.getPreferredAccountType();
611
- const isEipNetwork = currentCaipNetwork?.chainNamespace === CommonConstantsUtil.CHAIN.EVM;
612
- const caipNetworkId = currentCaipNetwork?.id;
613
- if (address) {
614
- if (isEipNetwork) {
615
- this.appKit?.setPreferredAccountType(preferredAccountType, this.chainNamespace);
616
- this.appKit?.setCaipAddress(`${this.chainNamespace}:${caipNetworkId}:${address}`, this.chainNamespace);
617
- this.syncConnectedWalletInfo();
618
- if (currentCaipNetwork?.blockExplorers) {
619
- this.appKit?.setAddressExplorerUrl(`${currentCaipNetwork.blockExplorers.default.url}/address/${address}`, this.chainNamespace);
620
- }
621
- await Promise.all([
622
- this.syncProfile(address),
623
- this.appKit?.setApprovedCaipNetworksData(this.chainNamespace)
624
- ]);
625
- }
626
- }
627
- else {
628
- this.appKit?.resetWcConnection();
629
- this.appKit?.resetNetwork(this.chainNamespace);
630
- this.appKit?.setAllAccounts([], this.chainNamespace);
631
- }
632
- }
633
- async syncProfile(address) {
634
- const caipNetwork = this.appKit?.getCaipNetwork();
635
- try {
636
- const identity = await this.appKit?.fetchIdentity({
637
- address
342
+ async switchNetwork(params) {
343
+ const { caipNetwork, provider, providerType } = params;
344
+ if (providerType === 'WALLET_CONNECT') {
345
+ ;
346
+ provider.setDefaultChain(String(`eip155:${String(caipNetwork.id)}`));
347
+ }
348
+ else if (providerType === 'AUTH') {
349
+ const authProvider = provider;
350
+ await authProvider.switchNetwork(caipNetwork.id);
351
+ await authProvider.connect({
352
+ chainId: caipNetwork.id
638
353
  });
639
- const name = identity?.name;
640
- const avatar = identity?.avatar;
641
- this.appKit?.setProfileName(name, this.chainNamespace);
642
- this.appKit?.setProfileImage(avatar, this.chainNamespace);
643
- if (!name) {
644
- await this.syncReownName(address);
645
- }
646
354
  }
647
- catch {
648
- if (caipNetwork?.id === 1) {
649
- const ensProvider = new ethers.providers.InfuraProvider('mainnet');
650
- const name = await ensProvider.lookupAddress(address);
651
- const avatar = await ensProvider.getAvatar(address);
652
- if (name) {
653
- this.appKit?.setProfileName(name, this.chainNamespace);
654
- }
655
- else {
656
- await this.syncReownName(address);
657
- }
658
- if (avatar) {
659
- this.appKit?.setProfileImage(avatar, this.chainNamespace);
660
- }
661
- }
662
- else {
663
- await this.syncReownName(address);
664
- this.appKit?.setProfileImage(null, this.chainNamespace);
665
- }
666
- }
667
- }
668
- async syncBalance(address, caipNetwork) {
669
- const isExistingNetwork = this.appKit
670
- ?.getCaipNetworks(caipNetwork.chainNamespace)
671
- .find(network => network.id === caipNetwork.id);
672
- const isEVMNetwork = caipNetwork.chainNamespace === CommonConstantsUtil.CHAIN.EVM;
673
- if (caipNetwork && isExistingNetwork && isEVMNetwork) {
674
- const jsonRpcProvider = new ethers.providers.JsonRpcProvider(caipNetwork.rpcUrls.default.http[0], {
675
- chainId: caipNetwork.id,
676
- name: caipNetwork.name
677
- });
678
- if (jsonRpcProvider) {
679
- const balance = await jsonRpcProvider.getBalance(address);
680
- const formattedBalance = ethers.utils.formatEther(balance);
681
- this.appKit?.setBalance(formattedBalance, caipNetwork.nativeCurrency.symbol, this.chainNamespace);
682
- }
683
- }
684
- }
685
- syncConnectedWalletInfo() {
686
- const currentActiveWallet = SafeLocalStorage.getItem(SafeLocalStorageKeys.WALLET_ID);
687
- const providerType = ProviderUtil.state.providerIds['eip155'];
688
- if (providerType === ConstantsUtil.EIP6963_CONNECTOR_ID) {
689
- if (currentActiveWallet) {
690
- const currentProvider = this.EIP6963Providers.find(provider => provider.info.name === currentActiveWallet);
691
- if (currentProvider) {
692
- this.appKit?.setConnectedWalletInfo({ ...currentProvider.info }, this.chainNamespace);
693
- }
694
- }
695
- }
696
- else if (providerType === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID) {
697
- const provider = ProviderUtil.getProvider('eip155');
698
- if (provider?.session) {
699
- this.appKit?.setConnectedWalletInfo({
700
- ...provider.session.peer.metadata,
701
- name: provider.session.peer.metadata.name,
702
- icon: provider.session.peer.metadata.icons?.[0]
703
- }, this.chainNamespace);
704
- }
705
- }
706
- else if (providerType === ConstantsUtil.COINBASE_SDK_CONNECTOR_ID) {
707
- const connector = this.appKit
708
- ?.getConnectors()
709
- .find(c => c.id === ConstantsUtil.COINBASE_SDK_CONNECTOR_ID);
710
- this.appKit?.setConnectedWalletInfo({ name: 'Coinbase Wallet', icon: this.appKit?.getConnectorImage(connector) }, this.chainNamespace);
711
- }
712
- else if (currentActiveWallet) {
713
- this.appKit?.setConnectedWalletInfo({ name: currentActiveWallet }, this.chainNamespace);
714
- }
715
- }
716
- syncRequestedNetworks(caipNetworks) {
717
- const uniqueChainNamespaces = [
718
- ...new Set(caipNetworks.map(caipNetwork => caipNetwork.chainNamespace))
719
- ];
720
- uniqueChainNamespaces.forEach(chainNamespace => {
721
- this.appKit?.setRequestedCaipNetworks(caipNetworks.filter(caipNetwork => caipNetwork.chainNamespace === chainNamespace), chainNamespace);
722
- });
723
- }
724
- async switchNetwork(caipNetwork) {
725
- async function requestSwitchNetwork(provider) {
355
+ else {
726
356
  try {
727
357
  await provider.request({
728
358
  method: 'wallet_switchEthereumChain',
@@ -736,147 +366,62 @@ export class Ethers5Adapter {
736
366
  WcConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID) {
737
367
  await EthersHelpersUtil.addEthereumChain(provider, caipNetwork);
738
368
  }
739
- else {
369
+ else if (providerType === 'ANNOUNCED' ||
370
+ providerType === 'EXTERNAL' ||
371
+ providerType === 'INJECTED') {
740
372
  throw new Error('Chain is not supported');
741
373
  }
742
374
  }
743
375
  }
744
- const provider = ProviderUtil.getProvider('eip155');
745
- const providerType = ProviderUtil.state.providerIds['eip155'];
746
- if (provider) {
747
- switch (providerType) {
748
- case ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID:
749
- this.appKit?.universalAdapter?.networkControllerClient.switchCaipNetwork(caipNetwork);
750
- break;
751
- case ConstantsUtil.INJECTED_CONNECTOR_ID:
752
- case ConstantsUtil.EIP6963_CONNECTOR_ID:
753
- case ConstantsUtil.COINBASE_SDK_CONNECTOR_ID:
754
- if (provider) {
755
- await requestSwitchNetwork(provider);
756
- }
757
- break;
758
- case ConstantsUtil.AUTH_CONNECTOR_ID:
759
- if (this.authProvider) {
760
- try {
761
- this.appKit?.setLoading(true);
762
- const { chainId } = await this.authProvider.switchNetwork(caipNetwork.id);
763
- const { address, preferredAccountType } = await this.authProvider.connect({
764
- chainId: caipNetwork.id
765
- });
766
- const caipAddress = `${this.chainNamespace}:${chainId}:${address}`;
767
- this.appKit?.setCaipNetwork(caipNetwork);
768
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
769
- this.appKit?.setPreferredAccountType(preferredAccountType, this.chainNamespace);
770
- await this.syncAccount({ address: address });
771
- this.appKit?.setLoading(false);
772
- }
773
- catch {
774
- throw new Error('Switching chain failed');
775
- }
776
- finally {
777
- this.appKit?.setLoading(false);
778
- }
779
- }
780
- break;
781
- default:
782
- throw new Error('Unsupported provider type');
783
- }
784
- }
785
376
  }
786
- syncConnectors(config) {
787
- const w3mConnectors = [];
788
- if (config.injected) {
789
- const injectedConnectorType = PresetsUtil.ConnectorTypesMap[ConstantsUtil.INJECTED_CONNECTOR_ID];
790
- if (injectedConnectorType) {
791
- w3mConnectors.push({
792
- id: ConstantsUtil.INJECTED_CONNECTOR_ID,
793
- explorerId: PresetsUtil.ConnectorExplorerIds[ConstantsUtil.INJECTED_CONNECTOR_ID],
794
- imageId: PresetsUtil.ConnectorImageIds[ConstantsUtil.INJECTED_CONNECTOR_ID],
795
- imageUrl: this.options?.connectorImages?.[ConstantsUtil.INJECTED_CONNECTOR_ID],
796
- name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.INJECTED_CONNECTOR_ID],
797
- type: injectedConnectorType,
798
- chain: this.chainNamespace
377
+ getWalletConnectProvider() {
378
+ return this.connectors.find(c => c.type === 'WALLET_CONNECT')?.provider;
379
+ }
380
+ async revokeProviderPermissions(provider) {
381
+ try {
382
+ const permissions = await provider.request({
383
+ method: 'wallet_getPermissions'
384
+ });
385
+ const ethAccountsPermission = permissions.find(permission => permission.parentCapability === 'eth_accounts');
386
+ if (ethAccountsPermission) {
387
+ await provider.request({
388
+ method: 'wallet_revokePermissions',
389
+ params: [{ eth_accounts: {} }]
799
390
  });
800
391
  }
801
392
  }
802
- if (config.coinbase) {
803
- w3mConnectors.push({
804
- id: ConstantsUtil.COINBASE_SDK_CONNECTOR_ID,
805
- explorerId: PresetsUtil.ConnectorExplorerIds[ConstantsUtil.COINBASE_SDK_CONNECTOR_ID],
806
- imageId: PresetsUtil.ConnectorImageIds[ConstantsUtil.COINBASE_SDK_CONNECTOR_ID],
807
- imageUrl: this.options?.connectorImages?.[ConstantsUtil.COINBASE_SDK_CONNECTOR_ID],
808
- name: PresetsUtil.ConnectorNamesMap[ConstantsUtil.COINBASE_SDK_CONNECTOR_ID],
809
- type: 'EXTERNAL',
810
- chain: this.chainNamespace
811
- });
393
+ catch (error) {
394
+ console.info('Could not revoke permissions from wallet. Disconnecting...', error);
812
395
  }
813
- this.appKit?.setConnectors(w3mConnectors);
814
396
  }
815
- async syncAuthConnector(projectId, bypassWindowCheck = false) {
816
- if (bypassWindowCheck || typeof window !== 'undefined') {
817
- this.authProvider = W3mFrameProviderSingleton.getInstance({
818
- projectId,
819
- onTimeout: () => {
820
- AlertController.open(ErrorUtil.ALERT_ERRORS.SOCIALS_TIMEOUT, 'error');
821
- }
822
- });
823
- this.appKit?.addConnector({
824
- id: ConstantsUtil.AUTH_CONNECTOR_ID,
825
- type: 'AUTH',
826
- name: 'Auth',
827
- provider: this.authProvider,
828
- chain: this.chainNamespace
829
- });
830
- this.appKit?.setLoading(true);
831
- const isLoginEmailUsed = this.authProvider.getLoginEmailUsed();
832
- this.appKit?.setLoading(isLoginEmailUsed);
833
- if (isLoginEmailUsed) {
834
- const { isConnected } = await this.authProvider.isConnected();
835
- if (isConnected) {
836
- await this.setAuthProvider();
837
- }
838
- else {
839
- this.appKit?.setLoading(false);
840
- }
397
+ async getCapabilities(params) {
398
+ const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM);
399
+ if (!provider) {
400
+ throw new Error('Provider is undefined');
401
+ }
402
+ const walletCapabilitiesString = provider.session?.sessionProperties?.['capabilities'];
403
+ if (walletCapabilitiesString) {
404
+ const walletCapabilities = Ethers5Methods.parseWalletCapabilities(walletCapabilitiesString);
405
+ const accountCapabilities = walletCapabilities[params];
406
+ if (accountCapabilities) {
407
+ return accountCapabilities;
841
408
  }
842
409
  }
410
+ return await provider.request({ method: 'wallet_getCapabilities', params: [params] });
843
411
  }
844
- eip6963EventHandler(event) {
845
- if (event.detail) {
846
- const { info, provider } = event.detail;
847
- const connectors = this.appKit?.getConnectors();
848
- const existingConnector = connectors?.find(c => c.name === info.name);
849
- const coinbaseConnector = connectors?.find(c => c.id === ConstantsUtil.COINBASE_SDK_CONNECTOR_ID);
850
- const isCoinbaseDuplicated = coinbaseConnector &&
851
- event.detail.info.rdns ===
852
- ConstantsUtil.CONNECTOR_RDNS_MAP[ConstantsUtil.COINBASE_SDK_CONNECTOR_ID];
853
- if (!existingConnector && !isCoinbaseDuplicated) {
854
- const type = PresetsUtil.ConnectorTypesMap[ConstantsUtil.EIP6963_CONNECTOR_ID];
855
- if (type) {
856
- this.appKit?.addConnector({
857
- id: ConstantsUtil.EIP6963_CONNECTOR_ID,
858
- type,
859
- imageUrl: info.icon ?? this.options?.connectorImages?.[ConstantsUtil.EIP6963_CONNECTOR_ID],
860
- name: info.name,
861
- provider,
862
- info,
863
- chain: this.chainNamespace
864
- });
865
- const eip6963ProviderObj = {
866
- provider,
867
- info
868
- };
869
- this.EIP6963Providers.push(eip6963ProviderObj);
870
- }
871
- }
412
+ async grantPermissions(params) {
413
+ const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM);
414
+ if (!provider) {
415
+ throw new Error('Provider is undefined');
872
416
  }
417
+ return await provider.request({ method: 'wallet_grantPermissions', params });
873
418
  }
874
- listenConnectors(enableEIP6963) {
875
- if (typeof window !== 'undefined' && enableEIP6963) {
876
- const handler = this.eip6963EventHandler.bind(this);
877
- window.addEventListener(ConstantsUtil.EIP6963_ANNOUNCE_EVENT, handler);
878
- window.dispatchEvent(new Event(ConstantsUtil.EIP6963_REQUEST_EVENT));
419
+ async revokePermissions(params) {
420
+ const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM);
421
+ if (!provider) {
422
+ throw new Error('Provider is undefined');
879
423
  }
424
+ return await provider.request({ method: 'wallet_revokePermissions', params: [params] });
880
425
  }
881
426
  }
882
427
  //# sourceMappingURL=client.js.map