WalletContract区块钱包链接到web3js
安装walletconnect
npm install --save web3 @walletconnect/web3-provider
官方给出的使用方法,并不能连接到想要的区块网络 默认是1
import WalletConnectProvider from "@walletconnect/web3-provider"; // Create WalletConnect Provider const provider = new WalletConnectProvider({ rpc: { 1: "https://mainnet.mycustomnode.com", 3: "https://ropsten.mycustomnode.com", 100: "https://dai.poa.network", // ... }, }); // Enable session (triggers QR Code modal) await provider.enable();
对其进行小小的修改
// 获取钱包地址async function Init(callback) {if (web3 != undefined) {const accounts = await web3.eth.getAccounts();callback(accounts[0])}}function _WalletContract(callback) {provider = new WalletConnectProvider({rpc: {66: "https://exchainrpc.okex.org",},"chainId": 66,//需要连接的区块链id"networkId": 66,qrcode: true,//二维码是否开启});provider.enable().then((res) => {web3 = new Web3(provider);//账户更改触发的方法provider.on("accountsChanged", (accounts) => {callback(accounts)});//账户断开的方法provider.on("disconnect", (code, reason) => {web3 = nullcallback(code)});//这里返回的是链接地址Init((accounts) => {callback(accounts)})}).catch((err) => {callback("fail")});}
这样的话所有支持WalletContract的钱包都能连接到,并能得到所需要的需求
文章版权声明:除非注明,否则均为彭超的博客原创文章,转载或复制请以超链接形式并注明出处。
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。