获取钱包地址信息
Account:
Network:
ChainId:
给某个钱包进行转帐
网络 和 地址切换 触发事件
current network:
current address:
获取钱包余额
const initialize = async ()=>{const isMetaMaskInstalled = ()=>{const { ethereum } = window;if (typeof ethereum === 'undefined'){return false;}return Boolean(ethereum && ethereum.isMetaMask);}const getAccount = async ()=>{try{// 连接就可以获取 // const accounts = await ethereum.request({method:'eth_requestAccounts'});// 登陆之后的权限const accounts = await ethereum.request({method:'eth_accounts'});accountsSpan.innerHTML = accounts;}catch (e) {console.error(e)}}const getNetworkAndChainId = async ()=>{try {const chainId = awaitethereum.request({method:'eth_chainId'});chainIdSpan.innerHTML =chainId;const networkId = awaitethereum.request({method:'net_version'});networkSpan.innerHTML = networkId;}catch (e) {console.error(e);}}const checkMetaMaskClient = async ()=>{if (!isMetaMaskInstalled()){alert("please install metaMask");}else {getNetworkAndChainId();getAccount();}}checkMetaMaskClient();}sendBtn.onclick = async () => {try {constaccounts = awaitethereum.request({method:'eth_requestAccounts'});// 初始化 web3web3 = new Web3(web3.currentProvider);if (web3.currentProvider.isMetaMask == true) {console.info("MetaMask可用")} else {console.info("非MetaMask环境")}web3.eth.sendTransaction({from:accounts[0],to:'0x4CCbD5D055fAd49d9278a6c43F1d27b9537737b5',value: 100000000000000000,gas: 21000,gasPrice: 20000000000},(result) =>{console.log(result);})}catch (e) {console.error(e)}}// 监听 地址变化ethereum.on('accountsChanged',function (accounts) {console.info("地址发生变化");currentAddress.innerHTML = accounts;})// 监听 链变化ethereum.on('chainChanged',function (network) {console.info("链 发生变化");currentNetwork.innerHTML = network;})//获取钱包余额balanceBtn.onclick = async ()=>{console.info("获取钱包余额")ethereum.request({method:'eth_getBalance',params:['0xA07843c563544941ACA9a2c0BB3361cdAB6601Fd','latest']}).then((result) =>{console.info("result:",result)console.info("result1:",parseInt(result, 16)/1000000000000000000)balanceSpan.innerHTML = parseInt(result, 16)/1000000000000000000 + "eth";}).catch(e =>{console.error(e)})}window.addEventListener("DOMContentLoaded",initialize);