python - "Web3.py: 'buildTransaction' not working for Uniswap V2 swapExactETHForTokens function&quo

admin2025-04-25  2

I am new to DeFi and I am writing a function to use Uniswap V2 to initiate a transaction but I am running into errors. The error I am getting is specifically: 'swapExactETHForTokens(uint256,address[],address,uint256)' object has no attribute 'buildTransaction'. I know that swapExactETHForTokens supports buildTransaction so I imagine it is a problem with my ABI maybe? Any help is greatly appreciated. I have attached the function below:

from web3 import Web3
import json
from dotenv import load_dotenv
import os
import time
from datetime import datetime, timedelta, timezone

# -----------------------FUNCTIONS--------------------

def swap_tokens_v2(token_in, token_out, amount_in, amount_out_min, to, deadline):
    uniswap_v2_router_address = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"  # Uniswap V2 Router
    # Load the ABI from the file
    with open('abi.json', 'r') as abi_file:
        uniswap_v2_abi = json.load(abi_file) #The ABI file was taken from the etherscan V2 contract under contract ABI: 

    # Create contract instance
    uniswap_v2_router = web3.eth.contract(address=uniswap_v2_router_address, abi=uniswap_v2_abi)

    # Calculate deadline (current time + 5 minutes)
    deadline = int(time.time()) + 300  # 5 minutes from now

    # Build the transaction
    transaction = uniswap_v2_router.functions.swapExactETHForTokens(
        amount_out_min,
        path,
        wallet_address,
        deadline
    ).buildTransaction({
        'from': wallet_address,
        'value': amount_in_wei,
        'gas': max_gas_price,
        'gasPrice': gas_price_in_wei,
        'nonce': web3.eth.getTransactionCount(wallet_address),
    })

    # Sign and send the transaction
    signed_tx = web3.eth.account.sign_transaction(transaction, private_key)
    tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)

    print(f"Swap initiated, transaction hash: {tx_hash.hex()}")

I have tried replacing buildTransaction with Transact but I am unable to do this as I am using Infura and Infura doesnt have access to private keys.

I am new to DeFi and I am writing a function to use Uniswap V2 to initiate a transaction but I am running into errors. The error I am getting is specifically: 'swapExactETHForTokens(uint256,address[],address,uint256)' object has no attribute 'buildTransaction'. I know that swapExactETHForTokens supports buildTransaction so I imagine it is a problem with my ABI maybe? Any help is greatly appreciated. I have attached the function below:

from web3 import Web3
import json
from dotenv import load_dotenv
import os
import time
from datetime import datetime, timedelta, timezone

# -----------------------FUNCTIONS--------------------

def swap_tokens_v2(token_in, token_out, amount_in, amount_out_min, to, deadline):
    uniswap_v2_router_address = "0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D"  # Uniswap V2 Router
    # Load the ABI from the file
    with open('abi.json', 'r') as abi_file:
        uniswap_v2_abi = json.load(abi_file) #The ABI file was taken from the etherscan V2 contract under contract ABI: https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D#code

    # Create contract instance
    uniswap_v2_router = web3.eth.contract(address=uniswap_v2_router_address, abi=uniswap_v2_abi)

    # Calculate deadline (current time + 5 minutes)
    deadline = int(time.time()) + 300  # 5 minutes from now

    # Build the transaction
    transaction = uniswap_v2_router.functions.swapExactETHForTokens(
        amount_out_min,
        path,
        wallet_address,
        deadline
    ).buildTransaction({
        'from': wallet_address,
        'value': amount_in_wei,
        'gas': max_gas_price,
        'gasPrice': gas_price_in_wei,
        'nonce': web3.eth.getTransactionCount(wallet_address),
    })

    # Sign and send the transaction
    signed_tx = web3.eth.account.sign_transaction(transaction, private_key)
    tx_hash = web3.eth.send_raw_transaction(signed_tx.rawTransaction)

    print(f"Swap initiated, transaction hash: {tx_hash.hex()}")

I have tried replacing buildTransaction with Transact but I am unable to do this as I am using Infura and Infura doesnt have access to private keys.

Share Improve this question asked Jan 15 at 7:43 Benjamin PaysonBenjamin Payson 92 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

What web3.py version do you use?

It seems you use web3 >= v6.0.0 where deprecated camelCase methods were removed in favor of snake_case ones while your code has been written for <v6.0.0.

In this case, you should replace:

  • buildTransaction with build_transaction
  • getTransactionCount with get_transaction_count

Do not change swapExactETHForTokens though, as it's part of the ABI.

转载请注明原文地址:http://anycun.com/QandA/1745594681a90931.html