1

I have a contract that I can deposit ethers by using a fallback function. The question is, I want to send the ethers INSIDE THIS smart contract to another random address. I am not asking to send ethers from one address to another. I am asking to send ethers in this contract to another address. Or the same question in other words: How can i send the ethers inside this smart contract to any address I want(without using selfdestruct).

function foo is sending ether from function caller address to the target address (_to). That is not what I want. I want send ethers inside this contract to the target address(_to). Do you have any idea how to do this?

//SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.7;

contract TestCall {

    fallback() external payable{}

    function foo(address payable _to) external payable{
        (bool success, ) = _to.call{value: msg.value}("");
        require(success, "transaction failed");
    }

    function getBalance() external view returns(uint){
        return address(this).balance;
    }

}

3 Answers 3

1

Looks good IMO, but I would do that instead:

//SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.7;

contract TestCall {

    fallback() external payable{}

    function foo(address payable _to, uint256 amount) external payable{
        (bool success, ) = _to.call{value: amount}("");
        require(success, "transaction failed");
    }

    function getBalance() external view returns(uint){
        return address(this).balance;
    }
}

With msg.value, you will need to include a value in the transaction you're sending to the contract and this value will be sent afterwards to the address you set. This is not what you want to do.

1

This is a general function to withdraw full contract balance to any address.

function withDraw(address payable to) public payable OnlyOwner {
        uint Balance = address(this).balance;
        require(Balance > 0 wei, "Error! No Balance to withdraw"); 
        to.transfer(Balance);
    }
1

Or you can include the transfer in the fallback function

    address payable extContract;

    fallback() external payable{
        extContract.transfer(msg.value);
    }

So when anybody sends eth to this contract, it is forwarded to another address. (Have not checked if this exceeds the gas limit for fallback functions)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.