Solidity

Solidity Contract Structure

Solidity Contract Structure Main Tips

  • Solidity contracts are much like classes in object-oriented programming languages;.
  • Contracts in Solidity can inherit elements from other contracts.
  • Every contract contains declarations of elements such as functions, function modifiersstate variables, struct and enum types, events as needed for its purpose.

Solidity Contract Structure

This tutorial will shortly describe the structure of a contract written in Solidity.

Every contract contains declarations of elements such as functions, function modifiers, state variables, struct and enum types, events as needed for its purpose.

Functions

Functions are blocks of code that are executed when called.

Functions have varying visibility to other contracts and can be called both internally and externally.

Example

function bid() payable { // Script to execute // ... }

 

Try on Remix Try live on Hosting

Function Modifiers

Function modifiers in Solidity are used in a declarative way to amend function semantics.

Example

address public seller;

    modifier sellerOnly() { // Modifier itself
        require(msg.sender == seller);
        _;
    }

    function abort() sellerOnly { // Usage of modifier
        // ...
    }

 

Try on Remix Try live on Hosting

State Variables

State variables are values, permanently stored in the contract’s storage.

Example

uint storageData;

 

Try on Remix Try live on Hosting

Struct Types

Struct types are custom defined types, containing a set of variables.

Example

struct Voter { // Struct
        uint voteWeight;
        bool hasVoted;
        address delegateAddress;
        uint voteIndex;
    }

 

Try on Remix Try live on Hosting

Enum Types

Enums’ use is to create custom types with finite value sets.

Example

enum contractState { Created, Locked, Inactive } // Enum type

 

Try on Remix Try live on Hosting

Events

Events in Solidity are a convenience interface for EVM logging facilities, making them excellent for keeping track of what is happening with a contract.

Example

event topBidIncreased(address bidderAddress, uint bidAmount); // Event

    function bid() payable {
        // ...
        topBidIncreased(msg.sender, msg.value); // Trigger event
    }

 

Try on Remix Try live on Hosting

Read previous post:
Solidity Importing

Solidity Importing Main Tips Solidity allows import statements, making libraries and other related features viable. Importing in Solidity is fairly well...

Close