This content originally appeared on bitsofcode and was authored by Ire Aderinokun
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.
There are three types of callers:
- The main contract itself (
MyContract
) - A contract derived (i.e. inheriting) from the main contract (
DerivedContract
) - 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.
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.
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.
public
#
Finally, a public
function can be called from all potential parties. Unless otherwise specified, all functions are made public by default.
This content originally appeared on bitsofcode and was authored by Ire Aderinokun
Ire Aderinokun | Sciencx (2019-08-27T00:00:00+00:00) Solidity function visibility, explained. Retrieved from https://www.scien.cx/2019/08/27/solidity-function-visibility-explained-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.