Issue in exection order of transactions
Aman9723 opened this issue · 4 comments
When sending two function calls one after another. They are not getting executed in order. In the below code approve function reaches the network later resulting in failure of swap call. Why is this occuring and how can I fix it without adding a time delay?
const { TOKEN_ADDRESS, COLLECT_ETH_WALLET } = setting
const tronWeb = this.creatTronWebInstance(wallet.privateKey)
const tokenContract = tronWeb.contract(tokenAbi, TOKEN_ADDRESS)
const routerContract = tronWeb.contract(v2RouterAbi, this.V2_ROUTER_ADDRESS)
const amountInResult = await tokenContract.methods.balanceOf(wallet.address).call()
const allowanceResult = await tokenContract.methods.allowance(wallet.address, this.V2_ROUTER_ADDRESS).call()
const amountIn = Array.isArray(amountInResult) ? BigInt(amountInResult[0]) : BigInt(amountInResult)
const allowance = Array.isArray(allowanceResult) ? BigInt(allowanceResult[0]) : BigInt(allowanceResult)
if (allowance < amountIn) {
await tokenContract.methods.approve(this.V2_ROUTER_ADDRESS, amountIn).send()
}
const path = [TOKEN_ADDRESS, this.WETH]
const to = COLLECT_ETH_WALLET
const deadline = Math.floor(Date.now() / 1000) + 60 * 20
const amountOutMin = 0
await routerContract.methods.swapExactTokensForETHSupportingFeeOnTransferTokens(amountIn, amountOutMin, path, to, deadline).send()
send()
method has an option called shouldPollResponse
to get the result of the method which will wait for the transaction to be solidity. So here's what you can do:
await tokenContract.methods.approve(this.V2_ROUTER_ADDRESS, amountIn).send({shouldPollResponse: true})
This takes 20-30 sec time. I don't want any time delays. Why does this situation occur on the first place? Is this the way tron protocol works or this issue is on the trongrid api level. Can you give me a brief explanation please.
After you approve, you have to wait it to be solidity so that your consequent function call could get the on chain data.