<aside> 💡 如何在浏览器Console环境里,通过MetaMask钱包,使用JavaScript程序,获取Ethereum链上数据并发送交易

</aside>

Metamask钱包

  1. 安装:https://metamask.io/
  2. 生成钱包
  3. 文档:https://docs.metamask.io/guide/

Ethereum测试网

  1. 加入测试网:Goerli
  2. 水龙头领币:https://faucets.chain.link/goerli
  3. 测试网浏览器:https://goerli.etherscan.io/

JavaScript编程

  1. 区块链

    const block = await ethereum.request({
      method: 'eth_getBlockByNumber',
      params: [
        'latest',
        true
      ]
    });
    console.log(block);
    
  2. 账户

    // 查看地址
    const accounts = await ethereum.request({method: 'eth_requestAccounts'});
    console.log(accounts);
    const account = accounts[0];
    console.log(account);
    
    // 查看余额
    const balance = await ethereum.request({
      method: 'eth_getBalance',
      params: [
        account,
        'latest'
      ]
    });
    console.log(balance);
    console.log(Number(balance));
    console.log(Number(balance)/1e18);
    
  3. 转账

    // 发起交易
    const txHash = await ethereum.request({
      method: 'eth_sendTransaction',
      params: [{
        from: account,
        to: '0x0F4b61d75Afbe799324aaE924199226875aFD4E4',
        value: Number(0.05 * 1e18).toString(16),
      }],
    });
    console.log(txHash);
    
    // 查看交易
    const tx = await ethereum.request({
      method: 'eth_getTransactionByHash',
      params: [txHash]
    });
    console.log(tx);
    
    // 查看交易回执
    const txReceipt = await ethereum.request({
      method: 'eth_getTransactionReceipt',
      params: [txHash]
    });
    console.log(txReceipt);
    
  4. 更多API:https://eth.wiki/json-rpc/API