gpt4 book ai didi

javascript - 使用 Ethers JS 估算 gas 价格

转载 作者:行者123 更新时间:2023-12-05 05:44:13 25 4
gpt4 key购买 nike

我正在尝试制作一个简单的 js 机器人,它检查每个区 block 的 eth(或链的主要 token )并将其发送到另一个钱包。

我有一个工作机器人:

const { ethers } = require('ethers')

const provider = new ethers.providers.JsonRpcProvider("")

const addressReceiver = ''

const privateKeys = [""]


const bot = async =>{
provider.on('block', async () => {
console.log('Listening to new block, waiting ;)');
for (let i = 0; i < privateKeys.length; i++){

const _target = new ethers.Wallet(privateKeys[i]);
const target = _target.connect(provider);
const balance = await provider.getBalance(target.address);
const txBuffer = ethers.utils.parseEther('0.005');
if (balance.sub(txBuffer) > 0){
console.log("New Account with Eth!");
const amount = balance.sub(txBuffer);
try {
await target.sendTransaction({
to: addressReceiver,
value: amount
});
console.log(`Success! transferred -->${ethers.utils.formatEther(balance)}`);
} catch(e){
console.log(`error: ${e}`);
}
}
}
})
}
bot();

但这有一个设置的交易缓冲区,在机器人运行后最终会在钱包中留下一些 eth。我想估算费用,然后从取出的总额中减去这些费用。像这样:

const {
ethers
} = require('ethers')

const provider = new ethers.providers.JsonRpcProvider("")

const addressReceiver = ''

const privateKeys = [""]

const bot = async =>{
provider.on('block', async () => {
console.log('Listening to new block, waiting ;)');

for (let i = 0; i < privateKeys.length; i++) {
const _target = new ethers.Wallet(privateKeys[i]);
const target = _target.connect(provider);
const balance = await provider.getBalance(target.address);
const gasLimit = await provider.estimateGas({
to: addressReceiver,
value: await provider.getBalance(target.address),
gasLimit: 21000,
gasPrice: ethers.utils.parseUnits('10', 'gwei'),
nonce: await provider.getTransactionCount(privateKeys[i])
})


if (balance.sub(gasLimit) > 0) {
console.log("New Account with Eth!");
const amount = balance.sub(gasLimit);
try {
await target.sendTransaction({
to: addressReceiver,
value: amount
});
console.log(`Success! transferred -->${ethers.utils.formatEther(balance)}`);
} catch (e) {
console.log(`error: ${e}`);
}
}
}
})

}
bot();

但这会抛出一个 ENS name not configured 错误。

最佳答案

这里有几个问题:

  1. 未计算出 ENS 名称可能是因为 addressReceiver 是一个 ENS 名称(以 .eth 结尾),而不是地址(以 0x)。使用地址。

  2. amount = balance.sub(gasLimit) 不对。 gasLimit 是使用的gas量,不是eth。您需要将其乘以每燃气费才能获得 ETH。计算出确切费用的最简单方法是将 tx.maxFeePerGastx.maxPriorityFeePerGas 设置为相同的值。这将导致你在大多数时候多付钱。那么新代码将是 amount = balance.sub(tx.maxFeePerGas.mul(gasLimit))

关于javascript - 使用 Ethers JS 估算 gas 价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71640718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com