Solidity function visibility, explained

When writing a smart contract, we can control who/what can call functions within that contract by specifying what is known as the function visibility. This allows us to easily secure certain parts of a contract without having to write too much custom logic.

Who can call a smart contract function? #

Before getting into the different types of function visibility, it’s helpful to understand what the different categories of potential callers to a function are first.

Actors-2

There are three types of callers:

  1. The main contract itself (MyContract)
  2. A contract derived (i.e. inheriting) from the main contract (DerivedContract)
  3. A third party (AnotherContract)

The visibility of a function determines what subset of these callers can legitimately execute the function.

Function visibility types #

The visibility of a smart contract function is specified using one of the four visibility keywords (private, internal, external, or public) and placed immediately following the function parameter list.

contract MyContract {

function myFunction () [visibility-here] {
// do something
}

}

private #

A private function is one that can only be called by the main contract itself. Although it’s not the default, it is generally good practice to keep your functions private unless a scope with more visibility is needed.

private-1

internal #

An internal function can be called by the main contract itself, plus any derived contracts. As with private functions, it's generally a good idea to keep your functions internal wherever possible.

internal

external #

An external function can only be called from a third party. It cannot be called from the main contract itself or any contracts derived from it.

External functions have the benefit that they can be more performant due to the fact that their arguments do not need to be copied to memory. So, where possible, it's advisable to keep logic that only needs to be accessed by an external party to an external function.

external

public #

Finally, a public function can be called from all potential parties. Unless otherwise specified, all functions are made public by default.

public-1

Keep in touch KeepinTouch

Subscribe to my Newsletter 📥

Receive quality articles and other exclusive content from myself. You’ll never receive any spam and can always unsubscribe easily.

Elsewhere 🌐