Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 47 ยท Object-Oriented Solidity

Inline Assembly and Yul

Learn Solidity inline assembly with Yul: variables, built-in opcodes, if, switch and for, memory and the free memory pointer, storage slots, and why unchecked math is risky.

Normally the compiler turns your Solidity into EVM instructions (opcodes) for you, adding safety checks such as overflow reverts and array bounds tests along the way. Inline assembly lets you write those instructions yourself inside a Solidity function. It uses a small language called Yul, which sits halfway between Solidity and raw opcodes.

You will rarely need it. Most contracts never use assembly, and it is the first place auditors look for bugs. But you will meet it in libraries such as OpenZeppelin and in gas-golfed code, and understanding it makes the EVM much less mysterious. This lesson covers the syntax, the most useful built-in functions, how memory and storage appear in assembly, and the risks. Read Storage, Memory and Calldata and Gas Costs and Optimization first.

Writing an assembly block

An assembly { ... } block can appear in any function. Inside it, you use Yul syntax rather than Solidity syntax: assignment is :=, there are no semicolons, and nearly everything is a function call on 256-bit words.

SOLIDITY
function add(uint256 a, uint256 b) external pure returns (uint256 result) {
    assembly {
        result := add(a, b)      // no overflow check here
    }
}

Key syntax:

Yul Meaning
let x := 5 Declare a variable (always a 256-bit word)
x := add(x, 1) Assign
if cond { ... } Run the block if cond is non-zero. There is no else
switch x case 0 { ... } case 1 { ... } default { ... } Multi-way branch
for { let i := 0 } lt(i, n) { i := add(i, 1) } { ... } Loop: init, condition, post, body
function f(a) -> r { r := mul(a, 2) } Define a helper function
leave Return early from a Yul function

Every Yul value is a 256-bit word, and "true" is any non-zero value. There are no types, so a pointer and a number look the same; you are responsible for keeping them straight.

Built-in functions

These are direct names for EVM opcodes.

Arithmetic and logic. add, sub, mul, div, mod, exp, plus signed forms sdiv and smod. Comparisons: lt, gt, eq and iszero, each returning 1 or 0. Bitwise: and, or, xor, not, shl(shift, value) and shr(shift, value) (note the shift amount comes first).

Memory. mload(p) reads 32 bytes starting at memory address p; mstore(p, v) writes 32 bytes; mstore8(p, v) writes one byte.

Storage. sload(slot) and sstore(slot, value) read and write permanent storage by slot number.

Call data and environment. calldataload(offset), calldatasize(), caller(), callvalue(), address(), balance(a), timestamp(), gas().

Hashing and control. keccak256(offset, length) hashes a memory range, revert(offset, length) and return(offset, length) end execution with data, and extcodesize(a) returns the code size of an address.

The big difference: no safety net

Inside assembly there is no overflow checking. add, sub and mul wrap around modulo 2^256 like the old Solidity 0.7. Also:

  • div(x, 0) and mod(x, 0) return 0, not a revert.
  • Reading memory or storage you never wrote returns zero; there are no bounds checks on arrays.
  • Writing to the wrong address can corrupt other data silently.

This is why assembly can save gas (no checks run) and why it is dangerous (no checks run). Use it only where you can explain every instruction, and keep blocks as small as possible.

Memory and the free memory pointer

Memory is a flat array of bytes, addressed from 0. Solidity reserves the first few words:

Address Purpose
0x00 to 0x3f Scratch space for hashing and short-term use
0x40 to 0x5f The free memory pointer: the address of the first unused byte
0x60 to 0x7f The zero slot (used for empty dynamic arrays)
0x80 onward Allocated memory

To allocate memory in assembly you read the pointer at 0x40, use that region, and move the pointer forward:

SOLIDITY
function hashPair(bytes32 a, bytes32 b) external pure returns (bytes32 h) {
    assembly {
        mstore(0x00, a)              // scratch space, no allocation needed
        mstore(0x20, b)
        h := keccak256(0x00, 0x40)   // hash 64 bytes
    }
}

This avoids allocating and encoding an array, which is why OpenZeppelin's MerkleProof hashing uses a similar trick. When your assembly follows the Solidity memory rules (only touches scratch space or memory it allocates above the free pointer) mark it assembly ("memory-safe") { ... }, so the optimizer can rely on that.

A string in memory is stored as a 32-byte length followed by the bytes, which is why mload(str) gives a string's length.

Storage and variables

Local variables are visible inside a block. For a state variable, assembly gives you its slot with .slot (and .offset for a packed variable):

SOLIDITY
uint256 public total;      // slot 0

function bump() external {
    assembly {
        let v := sload(total.slot)
        sstore(total.slot, add(v, 1))
    }
}

For mappings and arrays the slot of an element is keccak256(key . slot), as described in Mappings and Storage, Memory and Calldata. Proxy contracts use sload/sstore with a chosen slot constant (the "EIP-1967 slot") to store the implementation address without colliding with normal variables; see Proxies and Upgradeable Contracts.

Practical examples

Is this address a contract? extcodesize is non-zero only for accounts with code (it is zero during a contract's own constructor, so this is not a safe "not a bot" test):

SOLIDITY
function isContract(address a) internal view returns (bool r) {
    uint256 size;
    assembly { size := extcodesize(a) }
    r = size > 0;
}

Revert with a custom error without ABI-encoding helpers:

SOLIDITY
error Unauthorized();

function onlyOwner() internal view {
    assembly {
        if iszero(eq(caller(), sload(0))) {            // owner stored in slot 0
            mstore(0x00, 0x82b42900)                   // selector of Unauthorized()
            revert(0x1c, 0x04)                         // 4 bytes of the word
        }
    }
}

Loop with unchecked counters:

SOLIDITY
function sum(uint256[] calldata xs) external pure returns (uint256 total) {
    assembly {
        let end := add(xs.offset, shl(5, xs.length))   // length * 32
        for { let p := xs.offset } lt(p, end) { p := add(p, 0x20) } {
            total := add(total, calldataload(p))
        }
    }
}

Compare with the plain Solidity loop: it is cheaper because no bounds check or overflow check runs per element, but if the numbers could overflow, the result is silently wrong.

When should you use it?

  • To reach an operation Solidity does not expose (reading extcodesize, custom return data, EIP-1967 slots).
  • To squeeze gas out of a proven hot path, after measuring (see Gas Costs and Optimization).
  • In low-level library code that is heavily tested and audited.

Do not use it to look clever. Prefer readable Solidity, and rely on the optimizer, which is often as good as hand-written assembly. If you do use assembly, comment every block, add tests with edge cases, and fuzz it (Testing Contracts).

Try it: Yul arithmetic versus checked Solidity

This stand-in implements the 256-bit wrapping built-ins and compares them with Solidity 0.8's checked arithmetic.

JS Yul built-ins wrap and never revert

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

No output.

Try it: memory, the free pointer and a string

This model has a 32-byte-word memory, the free memory pointer at 0x40, and a bump allocator. It stores a string the way Solidity does, with the length in the first word, then reads it back.

JS mload, mstore and the free memory pointer

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

No output.

What is real: the Yul syntax, the built-in names, the wrap-around and zero-division behavior, the memory layout and the free memory pointer match the EVM. What is the stand-in: the JavaScript code only models arithmetic and memory; it is not a Yul interpreter, there is no gas, and keccak256 and storage are left out. Real assembly should be compiled and tested with Foundry or Hardhat.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does div(7, 0) return in Yul?

    In assembly, division and modulo by zero return 0. Solidity's own / operator reverts, but assembly has no such safety net.
  2. 2. What is stored at memory address 0x40 in Solidity?

    Solidity keeps a free memory pointer at 0x40. New memory is allocated at that address and the pointer is moved forward.
  3. 3. Which statement about Yul if is true?

    Yul's if has no else. For several branches use switch, and any non-zero value counts as true.
  4. 4. Why is inline assembly considered risky?

    The safety checks Solidity adds are absent, so you must verify every step yourself.
  5. 5. How do you get the storage slot of a state variable named total in assembly?

    Assembly can refer to a state variable's slot with .slot (and .offset for packed variables).

Summary

  • assembly { ... } embeds Yul in Solidity. Variables are 256-bit words, assignment is :=, and control flow is if, switch and for.
  • Built-ins map to opcodes: arithmetic, comparison and bitwise operations, mload/mstore, sload/sstore, calldataload, keccak256, revert and return.
  • There are no overflow, bounds or type checks: arithmetic wraps, division by zero gives 0, and bad memory writes corrupt data.
  • Memory has scratch space at 0x00, the free memory pointer at 0x40 and allocations from 0x80. Mark code that obeys these rules memory-safe.
  • Use assembly only for operations Solidity cannot express or for measured hot paths, keep it small, and test it heavily.

Next: learn how contracts are replaced and upgraded safely in Proxies and Upgradeable Contracts.