Functions and Visibility
Function visibility, payable, and return values.
Code
contract Functions {
uint256 private counter;
// public: callable internally + externally
function publicFunc() public returns (uint) {
counter++;
return counter;
}
// external: only callable from outside (cheaper for large inputs)
function externalFunc() external pure returns (string memory) {
return "external";
}
// internal: callable from this contract + subclasses (default)
function internalFunc() internal view returns (uint) {
return counter;
}
// private: only this contract (still visible on chain!)
function privateFunc() private view returns (uint) {
return counter;
}
// payable: accepts ETH
function deposit() external payable {
// msg.value is the ETH sent
require(msg.value > 0, "Send ETH");
}
// Multiple return values
function split(uint a, uint b)
external pure returns (uint sum, uint diff)
{
sum = a + b;
diff = a - b;
// Named returns auto-return
}
// Function selector (first 4 bytes of keccak256 signature)
bytes4 constant SELECTOR = bytes4(keccak256("transfer(address,uint256)"));
}Explanation
Visibility (most to least restrictive): public, external, internal, private. external can't be called internally (use this.func). private doesn't mean secret — all data is public on-chain. payable enables ETH receipt via msg.value. Named returns are auto-returned (no return statement needed). Function selectors identify functions in low-level calls (call, delegatecall).
More Solidity Snippets
Contract Basics
Define a basic smart contract with state and functions.
Modifiers and Access Control
Reuse validation logic with modifiers.
Events and Logs
Emit events for off-chain listeners.
Mappings, Structs & Nested Storage
Group related data with structs and look it up by key with mappings.
Inheritance, Abstract & Interfaces
Reuse logic via inheritance; define contracts with abstract and interface.
Payable, receive & fallback (ETH flows)
Receive ETH via payable functions and the receive/fallback hooks.