Hi there,
I’m getting failed transactions(reverted) when I try to buy tokens from uniswap v2 using the swapExactEthForToken method in my build transaction with web3.py. I have added my code below.
I have tried this on ropsten, rinkeby and even mainnet.
I have test ETH on both test networks also.
Any help will be greatly appreciated.
from web3 import Web3
import json
import config
import time
import pprint
infura_url = config.INFURA_URL_TESTNET
web3 = Web3(Web3.HTTPProvider(infura_url))
print(web3.isConnected())
uniswap address and abi
uniswap_router = ‘0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D’
uniswap_factory = web3.toChecksumAddress(‘0x5c69bee701ef814a2b6a3edd4b1652cb9cc5aa6f’)
uniswapABI = ‘I pasted the uniswap v2 abi here’
uniswap_factory_abi = json.loads(uniswapABI)
sender_address = “0x39DC57cf562736D62bE25EFC1B37ce43dEaf51Bc”
balance = web3.eth.get_balance(sender_address)
eth_bal = web3.fromWei(balance, ‘ether’)
print('My Test Eth Balance is: ', eth_bal)
tokenToBuy = web3.toChecksumAddress(“0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984”)
spend = web3.toChecksumAddress(“0xc778417E063141139Fce010982780140Aa0cD5Ab”) # wbnb contract
Setup the Uniswap contract
contract = web3.eth.contract(address=uniswap_factory, abi=uniswap_factory_abi)
nonce = web3.eth.get_transaction_count(sender_address)
start = time.time()
uniswapv2_txn = contract.functions.swapExactETHForTokens(
10000000000, # set to 0, or specify minimum amount of tokeny you want to receive - consider decimals!!!
[spend, tokenToBuy],
sender_address,
(int(time.time()) + 100000)
).buildTransaction({
‘from’: sender_address,
‘value’: web3.toWei(0.01, ‘ether’),
‘gas’: 2000000,
‘nonce’: nonce,
})
signed_txn = web3.eth.account.sign_transaction(uniswapv2_txn, private_key=config.private)
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
print(web3.toHex(tx_token))