tronprotocol / tronweb

Javascript API Library for interacting with the TRON Network
MIT License
445 stars 277 forks source link

Issue in exection order of transactions #563

Closed Aman9723 closed 1 month ago

Aman9723 commented 1 month ago

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() 
Satan-web3 commented 1 month ago

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})
Aman9723 commented 1 month ago

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.

Aman9723 commented 1 month ago

@Satan-web3?

Satan-web3 commented 1 month ago

After you approve, you have to wait it to be solidity so that your consequent function call could get the on chain data.