Visibility in Solidity smart contracts

Declare the visibility of functions and state variables in Solidity smart contracts. When writing a smart contract a programmer can control who or what can call functions or state variables by specifying the visibility. This allows one to secure certain parts of a contract without having to write custom logic.

There are several types of callers for a function. They are:

  1. Other functions in the contract itself can call the function
  2. A contract that is inheriting the contract that owns the function
  3. A third party can call the function. Examples are another contract, someone using Web3, etc.

Visibility defined

  • Private – A private function/state variable is only available inside the contract that defines it. It is generally good practice to keep functions private.
Visibility in Solidity smart contracts Private

  • Internal – A internal function/state variable is only available inside the contract that defines it AND any contracts that inherit it
Visibility in Solidity smart contracts Internal

  • External – An external function can only be called by external contacts.  Not visible inside the contract that defines it. 
Visibility in Solidity smart contracts External

  • Public – A public function/state variable is available to any contract or third party that wants to call it. Public is the default if visibility is not specified.
Visibility in Solidity smart contracts Public

Visibility in functions

The visibility of a smart contract function is specified by using one of the visibility keywords listed above (private, internal, external or public). The visibility is specified after the functions parameter list.

contract sampleContract {

    function myFunction () visibilityGoesHere {

     //do something
    }
}

Visibility of state variables

The visibility of a smart contract state variables is specified by using one of the visibility keywords listed above (private, internal, or public). External state variables do not exist since it does not make sense for a contract to save a variable to the block chain and not make it visible to the contract that created it. The visibility is specified after the data type.

contract sampleContract {

    uint public data;

     //do something
    }
}

For more information read the documentation.

Click here for more information about how to use the Ethereum test network and how to obtain test ETH.

Next Review – Pure and View in Solidity smart contracts

Ledger Nano X - The secure hardware wallet

Leave a Reply