iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Functions

Solidity functions have a visibility (public, external, internal, private) and a state mutability (view, pure, payable, default). Get these right and gas usage drops accordingly.

Visibility + mutability + a real contract

EXAMPLE
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;

contract Wallet {
    mapping(address => uint256) private balances;
    address public immutable owner;

    event Deposit(address indexed from, uint256 amount);
    event Withdrawal(address indexed to, uint256 amount);
    error InsufficientBalance(uint256 requested, uint256 available);
    error NotOwner();

    constructor() {
        owner = msg.sender;
    }

    // payable — accepts ETH
    function deposit() external payable {
        balances[msg.sender] += msg.value;
        emit Deposit(msg.sender, msg.value);
    }

    // view — reads state, no gas if called externally
    function balanceOf(address user) external view returns (uint256) {
        return balances[user];
    }

    // pure — no state read or write
    function add(uint256 a, uint256 b) external pure returns (uint256) {
        return a + b;
    }

    // internal helper — visible to derived contracts, NOT external
    function _transferTo(address payable to, uint256 amount) internal {
        (bool ok, ) = to.call{value: amount}("");
        require(ok, "transfer failed");
    }

    function withdraw(uint256 amount) external {
        uint256 bal = balances[msg.sender];
        if (amount > bal) revert InsufficientBalance(amount, bal);
        balances[msg.sender] = bal - amount;    // CEI: state BEFORE call
        _transferTo(payable(msg.sender), amount);
        emit Withdrawal(msg.sender, amount);
    }

    function setOwner(address) external pure {
        revert NotOwner();    // owner is immutable — function exists as documentation
    }
}

Why it matters

Default to external over public for entry points — saves a calldata copy. Default to view / pure when you can; the compiler verifies you actually meant it.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
function add(uint256 a, uint256 b) external pure returns (uint256) {
    return a + b;
}

function setOwner(address newOwner) external onlyOwner {
    owner = newOwner;
}
Try it Yourself »

Exercise

Visibility for an externally callable view function.

function get() view returns (uint256) { return n; }

Discussion

Loading…