Yul Dark Arts: Understanding the EVM from first principles
In this article, I want to walk you through my experience learning Yul to better understand how the EVM manages memory and how you can use this to your advantage, whether it is for learning more about the EVM or for trying to squeeze extra performance from a smart contract. What is Yul? Yul is a type-ish, low-level intermediate representation where EVM opcodes are represented as simple function…
Yul is a low-level intermediate representation for the EVM, which gives developers more control over memory management. It is highly flexible and interoperable with Solidity, making it faster for those who know how to use it effectively. However, it is not a fully-fledged programming language and requires developers to manually manage data types, storage, memory, events, and ABI encoding.
To use Yul, you typically write it inside an assembly block within a Solidity smart contract. While Yul can provide benefits in understanding the EVM and potentially improving performance, it also adds a significant mental overhead due to the need for manual memory management. It is generally recommended to stick to Solidity or Vyper for most smart contract development, reserving Yul for specific performance optimizations.
In Yul, you must think in terms of slots rather than variables, as everything in contract storage is represented as a key-value pair in a 32-byte word. Two main opcodes are used for reading and writing: sload and sstore. When reading a single key, you simply use the sload opcode with the appropriate storage slot. Writing is done similarly using the sstore opcode.
For mappings, a slot seed is used as a base, combined with the key to determine the actual slot where the mapping value is stored. This requires calculating the hash using keccak256, taking into account the address padding and seed placement within the memory word. Once the slot is determined, you can read or write the value using sload and sstore as usual.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.