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余额
let pendingBal = await rpcProvider.getBalance(address, "pending")
查询不同状态的余额”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));
来源:CSDN
作者:weixin_42248522
链接:https://blog.csdn.net/weixin_42248522/article/details/104054218