-
Notifications
You must be signed in to change notification settings - Fork 370
/
Copy pathWalletConnectUtil.ts
78 lines (73 loc) · 2.33 KB
/
WalletConnectUtil.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
import { Web3Wallet, IWeb3Wallet } from '@walletconnect/web3wallet'
import { Core } from '@walletconnect/core'
export let web3wallet: IWeb3Wallet
export async function createWeb3Wallet(relayerRegionURL: string) {
const core = new Core({
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
relayUrl: relayerRegionURL ?? process.env.NEXT_PUBLIC_RELAY_URL,
logger: 'debug'
})
web3wallet = await Web3Wallet.init({
core,
metadata: {
name: 'React Wallet Example',
description: 'React Wallet for WalletConnect',
url: 'https://walletconnect.com/',
icons: ['https://avatars.githubusercontent.com/u/37784886']
}
})
try {
const clientId = await web3wallet.engine.signClient.core.crypto.getClientId()
console.log('WalletConnect ClientID: ', clientId)
localStorage.setItem('WALLETCONNECT_CLIENT_ID', clientId)
} catch (error) {
console.error('Failed to set WalletConnect clientId in localStorage: ', error)
}
}
export async function updateSignClientChainId(chainId: string, address: string) {
console.log('chainId', chainId, address)
// get most recent session
const sessions = web3wallet.getActiveSessions()
if (!sessions) return
const namespace = chainId.split(':')[0]
Object.values(sessions).forEach(async session => {
await web3wallet.updateSession({
topic: session.topic,
namespaces: {
...session.namespaces,
[namespace]: {
...session.namespaces[namespace],
chains: [
...new Set([chainId].concat(Array.from(session?.namespaces?.[namespace]?.chains || [])))
],
accounts: [
...new Set(
[`${chainId}:${address}`].concat(
Array.from(session?.namespaces?.[namespace]?.accounts || [])
)
)
]
}
}
})
await new Promise(resolve => setTimeout(resolve, 1000))
const chainChanged = {
topic: session.topic,
event: {
name: 'chainChanged',
data: parseInt(chainId.split(':')[1])
},
chainId: chainId
}
const accountsChanged = {
topic: session.topic,
event: {
name: 'accountsChanged',
data: [`${chainId}:${address}`]
},
chainId
}
await web3wallet.emitSessionEvent(chainChanged)
await web3wallet.emitSessionEvent(accountsChanged)
})
}