文章目录[隐藏]
eip-155 定义的 eth 的 chainID
CHAIN_ID | Chain(s) |
---|---|
1 | Ethereum mainnet |
2 | Morden (disused), Expanse mainnet |
3 | Ropsten |
4 | Rinkeby |
5 | Goerli |
42 | Kovan |
1337 | Geth private chains (default) |
ethers.utils.HDNode.isValidMnemonic(): 验证助记词是否有效
ethers.utils.getAddress():转换为 checkSum 地址
1. send 方法后面可写入 rpc 调用方法名(eth 标准方法),后面跟参数
personal_importRawKey
let lockStatus = await rpcProvider.send(“personal_lockAccount”, address)
2.查询 token 余额
const getBalance_USDT = async () => { const contract = new ethers.Contract(USDTaddress, USDTabi, rpcProvider); const balance = await contract.balanceOf(address); return balance.toString(); };
//6 为 token 有效小数位。查到的余额除以有效小数位才是实际余额
let actuBalUSDT = ethers.utils.formatUnits(queryBalUSDT, 6)
3.查询 eth 余额
<code class="has-numbering"> let pendingBal = await rpcProvider.getBalance(address, "pending")</code>
查询不同状态的余额”latest”(已经确认了的), “earliest”(创世区块的) , “pending”(包含未确认的交易的余额)
4.utils
//去除地址前面的 0 位
let address = ethers.utils.hexStripZeros(addressQuery)
// 相当于从 wei 到 ether
let numberOfDecimals = 18;
let BNBbal = ethers.utils.parseUnits(queryBalBNB, numberOfDecimals);
5.发送 eth 交易
let wallet = new ethers.Wallet(privateKey, provider); let amount = ethers.utils.parseEther(amount); //let nonce = await rpcProvider.getTransactionCount(address, "pending") let nonce = await wallet.getTransactionCount(); let gasPrice=await provider.getGasPrice(); let tx = { nonce: nonce, gasLimit: 21000, gasPrice: ethers.utils.bigNumberify(gasPrice), to: toAddress, chainId: chainId, value: amount, data: "" }; // let signTx = await wallet.sign(tx) // let resp = await rpcProvider.sendTransaction(signTx) 或 let resp = await wallet.sendTransaction(tx);
6.发送 token 交易
let numberOfTokens = ethers.utils.parseUnits(amount, decims); // 先计算 transfer 需要的 gas 消耗量,这一步有默认值,非必须。 let gas = await contract.estimate.transfer(toAddress, numberOfTokens) let gasP = await rpcProvider.getGasPrice() // 必须关联一个有过签名钱包对象 let contractWithSigner = contract.connect(wallet); // 发起交易,前面 2 个参数是函数的参数,第 3 个是交易参数 let tx = await contractWithSigner.transfer(toAddress, numberOfTokens, { nonce: nonce, gasLimit: gas, gasPrice: ethers.utils.bigNumberify(gasP) , chainId: chainId })
7.获取节点所有账户的余额
async function checkAllBalances() { let e = await rpcProvider.listAccounts() for (let i = 0; i < e.length; i++) { let bal = await rpcProvider.getBalance(e[i]) let balance = ethers.utils.formatEther(bal) console.log(`${e[i]}: `+balance) } } checkAllBalances();
8. 单位转换
// 转换 cost 为 wei 单位的 BigNumber 类型 const costWei = ethers.utils.bigNumberify(21000).mul('0x3b9aca00') console.log(costWei); // 转换 cost 为 ether 单位的一般表示(可读的 10 进制) const costEther = ethers.utils.formatEther(costWei) console.log(costEther); // 转换 cost 为 ether 单位的 BigNumber 类型 const costBigNumber = ethers.utils.parseEther(costEther); console.log(costBigNumber); // 余额减去花费作为 新的转入余额, const amount = pendingBal.sub(costBigNumber) console.log(ethers.utils.formatEther(amount));