fbpx

Fallback Function in Solidity

In this post, we will learn what is fallback function & how to use them in Solidity Language.
Notice: This is one of the multi-post series of Learn Solidity - Build Decentralized Application in Ethereum. This is an attempt to teach you all about Solidity - A Programming Language for Ethereum Based Smart Contracts. If you want to take this as a video course please signup using below button.
pragma solidity 0.4.8; 

/*
* @title Example for Solidity Course
* @author Ethereum Community
* @notice Example for the Solidity Course
*/

contract Test {
    // This function is called for all messages sent to
    // this contract (there is no other function).
    // Sending Ether to this contract will cause an exception,
    // because the fallback function does not have the "payable"
    // modifier.
    function() { x = 1; }
    uint x;
}


// This contract keeps all Ether sent to it with no way
// to get it back.
contract Sink {
    //below line will make the default function payable by adding a payable modifier like this
    function() payable { }
}


contract Caller {
    function callTest(Test test) {
        test.call(0xabcdef01); // function hash does not exist
        // results in test.x becoming == 1.
    }
}
Previous: Function Modifiers in Solidity Next: Abstract Contract in Solidity