Jeancvllr - EVM Assembly

Solidity Tutorial : all about Assembly

Namespace

Quote from Solidity doc:

Different inline assembly blocks share no namespace, i.e. it is not possible to call a Yul function or access a Yul variable defined in a different inline assembly block.

Basic Example

In the inner working of the EVM, let performs the following:

  1. Creates a new stack slot

  2. The new slot is reserved for the variable.

  3. The slot is then automatically removed again when the end of the block is reached.

triangle-exclamation

Literals

Literals are also written in the same way than in Solidity. However, string literals can be up to 32 characters:

Blocks and Scope

Variables follow the standard rule of block scoping. A block scope is defined by adding code between two curly braces { ... }.

In the example below, y and z are only visible in the scope they are defined in. So Scope 1 for y and Scope 2 for z:

Loops

This is a for loop in Solidity:

This is its assembly equivalent:

Note that lt(i, n) is a functional-style expression. In fact, everything in Solidity assembly must be written in functional.

There is no while loop in Solidity assembly, but similar effect can be achieved by for loop:

Conditional Statements

Solidity inline assembly supports if statement to check conditions before executing code. However, there is no else part:

Curly braces for the body of the if statement are required.

EVM Assembly also includes switch statement. A switch statement takes the value of an expression and compares it to several constants. The branch corresponding to the matching constant is taken. You can also have a default case if none of the cases match:

Functions

Last updated