Web3.py – How to Programmatically Wrap ETH by Interacting with Wrapped Ether Contract in Web3.py

pythonsolidityweb3.pywrapped-tokens

Looking at the contract for Wrapped Ether, I noticed that it uses a function called deposit to wrap ETH.

The function deposit itself does not get an argument. However, at the top of the script, I noticed event Deposit(address indexed dst, uint wad);

I suppose I have to create this event with the proper arguments (wallet address and how much to be wrapped). I am not sure how to create this event when, I think, I can only interact with functions within the contract.

I am trying to do this in web3.py. I was able to successfully unwrap an existing wETH by calling the withdraw function in the wETH contract.

Best Answer

You just have to call the deposit() function of the WETH contract and define the number of ETH to be wrapped to WETH in the transaction's value key.

Example of working, unsigned tx:

tx = weth_contract.functions.deposit().buildTransaction({
        'chainId': 1,
        'gas': 100000,
        'gasPrice': w3.eth.gas_price,
        'nonce': w3.eth.get_transaction_count(use_this_address),
        'value': w3.toWei(1.0, "ether")
    })

As an alternative, you can just send ethers to the smart contract's address, as a normal transfer between two accounts. The contract has a fallback function function() public payable that will take care of all the logic because it actually calls deposit().

Related Topic