Solidity Yul at a First Look
Yul is a low-level language that sits between Solidity and bytecode. It lets a contract express simple operations in a very direct form.
Yul adds two numbers inside an assembly block
The add operation in Yul takes two values and returns their sum. The Solidity wrapper returns that result to the caller.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract YulAdd {
function add(uint256 a, uint256 b) public pure returns (uint256 result) {
assembly {
result := add(a, b)
}
}
}
A Yul function doubles a value
A Yul function names one operation and can be called inside the same assembly block. Here it multiplies its input by two.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract YulDouble {
function doubleValue(uint256 v) public pure returns (uint256 result) {
assembly {
function doubleIt(x) -> y {
y := mul(x, 2)
}
result := doubleIt(v)
}
}
}
A Yul switch picks a result by value
A switch checks its value against each case in turn. The default branch runs when no case matches.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract YulClassify {
function classify(uint256 x) public pure returns (uint256 result) {
assembly {
switch x
case 0 {
result := 0
}
case 1 {
result := 10
}
default {
result := 20
}
}
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract YulCalc {
function add(uint256 a, uint256 b) public pure returns (uint256 result) {
assembly {
function addValues(x, y) -> z {
z := add(x, y)
}
result := addValues(a, b)
}
}
function multiply(uint256 a, uint256 b) public pure returns (uint256 result) {
assembly {
function multiplyValues(x, y) -> z {
z := mul(x, y)
}
result := multiplyValues(a, b)
}
}
function classify(uint256 x) public pure returns (uint256 result) {
assembly {
switch x
case 0 {
result := 0
}
case 1 {
result := 10
}
default {
result := 20
}
}
}
}
Key points
- Yul: Yul is a low-level language that sits between Solidity and bytecode.
- Assembly block: An assembly block is a section of Solidity code written in Yul.
- Yul function: A Yul function is a small named operation defined inside an assembly block.
- Switch: A switch in Yul picks one branch based on the value it is given.
- Restatement: Yul gives a direct low-level form for operations that Solidity usually writes in a higher-level form.
In this example, add uses a Yul function that adds its two inputs. Multiply uses a Yul function that multiplies its two inputs. Classify uses a switch that returns one result for zero, one for one, and a default result for anything else.
Note
Standalone Yul files are out of scope here and only Yul inside Solidity is shown.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
What does a Yul function inside an assembly block do?