[Python] How to properly use swapExactETHForTokens function in a web3py

Discussão em 'Python' iniciado por Stack, Setembro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to use swapExactETHForTokens function using pancake router v2 and here is my code:

    #!/usr/bin/env python3
    import time
    from web3 import Web3

    bsc = "https://data-seed-prebsc-1-s1.binance.org:8545/"
    web3 = Web3(Web3.HTTPProvider(bsc))
    print("Is web3 connected? ", web3.is_connected())

    wallet_address = ""
    private_key = ""
    nonce = web3.eth.get_transaction_count(wallet_address)

    pancake_router_address = "0x6725F303b657a9451d8BA641348b6761A6CC7a17"
    pancake_router_ABI = []
    contract = web3.eth.contract(address = pancake_router_address, abi = pancake_router_ABI)

    WBNB_address = web3.to_checksum_address("0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd")
    cake2_address = web3.to_checksum_address("0x8d008B313C1d6C7fE2982F62d32Da7507cF43551")

    pancakeswap2_txn = contract.functions.swapExactETHForTokens(
    0, # The minimum destination token you want to have, set 0 if you don't care
    [WBNB_address, cake2_address],
    wallet_address,
    (int(time.time()) + 1000000) # 1000000 seconds later

    ).build_transaction({
    'from': wallet_address,
    'value': web3.to_wei(0.001,'ether'),
    'gas': 250000,
    'gasPrice': web3.to_wei('5','gwei'),
    'nonce': nonce,
    })

    signed_txn = web3.eth.account.sign_transaction(pancakeswap2_txn, private_key = private_key)
    tx_token = web3.eth.send_raw_transaction(signed_txn.raw_transaction)
    print('Transaction hex is: ', web3.to_hex(tx_token))



    I have used different pancake router addresses (all on testnet), each one has a problem, e.g., for 0xd9C500DfF816a1Da21A48A732d3498Bf09dc9AEB , 0x8d008B313C1d6C7fE2982F62d32Da7507cF43551 and 0x6725F303b657a9451d8BA641348b6761A6CC7a17 I get the error:

    web3.exceptions.ABIFunctionNotFound:
    ("The function 'swapExactETHForTokens' was not found in this ", "contract's abi.")


    And for 0x10ED43C718714eb63d5aA57B78B54704E256024E doesn't show this error but the transaction fails with the message:

    Warning! Error encountered during contract execution [execution reverted]


    Does any one know what is wrong in my code? Thank you in advance!

    P.s. My question is similar to this and this question I have considered the provided answers, but no luck.

    Continue reading...

Compartilhe esta Página