2022-06-15 21:50:04 +08:00

71 lines
1.7 KiB
JavaScript

import {AllChains} from './allchain'
export class BlockChain{
constructor() {
this.rpc= {}
for (const d of AllChains) {
const id = d.id
this.rpc[id] = d.rpc
}
}
async connectWallet() {
this.provider = await this.connectWalletConnect()
if (!this.provider) {
return
}
this.web3 = new Web3(this.provider)
const chainId = await this.web3.eth.getChainId()
this.subscribeToEvents()
}
async connectWalletConnect() {
const provider = new WalletConnectProvider.default({
infuraId: 'e7743d46923911fa8850619b7a7f6d9d',
rpc: this.rpc
})
try {
await provider.enable()
} catch (err) {
console.log('connect to wallet connect error: ', err)
await Promise.reject(err)
}
return provider
}
subscribeToEvents = () => {
// Subscribe to accounts change
this.provider.on('accountsChanged', async(accounts) => {
console.log('accountsChanged: ', accounts)
if (accounts && accounts.length > 0) {
this.accountId = accounts[0]
}
})
this.provider.on('wc_uri_change', async(uri) => {
console.log('wc_uri_change: ', uri)
jsb.reflection.callStaticMethod(
'org/cocos2dx/javascript/AppActivity',
'connectwallet',
'(Ljava/lang/String;)V',
uri
)
})
// Subscribe to chainId change
this.provider.on('chainChanged', async(chainId) => {
console.log('chainChanged', chainId)
const chainIdNum = parseInt(chainId)
this.chainId = chainIdNum
// this.saveProvider()
})
// Subscribe to session disconnection
this.provider.on('disconnect', (err) => {
console.log('disconnect', err)
})
}
}