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, Struct Types and Enum Types.Furthermore, contracts can inherit from other contracts.

State Variables¶

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

  1. pragma solidity ^0.4.0;
  2.  
  3. contract SimpleStorage {
  4. uint storedData; // State variable
  5. // ...
  6. }

See the Types section for valid state variable types andVisibility and Getters for possible choices forvisibility.

Functions¶

Functions are the executable units of code within a contract.

  1. pragma solidity ^0.4.0;
  2.  
  3. contract SimpleAuction {
  4. function bid() public payable { // Function
  5. // ...
  6. }
  7. }

Function Calls can happen internally or externallyand have different levels of visibility (Visibility and Getters)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).

  1. pragma solidity ^0.4.11;
  2.  
  3. contract Purchase {
  4. address public seller;
  5.  
  6. modifier onlySeller() { // Modifier
  7. require(msg.sender == seller);
  8. _;
  9. }
  10.  
  11. function abort() public onlySeller { // Modifier usage
  12. // ...
  13. }
  14. }

Events¶

Events are convenience interfaces with the EVM logging facilities.

  1. pragma solidity ^0.4.21;
  2.  
  3. contract SimpleAuction {
  4. event HighestBidIncreased(address bidder, uint amount); // Event
  5.  
  6. function bid() public payable {
  7. // ...
  8. emit HighestBidIncreased(msg.sender, msg.value); // Triggering event
  9. }
  10. }

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

Struct Types¶

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

  1. pragma solidity ^0.4.0;
  2.  
  3. contract Ballot {
  4. struct Voter { // Struct
  5. uint weight;
  6. bool voted;
  7. address delegate;
  8. uint vote;
  9. }
  10. }

Enum Types¶

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

  1. pragma solidity ^0.4.0;
  2.  
  3. contract Purchase {
  4. enum State { Created, Locked, Inactive } // Enum
  5. }

原文: http://solidity.apachecn.org/cn/doc/v0.4.21/structure-of-a-contract.html