Public | Internal | External | Private Functions in Solidity
Aim : To learn visibility in Solidity functions
In Solidity, there are four types of visibility for functions: public, external, internal, and private. The visibility determines where the function can be called from and how the function can be accessed.
public
external
internal
private
By default, functions are public
.
Code:
Functions can be declared as
public
- any contract and account can callprivate
- only inside the contract that defines the functioninternal
- only inside contract that inherits aninternal
function. Internal state variables can only be accessed from within the contract they are defined in and in derived contracts. They cannot be accessed externally. This is the default visibility level for state variables.external
- only other contracts and accounts can call
FUNCTIONVISIBILITY CONTRACT
1-Deploy firstly “FunctionVisibility”
2- We control all of the functions in the main contract.
We can’t see the internal and private functions in the main contract. Please look at the left bottom side in the picture.
EXTERNAL CONTRACT
1-Deploy “ExternalContract”
2- Take the address of “ExternalContract” by clicking blue button. We make copy of the main contract with this address.
FunctionVisibility public external_contract = new FunctionVisibility();
3- Choose “FUNCTIONVISIBILITY” in the contract section and paste the address to the “At Address” section and click “At Address” (do not click DEPLOY). We create the clon of the main contract.
4- You click the blue button in the clon “FUNCTIONVISIBILITY” contract and remix gives you “0”
5- Now we call “callExternalFromExternal()”
please click the callExternalFromExternal() in External Contract.
6- You can click blue button in “FUNCTIONVISIBILITY” contract and gives you “Hello World external”
7-Please click the callPublicFromExternal() in External Contract. It gives you “Hello World public”
The result is that External Contract can reach the public and external functions in Main Contract.
Please try to click “callInternalFromExternal” and “callPrivateFromExternal”
They can’t work because we are in the external contract.
DERIVED CONTRACT
1-We make same exercise with derived contract.Deploy firstly “DerivedContract”
2- Call callInternalFromDerived() from “DerivedContract”
3-Call callPublicFromDerived() from “DerivedContract”.
The result is that Derived Contract can reach the public and internal functions in Main Contract.
Please try to click “callExternalFromDerived” and “callPrivateFromDerived”
They can’t work because we are in the derived contract.