Structure of a Contract

Contracts in Solidity are similar to classes in object-oriented languages. Each contract can contain declarations of State Variables, Functions, Function Modifiers, Events, Structs Types and Enum Types. Furthermore, contracts can inherit from other contracts.

State Variables

State variables are values which are permanently stored in contract storage.

contract SimpleStorage {
  uint storedData; // State variable
  // ...
}

See the Types section for valid state variable types and Visibility and Accessors for possible choices for visibility.

Functions

Functions are the executable units of code within a contract.

contract SimpleAuction {
  function bid() { // Function
    // ...
  }
}

Function Calls can happen internally or externally and have different levels of visibility (Visibility and Accessors) towards other contracts.

Function Modifiers

Function modifiers can be used to amend the semantics of functions in a declarative way (see Function Modifiers in contracts section).

 contract Purchase {
   address public seller;

   modifier onlySeller() { // Modifier
       if (msg.sender != seller) throw;
       _
   }

   function abort() onlySeller { // Modifier usage
       // ...
   }
 }

in the section on contracts for a more in-depth explanation.

Events

Events are convenience interfaces with the EVM logging facilities.

contract SimpleAuction {
  event HighestBidIncreased(address bidder, uint amount); // Event

  function bid() {
    // ...
    HighestBidIncreased(msg.sender, msg.value); // Triggering event
  }
}

See Events in contracts section for information on how events are declared and can be used from within a dapp.

Structs Types

Structs are custom defined types that can group several variables (see Structs in types section).

contract Ballot {
  struct Voter { // Struct
    uint weight;
    bool voted;
    address delegate;
    uint vote;
  }
}

Enum Types

Enums can be used to create custom types with a finite set of values (see Enums in types section).

contract Purchase {
  enum State { Created, Locked, Inactive } // Enum
}