Web3 Python token sell pancakeswap slippage

1.7k views Asked by At

I am trying to sell my tokens via python web3. But I get an error "TRANSFER_FROM_FAILED" like this. I know why this error comes up and I know i need to set up Slippage Tolerance somewhere. Can you guys let me know how can I put 49.99% Slippage Tolerance in there?

Regards.


pancakeswap2_txn = contract.functions.swapExactTokensForETHSupportingFeeOnTransferTokens(
            tokenValue ,0, 
            [contract_id, spend],
            sender_address,
            (int(time.time()) + 1000000)

            ).buildTransaction({
            'from': sender_address,
            'gasPrice': web3.toWei('5','gwei'),
            'nonce': web3.eth.get_transaction_count(sender_address),
            })

1

There are 1 answers

0
Thuan Pham On

tokenValue ,0, when you transfer 0 parameter, it means that "I want to get with minimum is zero amount", so if you want to get with slippage tolerance like 49%, you need to expect how much token B you will get after trade token A, there is one simple way to trade

just do some calculate min_token you receive instead of put it 0. here is my simple code of get min token.

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