Symbiose
Symbiose

Reputation: 11

How to bundle multiple transactions in one on Ethereum using web3.py?

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!

Upvotes: 1

Views: 3325

Answers (2)

Elnaril
Elnaril

Reputation: 21

You can use the Uniswap Universal Router to perform multiple V2 & V3 swaps and transfers in one transaction.

With Python, you can use this SDK to easily build such transactions.

Disclaimer: I'm the author of this library.

Upvotes: 0

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83566

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.

For bundling multiple state-modifying smart contract calls in a single transaction you need to write your own smart contract to do this.

Multicall is only for optimising reading the chain state.

Upvotes: 0

Related Questions