Chapter 0x13: Learn EVM Opcodes in Yul Assembly With Solidity Best Guide
Chapter 0x13: Learn EVM Opcodes in Yul Assembly With Solidity Best Guide

Chapter 0x13: Learn EVM Opcodes in Yul Assembly With Solidity Best Guide

In this chapter, “Learn EVM Opcode in Yul Assembly With Solidity Best Guide,” If you’re diving into the world of Ethereum development, learning EVM (Ethereum Virtual Machine) opcodes is like unlocking the source code of the Ethereum ecosystem. We’ll explore the core concepts, their importance, and how to use them efficiently with Solidity and Yul. This guide is written for beginners with a human-friendly, casual tone, ensuring you’re not only learning but also enjoying the process.

Learn EVM Opcodes in Yul Assembly With Solidity


What is the EVM?

What is the EVM?
What is the EVM?

The Ethereum Virtual Machine (EVM) is the decentralized brain behind Ethereum. It processes and executes smart contracts. Every operation within the EVM is executed using opcodes, which are low-level machine instructions.

Think of opcodes as the building blocks of the EVM. They represent simple operations like adding numbers, storing data, or jumping to another part of the code.

Why Should You Learn EVM Opcodes?

  • Optimize Gas Usage: Knowing opcodes allows you to write more gas-efficient smart contracts.
  • Debugging Mastery: It helps you debug at the bytecode level when something goes wrong in a deployed contract.
  • Deeper Understanding: Learning opcodes bridges the gap between high-level Solidity and the machine-level operations of the EVM.
  • Security Awareness: A solid understanding of opcodes enhances your ability to write secure contracts.

What Are Opcodes in Solidity?

What Are Opcodes in Solidity?
What Are Opcodes in Solidity?

Opcodes are single instructions that the EVM understands. While writing smart contracts in Solidity, you’re using a high-level language. However, the compiler converts your Solidity code into EVM bytecode, a sequence of opcodes.

Here’s an example:

  • Solidity Code:
  • Compiled Opcodes: PUSH1 02 PUSH1 03 ADD

The Basics of Yul and Its Relation to EVM Opcodes

Yul is an intermediate language designed to write highly optimized EVM bytecode. It acts as a bridge between Solidity and raw bytecode, making it easier to manage low-level details.

Why Use Yul?

  1. Gas Optimization: You can write leaner code.
  2. Direct Control: Provides better control over memory and execution flow.
  3. Debugging: Allows a deeper dive into contract behavior.

Example:

The corresponding opcodes would look like: PUSH1 02 PUSH1 03 ADD SSTORE

How to Learn EVM Opcodes Using Solidity and Yul

How to Learn EVM Opcodes Using Solidity and Yul
How to Learn EVM Opcodes Using Solidity and Yul

1. Understand the EVM Memory Layout

The EVM uses three main data locations:

  • Stack: Temporary memory for calculations (max 1024 slots).
  • Memory: Volatile data storage during execution.
  • Storage: Persistent, expensive data storage.

2. Common Opcodes and Their Use

Here are some essential opcodes for beginners:

OpcodeDescriptionGas Cost
ADDAdds two values on the stack3 gas
MULMultiplies two values5 gas
PUSH1Pushes 1-byte value to stack3 gas
SSTOREStores data in storage20,000 gas
JUMPJumps to a specific bytecode8 gas

Writing Your First Yul Code

Let’s write a simple Yul program that performs addition and stores the result.

Example:

Explanation:

  1. let a := 5 initializes a variable a with value 5.
  2. add(a, b) adds the two variables.
  3. sstore(0x01, sum) stores the result in storage slot 0x01.

Gas Optimization Tips Using Opcodes

  1. Minimize Storage Operations: Storage operations like SSTORE are expensive. Cache frequently used values in memory or stack instead.
  2. Use Assembly Sparingly: Yul and assembly give you more control, but improper use can make your contract error-prone.
  3. Avoid Dynamic Loops: Loops can become costly if they depend on dynamic input.

EVM Opcode Reference for Beginners

EVM Opcode Reference for Beginners
EVM Opcode Reference for Beginners

Here’s a cheat sheet for some common EVM opcodes:

OpcodeOperationDescription
STOPHalts executionEnds execution gracefully.
PUSH32Push 32 bytes to stackUseful for constants.
CALLExternal function callCalls another contract or function.
LOG0-4Logging eventsEmits events with 0-4 topics.
RETURNReturns output dataEnds execution and returns data.

EVM Bytecode and Its Relation to Yul

How Solidity Converts to Bytecode

When you compile Solidity code, it’s converted into bytecode, which the EVM executes. Yul lets you bypass Solidity and write directly in an intermediate form for optimized bytecode generation.

For example:

  • Solidity:
  • Yul:
  • Opcodes: PUSH1 0A

Complete EVM Opcode List with Gas Consumption

Complete EVM Opcode List with Gas Consumption
Complete EVM Opcode List with Gas Consumption

Understanding the complete list of EVM opcodes and their gas consumption is crucial for writing efficient and optimized smart contracts. Below, we’ve included a detailed table that lists all the EVM opcodes, their descriptions, and corresponding gas costs. Bookmark this section as your go-to reference!

Arithmetic and Logic Opcodes

OpcodeGas CostDescription
STOP0Halts execution.
ADD3Adds two values.
MUL5Multiplies two values.
SUB3Subtracts the second value from the first.
DIV5Divides the first value by the second.
SDIV5Divides two signed integers.
MOD5Returns the remainder of division.
SMOD5Signed integer modulo operation.
ADDMOD8Modular addition.
MULMOD8Modular multiplication.
EXP10 + 50 per byteExponentiation.
SIGNEXTEND5Extends a signed number to a larger byte size.

Comparison and Bitwise Opcodes

OpcodeGas CostDescription
LT3Less-than comparison.
GT3Greater-than comparison.
SLT3Signed less-than comparison.
SGT3Signed greater-than comparison.
EQ3Checks equality.
ISZERO3Checks if the value is zero.
AND3Bitwise AND operation.
OR3Bitwise OR operation.
XOR3Bitwise XOR operation.
NOT3Bitwise NOT operation.
BYTE3Retrieves a byte from a 256-bit word.

Environmental Opcodes

OpcodeGas CostDescription
SHA330 + 6 per wordComputes the Keccak-256 hash.
ADDRESS2Gets the address of the current contract.
BALANCE400Retrieves the balance of an account.
ORIGIN2Gets the original sender of the transaction.
CALLER2Retrieves the sender of the current call.
CALLVALUE2Gets the value (in Wei) sent with the call.
CALLDATALOAD3Loads input data to the stack.
CALLDATASIZE2Returns the size of the call data.
CALLDATACOPY3 + 3 per wordCopies call data to memory.
CODESIZE2Returns the size of the contract’s code.
CODECOPY3 + 3 per wordCopies contract code to memory.
GASPRICE2Gets the current gas price.
EXTCODESIZE700Returns the size of an external contract’s code.
EXTCODECOPY700 + 3 per wordCopies external contract code.
RETURNDATASIZE2Size of returned data from the last external call.
RETURNDATACOPY3 + 3 per wordCopies returned data to memory.

Block Information Opcodes

OpcodeGas CostDescription
BLOCKHASH20Gets the hash of a specific block.
COINBASE2Retrieves the current block’s miner address.
TIMESTAMP2Gets the current block’s timestamp.
NUMBER2Retrieves the current block number.
DIFFICULTY2Gets the current block’s difficulty.
GASLIMIT2Returns the block’s gas limit.

Stack, Memory, and Storage Opcodes

OpcodeGas CostDescription
POP2Removes the top value from the stack.
MLOAD3Loads a word from memory.
MSTORE3Stores a word in memory.
MSTORE83Stores a byte in memory.
SLOAD100Loads a word from storage.
SSTORE20,000 or 5,000Stores a word in storage.
MSIZE2Gets the size of active memory.

Control Flow Opcodes

OpcodeGas CostDescription
JUMP8Jumps to a specified bytecode location.
JUMPI10Conditional jump to a specified location.
PC2Returns the current program counter.
JUMPDEST1Marks a valid jump destination.

Logging Opcodes

OpcodeGas CostDescription
LOG0375 + 8 per byteLogs an event with no topics.
LOG1375 + 8 per byteLogs an event with one topic.
LOG2375 + 8 per byteLogs an event with two topics.
LOG3375 + 8 per byteLogs an event with three topics.
LOG4375 + 8 per byteLogs an event with four topics.

System Opcodes

OpcodeGas CostDescription
CREATE32,000Creates a new contract.
CALL700 + dynamicCalls an external function.
CALLCODE700 + dynamicExecutes code in another contract’s context.
DELEGATECALL700 + dynamicExecutes code in the caller’s context.
STATICCALL700 + dynamicExecutes a static call to another contract.
RETURN0Returns data from a function call.
REVERT0Reverts state changes and optionally returns data.
SELFDESTRUCTRefunds gasDestroys the contract and sends funds to an address.

Additional Tips

  1. Understand Gas Implications: Each opcode has a specific gas cost, which affects the execution cost of your smart contract.
  2. Combine Opcodes Efficiently: For example, avoid using multiple arithmetic operations in sequence when you can calculate the result in one step.
  3. Practice with Yul: Use Yul assembly to optimize your opcode usage.

By mastering this complete list of EVM opcodes, you’ll gain deep insights into Ethereum development. Use this reference while coding to create gas-efficient, secure, and optimized smart contracts!

FAQs :

What is the opcode in EVM?

Opcodes are the fundamental instructions the EVM understands. They perform operations like addition, storage, and control flow.

What are opcodes in Solidity?

When you write Solidity code, the compiler converts it into EVM opcodes, which are low-level machine instructions.

How can I learn EVM opcodes for free?

1. Explore resources like GitHub, Reddit communities, and free tutorials.
2. Study Solidity’s compiled bytecode using tools like Remix and Hardhat.

What is the gas cost of an opcode?

Each opcode has a predefined gas cost. For instance, ADD costs 3 gas, while SSTORE costs 20,000 gas.

What’s the relation between Yul and EVM bytecode?

Yul serves as a bridge, allowing developers to write optimized code that compiles directly to bytecode.

Conclusion

Learning EVM opcodes in Solidity and Yul assembly opens up a new dimension of Ethereum development. It’s not just about writing smart contracts; it’s about understanding how they work at the lowest level, optimizing for gas, and ensuring security.

Dive deep, experiment with Yul, and make use of tools like Remix, Etherscan, and opcode reference guides to master this skill. The journey might seem challenging at first, but with practice, you’ll unlock the true potential of blockchain programming.

Happy coding! 🚀

Spread the love