How to send() or transfer() from the contract address to an account address in solidity (I mean to deduct from address(this).balance)

Viewed 699

When the contract is deployed it has an address that we can call by address(this). My contract is receivable from an address which means I can send() or transfer() to this contract but If I want to transfer from this actual contract to any account how can I do that?

example code:

    function submitTransaction(address _to,uint _value,string memory _desc) public 
    onlyOwner 
    {
        require(_value <= address(this).balance,"This wallet does not have enough balace to send");
        if(!_to.send(_value)){
             revert("doposit fail");
        }
    }

but how can I deduct from address(this).balance?

3 Answers

You can see this example of smart contract code:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Bank {
    address owner;
    
    constructor() {
        owner = msg.sender;
    }

    modifier onlyOwner() {
        require(msg.sender == owner, "You're not the smart contract owner!");
        _;
    }

    event Deposited(address from, uint amount);

    function depositMoney() public payable {
        emit Deposited(msg.sender, msg.value);
    }

    // Use transfer method to withdraw an amount of money and for updating automatically the balance
    function withdrawMoney(address _to, uint _value) public onlyOwner {
        payable(_to).transfer(_value);
    }

    // Getter smart contract Balance
    function getSmartContractBalance() external view returns(uint) {
        return address(this).balance;
    }

}

ADVICE: In this case, if you want use only transfer or send, I advice you to use transfer() method instead send(), because it throws on failure if transfer didn't work. I recommend to read this thread. On the contrary for avoid reentracy attack you must to call method to transfer ether.

Don't use safe if you don't have a good reason, use transfer instead. While transfer will throw an error in case of a failure, the safe method will just return false, which means the next lines of the code will still be executed and the transaction will not be reverted if you don't handle the error.

function submitTransaction(address _to,uint _value,string memory _desc) public 
    onlyOwner 
    {
        require(_value <= address(this).balance,"This wallet does not have enough balace to send");
        _to.transfer(_value);
    }
 (bool success, ) = addressToTransfer.call{value: address(this).balance}("");
 require(success, "Transfer failed.");
Related