Immutable & Const
- Constants are variables that cannot be modified.
- Immutable variables are like constants. Values of immutable variables can be set inside the constructor but cannot be modified afterwards.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
contract Immutable {
uint public immutable IMMU;
uint public constant CONST = 1;
constructor(uint input) {
IMMU = input;
// CONST = input; cannot compile
}
}
Function Modifiers
view
read-only to state variables
pure
no read/write to state variables
- Visibility: whether functions are accessible by other contracts
public
- any contract and account can call
private
- only inside the contract that defines the function
internal
- only inside this contract or children contracts
external
- only other contracts and accounts can call
virtual
Function that is going to be overridden by a child contract must be declared as virtual
.
overload
Function that is going to override a parent function must use the keyword override
.
payable
Functions and addresses declared payable
can receive ether
into the contract.
- custom modifiers - similar to decorators in Python
// Modifiers can take inputs. This modifier checks that the
// address passed in is not the zero address.
modifier validAddress(address _addr) {
require(_addr != address(0), "Not valid address");
// Underscore is a special character only used inside
// a function modifier and it tells Solidity to
// execute the rest of the code.
_;
}
function changeOwner(address _newOwner) public onlyOwner validAddress(_newOwner) {
owner = _newOwner;
}
// Modifiers can be called before and / or after a function.
// This modifier prevents a function from being called while
// it is still executing.
modifier noReentrancy() {
require(!locked, "No reentrancy");
locked = true;
_;
locked = false;
}
function decrement(uint i) public noReentrancy {
x -= i;
if (i > 1) {
decrement(i - 1);
}
}
Data Locations
storage
- variable is a state variable (store on blockchain)
memory
- variable is in memory and it exists while a function is being called
calldata
- special data location that contains function arguments
function h(uint[] calldata _arr) external {
// do something with calldata array
}