@reown/appkit-adapter-wagmi 1.3.2 → 1.4.1

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,54 +1,37 @@
1
- import { connect, disconnect, signMessage, getBalance, getEnsAvatar as wagmiGetEnsAvatar, getEnsName, watchAccount, watchConnectors, estimateGas as wagmiEstimateGas, writeContract as wagmiWriteContract, getAccount, getEnsAddress as wagmiGetEnsAddress, reconnect, switchChain, waitForTransactionReceipt, getConnections, switchAccount, injected, createConfig } from '@wagmi/core';
2
- import { ChainController, ConstantsUtil as CoreConstantsUtil, CoreHelperUtil, StorageUtil } from '@reown/appkit-core';
3
- import { prepareTransactionRequest, sendTransaction as wagmiSendTransaction } from '@wagmi/core';
4
- import { mainnet } from 'viem/chains';
5
- import { formatUnits, parseUnits } from 'viem';
6
- import { ConstantsUtil, PresetsUtil, HelpersUtil, ErrorUtil, CaipNetworksUtil } from '@reown/appkit-utils';
7
- import { isReownName, SafeLocalStorage, SafeLocalStorageKeys } from '@reown/appkit-common';
8
- import { getEmailCaipNetworks, getWalletConnectCaipNetworks, parseWalletCapabilities, requireCaipAddress } from './utils/helpers.js';
9
- import { W3mFrameHelpers, W3mFrameRpcConstants } from '@reown/appkit-wallet';
10
- import { NetworkUtil } from '@reown/appkit-common';
11
- import { normalize } from 'viem/ens';
12
- import { ConstantsUtil as CommonConstantsUtil } from '@reown/appkit-common';
1
+ import { AdapterBlueprint } from '@reown/appkit/adapters';
2
+ import { connect, disconnect as wagmiDisconnect, createConfig, getConnections, switchChain, injected, watchAccount, watchConnections, getBalance, getEnsName, getEnsAvatar, signMessage, estimateGas as wagmiEstimateGas, sendTransaction as wagmiSendTransaction, getEnsAddress as wagmiGetEnsAddress, writeContract as wagmiWriteContract, waitForTransactionReceipt, getAccount, prepareTransactionRequest, reconnect } from '@wagmi/core';
3
+ import {} from '@wagmi/core/chains';
4
+ import { ConstantsUtil as CommonConstantsUtil, isReownName, NetworkUtil } from '@reown/appkit-common';
5
+ import { authConnector } from './connectors/AuthConnector.js';
6
+ import { AppKit, WcHelpersUtil } from '@reown/appkit';
13
7
  import { walletConnect } from './connectors/UniversalConnector.js';
14
8
  import { coinbaseWallet } from '@wagmi/connectors';
15
- import { authConnector } from './connectors/AuthConnector.js';
16
- import { ProviderUtil } from '@reown/appkit/store';
17
- const OPTIONAL_METHODS = [
18
- 'eth_accounts',
19
- 'eth_requestAccounts',
20
- 'eth_sendRawTransaction',
21
- 'eth_sign',
22
- 'eth_signTransaction',
23
- 'eth_signTypedData',
24
- 'eth_signTypedData_v3',
25
- 'eth_signTypedData_v4',
26
- 'eth_sendTransaction',
27
- 'personal_sign',
28
- 'wallet_switchEthereumChain',
29
- 'wallet_addEthereumChain',
30
- 'wallet_getPermissions',
31
- 'wallet_requestPermissions',
32
- 'wallet_registerOnboarding',
33
- 'wallet_watchAsset',
34
- 'wallet_scanQRCode',
35
- 'wallet_getCallsStatus',
36
- 'wallet_sendCalls',
37
- 'wallet_getCapabilities',
38
- 'wallet_grantPermissions'
39
- ];
40
- export class WagmiAdapter {
9
+ import { ConstantsUtil as CoreConstantsUtil } from '@reown/appkit-core';
10
+ import { CaipNetworksUtil, ConstantsUtil, PresetsUtil } from '@reown/appkit-utils';
11
+ import { formatUnits, parseUnits } from 'viem';
12
+ import { normalize } from 'viem/ens';
13
+ import { parseWalletCapabilities } from './utils/helpers.js';
14
+ export class WagmiAdapter extends AdapterBlueprint {
41
15
  constructor(configParams) {
42
- this.appKit = undefined;
43
- this.options = undefined;
44
- this.chainNamespace = CommonConstantsUtil.CHAIN.EVM;
45
- this.defaultCaipNetwork = undefined;
46
- this.tokens = HelpersUtil.getCaipTokens(this.options?.tokens);
47
- this.siweControllerClient = this.options?.siweConfig;
16
+ super({
17
+ projectId: configParams.projectId,
18
+ networks: CaipNetworksUtil.extendCaipNetworks(configParams.networks, {
19
+ projectId: configParams.projectId,
20
+ customNetworkImageUrls: {}
21
+ })
22
+ });
48
23
  this.adapterType = 'wagmi';
49
- if (!configParams.projectId) {
50
- throw new Error(ErrorUtil.ALERT_ERRORS.PROJECT_ID_NOT_CONFIGURED.shortMessage);
51
- }
24
+ this.namespace = CommonConstantsUtil.CHAIN.EVM;
25
+ this.createConfig({
26
+ networks: CaipNetworksUtil.extendCaipNetworks(configParams.networks, {
27
+ projectId: configParams.projectId,
28
+ customNetworkImageUrls: {}
29
+ }),
30
+ projectId: configParams.projectId
31
+ });
32
+ this.setupWatchers();
33
+ }
34
+ createConfig(configParams) {
52
35
  this.caipNetworks = CaipNetworksUtil.extendCaipNetworks(configParams.networks, {
53
36
  projectId: configParams.projectId,
54
37
  customNetworkImageUrls: {}
@@ -75,23 +58,34 @@ export class WagmiAdapter {
75
58
  transports,
76
59
  connectors
77
60
  });
78
- ChainController.subscribeKey('activeCaipAddress', val => {
79
- const isEVMAddress = val?.startsWith('eip155:');
80
- const caipNetwork = ChainController.state.activeCaipNetwork;
81
- const isEVMNetwork = caipNetwork?.chainNamespace === this.chainNamespace;
82
- if (caipNetwork && isEVMAddress && isEVMNetwork) {
83
- this.setProfileAndBalance(CoreHelperUtil.getPlainAddress(val), Number(caipNetwork.id));
61
+ }
62
+ setupWatchers() {
63
+ watchAccount(this.wagmiConfig, {
64
+ onChange: accountData => {
65
+ if (accountData.address) {
66
+ this.emit('accountChanged', {
67
+ address: accountData.address,
68
+ chainId: accountData.chainId
69
+ });
70
+ }
71
+ if (accountData.chainId) {
72
+ this.emit('switchNetwork', {
73
+ address: accountData.address,
74
+ chainId: accountData.chainId
75
+ });
76
+ }
77
+ }
78
+ });
79
+ watchConnections(this.wagmiConfig, {
80
+ onChange: connections => {
81
+ if (connections.length === 0) {
82
+ this.emit('disconnect');
83
+ }
84
84
  }
85
85
  });
86
86
  }
87
- setCustomConnectors(options, appKit) {
87
+ addWagmiConnectors(options, appKit) {
88
88
  const customConnectors = [];
89
- if (options.enableWalletConnect !== false) {
90
- customConnectors.push(walletConnect(options, appKit, this.caipNetworks));
91
- }
92
- if (options.enableInjected !== false) {
93
- customConnectors.push(injected({ shimDisconnect: true }));
94
- }
95
89
  if (options.enableCoinbase !== false) {
96
90
  customConnectors.push(coinbaseWallet({
97
91
  version: '4',
@@ -100,6 +94,12 @@ export class WagmiAdapter {
100
94
  preference: options.coinbasePreference ?? 'all'
101
95
  }));
102
96
  }
97
+ if (options.enableWalletConnect !== false) {
98
+ customConnectors.push(walletConnect(options, appKit, this.caipNetworks));
99
+ }
100
+ if (options.enableInjected !== false) {
101
+ customConnectors.push(injected({ shimDisconnect: true }));
102
+ }
103
103
  const emailEnabled = options.features?.email === undefined
104
104
  ? CoreConstantsUtil.DEFAULT_FEATURES.email
105
105
  : options.features?.email;
@@ -109,7 +109,9 @@ export class WagmiAdapter {
109
109
  if (emailEnabled || socialsEnabled) {
110
110
  customConnectors.push(authConnector({
111
111
  chains: this.wagmiChains,
112
- options: { projectId: options.projectId }
112
+ options: { projectId: options.projectId },
113
+ provider: this.availableConnectors.find(c => c.id === ConstantsUtil.AUTH_CONNECTOR_ID)
114
+ ?.provider
113
115
  }));
114
116
  }
115
117
  customConnectors.forEach(connector => {
@@ -117,674 +119,272 @@ export class WagmiAdapter {
117
119
  this.wagmiConfig._internal.connectors.setState(prev => [...prev, cnctr]);
118
120
  });
119
121
  }
120
- construct(appKit, options) {
121
- this.appKit = appKit;
122
- this.options = options;
123
- this.caipNetworks = options.networks;
124
- this.defaultCaipNetwork = options.defaultNetwork || options.networks?.[0];
125
- this.tokens = HelpersUtil.getCaipTokens(options.tokens);
126
- this.setCustomConnectors(options, appKit);
127
- if (!this.wagmiConfig) {
128
- throw new Error('appkit:wagmiConfig - is undefined');
122
+ async signMessage(params) {
123
+ try {
124
+ const signature = await signMessage(this.wagmiConfig, {
125
+ message: params.message,
126
+ account: params.address
127
+ });
128
+ return { signature };
129
+ }
130
+ catch (error) {
131
+ throw new Error('WagmiAdapter:signMessage - Sign message failed');
129
132
  }
130
- this.networkControllerClient = {
131
- switchCaipNetwork: async (caipNetwork) => {
132
- const chainId = caipNetwork?.id;
133
- if (chainId && this.wagmiConfig) {
134
- await switchChain(this.wagmiConfig, { chainId });
135
- }
136
- },
137
- getApprovedCaipNetworksData: async () => {
138
- if (!this.wagmiConfig) {
139
- throw new Error('networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined');
140
- }
141
- return new Promise(resolve => {
142
- const connections = new Map(this.wagmiConfig.state.connections);
143
- const connection = connections.get(this.wagmiConfig.state.current || '');
144
- if (connection?.connector?.id === ConstantsUtil.AUTH_CONNECTOR_ID) {
145
- resolve(getEmailCaipNetworks());
146
- }
147
- else if (connection?.connector?.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID) {
148
- const connector = this.wagmiConfig.connectors.find(c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID);
149
- resolve(getWalletConnectCaipNetworks(connector));
150
- }
151
- resolve({ approvedCaipNetworkIds: [], supportsAllNetworks: true });
152
- });
153
- }
154
- };
155
- this.connectionControllerClient = {
156
- connectWalletConnect: async () => {
157
- if (!this.wagmiConfig) {
158
- throw new Error('connectionControllerClient:getWalletConnectUri - wagmiConfig is undefined');
159
- }
160
- const connector = this.wagmiConfig.connectors.find(c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID);
161
- if (!connector) {
162
- throw new Error('connectionControllerClient:getWalletConnectUri - connector is undefined');
163
- }
164
- const provider = (await connector.getProvider());
165
- const clientId = await provider?.client?.core?.crypto?.getClientId();
166
- if (clientId) {
167
- this.appKit?.setClientId(clientId);
168
- }
169
- const siweParams = await this.options?.siweConfig?.getMessageParams?.();
170
- const isSiweEnabled = this.options?.siweConfig?.options?.enabled;
171
- const isProviderSupported = typeof provider?.authenticate === 'function';
172
- const isSiweParamsValid = siweParams && Object.keys(siweParams || {}).length > 0;
173
- const siweConfig = this.options?.siweConfig;
174
- if (isSiweEnabled && isProviderSupported && isSiweParamsValid && siweConfig) {
175
- await connector.setRequestedChainsIds(siweParams.chains);
176
- const { SIWEController, getDidChainId, getDidAddress } = await import('@reown/appkit-siwe');
177
- const chains = this.caipNetworks
178
- ?.filter(network => network.chainNamespace === 'eip155')
179
- .map(chain => chain.caipNetworkId);
180
- siweParams.chains = this.caipNetworks
181
- ?.filter(network => network.chainNamespace === 'eip155')
182
- .map(chain => chain.id);
183
- const result = await provider.authenticate({
184
- nonce: await siweConfig.getNonce(),
185
- methods: [...OPTIONAL_METHODS],
186
- ...siweParams,
187
- chains
188
- });
189
- const signedCacao = result?.auths?.[0];
190
- if (signedCacao) {
191
- const { p, s } = signedCacao;
192
- const cacaoChainId = getDidChainId(p.iss);
193
- const address = getDidAddress(p.iss);
194
- if (address && cacaoChainId) {
195
- SIWEController.setSession({
196
- address,
197
- chainId: parseInt(cacaoChainId, 10)
198
- });
199
- }
200
- try {
201
- const message = provider.client.formatAuthMessage({
202
- request: p,
203
- iss: p.iss
204
- });
205
- await SIWEController.verifyMessage({
206
- message,
207
- signature: s.s,
208
- cacao: signedCacao
209
- });
210
- }
211
- catch (error) {
212
- console.error('Error verifying message', error);
213
- await provider.disconnect().catch(console.error);
214
- await SIWEController.signOut().catch(console.error);
215
- throw error;
216
- }
217
- }
218
- }
219
- const chainId = this.appKit?.getCaipNetworkId();
220
- await connect(this.wagmiConfig, { connector, chainId });
221
- },
222
- connectExternal: async ({ id, provider, info }) => {
223
- if (!this.wagmiConfig) {
224
- throw new Error('networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined');
225
- }
226
- const connector = this.wagmiConfig.connectors.find(c => c.id === id);
227
- if (!connector) {
228
- throw new Error('connectionControllerClient:connectExternal - connector is undefined');
229
- }
230
- this.appKit?.setClientId(null);
231
- if (provider && info && connector.id === ConstantsUtil.EIP6963_CONNECTOR_ID) {
232
- connector.setEip6963Wallet?.({ provider, info });
233
- }
234
- const chainId = this.appKit?.getCaipNetworkId();
235
- await connect(this.wagmiConfig, { connector, chainId });
236
- },
237
- reconnectExternal: async ({ id }) => {
238
- if (!this.wagmiConfig) {
239
- throw new Error('networkControllerClient:reconnectExternal - wagmiConfig is undefined');
240
- }
241
- const connector = this.wagmiConfig.connectors.find(c => c.id === id);
242
- if (!connector) {
243
- throw new Error('connectionControllerClient:reconnectExternal - connector is undefined');
244
- }
245
- await reconnect(this.wagmiConfig, { connectors: [connector] });
246
- },
247
- checkInstalled: ids => {
248
- const injectedConnector = this.appKit
249
- ?.getConnectors()
250
- .find((c) => c.type === 'INJECTED');
251
- if (!ids) {
252
- return Boolean(window.ethereum);
253
- }
254
- if (injectedConnector) {
255
- if (!window?.ethereum) {
256
- return false;
257
- }
258
- return ids.some(id => Boolean(window.ethereum?.[String(id)]));
259
- }
260
- return false;
261
- },
262
- disconnect: async () => {
263
- await disconnect(this.wagmiConfig);
264
- if (this.options?.siweConfig?.options?.signOutOnDisconnect) {
265
- const { SIWEController } = await import('@reown/appkit-siwe');
266
- await SIWEController.signOut();
267
- }
268
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
269
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.CONNECTED_CONNECTOR);
270
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_NAME);
271
- this.appKit?.setClientId(null);
272
- this.syncAccount({
273
- address: undefined,
274
- chainId: undefined,
275
- connector: undefined,
276
- addresses: undefined,
277
- status: 'disconnected'
278
- });
279
- this.appKit?.resetAccount('solana');
280
- },
281
- signMessage: async (message) => {
282
- const caipAddress = this.appKit?.getCaipAddress() || '';
283
- const account = requireCaipAddress(caipAddress);
284
- return signMessage(this.wagmiConfig, { message, account });
285
- },
286
- estimateGas: async (args) => {
287
- if (args.chainNamespace && args.chainNamespace !== 'eip155') {
288
- throw new Error(`Invalid chain namespace - Expected eip155, got ${args.chainNamespace}`);
289
- }
290
- try {
291
- return await wagmiEstimateGas(this.wagmiConfig, {
292
- account: args.address,
293
- to: args.to,
294
- data: args.data,
295
- type: 'legacy'
296
- });
297
- }
298
- catch (error) {
299
- return BigInt(0);
300
- }
301
- },
302
- getCapabilities: async (params) => {
303
- if (!this.wagmiConfig) {
304
- throw new Error('connectionControllerClient:getCapabilities - wagmiConfig is undefined');
305
- }
306
- const connections = getConnections(this.wagmiConfig);
307
- const connection = connections[0];
308
- if (!connection?.connector) {
309
- throw new Error('connectionControllerClient:getCapabilities - connector is undefined');
310
- }
311
- const provider = (await connection.connector.getProvider());
312
- if (!provider) {
313
- throw new Error('connectionControllerClient:getCapabilities - provider is undefined');
314
- }
315
- const walletCapabilitiesString = provider.session?.sessionProperties?.['capabilities'];
316
- if (walletCapabilitiesString) {
317
- const walletCapabilities = parseWalletCapabilities(walletCapabilitiesString);
318
- const accountCapabilities = walletCapabilities[params];
319
- if (accountCapabilities) {
320
- return accountCapabilities;
321
- }
322
- }
323
- return await provider.request({ method: 'wallet_getCapabilities', params: [params] });
324
- },
325
- grantPermissions: async (params) => {
326
- if (!this.wagmiConfig) {
327
- throw new Error('connectionControllerClient:grantPermissions - wagmiConfig is undefined');
328
- }
329
- const connections = getConnections(this.wagmiConfig);
330
- const connection = connections[0];
331
- if (!connection?.connector) {
332
- throw new Error('connectionControllerClient:grantPermissions - connector is undefined');
333
- }
334
- const provider = (await connection.connector.getProvider());
335
- if (!provider) {
336
- throw new Error('connectionControllerClient:grantPermissions - provider is undefined');
337
- }
338
- return provider.request({ method: 'wallet_grantPermissions', params });
339
- },
340
- revokePermissions: async (session) => {
341
- if (!this.wagmiConfig) {
342
- throw new Error('connectionControllerClient:revokePermissions - wagmiConfig is undefined');
343
- }
344
- const connections = getConnections(this.wagmiConfig);
345
- const connection = connections[0];
346
- if (!connection?.connector) {
347
- throw new Error('connectionControllerClient:revokePermissions - connector is undefined');
348
- }
349
- const provider = (await connection.connector.getProvider());
350
- if (!provider) {
351
- throw new Error('connectionControllerClient:revokePermissions - provider is undefined');
352
- }
353
- return provider.request({ method: 'wallet_revokePermissions', params: [session] });
354
- },
355
- sendTransaction: async (data) => {
356
- if (data.chainNamespace && data.chainNamespace !== 'eip155') {
357
- throw new Error(`Invalid chain namespace - Expected eip155, got ${data.chainNamespace}`);
358
- }
359
- const { chainId } = getAccount(this.wagmiConfig);
360
- const txParams = {
361
- account: data.address,
362
- to: data.to,
363
- value: data.value,
364
- gas: data.gas,
365
- gasPrice: data.gasPrice,
366
- data: data.data,
367
- chainId,
368
- type: 'legacy'
369
- };
370
- await prepareTransactionRequest(this.wagmiConfig, txParams);
371
- const tx = await wagmiSendTransaction(this.wagmiConfig, txParams);
372
- await waitForTransactionReceipt(this.wagmiConfig, { hash: tx, timeout: 25000 });
373
- return tx;
374
- },
375
- writeContract: async (data) => {
376
- const caipAddress = this.appKit?.getCaipAddress() || '';
377
- const account = requireCaipAddress(caipAddress);
378
- const chainId = this.appKit?.getCaipNetworkId();
379
- if (!chainId) {
380
- throw new Error('networkControllerClient:writeContract - chainId is undefined');
381
- }
382
- const tx = await wagmiWriteContract(this.wagmiConfig, {
383
- chain: this.wagmiChains?.[chainId],
384
- chainId,
385
- address: data.tokenAddress,
386
- account,
387
- abi: data.abi,
388
- functionName: data.method,
389
- args: [data.receiverAddress, data.tokenAmount]
390
- });
391
- return tx;
392
- },
393
- getEnsAddress: async (value) => {
394
- try {
395
- if (!this.wagmiConfig) {
396
- throw new Error('networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined');
397
- }
398
- const chainId = this.appKit?.getCaipNetworkId();
399
- let ensName = false;
400
- let wcName = false;
401
- if (isReownName(value)) {
402
- wcName = (await this.appKit?.resolveReownName(value)) || false;
403
- }
404
- if (chainId === 1) {
405
- ensName = await wagmiGetEnsAddress(this.wagmiConfig, {
406
- name: normalize(value),
407
- chainId
408
- });
409
- }
410
- return ensName || wcName || false;
411
- }
412
- catch {
413
- return false;
414
- }
415
- },
416
- getEnsAvatar: async (value) => {
417
- const chainId = this.appKit?.getCaipNetworkId();
418
- if (chainId !== mainnet.id) {
419
- return false;
420
- }
421
- const avatar = await wagmiGetEnsAvatar(this.wagmiConfig, {
422
- name: normalize(value),
423
- chainId
424
- });
425
- return avatar || false;
426
- },
427
- parseUnits,
428
- formatUnits
429
- };
430
- ChainController.state.chains.set(this.chainNamespace, {
431
- chainNamespace: this.chainNamespace,
432
- connectionControllerClient: this.connectionControllerClient,
433
- networkControllerClient: this.networkControllerClient,
434
- adapterType: this.adapterType,
435
- caipNetworks: this.caipNetworks
436
- });
437
- this.syncConnectors(this.wagmiConfig.connectors);
438
- this.syncAuthConnector(this.wagmiConfig?.connectors.find(c => c.id === ConstantsUtil.AUTH_CONNECTOR_ID));
439
- this.syncRequestedNetworks(this.caipNetworks);
440
- watchConnectors(this.wagmiConfig, {
441
- onChange: _connectors => {
442
- this.syncConnectors(_connectors);
443
- this.syncAuthConnector(_connectors.find(c => c.id === ConstantsUtil.AUTH_CONNECTOR_ID));
444
- }
445
- });
446
- watchAccount(this.wagmiConfig, {
447
- onChange: accountData => {
448
- this.syncAccount(accountData);
449
- }
450
- });
451
- this.appKit?.setEIP6963Enabled(options.enableEIP6963 !== false);
452
- this.appKit?.subscribeShouldUpdateToAddress((newAddress) => {
453
- if (newAddress) {
454
- const connections = getConnections(this.wagmiConfig);
455
- const connector = connections[0]?.connector;
456
- if (connector) {
457
- switchAccount(this.wagmiConfig, {
458
- connector
459
- }).then(response => this.syncAccount({
460
- address: newAddress,
461
- isConnected: true,
462
- addresses: response.accounts,
463
- connector,
464
- chainId: response.chainId,
465
- status: 'connected'
466
- }));
467
- }
468
- }
469
- });
470
133
  }
471
- subscribeState(callback) {
472
- return this.appKit?.subscribeState((state) => callback({
473
- ...state,
474
- selectedNetworkId: state.selectedNetworkId
475
- ? Number(NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId))
476
- : undefined
477
- }));
134
+ async sendTransaction(params) {
135
+ const { chainId } = getAccount(this.wagmiConfig);
136
+ const txParams = {
137
+ account: params.address,
138
+ to: params.to,
139
+ value: params.value,
140
+ gas: params.gas,
141
+ gasPrice: params.gasPrice,
142
+ data: params.data,
143
+ chainId,
144
+ type: 'legacy'
145
+ };
146
+ await prepareTransactionRequest(this.wagmiConfig, txParams);
147
+ const tx = await wagmiSendTransaction(this.wagmiConfig, txParams);
148
+ await waitForTransactionReceipt(this.wagmiConfig, { hash: tx, timeout: 25000 });
149
+ return { hash: tx };
478
150
  }
479
- syncRequestedNetworks(caipNetworks) {
480
- const uniqueChainNamespaces = Array.from(new Set(caipNetworks.map(caipNetwork => caipNetwork.chainNamespace)));
481
- uniqueChainNamespaces
482
- .filter(c => Boolean(c))
483
- .forEach(chainNamespace => {
484
- this.appKit?.setRequestedCaipNetworks(caipNetworks.filter(caipNetwork => caipNetwork.chainNamespace === chainNamespace), chainNamespace);
151
+ async writeContract(params) {
152
+ const { caipNetwork, ...data } = params;
153
+ const chainId = Number(NetworkUtil.caipNetworkIdToNumber(caipNetwork.caipNetworkId));
154
+ const tx = await wagmiWriteContract(this.wagmiConfig, {
155
+ chain: this.wagmiChains?.[chainId],
156
+ chainId,
157
+ address: data.tokenAddress,
158
+ account: data.fromAddress,
159
+ abi: data.abi,
160
+ functionName: data.method,
161
+ args: [data.receiverAddress, data.tokenAmount]
485
162
  });
163
+ return { hash: tx };
486
164
  }
487
- async setProfileAndBalance(address, chainId) {
488
- await Promise.all([this.syncProfile(address, chainId), this.syncBalance(address, chainId)]);
489
- }
490
- async syncAccount({ address, chainId, connector, addresses, status }) {
491
- const isAuthConnector = connector?.id === ConstantsUtil.AUTH_CONNECTOR_ID;
492
- if (status === 'disconnected') {
493
- this.appKit?.resetAccount(this.chainNamespace);
494
- this.appKit?.resetWcConnection();
495
- this.appKit?.resetNetwork(this.chainNamespace);
496
- this.appKit?.setAllAccounts([], this.chainNamespace);
497
- this.appKit?.setStatus(status, this.chainNamespace);
498
- this.appKit?.setLoading(false);
499
- SafeLocalStorage.removeItem(SafeLocalStorageKeys.WALLET_ID);
500
- if (isAuthConnector) {
501
- await connector.disconnect();
502
- }
503
- return;
504
- }
505
- if (this.wagmiConfig) {
506
- if (connector) {
507
- if (connector.name === 'WalletConnect' && connector.getProvider && address) {
508
- const activeCaipNetwork = this.appKit?.getCaipNetwork();
509
- const currentChainId = chainId || activeCaipNetwork?.id;
510
- const provider = (await connector.getProvider());
511
- const namespaces = provider?.session?.namespaces || {};
512
- const namespaceKeys = namespaces ? Object.keys(namespaces) : [];
513
- const preferredAccountType = this.appKit?.getPreferredAccountType();
514
- namespaceKeys.forEach(key => {
515
- const chainNamespace = key;
516
- const caipAddress = namespaces?.[key]?.accounts[0];
517
- ProviderUtil.setProvider(chainNamespace, provider);
518
- ProviderUtil.setProviderId(chainNamespace, 'walletConnect');
519
- this.appKit?.setPreferredAccountType(preferredAccountType, chainNamespace);
520
- this.appKit?.setCaipAddress(caipAddress, chainNamespace);
521
- this.appKit?.setStatus(status, chainNamespace);
522
- });
523
- if (this.appKit?.getCaipNetwork()?.chainNamespace !== CommonConstantsUtil.CHAIN.SOLANA &&
524
- currentChainId) {
525
- this.syncNetwork(address, currentChainId, true);
526
- await Promise.all([
527
- this.syncConnectedWalletInfo(connector),
528
- this.appKit?.setApprovedCaipNetworksData(this.chainNamespace)
529
- ]);
530
- }
531
- this.appKit?.setLoading(false);
532
- }
533
- else if (status === 'connected' && address && chainId) {
534
- ProviderUtil.setProvider(this.chainNamespace, await connector.getProvider());
535
- ProviderUtil.setProviderId(this.chainNamespace, connector.id);
536
- const caipAddress = `eip155:${chainId}:${address}`;
537
- this.syncNetwork(address, chainId, true);
538
- await Promise.all([
539
- this.syncConnectedWalletInfo(connector),
540
- this.appKit?.setApprovedCaipNetworksData(this.chainNamespace)
541
- ]);
542
- this.appKit?.setLoading(false);
543
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
544
- this.appKit?.setStatus('connected', this.chainNamespace);
545
- if (!isAuthConnector && addresses?.length) {
546
- this.appKit?.setAllAccounts(addresses.map(addr => ({ address: addr, type: 'eoa' })), this.chainNamespace);
547
- }
548
- }
549
- else if (status === 'reconnecting') {
550
- this.appKit?.setLoading(true);
551
- }
552
- }
553
- }
554
- }
555
- syncNetwork(address, chainId, isConnected) {
556
- const caipNetwork = this.caipNetworks.find((c) => c.id === chainId);
557
- if (caipNetwork && chainId) {
558
- this.appKit?.setCaipNetwork(caipNetwork);
559
- if (isConnected && address && chainId) {
560
- const caipAddress = `eip155:${chainId}:${address}`;
561
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
562
- if (caipNetwork?.blockExplorers?.default.url) {
563
- const url = `${caipNetwork.blockExplorers.default.url}/address/${address}`;
564
- this.appKit?.setAddressExplorerUrl(url, this.chainNamespace);
565
- }
566
- else {
567
- this.appKit?.setAddressExplorerUrl(undefined, this.chainNamespace);
568
- }
569
- }
570
- }
571
- }
572
- async syncReownName(address) {
573
- if (!this.appKit) {
574
- throw new Error('syncReownName - appKit is undefined');
575
- }
165
+ async getEnsAddress(params) {
166
+ const { name, caipNetwork } = params;
576
167
  try {
577
- const registeredWcNames = await this.appKit.getReownName(address);
578
- if (registeredWcNames[0]) {
579
- const wcName = registeredWcNames[0];
580
- this.appKit?.setProfileName(wcName.name, this.chainNamespace);
168
+ if (!this.wagmiConfig) {
169
+ throw new Error('networkControllerClient:getApprovedCaipNetworksData - wagmiConfig is undefined');
581
170
  }
582
- else {
583
- this.appKit?.setProfileName(null, this.chainNamespace);
171
+ let ensName = false;
172
+ let wcName = false;
173
+ if (isReownName(name)) {
174
+ wcName = (await WcHelpersUtil.resolveReownName(name)) || false;
175
+ }
176
+ if (caipNetwork.id === 1) {
177
+ ensName = await wagmiGetEnsAddress(this.wagmiConfig, {
178
+ name: normalize(name),
179
+ chainId: caipNetwork.id
180
+ });
584
181
  }
182
+ return { address: ensName || wcName || false };
585
183
  }
586
184
  catch {
587
- this.appKit?.setProfileName(null, this.chainNamespace);
185
+ return { address: false };
588
186
  }
589
187
  }
590
- async syncProfile(address, chainId) {
591
- if (!this.appKit) {
592
- throw new Error('syncProfile - appKit is undefined');
593
- }
188
+ async estimateGas(params) {
594
189
  try {
595
- const { name, avatar } = await this.appKit.fetchIdentity({
596
- address
190
+ const result = await wagmiEstimateGas(this.wagmiConfig, {
191
+ account: params.address,
192
+ to: params.to,
193
+ data: params.data,
194
+ type: 'legacy'
597
195
  });
598
- this.appKit?.setProfileName(name, this.chainNamespace);
599
- this.appKit?.setProfileImage(avatar, this.chainNamespace);
600
- if (!name) {
601
- await this.syncReownName(address);
602
- }
196
+ return { gas: result };
603
197
  }
604
- catch {
605
- if (chainId === mainnet.id) {
606
- const profileName = await getEnsName(this.wagmiConfig, { address, chainId });
607
- if (profileName) {
608
- this.appKit?.setProfileName(profileName, this.chainNamespace);
609
- const profileImage = await wagmiGetEnsAvatar(this.wagmiConfig, {
610
- name: profileName,
611
- chainId
612
- });
613
- if (profileImage) {
614
- this.appKit?.setProfileImage(profileImage, this.chainNamespace);
615
- }
616
- }
617
- else {
618
- await this.syncReownName(address);
619
- this.appKit?.setProfileImage(null, this.chainNamespace);
620
- }
621
- }
622
- else {
623
- await this.syncReownName(address);
624
- this.appKit?.setProfileImage(null, this.chainNamespace);
625
- }
198
+ catch (error) {
199
+ throw new Error('WagmiAdapter:estimateGas - error estimating gas');
626
200
  }
627
201
  }
628
- async syncBalance(address, chainId) {
629
- const caipNetwork = this.caipNetworks.find((c) => c.id === chainId);
630
- if (caipNetwork && this.wagmiConfig) {
631
- const balance = await getBalance(this.wagmiConfig, {
632
- address,
633
- chainId,
634
- token: this.options?.tokens?.[caipNetwork.caipNetworkId]?.address
635
- });
636
- this.appKit?.setBalance(balance.formatted, balance.symbol, this.chainNamespace);
637
- return;
638
- }
639
- this.appKit?.setBalance(undefined, undefined, this.chainNamespace);
202
+ parseUnits(params) {
203
+ return parseUnits(params.value, params.decimals);
640
204
  }
641
- async syncConnectedWalletInfo(connector) {
642
- if (!connector) {
643
- throw Error('syncConnectedWalletInfo - connector is undefined');
644
- }
645
- if (connector.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID && connector.getProvider) {
646
- const walletConnectProvider = (await connector.getProvider());
647
- if (walletConnectProvider.session) {
648
- this.appKit?.setConnectedWalletInfo({
649
- ...walletConnectProvider.session.peer.metadata,
650
- name: walletConnectProvider.session.peer.metadata.name,
651
- icon: walletConnectProvider.session.peer.metadata.icons?.[0]
652
- }, this.chainNamespace);
653
- }
654
- }
655
- else {
656
- const wagmiConnector = this.appKit?.getConnectors().find(c => c.id === connector.id);
657
- this.appKit?.setConnectedWalletInfo({
658
- name: connector.name,
659
- icon: connector.icon || this.appKit.getConnectorImage(wagmiConnector)
660
- }, this.chainNamespace);
661
- }
205
+ formatUnits(params) {
206
+ return formatUnits(params.value, params.decimals);
662
207
  }
663
- syncConnectors(_connectors) {
664
- const connectors = _connectors.map(connector => ({ ...connector, chain: this.chainNamespace }));
208
+ syncConnectors(options, appKit) {
209
+ this.addWagmiConnectors(options, appKit);
210
+ const connectors = this.wagmiConfig.connectors.map(connector => ({
211
+ ...connector,
212
+ chain: this.namespace
213
+ }));
665
214
  const uniqueIds = new Set();
666
215
  const filteredConnectors = connectors.filter(item => {
667
216
  const isDuplicate = uniqueIds.has(item.id);
668
217
  uniqueIds.add(item.id);
669
218
  return !isDuplicate;
670
219
  });
671
- const w3mConnectors = [];
672
- filteredConnectors.forEach(({ id, name, type, icon }) => {
673
- const shouldSkip = ConstantsUtil.AUTH_CONNECTOR_ID === id;
674
- if (!shouldSkip) {
675
- const injectedConnector = id === ConstantsUtil.INJECTED_CONNECTOR_ID;
676
- w3mConnectors.push({
677
- id,
678
- explorerId: PresetsUtil.ConnectorExplorerIds[id],
679
- imageUrl: this.options?.connectorImages?.[id] ?? icon,
680
- name: PresetsUtil.ConnectorNamesMap[id] ?? name,
681
- imageId: PresetsUtil.ConnectorImageIds[id],
682
- type: PresetsUtil.ConnectorTypesMap[type] ?? 'EXTERNAL',
683
- info: injectedConnector ? undefined : { rdns: id },
684
- chain: this.chainNamespace
220
+ filteredConnectors.forEach(connector => {
221
+ const shouldSkip = ConstantsUtil.AUTH_CONNECTOR_ID === connector.id;
222
+ if (!shouldSkip && this.namespace) {
223
+ this.addConnector({
224
+ id: connector.id,
225
+ explorerId: PresetsUtil.ConnectorExplorerIds[connector.id],
226
+ imageUrl: options?.connectorImages?.[connector.id] ?? connector.icon,
227
+ name: PresetsUtil.ConnectorNamesMap[connector.id] ?? connector.name,
228
+ imageId: PresetsUtil.ConnectorImageIds[connector.id],
229
+ type: PresetsUtil.ConnectorTypesMap[connector.type] ?? 'EXTERNAL',
230
+ info: { rdns: connector.id },
231
+ chain: this.namespace,
232
+ chains: []
685
233
  });
686
234
  }
687
235
  });
688
- this.appKit?.setConnectors(w3mConnectors);
689
236
  }
690
- async syncAuthConnector(_authConnector) {
691
- const connector = _authConnector;
692
- if (connector) {
693
- const provider = await connector.getProvider();
694
- this.appKit?.addConnector({
695
- id: ConstantsUtil.AUTH_CONNECTOR_ID,
696
- type: 'AUTH',
697
- name: 'w3mAuth',
698
- provider,
699
- chain: this.chainNamespace
700
- });
701
- this.initAuthConnectorListeners(_authConnector);
237
+ async syncConnection(params) {
238
+ const { id, chainId } = params;
239
+ const connections = getConnections(this.wagmiConfig);
240
+ const connection = connections.find(c => c.connector.id === id);
241
+ const connector = this.wagmiConfig.connectors.find(c => c.id === id);
242
+ const provider = (await connector?.getProvider());
243
+ return {
244
+ chainId: Number(chainId),
245
+ address: connection?.accounts[0],
246
+ provider,
247
+ type: connection?.connector.type,
248
+ id: connection?.connector.id
249
+ };
250
+ }
251
+ async connectWalletConnect(onUri, chainId) {
252
+ const connector = this.wagmiConfig.connectors.find(c => c.type === 'walletConnect');
253
+ const provider = (await connector.getProvider());
254
+ if (!this.caipNetworks || !provider) {
255
+ throw new Error('UniversalAdapter:connectWalletConnect - caipNetworks or provider is undefined');
256
+ }
257
+ provider.on('display_uri', (uri) => {
258
+ onUri(uri);
259
+ });
260
+ await connect(this.wagmiConfig, { connector, chainId: chainId ? Number(chainId) : undefined });
261
+ }
262
+ async connect(params) {
263
+ const { id, provider, type, info, chainId } = params;
264
+ const connector = this.wagmiConfig.connectors.find(c => c.id === id);
265
+ if (!connector) {
266
+ throw new Error('connectionControllerClient:connectExternal - connector is undefined');
702
267
  }
268
+ if (provider && info && connector.id === ConstantsUtil.EIP6963_CONNECTOR_ID) {
269
+ connector.setEip6963Wallet?.({ provider, info });
270
+ }
271
+ const res = await connect(this.wagmiConfig, {
272
+ connector,
273
+ chainId: chainId ? Number(chainId) : undefined
274
+ });
275
+ return {
276
+ address: res.accounts[0],
277
+ chainId: res.chainId,
278
+ provider: provider,
279
+ type: type,
280
+ id
281
+ };
703
282
  }
704
- async initAuthConnectorListeners(_authConnector) {
705
- if (_authConnector) {
706
- await this.listenAuthConnector(_authConnector);
707
- await this.listenModal(_authConnector);
283
+ async reconnect(params) {
284
+ const { id } = params;
285
+ const connector = this.wagmiConfig.connectors.find(c => c.id === id);
286
+ if (!connector) {
287
+ throw new Error('connectionControllerClient:connectExternal - connector is undefined');
708
288
  }
289
+ await reconnect(this.wagmiConfig, {
290
+ connectors: [connector]
291
+ });
709
292
  }
710
- async listenAuthConnector(connector, bypassWindowCheck = false) {
711
- if (bypassWindowCheck || (typeof window !== 'undefined' && connector)) {
712
- const provider = (await connector.getProvider());
713
- provider.onRpcRequest((request) => {
714
- if (W3mFrameHelpers.checkIfRequestExists(request)) {
715
- if (!W3mFrameHelpers.checkIfRequestIsSafe(request)) {
716
- this.appKit?.handleUnsafeRPCRequest();
717
- }
718
- }
719
- else {
720
- this.appKit?.open();
721
- console.error(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_MESSAGE, {
722
- method: request.method
723
- });
724
- setTimeout(() => {
725
- this.appKit?.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE);
726
- }, 300);
727
- provider.rejectRpcRequests();
728
- }
729
- });
730
- provider.onRpcError(() => {
731
- const isModalOpen = this.appKit?.isOpen();
732
- if (isModalOpen) {
733
- if (this.appKit?.isTransactionStackEmpty()) {
734
- this.appKit?.close();
735
- }
736
- else {
737
- this.appKit?.popTransactionStack(true);
738
- }
739
- }
740
- });
741
- provider.onRpcSuccess((_, request) => {
742
- const isSafeRequest = W3mFrameHelpers.checkIfRequestIsSafe(request);
743
- if (isSafeRequest) {
744
- return;
745
- }
746
- if (this.appKit?.isTransactionStackEmpty()) {
747
- this.appKit?.close();
748
- }
749
- else {
750
- this.appKit?.popTransactionStack();
751
- }
752
- });
753
- provider.onNotConnected(() => {
754
- const isConnected = this.appKit?.getIsConnectedState();
755
- const connectedConnector = SafeLocalStorage.getItem(SafeLocalStorageKeys.CONNECTED_CONNECTOR);
756
- const isConnectedWithAuth = connectedConnector === 'AUTH';
757
- if (!isConnected && isConnectedWithAuth) {
758
- this.appKit?.setCaipAddress(undefined, this.chainNamespace);
759
- this.appKit?.setLoading(false);
760
- }
761
- });
762
- provider.onConnect(user => {
763
- const caipAddress = `eip155:${user.chainId}:${user.address}`;
764
- this.appKit?.setCaipAddress(caipAddress, this.chainNamespace);
765
- this.appKit?.setSmartAccountDeployed(Boolean(user.smartAccountDeployed), this.chainNamespace);
766
- this.appKit?.setPreferredAccountType(user.preferredAccountType, this.chainNamespace);
767
- this.appKit?.setAllAccounts(user.accounts || [
768
- {
769
- address: user.address,
770
- type: (user.preferredAccountType || 'eoa')
771
- }
772
- ], this.chainNamespace);
773
- StorageUtil.setConnectedConnector('AUTH');
774
- this.appKit?.setLoading(false);
293
+ async getBalance(params) {
294
+ const caipNetwork = this.caipNetworks?.find(network => network.id === params.chainId);
295
+ if (caipNetwork && this.wagmiConfig) {
296
+ const chainId = Number(params.chainId);
297
+ const balance = await getBalance(this.wagmiConfig, {
298
+ address: params.address,
299
+ chainId,
300
+ token: params.tokens?.[caipNetwork.caipNetworkId]?.address
775
301
  });
776
- provider.onGetSmartAccountEnabledNetworks(networks => {
777
- this.appKit?.setSmartAccountEnabledNetworks(networks, this.chainNamespace);
302
+ return { balance: balance.formatted, symbol: balance.symbol };
303
+ }
304
+ return { balance: '', symbol: '' };
305
+ }
306
+ async getProfile(params) {
307
+ const chainId = params.chainId;
308
+ const profileName = await getEnsName(this.wagmiConfig, {
309
+ address: params.address,
310
+ chainId
311
+ });
312
+ if (profileName) {
313
+ const profileImage = await getEnsAvatar(this.wagmiConfig, {
314
+ name: profileName,
315
+ chainId
778
316
  });
317
+ return { profileName, profileImage: profileImage ?? undefined };
779
318
  }
319
+ return { profileName: undefined, profileImage: undefined };
780
320
  }
781
- async listenModal(connector) {
782
- const provider = (await connector.getProvider());
783
- this.subscribeState(val => {
784
- if (!val.open) {
785
- provider.rejectRpcRequests();
321
+ getWalletConnectProvider() {
322
+ return this.wagmiConfig.connectors.find(c => c.type === 'walletConnect')?.['provider'];
323
+ }
324
+ async disconnect() {
325
+ const connections = getConnections(this.wagmiConfig);
326
+ await Promise.all(connections.map(async (connection) => {
327
+ const connector = connection?.connector;
328
+ if (connector) {
329
+ await wagmiDisconnect(this.wagmiConfig, { connector });
786
330
  }
787
- });
331
+ }));
332
+ }
333
+ async switchNetwork(params) {
334
+ await switchChain(this.wagmiConfig, { chainId: params.caipNetwork.id });
335
+ }
336
+ async getCapabilities(params) {
337
+ if (!this.wagmiConfig) {
338
+ throw new Error('connectionControllerClient:getCapabilities - wagmiConfig is undefined');
339
+ }
340
+ const connections = getConnections(this.wagmiConfig);
341
+ const connection = connections[0];
342
+ if (!connection?.connector) {
343
+ throw new Error('connectionControllerClient:getCapabilities - connector is undefined');
344
+ }
345
+ const provider = (await connection.connector.getProvider());
346
+ if (!provider) {
347
+ throw new Error('connectionControllerClient:getCapabilities - provider is undefined');
348
+ }
349
+ const walletCapabilitiesString = provider.session?.sessionProperties?.['capabilities'];
350
+ if (walletCapabilitiesString) {
351
+ const walletCapabilities = parseWalletCapabilities(walletCapabilitiesString);
352
+ const accountCapabilities = walletCapabilities[params];
353
+ if (accountCapabilities) {
354
+ return accountCapabilities;
355
+ }
356
+ }
357
+ return await provider.request({ method: 'wallet_getCapabilities', params: [params] });
358
+ }
359
+ async grantPermissions(params) {
360
+ if (!this.wagmiConfig) {
361
+ throw new Error('connectionControllerClient:grantPermissions - wagmiConfig is undefined');
362
+ }
363
+ const connections = getConnections(this.wagmiConfig);
364
+ const connection = connections[0];
365
+ if (!connection?.connector) {
366
+ throw new Error('connectionControllerClient:grantPermissions - connector is undefined');
367
+ }
368
+ const provider = (await connection.connector.getProvider());
369
+ if (!provider) {
370
+ throw new Error('connectionControllerClient:grantPermissions - provider is undefined');
371
+ }
372
+ return provider.request({ method: 'wallet_grantPermissions', params });
373
+ }
374
+ async revokePermissions(params) {
375
+ if (!this.wagmiConfig) {
376
+ throw new Error('connectionControllerClient:revokePermissions - wagmiConfig is undefined');
377
+ }
378
+ const connections = getConnections(this.wagmiConfig);
379
+ const connection = connections[0];
380
+ if (!connection?.connector) {
381
+ throw new Error('connectionControllerClient:revokePermissions - connector is undefined');
382
+ }
383
+ const provider = (await connection.connector.getProvider());
384
+ if (!provider) {
385
+ throw new Error('connectionControllerClient:revokePermissions - provider is undefined');
386
+ }
387
+ return provider.request({ method: 'wallet_revokePermissions', params });
788
388
  }
789
389
  }
790
390
  //# sourceMappingURL=client.js.map