Smart Contracts – Transferring ETH to Wallet From a Contract

contract-debuggingcontract-designcontract-developmentethertokens

I actually my partner created a Smart Contract which is able to create a new smart contract and send the proceeds. I'm quite new to Solidity unable to figure out a way to modify the smart contract to accept ETH from the sender, store it or send it directly to the Owner of the Smart Contract. Here's the code, help will be appreciated!

    pragma solidity ^0.4.0;

    contract EtherTransferTo {
    function () public payable {
    }

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

    contract EtherTransferFrom {

    EtherTransferTo private _instance;

    function EtherTransferFrom() public {
    // _instance = EtherTransferTo(address(this));
    _instance = new EtherTransferTo();
   }

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

    function getBalanceOfInstance() public returns (uint) {
    //return address(_instance).balance;
    return _instance.getBalance();
    }

    function () public payable {
    //msg.sender.send(msg.value);
    address(_instance).send(msg.value);
    }
}

Best Answer

If you want to make a contract which simply forwards any ETH to the contract owner, you will need to:

  • Define an owner of the contract on contract creation
  • Create a payable function on the contract
  • Have that payable function forward the funds to that owner

Here is a really simple sample to get started (untested and not ready for production):

pragma solidity 0.4.24;

contract EthForward {
    address _owner;

    constructor() public {
        _owner = msg.sender;
    }

    function() public payable {
        _owner.transfer(msg.value);
    }
}

This contract takes advantage of two key concepts:

  1. The constructor function
  2. The fallback function

You should spend time learning more about solidity through official documentation and tutorials like Cryptozombies

Related Topic