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,
abi=pancakeABI)
nonce = web3.eth.get_transaction_count(walletAddress)
start = time.time()
pancakeswap2_txn = contract.functions.swapExactETHForTokens(
0,
[spend, tokenToBuy],
walletAddress,
(int(time.time()) + transactionRevertTime)
).buildTransaction({
'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,
private_key)
tx_token = web3.eth.send_raw_transaction(
signed_txn.rawTransaction
) # 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"
But the method called for the tx that fails everytime is : "Swap Exact Tokens For ETH"
I just wonder if there is another method to call in python than "swapExactETHForTokens()" that would work better.
BTW here is the failed tx