How To Calculate Slippage Percent Before Send Transaction In Web3?

- 1 answer

Every time I want to check slippage, I have to send the transaction first, and if the transaction failed because of "INSUFFICIENT_OUTPUT_AMOUNT", I know that this slippage is higher than I expected, BUT I LOST FEE FOR THIS WAY, it takes fee gas and I lost money, how can I check slippage percent in web3? or does any library can help me solve this? here is my code of simple transactions in web3 with pancakeswap smart contract.

amount_out = contract.functions.getAmountsOut(amountBNB, [spend,tokenToBuy]).call()[-1]
        min_tokens = int(amount_out * (1 - (slippage / 100)))
 pancakeswap2_txn = contract.functions.swapExactETHForTokens(
            (int(time.time()) + 10000)
            'from': sender_address,
            'value': web3.toWei(price,'ether'),
            'gas': gas_limit,
            'gasPrice': web3.toWei(gasPriceEntry.get(),'gwei'),
            'nonce': nonce,


Comment out the "'gas': gas_limit," part.

I can't remember why, but without setting the "gas" parameter you should get the same error, which you now get to see on the blockchain + you pay fees, already while executing your code. This way you know what the error is, but no actual transaction is being sent thus there is no gas/transaction fee for you to pay.

Next, if you intend to execute the trade nevertheless in the case if the slippage is below your maximum slippage expectations (e.g. below 10%) you could consider the next procedure. What if instead of "knowing the minimum slippage and then using it" you try to "find the minimum slippage to work with and execute the trade"?

Could the next procedure help you out:

  • use of for loop
  • default slippage is 1%, set maxSlippageAllowed (e.g. 10%)
  • run for loop, on each unsuccessful trade execution (we assume because of low slippage) increase slippage for +1%
  • run the loop until the trade is: 1.) either successfully executed when hitting slippage point (break), or 2.) the maximum slippage allowed is hit (break)

However, remember that if you will keep the "gas" parameter in your swapExactETHForTokens you will be paying all gas fees for each execution through for loop!!