Search code examples
soliditysmartcontractsweb3py

How to withdraw the current balance of the smart contract using web3.py?


I have already created a function for doing so in solidity, but in the frontend, I want to be able to call that function and transfer ether from the contract to an account. Here is the code from solidity.

    function withdraw() public payable onlyOwner {
        payable(msg.sender).transfer(address(this).balance);
    }

So far, for calling other functions that involve a state change I have used build transaction from web3.py. In order to transfer ether to the contract, I have done this -

booking_contract = w3.eth.contract(address=self.receipt.contractAddress, abi=abi)
        nonce = w3.eth.getTransactionCount(address)
        booking_transaction = booking_contract.functions.book(machine_name, start_time, end_time).buildTransaction(
            {
                "chainId": chain_id,
                "gasPrice": w3.eth.gas_price,
                "from": address,
                "nonce": nonce,
                "value": 100
            }
        )
        signed_txn = w3.eth.account.sign_transaction(booking_transaction, private_key=key)
        txn_hash = w3.eth.send_raw_transaction(signed_txn.rawTransaction)

Is there any way to transfer the ether sent to the contract here to any account I want?


Solution

  • Is there any way to transfer the ether sent to the contract here to any account I want?

    You can specify the recipient in the withdraw() function argument, and then pass it to the payable() function.

    function withdraw(address _recipient) public payable onlyOwner {
        payable(_recipient).transfer(address(this).balance);
    }
    

    Don't forget to specify the recipient in the .py script:

    booking_contract.functions.withdraw(recipient_address)