I have been with this error for a couple of days, I am trying to calculate the necessary Slippage in PancakeSweap automatically, for this I am trying different percentages and I call estimateGas to see if the transaction fails. But I only get the error "TransferHelper: TRANSFER_FROM_FAILED". I have tried a lot of methods and none of them work for me. I'm sure the contract is approved and that it should work in the blockchain side. In pancakeswap it works for me, same wallet, same tokens and same amounts. I do not understand that it can fail.
const Web3 = require("web3");
const abi = require("./abi.json");
const web3 = new Web3("https://bsc-dataseed.binance.org/");
const contract = new web3.eth.Contract(abi, "0x10ed43c718714eb63d5aa57b78b54704e256024e");
function isValid(res) {
return new Promise((resolve, reject) => {
contract.methods.swapExactTokensForTokens(res[0], res[1], ["TOKEN_A", "TOKEN_B" ], "MI_WALLET", 1639969436 ).estimateGas(function(error, result) {
console.log(error.message)
if(error.message.includes("INSUFFICIENT_OUTPUT_AMOUNT")) {
console.log("Bad slippage")
reject()
}
else if(error) {
reject()
}
else {
resolve()
}
});
})
}
(async () => {
contract.methods.getAmountsOut("20000000000", ["TOKEN_A", "TOKEN_B" ]).call().then(async res => {
const data = res;
let slippage = 0;
while (true) {
try {
await isValid(data);
break;
}
catch(e) {
slippage++;
console.log(slippage / 100 * data[1])
let newS = data[1] - (slippage / 100 * data[1])
console.log(slippage, newS);
if(slippage == 20) {
break;
}
}
}
console.log(slippage)
})
})();
Thank you all!