1

I'm looking to execute functions in my smart contract immediately upon deployment to the blockchain. Yes I could probably program in a execution of the functions just after the code to deploy the smart contract, but it seems like a waste of gas, is there some more efficient way to do this. The contract is really simple.

    pragma solidity ^0.4.18;

contract EtherTransfer {

    address public owner;

    function transfer() public {
    owner = 0x627306090abaB3A6e1400e9345bC60c78a8BEf57;
    owner.transfer(1000000000000000000);
    }

    function() payable public {}

function kill() public {
        if (msg.sender == owner)
        selfdestruct(owner);
    }

}
  • You mean use a constructor? Here instead of transfer you call it EthTransfer and it gets executed upon deployment – comodoro Feb 2 '18 at 5:57
1

Yes, you can call any function in your contract from within the contract constructor, also you can make calls to external contracts.

You have to consider if you call an external contracts from the constructor they cannot make function calls to your contract.

You can consult more details of the contract creation process in the article Diving Into The Ethereum VM Part 5 — The Smart Contract Creation Process

pragma solidity ^0.4.19;

contract EtherTransfer {
    // Make constructor payable to accept ether
    function EtherTransfer(address owner) public payable {
        foo(owner);
    }

    function foo(address owner) private {
        // This will transfer the balance of the contract to owner
        selfdestruct(owner);
    }
}
  • Thanks for the help! Did not know you could make a constructor in Solidity. – Adam Feb 2 '18 at 20:01
0

Yes, just put your code in the constructor. A function with the same name as the contract will be treated as a constructor function and will only be executed once (when the contract is first deployed).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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