1

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"

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

1
  • I had the similar problem. Add 20000 gas
    – att
    Aug 26, 2022 at 20:16

3 Answers 3

2

This is my buy script in javascript

export const buyBeast = async (targetAccount, amount) => {
  var amountToBuyWith = web3.utils.toHex(amount);

  // var amountOutMin = '100' + Math.random().toString().slice(2, 6);
  var amountOutMin = 0;

  var txData = pancakeswapContract.methods.swapExactETHForTokens(
    web3.utils.toHex(amountOutMin),
    [WBNB_ADDRESS, B_ADDRESS],
    targetAccount.address,
    web3.utils.toHex(Math.round(Date.now() / 1000) + 60 * 20)
  );

  let estimatedGas = await txData.estimateGas({
    from: targetAccount.address,
    value: amountToBuyWith,
  });
  estimatedGas = estimatedGas + 20000; // Add 20000 gas buffer

  let gasPrice = await web3.eth.getGasPrice();
  
  var count = await web3.eth.getTransactionCount(targetAccount.address);

  var rawTransaction = {
    from: targetAccount.address,
    gasPrice: gasPrice,
    gas: web3.utils.toHex(estimatedGas),
    to: PANCAKESWAP_ROUTER_ADDRESS,
    value: web3.utils.toHex(amountToBuyWith),
    data: txData.encodeABI(),
    nonce: web3.utils.toHex(count),
  };
  try {
    var signedTxn = await web3.eth.accounts.signTransaction(rawTransaction, targetAccount.privateKey);
    var result = await web3.eth.sendSignedTransaction(signedTxn.rawTransaction);
    logger.info(
      `✅ Successfully bought B token for account ${targetAccount.address}, tx hash ${result.transactionHash}`
    );
    return result.transactionHash;
  } catch (error) {
    logger.error(`❌ Buy error ${error.message}`);
    return null
  }
};
1
sender_address = '0xxxxxxxxxxxxxxxxxxxxxxxxxxx'

balance = web3.eth.get_balance(sender_address)

read = web3.fromWei(balance,'ether')
print(read)

tokenToBuy = web3.toChecksumAddress(input("Nhap Contract:"))
spend = web3.toChecksumAddress("0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c")

contract = web3.eth.contract(address=panRouterContractAddress, abi=panabi)

nonce = web3.eth.get_transaction_count(sender_address)

start = time.time()

pancakeswap2_txn = contract.functions.swapExactETHForTokens(
0,
[spend,tokenToBuy],
sender_address,
(int(time.time()) + 10000)
).buildTransaction({
'from': sender_address,
'value': web3.toWei(0.01,'ether'),
'gasPrice': web3.toWei('10','gwei'),
'nonce': nonce,
})

signed_txn = web3.eth.account.sign_transaction(pancakeswap2_txn, private_key="")
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(web3.toHex(tx_token))
1
  • 1
    Please, add a description for the code.
    – Ismael
    Sep 30, 2022 at 2:24
0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.