wallet-connect-web-examples/wallets/react-wallet-v2/src/utils/WalletConnectUtil.ts
Gancho Radkov 2e23016873
feat: just works (#261)
* feat: implements just works in example dapp

* feat: implements just works in example wallet

* feat: adds toast on app pairing attempt

* chore: updates canary

* refactor: resets app only after successful disconnect

* chore: updates wallet canary

* fix: modal state

* chore: updates canary to rc

* fix: session update & session events

* fix: fixes accounts changed and updates canary

* chore: updates dapp canary

* chore: updates examples to latest

---------

Co-authored-by: Gancho Radkov <ganchoradkov@gmail.com>
2023-08-17 19:53:56 +03:00

73 lines
2.1 KiB
TypeScript

import SignClient from '@walletconnect/sign-client'
export let signClient: SignClient
export async function createSignClient(relayerRegionURL: string) {
signClient = await SignClient.init({
logger: 'debug',
projectId: process.env.NEXT_PUBLIC_PROJECT_ID,
relayUrl: relayerRegionURL ?? process.env.NEXT_PUBLIC_RELAY_URL,
metadata: {
name: 'React Wallet',
description: 'React Wallet for WalletConnect',
url: 'https://walletconnect.com/',
icons: ['https://avatars.githubusercontent.com/u/37784886']
}
})
try {
const clientId = await 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 = signClient.session.getAll()
if (!sessions) return
const namespace = chainId.split(':')[0]
sessions.forEach(async session => {
await signClient.update({
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 signClient.emit(chainChanged)
await signClient.emit(accountsChanged)
})
}