How to do it...

  1. If you want the function to be accessible both externally and internally, it has to be marked as public. Public state variables will generate a getter function automatically:

pragma solidity ^0.4.21;
contract Visibility {
// Public state variables generate an automatic getter
uint public limit = 110021;

// Accessible externally and internally
function changeLimit(uint _newLimit) public {
limit = _newLimit;
}
}

You can see the getter methods generated from the ABI output of this contract:

[{
"constant":false,
"inputs":[{
"name":"_newLimit",
"type":"uint256"
}],
"name":"changeLimit", // public function
"outputs":[],
"payable":false,
"stateMutability":"nonpayable",
"type":"function"
},{
"constant":true,
"inputs":[],
"name":"limit", // public state variable
"outputs":[{
"name":"",
"type":"uint256"
}],
"payable":false,
"stateMutability":"view",
"type":"function"
}]
  1. If you want your function to be only accessible from other contracts and via transactions, use external. This only works with functions:
pragma solidity ^0.4.21;
contract Visibility {
// External function
function f() external {
// Do something
}
}

An external function f() cannot be directly used internally. You need to use this.f() while calling from the same contract. External functions can also help save some gas for large inputs. It is recommended to use external whenever possible.

  1. Internal functions can only be accessed from within the contract or the contracts inheriting from it. State variables are internal by default:
pragma solidity ^0.4.21;

contract Base {
// Internal state varible
uint internal limit = 110021;

function update(uint _newLimit) internal {
limit = _newLimit;
}
}

contract Visibility is Base {
function increment() public {
uint newLimit = limit + 1;
update(newLimit);
}
}
  1. If you want the function or state variable to be used only within the contract and not for external or inherited contracts, mark them as private:
pragma solidity ^0.4.21;

contract Visibility {
// Private state varible
uint private limit = 110021;

function update(uint _newLimit) public {
limit = _newLimit;
}
}

Defining a state variable as private only prevents others from modifying it. Everyone in the network can read what data is stored in a private variable. This is often overlooked and can cause security flaws in the contract. More details are explained in Chapter 8, Smart Contract Security.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.54.136