web3.js和ether.js连接MetaMask钱包,并查询余额!

  • dlnuchunge
  • 更新于 2023-09-07 15:57
  • 阅读 2377

web3.js和ether.js连接MetaMask钱包,并查询余额!

一、web3.js

const web3_connect = async () => {
        const rpcURL = "https://mainnet.infura.io/v3/xxxx"

        let web3 = new Web3(window.ethereum || rpcURL);

        //获取账号地址
        let accounts = await web3.eth.requestAccounts()

        let address = accounts[0];

        //查询余额
        let wei = await web3.eth.getBalance(address);
        balance = web3.utils.fromWei(wei, 'ether')
        console.log("balance: " + balance)

    }

二、ether.js

const ether_connect = async () => {
        const provider = new ethers.providers.Web3Provider(web3.currentProvider);
        let signer = null;
        let address = null;
        if (!provider) {
            return;
        }

        //请求获取账号
        await provider.send('eth_requestAccounts', []);

        signer = provider.getSigner();
        // 获取账号地址
        address = await signer.getAddress();
        //查询余额
        provider.getBalance(address).then((balance) => {
            // 余额是 BigNumber (in wei); 格式化为 ether 字符串
            let etherString = ethers.utils.formatEther(balance);
            console.log("Balance: " + etherString);
        });
    }
点赞 1
收藏 0
分享
本文参与登链社区写作激励计划 ,好文好收益,欢迎正在阅读的你也加入。

0 条评论

请先 登录 后评论
dlnuchunge
dlnuchunge
0x0d2e...8b3F
看好Web3,自学Web3前端,想找份Web3相关工作!