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