-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
client.ts
627 lines (517 loc) · 19 KB
/
client.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
import { AdapterBlueprint } from '@reown/appkit/adapters'
import type { CaipNetwork } from '@reown/appkit-common'
import { ConstantsUtil as CommonConstantsUtil } from '@reown/appkit-common'
import {
CoreHelperUtil,
type CombinedProvider,
type Connector,
type ConnectorType,
type Provider
} from '@reown/appkit-core'
import { ConstantsUtil, PresetsUtil } from '@reown/appkit-utils'
import { EthersHelpersUtil, type ProviderType } from '@reown/appkit-utils/ethers'
import { WcConstantsUtil, WcHelpersUtil, type AppKitOptions } from '@reown/appkit'
import UniversalProvider from '@walletconnect/universal-provider'
import * as ethers from 'ethers'
import { CoinbaseWalletSDK, type ProviderInterface } from '@coinbase/wallet-sdk'
import type { W3mFrameProvider } from '@reown/appkit-wallet'
import { Ethers5Methods } from './utils/Ethers5Methods.js'
import { formatEther } from 'ethers/lib/utils.js'
import { ProviderUtil } from '@reown/appkit/store'
export interface EIP6963ProviderDetail {
info: Connector['info']
provider: Provider
}
export class Ethers5Adapter extends AdapterBlueprint {
private ethersConfig?: ProviderType
public adapterType = 'ethers'
constructor() {
super({})
this.namespace = CommonConstantsUtil.CHAIN.EVM
}
private createEthersConfig(options: AppKitOptions) {
if (!options.metadata) {
return undefined
}
let injectedProvider: Provider | undefined = undefined
// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
let coinbaseProvider: ProviderInterface | undefined = undefined
function getInjectedProvider() {
if (injectedProvider) {
return injectedProvider
}
if (typeof window === 'undefined') {
return undefined
}
if (!window.ethereum) {
return undefined
}
// @ts-expect-error window.ethereum satisfies Provider
injectedProvider = window.ethereum
return injectedProvider
}
function getCoinbaseProvider() {
if (coinbaseProvider) {
return coinbaseProvider
}
if (typeof window === 'undefined') {
return undefined
}
const coinbaseWallet = new CoinbaseWalletSDK({
appName: options?.metadata?.name,
appLogoUrl: options?.metadata?.icons[0],
appChainIds: options.networks?.map(caipNetwork => caipNetwork.id as number) || [1, 84532]
})
coinbaseProvider = coinbaseWallet.makeWeb3Provider({
options: options.coinbasePreference ?? 'all'
})
return coinbaseProvider
}
const providers: ProviderType = { metadata: options.metadata }
if (options.enableInjected !== false) {
providers.injected = getInjectedProvider()
}
if (options.enableCoinbase !== false) {
providers.coinbase = getCoinbaseProvider()
}
providers.EIP6963 = options.enableEIP6963 !== false
return providers
}
public async signMessage(
params: AdapterBlueprint.SignMessageParams
): Promise<AdapterBlueprint.SignMessageResult> {
const { message, address, provider } = params
if (!provider) {
throw new Error('Provider is undefined')
}
try {
const signature = await Ethers5Methods.signMessage(message, provider as Provider, address)
return { signature }
} catch (error) {
throw new Error('EthersAdapter:signMessage - Sign message failed')
}
}
public async sendTransaction(
params: AdapterBlueprint.SendTransactionParams
): Promise<AdapterBlueprint.SendTransactionResult> {
if (!params.provider) {
throw new Error('Provider is undefined')
}
const tx = await Ethers5Methods.sendTransaction(
{
value: params.value as bigint,
to: params.to as `0x${string}`,
data: params.data as `0x${string}`,
gas: params.gas as bigint,
gasPrice: params.gasPrice as bigint,
address: params.address
},
params.provider as Provider,
params.address,
Number(params.caipNetwork?.id)
)
return { hash: tx }
}
public async writeContract(
params: AdapterBlueprint.WriteContractParams
): Promise<AdapterBlueprint.WriteContractResult> {
if (!params.provider) {
throw new Error('Provider is undefined')
}
const result = await Ethers5Methods.writeContract(
params,
params.provider as Provider,
params.caipAddress,
Number(params.caipNetwork?.id)
)
return { hash: result }
}
public async estimateGas(
params: AdapterBlueprint.EstimateGasTransactionArgs
): Promise<AdapterBlueprint.EstimateGasTransactionResult> {
const { provider, caipNetwork, address } = params
if (!provider) {
throw new Error('Provider is undefined')
}
try {
const result = await Ethers5Methods.estimateGas(
{
data: params.data as `0x${string}`,
to: params.to as `0x${string}`,
address: address as `0x${string}`
},
provider as Provider,
address as `0x${string}`,
Number(caipNetwork?.id)
)
return { gas: result }
} catch (error) {
throw new Error('EthersAdapter:estimateGas - Estimate gas failed')
}
}
public async getEnsAddress(
params: AdapterBlueprint.GetEnsAddressParams
): Promise<AdapterBlueprint.GetEnsAddressResult> {
const { name, caipNetwork } = params
if (caipNetwork) {
const result = await Ethers5Methods.getEnsAddress(name, caipNetwork)
return { address: result as string }
}
return { address: '' }
}
public parseUnits(params: AdapterBlueprint.ParseUnitsParams): AdapterBlueprint.ParseUnitsResult {
return Ethers5Methods.parseUnits(params.value, params.decimals)
}
public formatUnits(
params: AdapterBlueprint.FormatUnitsParams
): AdapterBlueprint.FormatUnitsResult {
return Ethers5Methods.formatUnits(params.value, params.decimals)
}
public async syncConnection(
params: AdapterBlueprint.SyncConnectionParams
): Promise<AdapterBlueprint.ConnectResult> {
const { id, chainId } = params
const connector = this.connectors.find(c => c.id === id)
const selectedProvider = connector?.provider as Provider
if (!selectedProvider) {
throw new Error('Provider not found')
}
const accounts: string[] = await selectedProvider.request({
method: 'eth_requestAccounts'
})
const requestChainId = await selectedProvider.request({
method: 'eth_chainId'
})
this.listenProviderEvents(selectedProvider)
if (!accounts[0]) {
throw new Error('No accounts found')
}
if (!connector?.type) {
throw new Error('Connector type not found')
}
return {
address: accounts[0],
chainId: Number(requestChainId) || Number(chainId),
provider: selectedProvider,
type: connector.type,
id
}
}
public syncConnectors(options: AppKitOptions) {
this.ethersConfig = this.createEthersConfig(options)
if (this.ethersConfig?.EIP6963) {
this.listenInjectedConnector(true)
}
const connectors = Object.keys(this.ethersConfig || {}).filter(
key => key !== 'metadata' && key !== 'EIP6963'
)
connectors.forEach(connector => {
const key = connector === 'coinbase' ? 'coinbaseWalletSDK' : connector
const injectedConnector = connector === ConstantsUtil.INJECTED_CONNECTOR_ID
if (this.namespace) {
this.addConnector({
id: key,
explorerId: PresetsUtil.ConnectorExplorerIds[key],
imageUrl: options?.connectorImages?.[key],
name: PresetsUtil.ConnectorNamesMap[key],
imageId: PresetsUtil.ConnectorImageIds[key],
type: PresetsUtil.ConnectorTypesMap[key] ?? 'EXTERNAL',
info: injectedConnector ? undefined : { rdns: key },
chain: this.namespace,
chains: [],
provider: this.ethersConfig?.[connector as keyof ProviderType] as Provider
})
}
})
}
public async connectWalletConnect(onUri: (uri: string) => void) {
const connector = this.connectors.find(c => c.type === 'WALLET_CONNECT')
const provider = connector?.provider as UniversalProvider
if (!this.caipNetworks || !provider) {
throw new Error(
'UniversalAdapter:connectWalletConnect - caipNetworks or provider is undefined'
)
}
provider.on('display_uri', (uri: string) => {
onUri(uri)
})
const namespaces = WcHelpersUtil.createNamespaces(this.caipNetworks)
await provider.connect({ optionalNamespaces: namespaces })
}
private eip6963EventHandler(event: CustomEventInit<EIP6963ProviderDetail>) {
if (event.detail) {
const { info, provider } = event.detail
const existingConnector = this.connectors?.find(c => c.name === info?.name)
if (!existingConnector) {
const type = PresetsUtil.ConnectorTypesMap[ConstantsUtil.EIP6963_CONNECTOR_ID]
if (type && this.namespace) {
this.addConnector({
id: info?.rdns || '',
type,
imageUrl: info?.icon,
name: info?.name,
provider,
info,
chain: this.namespace,
chains: []
})
}
}
}
}
private listenInjectedConnector(enableEIP6963: boolean) {
if (typeof window !== 'undefined' && enableEIP6963) {
const handler = this.eip6963EventHandler.bind(this)
window.addEventListener(ConstantsUtil.EIP6963_ANNOUNCE_EVENT, handler)
window.dispatchEvent(new Event(ConstantsUtil.EIP6963_REQUEST_EVENT))
}
}
public async connect({
id,
type,
chainId
}: AdapterBlueprint.ConnectParams): Promise<AdapterBlueprint.ConnectResult> {
const connector = this.connectors.find(c => c.id === id)
const selectedProvider = connector?.provider as Provider
if (!selectedProvider) {
throw new Error('Provider not found')
}
let accounts: string[] = []
let requestChainId: string | undefined = undefined
if (type === 'AUTH') {
const { address } = await (selectedProvider as unknown as W3mFrameProvider).connect({
chainId
})
accounts = [address]
} else {
accounts = await selectedProvider.request({
method: 'eth_requestAccounts'
})
requestChainId = await selectedProvider.request({
method: 'eth_chainId'
})
this.listenProviderEvents(selectedProvider)
}
return {
address: accounts[0] as `0x${string}`,
chainId: Number(requestChainId) || Number(chainId),
provider: selectedProvider,
type: type as ConnectorType,
id
}
}
public async getAccounts(
params: AdapterBlueprint.GetAccountsParams
): Promise<AdapterBlueprint.GetAccountsResult> {
const connector = this.connectors.find(c => c.id === params.id)
const selectedProvider = connector?.provider as Provider
if (!selectedProvider || !connector) {
throw new Error('Provider not found')
}
if (params.id === ConstantsUtil.AUTH_CONNECTOR_ID) {
const provider = connector['provider'] as W3mFrameProvider
const { address, accounts } = await provider.connect()
return Promise.resolve({
accounts: (accounts || [{ address, type: 'eoa' }]).map(account =>
CoreHelperUtil.createAccount('eip155', account.address, account.type)
)
})
}
const accounts: string[] = await selectedProvider.request({
method: 'eth_requestAccounts'
})
return {
accounts: accounts.map(account => CoreHelperUtil.createAccount('eip155', account, 'eoa'))
}
}
public override async reconnect(params: AdapterBlueprint.ConnectParams): Promise<void> {
const { id, chainId } = params
const connector = this.connectors.find(c => c.id === id)
if (connector && connector.type === 'AUTH' && chainId) {
await (connector.provider as W3mFrameProvider).connect({ chainId })
}
}
public async disconnect(params: AdapterBlueprint.DisconnectParams): Promise<void> {
if (!params.provider || !params.providerType) {
throw new Error('Provider or providerType not provided')
}
switch (params.providerType) {
case 'WALLET_CONNECT':
if ((params.provider as UniversalProvider).session) {
;(params.provider as UniversalProvider).disconnect()
}
break
case 'AUTH':
await params.provider.disconnect()
break
case 'ANNOUNCED':
case 'EXTERNAL':
await this.revokeProviderPermissions(params.provider as Provider)
break
default:
throw new Error('Unsupported provider type')
}
}
public async getBalance(
params: AdapterBlueprint.GetBalanceParams
): Promise<AdapterBlueprint.GetBalanceResult> {
const caipNetwork = this.caipNetworks?.find((c: CaipNetwork) => c.id === params.chainId)
if (caipNetwork) {
const jsonRpcProvider = new ethers.providers.JsonRpcProvider(
caipNetwork.rpcUrls.default.http[0],
{
chainId: caipNetwork.id as number,
name: caipNetwork.name
}
)
if (jsonRpcProvider) {
try {
const balance = await jsonRpcProvider.getBalance(params.address)
const formattedBalance = formatEther(balance)
return { balance: formattedBalance, symbol: caipNetwork.nativeCurrency.symbol }
} catch (error) {
return { balance: '', symbol: '' }
}
}
}
return { balance: '', symbol: '' }
}
public async getProfile(
params: AdapterBlueprint.GetProfileParams
): Promise<AdapterBlueprint.GetProfileResult> {
if (params.chainId === 1) {
const ensProvider = new ethers.providers.InfuraProvider('mainnet')
const name = await ensProvider.lookupAddress(params.address)
const avatar = await ensProvider.getAvatar(params.address)
return { profileName: name || undefined, profileImage: avatar || undefined }
}
return { profileName: undefined, profileImage: undefined }
}
private providerHandlers: {
disconnect: () => void
accountsChanged: (accounts: string[]) => void
chainChanged: (chainId: string) => void
} | null = null
private listenProviderEvents(provider: Provider | CombinedProvider) {
const disconnectHandler = () => {
this.removeProviderListeners(provider)
this.emit('disconnect')
}
const accountsChangedHandler = (accounts: string[]) => {
if (accounts.length > 0) {
this.emit('accountChanged', {
address: accounts[0] as `0x${string}`
})
}
}
const chainChangedHandler = (chainId: string) => {
const chainIdNumber =
typeof chainId === 'string' ? EthersHelpersUtil.hexStringToNumber(chainId) : Number(chainId)
this.emit('switchNetwork', { chainId: chainIdNumber })
}
provider.on('disconnect', disconnectHandler)
provider.on('accountsChanged', accountsChangedHandler)
provider.on('chainChanged', chainChangedHandler)
this.providerHandlers = {
disconnect: disconnectHandler,
accountsChanged: accountsChangedHandler,
chainChanged: chainChangedHandler
}
}
private removeProviderListeners(provider: Provider | CombinedProvider) {
if (this.providerHandlers) {
provider.removeListener('disconnect', this.providerHandlers.disconnect)
provider.removeListener('accountsChanged', this.providerHandlers.accountsChanged)
provider.removeListener('chainChanged', this.providerHandlers.chainChanged)
this.providerHandlers = null
}
}
public async switchNetwork(params: AdapterBlueprint.SwitchNetworkParams): Promise<void> {
const { caipNetwork, provider, providerType } = params
if (providerType === 'WALLET_CONNECT') {
;(provider as UniversalProvider).setDefaultChain(String(`eip155:${String(caipNetwork.id)}`))
} else if (providerType === 'AUTH') {
const authProvider = provider as W3mFrameProvider
await authProvider.switchNetwork(caipNetwork.id)
await authProvider.connect({
chainId: caipNetwork.id
})
} else {
try {
await (provider as Provider).request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: EthersHelpersUtil.numberToHexString(caipNetwork.id) }]
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (switchError: any) {
if (
switchError.code === WcConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID ||
switchError.code === WcConstantsUtil.ERROR_CODE_DEFAULT ||
switchError?.data?.originalError?.code ===
WcConstantsUtil.ERROR_CODE_UNRECOGNIZED_CHAIN_ID
) {
await EthersHelpersUtil.addEthereumChain(provider as Provider, caipNetwork)
} else if (
providerType === 'ANNOUNCED' ||
providerType === 'EXTERNAL' ||
providerType === 'INJECTED'
) {
throw new Error('Chain is not supported')
}
}
}
}
public getWalletConnectProvider(): AdapterBlueprint.GetWalletConnectProviderResult {
return this.connectors.find(c => c.type === 'WALLET_CONNECT')?.provider as UniversalProvider
}
private async revokeProviderPermissions(provider: Provider | CombinedProvider) {
try {
const permissions: { parentCapability: string }[] = await provider.request({
method: 'wallet_getPermissions'
})
const ethAccountsPermission = permissions.find(
permission => permission.parentCapability === 'eth_accounts'
)
if (ethAccountsPermission) {
await provider.request({
method: 'wallet_revokePermissions',
params: [{ eth_accounts: {} }]
})
}
} catch (error) {
// eslint-disable-next-line no-console
console.info('Could not revoke permissions from wallet. Disconnecting...', error)
}
}
public async getCapabilities(params: AdapterBlueprint.GetCapabilitiesParams): Promise<unknown> {
const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM)
if (!provider) {
throw new Error('Provider is undefined')
}
const walletCapabilitiesString = provider.session?.sessionProperties?.['capabilities']
if (walletCapabilitiesString) {
const walletCapabilities = Ethers5Methods.parseWalletCapabilities(walletCapabilitiesString)
const accountCapabilities = walletCapabilities[params]
if (accountCapabilities) {
return accountCapabilities
}
}
return await provider.request({ method: 'wallet_getCapabilities', params: [params] })
}
public async grantPermissions(params: AdapterBlueprint.GrantPermissionsParams): Promise<unknown> {
const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM)
if (!provider) {
throw new Error('Provider is undefined')
}
return await provider.request({ method: 'wallet_grantPermissions', params })
}
public async revokePermissions(
params: AdapterBlueprint.RevokePermissionsParams
): Promise<`0x${string}`> {
const provider = ProviderUtil.getProvider(CommonConstantsUtil.CHAIN.EVM)
if (!provider) {
throw new Error('Provider is undefined')
}
return await provider.request({ method: 'wallet_revokePermissions', params: [params] })
}
}