-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
client.ts
803 lines (698 loc) · 26.3 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
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
/* eslint-disable no-console */
import { EthereumProvider, OPTIONAL_METHODS } from '@walletconnect/ethereum-provider'
import {
connect,
disconnect,
signMessage,
getBalance,
getEnsAvatar as wagmiGetEnsAvatar,
getEnsName,
watchAccount,
watchConnectors,
estimateGas as wagmiEstimateGas,
writeContract as wagmiWriteContract,
getAccount,
getEnsAddress as wagmiGetEnsAddress,
switchChain,
waitForTransactionReceipt,
getConnections,
switchAccount,
reconnect
} from '@wagmi/core'
import type { ChainAdapter, OptionsControllerState } from '@web3modal/core'
import { mainnet } from 'viem/chains'
import { prepareTransactionRequest, sendTransaction as wagmiSendTransaction } from '@wagmi/core'
import type { Chain } from '@wagmi/core/chains'
import type { GetAccountReturnType, GetEnsAddressReturnType, Config } from '@wagmi/core'
import type {
CaipAddress,
CaipNetwork,
ConnectionControllerClient,
Connector,
NetworkControllerClient,
PublicStateControllerState,
SendTransactionArgs,
SocialProvider,
WriteContractArgs
} from '@web3modal/core'
import { formatUnits, parseUnits } from 'viem'
import type { Hex } from 'viem'
import { ConstantsUtil, PresetsUtil, HelpersUtil } from '@web3modal/scaffold-utils'
import { ConstantsUtil as CommonConstants } from '@web3modal/common'
import {
getCaipDefaultChain,
getEmailCaipNetworks,
getWalletConnectCaipNetworks,
requireCaipAddress
} from './utils/helpers.js'
import { W3mFrameHelpers, W3mFrameRpcConstants } from '@web3modal/wallet'
import type { W3mFrameProvider, W3mFrameTypes } from '@web3modal/wallet'
import { NetworkUtil } from '@web3modal/common'
import { normalize } from 'viem/ens'
import type { AppKitOptions } from '../../../utils/TypesUtil.js'
import type { Chain as AvailableChain, CaipNetworkId } from '@web3modal/common'
import { ConstantsUtil as CommonConstantsUtil } from '@web3modal/common'
import type { AppKit } from '../../../src/client.js'
// -- Types ---------------------------------------------------------------------
export interface AdapterOptions<C extends Config>
extends Pick<AppKitOptions, 'siweConfig' | 'enableEIP6963'> {
wagmiConfig: C
defaultChain?: Chain
}
// @ts-expect-error: Overridden state type is correct
interface Web3ModalState extends PublicStateControllerState {
selectedNetworkId: number | undefined
}
// -- Client --------------------------------------------------------------------
export class EVMWagmiClient implements ChainAdapter {
// -- Private variables -------------------------------------------------------
private appKit: AppKit | undefined = undefined
private wagmiConfig: AdapterOptions<Config>['wagmiConfig']
// -- Public variables --------------------------------------------------------
public options: AppKitOptions | undefined = undefined
public chain: AvailableChain = CommonConstantsUtil.CHAIN.EVM
public networkControllerClient: NetworkControllerClient
public connectionControllerClient: ConnectionControllerClient
public defaultChain: CaipNetwork | undefined = undefined
public tokens = HelpersUtil.getCaipTokens(this.options?.tokens)
public getCaipDefaultChain = this.options?.defaultChain
public siweControllerClient = this.options?.siweConfig
public constructor(options: AdapterOptions<Config>) {
const { wagmiConfig, defaultChain } = options
if (!wagmiConfig) {
throw new Error('wagmiConfig is undefined')
}
this.wagmiConfig = wagmiConfig
this.defaultChain = getCaipDefaultChain(defaultChain)
this.siweControllerClient = options.siweConfig
this.networkControllerClient = {
switchCaipNetwork: async caipNetwork => {
const chainId = NetworkUtil.caipNetworkIdToNumber(caipNetwork?.id)
if (chainId) {
await switchChain(this.wagmiConfig, { chainId })
}
},
getApprovedCaipNetworksData: async () =>
new Promise(resolve => {
const connections = new Map(this.wagmiConfig.state.connections)
const connection = connections.get(this.wagmiConfig.state.current || '')
if (connection?.connector?.id === ConstantsUtil.AUTH_CONNECTOR_ID) {
resolve(getEmailCaipNetworks())
} else if (connection?.connector?.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID) {
const connector = this.wagmiConfig.connectors.find(
c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID
)
resolve(getWalletConnectCaipNetworks(connector))
}
resolve({ approvedCaipNetworkIds: undefined, supportsAllNetworks: true })
})
}
this.connectionControllerClient = {
connectWalletConnect: async onUri => {
const siweConfig = this.options?.siweConfig
const connector = this.wagmiConfig.connectors.find(
c => c.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID
)
if (!connector) {
throw new Error('connectionControllerClient:getWalletConnectUri - connector is undefined')
}
const provider = (await connector.getProvider()) as Awaited<
ReturnType<(typeof EthereumProvider)['init']>
>
provider.on('display_uri', data => {
onUri(data)
})
const clientId = await provider.signer?.client?.core?.crypto?.getClientId()
if (clientId) {
this.appKit?.setClientId(clientId)
}
const chainId = NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id)
const siweParams = await siweConfig?.getMessageParams?.()
// Make sure client uses ethereum provider version that supports `authenticate`
if (
siweConfig?.options?.enabled &&
typeof provider?.authenticate === 'function' &&
siweParams &&
Object.keys(siweParams || {}).length > 0
) {
const { SIWEController, getDidChainId, getDidAddress } = await import('@web3modal/siwe')
// @ts-expect-error - setting requested chains beforehand avoids wagmi auto disconnecting the session when `connect` is called because it things chains are stale
await connector.setRequestedChainsIds(siweParams.chains)
// Make active chain first in requested chains to make it default for siwe message
let reorderedChains = siweParams.chains
if (chainId) {
reorderedChains = [chainId, ...siweParams.chains.filter(c => c !== chainId)]
}
const result = await provider.authenticate({
nonce: await siweConfig.getNonce(),
methods: [...OPTIONAL_METHODS],
...siweParams,
chains: reorderedChains
})
// Auths is an array of signed CACAO objects https://github.com/ChainAgnostic/CAIPs/blob/main/CAIPs/caip-74.md
const signedCacao = result?.auths?.[0]
if (signedCacao) {
const { p, s } = signedCacao
const cacaoChainId = getDidChainId(p.iss) || ''
const address = getDidAddress(p.iss)
if (address && cacaoChainId) {
SIWEController.setSession({
address,
chainId: parseInt(cacaoChainId, 10)
})
}
try {
// Kicks off verifyMessage and populates external states
const message = provider.signer.client.formatAuthMessage({
request: p,
iss: p.iss
})
await SIWEController.verifyMessage({
message,
signature: s.s,
cacao: signedCacao
})
} catch (error) {
// eslint-disable-next-line no-console
console.error('Error verifying message', error)
// eslint-disable-next-line no-console
await provider.disconnect().catch(console.error)
// eslint-disable-next-line no-console
await SIWEController.signOut().catch(console.error)
throw error
}
}
/*
* Unassign the connector from the wagmiConfig and allow connect() to reassign it in the next step
* this avoids case where wagmi throws because the connector is already connected
* what we need connect() to do is to only setup internal event listeners
*/
this.wagmiConfig.state.current = ''
}
await connect(this.wagmiConfig, { connector, chainId })
},
connectExternal: async ({ id, provider, info }) => {
const connector = this.wagmiConfig.connectors.find(c => c.id === id)
if (!connector) {
throw new Error('connectionControllerClient:connectExternal - connector is undefined')
}
this.appKit?.setClientId(null)
if (provider && info && connector.id === ConstantsUtil.EIP6963_CONNECTOR_ID) {
// @ts-expect-error Exists on EIP6963Connector
connector.setEip6963Wallet?.({ provider, info })
}
const chainId = NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id)
await connect(this.wagmiConfig, { connector, chainId })
},
checkInstalled: ids => {
const injectedConnector = this.appKit
?.getConnectors()
.find((c: Connector) => c.type === 'INJECTED')
if (!ids) {
return Boolean(window.ethereum)
}
if (injectedConnector) {
if (!window?.ethereum) {
return false
}
return ids.some(id => Boolean(window.ethereum?.[String(id)]))
}
return false
},
disconnect: async () => {
await disconnect(this.wagmiConfig)
this.appKit?.setClientId(null)
if (this.options?.siweConfig?.options?.signOutOnDisconnect) {
const { SIWEController } = await import('@web3modal/siwe')
await SIWEController.signOut()
}
},
signMessage: async message => {
const caipAddress = this.appKit?.getCaipAddress() || ''
const account = requireCaipAddress(caipAddress)
return signMessage(this.wagmiConfig, { message, account })
},
estimateGas: async args => {
try {
return await wagmiEstimateGas(this.wagmiConfig, {
account: args.address,
to: args.to,
data: args.data,
type: 'legacy'
})
} catch (error) {
return 0n
}
},
sendTransaction: async (data: SendTransactionArgs) => {
const { chainId } = getAccount(this.wagmiConfig)
const txParams = {
account: data.address,
to: data.to,
value: data.value,
gas: data.gas,
gasPrice: data.gasPrice,
data: data.data,
chainId,
type: 'legacy' as const
}
await prepareTransactionRequest(this.wagmiConfig, txParams)
const tx = await wagmiSendTransaction(this.wagmiConfig, txParams)
await waitForTransactionReceipt(this.wagmiConfig, { hash: tx, timeout: 25000 })
return tx
},
writeContract: async (data: WriteContractArgs) => {
const caipAddress = this.appKit?.getCaipAddress() || ''
const account = requireCaipAddress(caipAddress)
const chainId = NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id)
const tx = await wagmiWriteContract(this.wagmiConfig, {
chainId,
address: data.tokenAddress,
account,
abi: data.abi,
functionName: data.method,
args: [data.receiverAddress, data.tokenAmount]
})
return tx
},
getEnsAddress: async (value: string) => {
try {
const chainId = NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id)
let ensName: boolean | GetEnsAddressReturnType = false
let wcName: boolean | string = false
if (value?.endsWith(CommonConstants.WC_NAME_SUFFIX)) {
wcName = (await this.appKit?.resolveWalletConnectName(value)) || false
}
if (chainId === mainnet.id) {
ensName = await wagmiGetEnsAddress(this.wagmiConfig, {
name: normalize(value),
chainId
})
}
return ensName || wcName || false
} catch {
return false
}
},
getEnsAvatar: async (value: string) => {
const chainId = NetworkUtil.caipNetworkIdToNumber(this.appKit?.getCaipNetwork()?.id)
if (chainId !== mainnet.id) {
return false
}
const avatar = await wagmiGetEnsAvatar(this.wagmiConfig, {
name: normalize(value),
chainId
})
return avatar || false
},
parseUnits,
formatUnits
}
}
public construct(appKit: AppKit, options: OptionsControllerState) {
if (!options.projectId) {
throw new Error('projectId is undefined')
}
this.appKit = appKit
this.options = options
this.tokens = HelpersUtil.getCaipTokens(options.tokens)
this.syncRequestedNetworks([...this.wagmiConfig.chains])
this.syncConnectors(this.wagmiConfig.connectors)
this.initAuthConnectorListeners([...this.wagmiConfig.connectors])
watchConnectors(this.wagmiConfig, {
onChange: connectors => this.syncConnectors(connectors)
})
watchAccount(this.wagmiConfig, {
onChange: accountData => this.syncAccount({ ...accountData })
})
this.appKit?.setEIP6963Enabled(options.enableEIP6963 !== false)
this.appKit?.subscribeShouldUpdateToAddress((newAddress?: string) => {
if (newAddress) {
const connections = getConnections(this.wagmiConfig)
const connector = connections[0]?.connector
if (connector) {
switchAccount(this.wagmiConfig, {
connector
}).then(response =>
this.syncAccount({
address: newAddress as Hex,
isConnected: true,
addresses: response.accounts,
connector,
chainId: response.chainId
})
)
}
}
})
}
// @ts-expect-error: Overriden state type is correct
public override subscribeState(callback: (state: Web3ModalState) => void) {
return this.appKit?.subscribeState((state: PublicStateControllerState) =>
callback({
...state,
selectedNetworkId: NetworkUtil.caipNetworkIdToNumber(state.selectedNetworkId)
})
)
}
// -- Private -----------------------------------------------------------------
private syncRequestedNetworks(chains: Chain[]) {
const requestedCaipNetworks = chains?.map(
chain =>
({
id: `${ConstantsUtil.EIP155}:${chain.id}`,
name: chain.name,
imageId: PresetsUtil.EIP155NetworkImageIds[chain.id],
imageUrl: this.options?.chainImages?.[chain.id],
chain: this.chain
}) as CaipNetwork
)
this.appKit?.setRequestedCaipNetworks(requestedCaipNetworks ?? [], this.chain)
}
private async syncAccount({
address,
chainId,
connector,
addresses,
status
}: Partial<
Pick<
GetAccountReturnType,
| 'address'
| 'isConnected'
| 'isDisconnected'
| 'chainId'
| 'connector'
| 'addresses'
| 'status'
>
>) {
const caipAddress: CaipAddress = `${ConstantsUtil.EIP155}:${chainId}:${address}`
if (this.appKit?.getCaipAddress() === caipAddress) {
return
}
if (status === 'connected' && address && chainId) {
this.syncNetwork(address, chainId, true)
this.appKit?.setIsConnected(true, this.chain)
this.appKit?.setCaipAddress(caipAddress, this.chain)
await Promise.all([
this.syncProfile(address, chainId),
this.syncBalance(address, chainId),
this.syncConnectedWalletInfo(connector),
this.appKit?.setApprovedCaipNetworksData(this.chain)
])
if (connector) {
this.syncConnectedWalletInfo(connector)
}
// Set by authConnector.onIsConnectedHandler as we need the account type
const isAuthConnector = connector?.id === ConstantsUtil.AUTH_CONNECTOR_ID
if (!isAuthConnector && addresses?.length) {
this.appKit?.setAllAccounts(
addresses.map(addr => ({ address: addr, type: 'eoa' })),
this.chain
)
}
} else if (status === 'disconnected') {
this.appKit?.resetAccount(this.chain)
this.appKit?.resetWcConnection()
this.appKit?.resetNetwork()
this.appKit?.setAllAccounts([], this.chain)
this.appKit?.setIsConnected(false, this.chain)
}
}
private async syncNetwork(address?: Hex, chainId?: number, isConnected?: boolean) {
const chain = this.wagmiConfig.chains.find((c: Chain) => c.id === chainId)
if (chain || chainId) {
const name = chain?.name ?? chainId?.toString()
const id = Number(chain?.id ?? chainId)
const caipChainId: CaipNetworkId = `${ConstantsUtil.EIP155}:${id}`
this.appKit?.setCaipNetwork({
id: caipChainId,
name,
imageId: PresetsUtil.EIP155NetworkImageIds[id],
imageUrl: this.options?.chainImages?.[id],
chain: this.chain
})
if (isConnected && address && chainId) {
const caipAddress: CaipAddress = `${ConstantsUtil.EIP155}:${id}:${address}`
this.appKit?.setCaipAddress(caipAddress, this.chain)
if (chain?.blockExplorers?.default?.url) {
const url = `${chain.blockExplorers.default.url}/address/${address}`
this.appKit?.setAddressExplorerUrl(url, this.chain)
} else {
this.appKit?.setAddressExplorerUrl(undefined, this.chain)
}
await this.syncBalance(address, chainId)
}
}
}
private async syncWalletConnectName(address: Hex) {
if (!this.appKit) {
throw new Error('syncWalletConnectName - appKit is undefined')
}
try {
const registeredWcNames = await this.appKit.getWalletConnectName(address)
if (registeredWcNames[0]) {
const wcName = registeredWcNames[0]
this.appKit?.setProfileName(wcName.name, this.chain)
} else {
this.appKit?.setProfileName(null, this.chain)
}
} catch {
this.appKit?.setProfileName(null, this.chain)
}
}
private async syncProfile(address: Hex, chainId: Chain['id']) {
if (!this.appKit) {
throw new Error('syncProfile - appKit is undefined')
}
try {
const { name, avatar } = await this.appKit.fetchIdentity({
address
})
this.appKit?.setProfileName(name, this.chain)
this.appKit?.setProfileImage(avatar, this.chain)
if (!name) {
await this.syncWalletConnectName(address)
}
} catch {
if (chainId === mainnet.id) {
const profileName = await getEnsName(this.wagmiConfig, { address, chainId })
if (profileName) {
this.appKit?.setProfileName(profileName, this.chain)
const profileImage = await wagmiGetEnsAvatar(this.wagmiConfig, {
name: profileName,
chainId
})
if (profileImage) {
this.appKit?.setProfileImage(profileImage, this.chain)
}
} else {
await this.syncWalletConnectName(address)
this.appKit?.setProfileImage(null, this.chain)
}
} else {
await this.syncWalletConnectName(address)
this.appKit?.setProfileImage(null, this.chain)
}
}
}
private async syncBalance(address: Hex, chainId: number) {
const chain = this.wagmiConfig.chains.find((c: Chain) => c.id === chainId)
if (chain) {
const balance = await getBalance(this.wagmiConfig, {
address,
chainId: chain.id,
token: this.options?.tokens?.[chain.id]?.address as Hex
})
this.appKit?.setBalance(balance.formatted, balance.symbol, this.chain)
return
}
this.appKit?.setBalance(undefined, undefined, this.chain)
}
private async syncConnectedWalletInfo(connector: GetAccountReturnType['connector']) {
if (!connector) {
throw Error('syncConnectedWalletInfo - connector is undefined')
}
if (connector.id === ConstantsUtil.WALLET_CONNECT_CONNECTOR_ID && connector.getProvider) {
const walletConnectProvider = (await connector.getProvider()) as Awaited<
ReturnType<(typeof EthereumProvider)['init']>
>
if (walletConnectProvider.session) {
this.appKit?.setConnectedWalletInfo(
{
...walletConnectProvider.session.peer.metadata,
name: walletConnectProvider.session.peer.metadata.name,
icon: walletConnectProvider.session.peer.metadata.icons?.[0]
},
this.chain
)
}
} else {
const wagmiConnector = this.appKit?.getConnectors().find(c => c.id === connector.id)
this.appKit?.setConnectedWalletInfo(
{
name: connector.name,
icon: connector.icon || this.appKit.getConnectorImage(wagmiConnector)
},
this.chain
)
}
}
private syncConnectors(connectors: AdapterOptions<Config>['wagmiConfig']['connectors']) {
const uniqueIds = new Set()
const filteredConnectors = connectors.filter(
item => !uniqueIds.has(item.id) && uniqueIds.add(item.id)
)
const w3mConnectors: Connector[] = []
filteredConnectors.forEach(({ id, name, type, icon }) => {
// Auth connector is initialized separately
const shouldSkip = ConstantsUtil.AUTH_CONNECTOR_ID === id
if (!shouldSkip) {
w3mConnectors.push({
id,
explorerId: PresetsUtil.ConnectorExplorerIds[id],
imageUrl: this.options?.connectorImages?.[id] ?? icon,
name: PresetsUtil.ConnectorNamesMap[id] ?? name,
imageId: PresetsUtil.ConnectorImageIds[id],
type: PresetsUtil.ConnectorTypesMap[type] ?? 'EXTERNAL',
info: {
rdns: id
},
chain: this.chain
})
}
})
this.appKit?.setConnectors(w3mConnectors)
this.syncAuthConnector(filteredConnectors)
}
private async syncAuthConnector(connectors: AdapterOptions<Config>['wagmiConfig']['connectors']) {
const authConnector = connectors.find(
({ id }) => id === ConstantsUtil.AUTH_CONNECTOR_ID
) as unknown as AdapterOptions<Config>['wagmiConfig']['connectors'][0] & {
email: boolean
socials: SocialProvider[]
showWallets?: boolean
walletFeatures?: boolean
}
if (authConnector) {
const provider = await authConnector.getProvider()
this.appKit?.addConnector({
id: ConstantsUtil.AUTH_CONNECTOR_ID,
type: 'AUTH',
name: 'Auth',
provider,
email: authConnector.email,
socials: authConnector.socials,
showWallets: authConnector.showWallets,
chain: this.chain,
walletFeatures: authConnector.walletFeatures
})
}
}
private async initAuthConnectorListeners(
connectors: AdapterOptions<Config>['wagmiConfig']['connectors']
) {
const authConnector = connectors.find(({ id }) => id === ConstantsUtil.AUTH_CONNECTOR_ID)
if (authConnector) {
await this.listenAuthConnector(authConnector)
await this.listenModal(authConnector)
}
}
private async listenAuthConnector(
connector: AdapterOptions<Config>['wagmiConfig']['connectors'][number]
) {
if (typeof window !== 'undefined' && connector) {
this.appKit?.setLoading(true)
const provider = (await connector.getProvider()) as W3mFrameProvider
const isLoginEmailUsed = provider.getLoginEmailUsed()
this.appKit?.setLoading(isLoginEmailUsed)
if (isLoginEmailUsed) {
this.appKit?.setIsConnected(false, this.chain)
}
provider.onRpcRequest((request: W3mFrameTypes.RPCRequest) => {
if (W3mFrameHelpers.checkIfRequestExists(request)) {
if (!W3mFrameHelpers.checkIfRequestIsSafe(request)) {
this.appKit?.handleUnsafeRPCRequest()
}
} else {
this.appKit?.open()
// eslint-disable-next-line no-console
console.error(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_MESSAGE, {
method: request.method
})
setTimeout(() => {
this.appKit?.showErrorMessage(W3mFrameRpcConstants.RPC_METHOD_NOT_ALLOWED_UI_MESSAGE)
}, 300)
provider.rejectRpcRequests()
}
})
provider.onRpcError(() => {
const isModalOpen = this.appKit?.isOpen()
if (isModalOpen) {
if (this.appKit?.isTransactionStackEmpty()) {
this.appKit?.close()
} else {
this.appKit?.popTransactionStack(true)
}
}
})
provider.onRpcSuccess((_, request) => {
const isSafeRequest = W3mFrameHelpers.checkIfRequestIsSafe(request)
if (isSafeRequest) {
return
}
if (this.appKit?.isTransactionStackEmpty()) {
this.appKit?.close()
} else {
this.appKit?.popTransactionStack()
}
})
provider.onNotConnected(() => {
const isConnected = this.appKit?.getIsConnectedState()
if (!isConnected) {
this.appKit?.setIsConnected(false, this.chain)
this.appKit?.setLoading(false)
}
})
provider.onIsConnected(req => {
this.appKit?.setIsConnected(true, this.chain)
this.appKit?.setSmartAccountDeployed(Boolean(req.smartAccountDeployed), this.chain)
this.appKit?.setPreferredAccountType(
req.preferredAccountType as W3mFrameTypes.AccountType,
this.chain
)
this.appKit?.setLoading(false)
this.appKit?.setAllAccounts(
req.accounts || [
{
address: req.address,
type: (req.preferredAccountType || 'eoa') as W3mFrameTypes.AccountType
}
],
this.chain
)
})
provider.onGetSmartAccountEnabledNetworks(networks => {
this.appKit?.setSmartAccountEnabledNetworks(networks, this.chain)
})
provider.onSetPreferredAccount(({ address, type }) => {
if (!address) {
return
}
this.appKit?.setPreferredAccountType(type as W3mFrameTypes.AccountType, this.chain)
reconnect(this.wagmiConfig, { connectors: [connector] })
})
}
}
private async listenModal(
connector: AdapterOptions<Config>['wagmiConfig']['connectors'][number]
) {
const provider = (await connector.getProvider()) as W3mFrameProvider
this.subscribeState(val => {
if (!val.open) {
provider.rejectRpcRequests()
}
})
}
}