<aside> 💡 如何在浏览器Console环境里,通过MetaMask钱包,使用JavaScript程序,获取Ethereum链上数据并发送交易
</aside>
区块链
const block = await ethereum.request({
method: 'eth_getBlockByNumber',
params: [
'latest',
true
]
});
console.log(block);
账户
// 查看地址
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);
转账
// 发起交易
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);