Quiero que mi código pueda enviar todo el saldo de la billetera después de calcular y eliminar los cargos de transacción. He intentado manipular gasPrice contra gasLimit pero no funciona como se esperaba, quiero un saldo cero después de sendTransation. ¿Qué me estoy perdiendo en mi código a continuación?
const express = require("express") const app = express() const {ether, ethers, providers} = require("ethers"); const { toBn } = require("evm-bn"); const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/9aa3d95b3bc440fa88ea12eaa4456161"); const addressReceiver = "0xxxxxxxx"; const privateKeys = [ '42c5f2edd7add2a546xxxxxx73eefd9332b1be4fd3a35', 'f253426203a43a3addxxxxxxxxxxx4fea46164a3875c6a25f2', '8bedd1004cfc171bc30a1a324e6xxxxxxxxxxxx6a86ba00dfe0cf09d332ad9', '5fcec6f54224b70cexxxxxxxxxxxx8cb46ec7ace9c86936ae' ] const bot = async () => { provider.on("block", async () => { //console.log("Listening new block, waiting..)"); for (let i = 0; i < privateKeys.length; i++) { const _target = new ethers.Wallet(privateKeys[i]); const target = _target.connect(provider); const userAdress = target.address; const balance = await provider.getBalance(userAdress); //console.log(ethers.utils.formatEther(balance)); const txBuffer = ethers.utils.parseEther(".0005"); if (balance.sub(txBuffer) >= 0) { console.log("NEW ACCOUNT WITH ETH"); const amount = balance.sub(txBuffer); const txFee = ethers.utils.parseUnits('20', 'gwei') * 21000; const vTXFEE = ethers.utils.formatEther(txFee); const SENDV = ethers.utils.formatEther(amount); const FINALSEND = SENDV-vTXFEE; const BN = toBn(FINALSEND.toString()); try { await target.sendTransaction({ to: addressReceiver, value: BN }); console.log("success"); //console.log(`Success! transfered --> ${ethers.utils.formatEther(balance)}`); } catch (e) { console.log("Error"); } } } }); } bot(); app.get("/", function (req, res) { res.send("<h1>Ethereum Bot Started!</h1>") }) app.listen(process.env.PORT || 3000, () => console.log("Server is running..."));Necesita obtener el precio del gas y luego multiplicarlo por 21000
const gasPrice = await provider.getGasPrice() const estimateTxFee = gasPrice.mul(21000) const BN = balance.sub(estimateTxFee)El gas en ethereum es una unidad diferente de la tarifa de transacción que está en wei/gwei. Obtiene la tarifa de transacción al multiplicar el gas y el precio del gas, que varía de vez en cuando.
Aunque no estoy seguro de si 21000 es una cantidad de gas fija para una transacción de envío normal. Así que podrías hacer algo como esto también:
const estimateGas = await providers.estimateGas({ to: addressReceiver, value: balance }) const gasPrice = await provider.getGasPrice() const estimateTxFee = gasPrice.mul(estimateGas) const BN = balance.sub(estimateTxFee)