I'm trying to use Python to make multiple swaps in one transaction on Uniswap (swaping ETH against the token).
I successfully wrote a Python function that does just that, using swapExactETHForTokens from the Uniswap v2 router (web3 has been instantiated before that):
def buyToken(token_to_buy, eth_amount):
token_to_buy = web3.to_checksum_address(token_to_buy)
token_to_spend = web3.to_checksum_address(chain_token)
contract = web3.eth.contract(address=Web3.to_checksum_address(uni_v2_router_address), abi=uni_v2_router_abi)
nonce = web3.eth.get_transaction_count(wallet_address)
call_function = contract.functions.swapExactETHForTokens(
0,
[token_to_spend, token_to_buy],
wallet_address,
(int(time.time()) + 600)
).build_transaction({
'from': wallet_address,
'value': web3.to_wei(eth_amount,'ether'),
'nonce': nonce,
})
signed_txn = web3.eth.account.sign_transaction(call_function, private_key=wallet_private_key)
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
return web3.to_hex(tx_token)
So far so good. Now I'd like to buy tokens in small amounts in multiple transactions. This would result in me sending and paying gas for multiple transactions, which is why I want to bundle them in one transaction. I'm not sure what would be the best way to go about it, or if it's even possible using Python. I considered using the Multicall3 contract (https://www.multicall3.com/), but I can't find any documentation or example on how to use it with raw transactions.
There's also a multicall function in the Uniswap v3 router, but if it would be easier to implement in my code
I'll also later need to send the token to a few different wallets, so it would be great if the solution could be expanded so that I could do that in one transaction as well. Thanks!