Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 47 ยท Contract Structure

Modifiers and Access Control

Write Solidity modifiers, build onlyOwner, roles, two-step ownership transfer and a pause switch, and see the guard pattern in a runnable JavaScript stand-in.

Every public function of a contract can be called by anyone on Earth. That is great for a token transfer and terrible for "set the price" or "withdraw all funds". Access control is the set of checks that decide who may call what, and in Solidity the usual tool for it is the modifier: a reusable piece of code that wraps a function and runs before (or around) its body.

This lesson covers how modifiers work, how to build the common guards (onlyOwner, roles, a pause switch), why ownership transfer should take two steps, and what the pattern looks like when you rebuild it with higher-order functions in JavaScript.

Four guards you will write

onlyOwner One address is in charge.
Roles Several jobs, each with its own members.
Two-step transfer New owner must accept the job.
Pause A switch that freezes risky functions.

All four are checks that run before the function body.

1 / 2

How a modifier works

A modifier looks like a function, but it contains a special placeholder statement, _;. When a function uses the modifier, the compiler runs the modifier's code and substitutes the function body wherever _; appears.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract Vault {
    address public owner;
    uint256 public fee;

    error NotOwner(address caller);

    constructor() {
        owner = msg.sender;
    }

    modifier onlyOwner() {
        if (msg.sender != owner) revert NotOwner(msg.sender);
        _;
    }

    function setFee(uint256 newFee) external onlyOwner {
        fee = newFee;
    }
}

When setFee is called, the check runs first. If it passes, execution reaches _; and the body runs. If it reverts, the whole transaction is undone and the body never starts. This is why the check belongs before _; for guards. Code after _; runs once the body finishes, which is useful for cleanup or post-conditions.

Modifiers can take arguments, and a function can list several of them. They run left to right:

SOLIDITY
modifier atLeast(uint256 minimum) {
    require(msg.value >= minimum, "too little ether");
    _;
}

function join() external payable onlyMembers atLeast(1 ether) {
    // runs only if both modifiers let it through
}

Keep modifiers short. Their code is copied into every function that uses them, so a long modifier inflates the contract. A common trick is to put the real logic in an internal function (_checkOwner()) and let the modifier simply call it.

onlyOwner and why msg.sender

The check compares msg.sender, the account or contract that called this function right now. Never use tx.origin for it. tx.origin is the wallet that began the whole transaction, so a malicious contract that tricks the owner into calling it can then call your contract, and tx.origin would still say "owner". msg.sender, msg.value and Global Variables explains the difference, and Common Vulnerabilities shows the attack.

Roles

One owner who can do everything is simple, but it is a single point of failure. Role-based access control splits powers: one group can mint, another can pause, another can change settings. A role is just a label, usually a hash, and a nested mapping records who has it.

SOLIDITY
contract Roles {
    bytes32 public constant MINTER = keccak256("MINTER");
    bytes32 public constant PAUSER = keccak256("PAUSER");

    mapping(bytes32 => mapping(address => bool)) private _has;

    error MissingRole(bytes32 role, address account);

    modifier onlyRole(bytes32 role) {
        if (!_has[role][msg.sender]) revert MissingRole(role, msg.sender);
        _;
    }

    function mint(address to, uint256 amount) external onlyRole(MINTER) {
        // ...
    }
}

In practice you rarely write this yourself. OpenZeppelin's AccessControl adds an admin role that can grant and revoke the others, and events for every change (see Using OpenZeppelin). Grant and revoke functions should themselves be guarded and should emit events so that watchers can see powers changing.

Two-step ownership transfer

A one-step transferOwnership(newOwner) has a nasty failure: type the wrong address and the contract is owned by nobody forever. The safer pattern has two steps. The current owner proposes a new owner, and the new owner must accept, proving that the address is real and under someone's control.

SOLIDITY
address public owner;
address public pendingOwner;

function proposeOwner(address next) external onlyOwner {
    pendingOwner = next;
}

function acceptOwnership() external {
    require(msg.sender == pendingOwner, "not pending owner");
    owner = pendingOwner;
    pendingOwner = address(0);
}

OpenZeppelin ships this as Ownable2Step. Renouncing ownership (setting it to the zero address) is a separate, deliberate act, and it is permanent: nobody can ever call the onlyOwner functions again.

Pausing

A pause switch (sometimes called a circuit breaker) lets a trusted account freeze the risky functions if a bug is discovered, while leaving safe ones, such as withdrawals, usable.

SOLIDITY
bool public paused;

error IsPaused();

modifier whenNotPaused() {
    if (paused) revert IsPaused();
    _;
}

function pause() external onlyRole(PAUSER) { paused = true; }
function unpause() external onlyRole(PAUSER) { paused = false; }

A pause is power, and power must be trusted. Whoever holds the key can freeze user funds, so serious projects give it to a multisig wallet (Project: A Multisig Wallet) or a timelock rather than a single laptop.

An access check protects a function only if you remember to write it. The most common access-control bug is a sensitive function left public with no modifier, including initialize functions in upgradeable contracts. List every function that changes state and ask who should be able to call it.

The pattern with higher-order functions

JavaScript has no modifiers, but a function that takes a function and returns a guarded version of it does the same job. The stand-in below is not Solidity: there is no blockchain, no msg.sender supplied by a signature, and no revert opcode. A ctx object plays the part of msg.sender, and a thrown error plays the part of revert. The structure, though, mirrors the real pattern: a guard wraps a body, guards run left to right, and a failing guard stops everything.

JS Guards as higher-order functions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Bob is stopped by onlyOwner. After Alice pauses, even she is stopped, because whenNotPaused is the second guard in the chain. Now the roles and the two-step transfer, with a failed accept in between:

JS Roles and two-step ownership

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the roles-as-nested-mapping idea, the propose and accept steps, and the effect of a failing check. Stand-in: sender is passed as an argument instead of being proved by a signature, there are no events, and a JavaScript exception is a pale copy of a revert, which also undoes all state changes automatically.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the _; statement inside a modifier do?

    The compiler places the function's body at the _; position. A guard puts its check before _; so a failing check stops the function before it starts.
  2. 2. Why should an owner check use msg.sender and not tx.origin?

    tx.origin is the wallet that started the whole transaction, so any contract the owner is tricked into calling can forward calls that still appear to come from the owner.
  3. 3. What problem does two-step ownership transfer solve?

    The proposed owner must send an accept transaction, which proves the address is correct and controlled by someone. A typo then leaves the old owner in charge.
  4. 4. A function is declared external onlyOwner whenNotPaused. In what order do the checks run?

    Modifiers are applied in the order listed. Each one runs until its _;, which hands control to the next modifier and finally the body.

Summary

  • A modifier wraps a function: its code runs, and _; marks where the function body goes.
  • Guards check before _; and revert on failure, so the body never runs. Keep modifiers short and move shared logic into an internal function.
  • Use msg.sender, never tx.origin, for authorization.
  • Roles split powers across accounts using a nested mapping, and OpenZeppelin's AccessControl is the audited version of it.
  • Transfer ownership in two steps (propose, then accept), and treat renouncing as permanent.
  • A pause switch is a trusted power, best held by a multisig or timelock. Always review every state-changing function for a missing guard.

Next: Sending and Receiving Ether.