[Ethereum] Is swapExactETHForTokens the right function for buying ? python, web3


I'm trying the make a simple piece of code to buy token with BNB on BSC trough the PancakeSwap protocol.

def buy(tokenAddress, tokenSymbol):
    if tokenAddress != None:
        tokenToBuy = web3.toChecksumAddress(tokenAddress)
        spend = web3.toChecksumAddress("0xbb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c")  # wbnb
        contract = web3.eth.contract(address=pancakeSwapRouterAddress,
        nonce = web3.eth.get_transaction_count(walletAddress)
        start = time.time()
        pancakeswap2_txn = contract.functions.swapExactETHForTokens(
            [spend, tokenToBuy],
            (int(time.time()) + transactionRevertTime)
            'from': walletAddress,
            'value': web3.toWei(float(BNBAmount), 'ether'),
            'gas': gasAmount,
            'gasPrice': web3.toWei(gasPrice, 'gwei'),
            'nonce': nonce,

        signed_txn = web3.eth.account.sign_transaction(pancakeswap2_txn,
        tx_token = web3.eth.send_raw_transaction(
        )  # BUY THE TOKEN

Somehow, the transaction happens, but fail every time. But I spotted a difference between a "regular" transaction made with metamask or pancakeswap UI and the one made with code :

Indeed on bscscan I see that the method called for a successful tx is : "Swap Exact Tokens For ETH Supporting Fee On Transfer Tokens"

enter image description here

But the method called for the tx that fails everytime is : "Swap Exact Tokens For ETH"

enter image description here

I just wonder if there is another method to call in python than "swapExactETHForTokens()" that would work better.

BTW here is the failed tx

enter image description here

Best Answer

swapExactTokensForETHSupportingFeeOnTransferTokens is used to sell fee on transfer tokens (e.g. Safemoon) for BNB (on the BSC of course). Its counterpart (swapExactETHForTokensSupportingFeeOnTransferTokens) is probably what you're looking for if you're trying to buy that kind of tokens with BNB (it also works with "normal" tokens but costs more gas IIRC, id love someone to confirm that as im not home rn and cant check the pancake router code)