Basic Setup
All examples use the core library API. Add this to yourCargo.toml:
Basic Bytecode Execution
Basic Bytecode Execution
Execute EVM bytecode and inspect the result:What this does:
- Pushes
0x20(32) and0x40(64) onto the stack - Adds them together
- Result
0x60(96) is left on the stack
Arithmetic Operations
Arithmetic Operations
Perform various arithmetic operations:
Comparison and Logic Operations
Comparison and Logic Operations
Use comparison and bitwise logic operations:
Memory Operations
Memory Operations
Store and load data from memory:Memory Layout:
- Memory expands automatically in 32-byte words
- MSTORE stores 32 bytes at the specified location
- MLOAD reads 32 bytes from the specified location
Storage Operations
Storage Operations
Work with persistent storage:Storage Characteristics:
- Key-value store with 32-byte keys and values
- Persistent across VM execution
- SSTORE saves to storage, SLOAD retrieves
Stack Manipulation
Stack Manipulation
Manipulate the stack with DUP, SWAP, and POP:Stack Operations:
- DUP1-DUP16: Duplicate the Nth stack item
- SWAP1-SWAP16: Swap the top item with the Nth item
- POP: Remove and discard the top stack item
Accessing Stack State After Execution
Accessing Stack State After Execution
Inspect stack contents after running bytecode:
Using Verbose Mode
Using Verbose Mode
Enable verbose mode for detailed execution history:Verbose Mode Benefits:
- Detailed execution trace for debugging
- Track all stack operations with indices
- Monitor memory and storage access patterns
- Useful for understanding complex bytecode behavior
Error Handling
Error Handling
Handle common errors gracefully:Common Errors:
- StackUnderflow: Trying to pop from empty stack
- StackOverflow: Exceeding 1024 item limit
- ShallowStack: Insufficient items for operation
- InvalidInstruction: Unknown opcode
- InvalidNibble: Malformed bytecode hex
Cryptographic Operations
Cryptographic Operations
Use KECCAK256 for hashing:Note: You can verify the hash using:
Complex Example: Complete Smart Contract Logic
Complex Example: Complete Smart Contract Logic
Simulate a complete smart contract execution:This example demonstrates:
- Memory pointer initialization
- Storage updates
- State verification
- Execution history tracking
Testing Your Code
All examples can be run as unit tests. Here’s a complete test module:Next Steps
- VM Reference - Detailed VM structure and methods
- Stack Operations - Complete stack manipulation guide
- Memory Management - Memory allocation and access
- Storage System - Persistent storage operations