๐ง Ethereum & EVM Fundamentals
๐ฏ What is Ethereum?
Ethereum is a decentralized, open-source blockchain with smart contract functionality. It is the second-largest cryptocurrency by market capitalization and the most programmable blockchain, enabling decentralized applications (dApps), DeFi, NFTs, DAOs, and Web3. The EVM (Ethereum Virtual Machine) is the runtime environment that executes smart contracts, making Ethereum a "world computer."
Why Ethereum Matters
Programmable: Smart contracts. EVM: World computer. DeFi: $50B+ TVL. NFTs: Digital ownership. DAOs: On-chain governance. Web3: Decentralized internet.
# Ethereum & EVM โ the big picture
# The world's most programmable blockchain.
print("""
=== Ethereum & EVM ===
What it is:
- Decentralized blockchain
- Smart contract platform
- World computer
- EVM runtime
Why it matters:
- Programmable
- EVM
- DeFi
- NFTs
- DAOs
- Web3
Key concepts:
- Accounts (EOA, Contract)
- World State
- Transactions
- Gas & Fees
- EVM
- Opcodes
- Stack, Memory, Storage
- Calldata
- Bytecode
- Merkle Patricia Trie
- Consensus (PoS)
- Layer 2
- dApps
- DeFi
- NFTs
- Solidity
Applications:
- DeFi (Uniswap, Aave)
- NFTs (OpenSea)
- DAOs
- Stablecoins (USDC, USDT)
- Layer 2 (Arbitrum, Optimism)
- Web3
""")
print("=== Historical Context ===")
print("""
2013: Vitalik Buterin whitepaper
2014: Crowdsale
2015: Frontier launch
2016: The DAO hack, fork
2017: ICO boom, CryptoKitties
2020: DeFi Summer
2021: NFT boom, EIP-1559
2022: The Merge (PoS)
2023: Shapella, Layer 2 growth
2025: Dencun, Proto-Danksharding
""")
print("=== Why It's Hard ===")
print("""
1. SCALABILITY
- 15-30 TPS
- Layer 2
- Sharding
2. GAS
- Expensive
- Optimization
- EIP-1559
3. EVM
- Stack-based
- 256-bit
- Complex
4. STATE
- Merkle Patricia Trie
- Large
- Pruning
5. SECURITY
- Reentrancy
- Overflow
- Access control
""")๐ฏ Why Ethereum Matters
๐ฏ The Value of Ethereum
Ethereum is the world's most programmable blockchain, enabling a new generation of decentralized applications that run without intermediaries, censorship, or downtime.
Key Benefits
Programmable: Turing-complete. Decentralized: No single point. Composable: Money Legos. Permissionless: Anyone. Transparent: Public. Innovation: DeFi, NFTs.
# Why Ethereum Matters
print("=== 1. Programmable ===")
print("""
Programmable:
- Turing-complete
- Smart contracts
- Any logic
Example:
Solidity
โ DeFi
""")
print("\n=== 2. Decentralized ===")
print("""
Decentralized:
- No single point
- Censorship-resistant
- Trustless
Example:
Ethereum
โ ~1M validators
""")
print("\n=== 3. Composable ===")
print("""
Composable:
- Money Legos
- Interoperable
- Building blocks
Example:
Uniswap + Aave
โ Composability
""")
print("\n=== 4. Permissionless ===")
print("""
Permissionless:
- Anyone
- No approval
- Open
Example:
Deploy contract
โ Anyone
""")
print("\n=== 5. Transparent ===")
print("""
Transparent:
- Public
- Auditable
- Open
Example:
Etherscan
โ Transparent
""")
print("\n=== 6. Innovation ===")
print("""
Innovation:
- DeFi
- NFTs
- DAOs
- Layer 2
Example:
Ethereum
โ Innovation
""")
print("\n=== 7. Network Effects ===")
print("""
Network Effects:
- Largest
- Most developers
- Most TVL
Example:
Ethereum
โ Network
""")
print("\n=== 8. Security ===")
print("""
Security:
- PoS
- ~1M validators
- $100B+ staked
Example:
Ethereum
โ Secure
""")
print("\n=== 9. EVM Standard ===")
print("""
EVM:
- Standard
- Many chains
- Compatible
Example:
EVM
โ Polygon, BSC, Avalanche
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- DeFi
- NFTs
- DAOs
- Stablecoins
- Layer 2
- Web3
""")๐ค Accounts
๐ฏ Ethereum Accounts
Ethereum has two types of accounts: Externally Owned Accounts (EOA) controlled by private keys, and Contract Accounts controlled by code. Each account has a balance, nonce, storage, and code.
Accounts
EOA: Private key. Contract: Code. Address: 20 bytes. Balance: Wei. Nonce: Counter. Storage: Contract.
# Accounts
print("=== 1. Externally Owned Accounts (EOA) ===")
print("""
EOA:
- Private key
- Public key
- Address
- No code
Example:
Private key
โ Public key
โ Address
""")
print("\n=== 2. Contract Accounts ===")
print("""
Contract:
- Code
- Storage
- Address
- No private key
Example:
Deploy
โ Contract
""")
print("\n=== 3. Address ===")
print("""
Address:
- 20 bytes
- 40 hex chars
- 0x prefix
Example:
0x742d35Cc6634C0532925a3b844Bc454e4438f44e
""")
print("\n=== 4. Account State ===")
print("""
State:
- nonce
- balance
- storageRoot
- codeHash
Example:
Account
โ State
""")
print("\n=== 5. Nonce ===")
print("""
Nonce:
- Transaction count
- EOA: sent
- Contract: created
Example:
Nonce 0
โ 1
โ 2
""")
print("\n=== 6. Balance ===")
print("""
Balance:
- Wei
- 1 ETH = 10^18 wei
- Uint256
Example:
1 ETH
โ 10^18 wei
""")
print("\n=== 7. Python Account ===")
print("""
from eth_account import Account
# Create account
acct = Account.create()
print(f"Address: {acct.address}")
print(f"Private key: {acct.key.hex()}")
# From private key
acct = Account.from_key('0x...')
print(f"Address: {acct.address}")
""")
print("\n=== 8. Python Example ===")
print("""
from eth_account import Account
from web3 import Web3
# Create
acct = Account.create()
# Balance
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_KEY'))
balance = w3.eth.getBalance(acct.address)
print(f"Balance: {w3.fromWei(balance, 'ether')} ETH")
# Nonce
nonce = w3.eth.getTransactionCount(acct.address)
print(f"Nonce: {nonce}")
""")
print("\n=== 9. Comparison ===")
print(f"{'Feature':<20} {'EOA':<15} {'Contract':<15}")
print("-" * 50)
print(f"{'Private Key':<20} {'Yes':<15} {'No':<15}")
print(f"{'Code':<20} {'No':<15} {'Yes':<15}")
print(f"{'Storage':<20} {'No':<15} {'Yes':<15}")
print(f"{'Initiate Tx':<20} {'Yes':<15} {'No':<15}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Wallets
- Smart contracts
- DeFi
- NFTs
""")๐ World State
๐ฏ The World State
The World State is a mapping of addresses to account states. It is stored in a Merkle Patricia Trie and updated with every transaction. The state root is stored in each block header.
World State
Mapping: Address โ Account. Trie: Merkle Patricia. Root: State root. Update: Every tx. Commitment: Cryptographic. Size: Large.
# World State
print("=== 1. What is World State? ===")
print("""
World State:
- Mapping
- Address โ Account
- Merkle Patricia Trie
- State root
Example:
0x1234... โ {balance, nonce, ...}
""")
print("\n=== 2. State Root ===")
print("""
State Root:
- Hash
- Commitment
- Block header
Example:
State root
โ 0xabc...
""")
print("\n=== 3. Update ===")
print("""
Update:
- Every tx
- Modify state
- New root
Example:
Transfer
โ Update
โ New root
""")
print("\n=== 4. Merkle Patricia Trie ===")
print("""
MPT:
- Merkle tree
- Patricia trie
- Key-value
- Efficient
Example:
State
โ MPT
โ Root
""")
print("\n=== 5. State Size ===")
print("""
Size:
- Large
- ~100 GB+
- Pruning
Example:
State
โ Large
""")
print("\n=== 6. State Pruning ===")
print("""
Pruning:
- Remove old
- Save space
- Archive
Example:
Pruning
โ Smaller
""")
print("\n=== 7. Python State ===")
print("""
class WorldState:
def __init__(self):
self.accounts = {}
def get_account(self, address):
return self.accounts.get(address, {
'nonce': 0,
'balance': 0,
'storage': {},
'code': b''
})
def set_account(self, address, account):
self.accounts[address] = account
def update_balance(self, address, amount):
account = self.get_account(address)
account['balance'] += amount
self.set_account(address, account)
# Example
# ws = WorldState()
# ws.update_balance('0x1234', 1000)
# print(ws.get_account('0x1234'))
""")
print("\n=== 8. Python State Root ===")
print("""
import hashlib
def compute_state_root(accounts):
\"\"\"Compute state root (simplified).\"\"\"
data = str(sorted(accounts.items()))
return hashlib.sha256(data.encode()).hexdigest()
# Example
# accounts = {'0x1234': {'balance': 1000}}
# print(compute_state_root(accounts))
""")
print("\n=== 9. Comparison ===")
print(f"{'Feature':<20} {'Ethereum':<15} {'Bitcoin':<15}")
print("-" * 50)
print(f"{'Model':<20} {'Account':<15} {'UTXO':<15}")
print(f"{'State':<20} {'Global':<15} {'UTXO set':<15}")
print(f"{'Trie':<20} {'MPT':<15} {'Merkle':<15}")
print(f"{'Programmable':<20} {'Yes':<15} {'No':<15}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Smart contracts
- DeFi
- State channels
- Rollups
""")๐ค Transactions
๐ฏ Ethereum Transactions
A transaction is a signed message that changes the state of Ethereum. It can transfer ETH, deploy a contract, or call a contract function. Transactions are executed by the EVM and cost gas.
Transactions
From: Sender. To: Recipient. Value: ETH. Data: Calldata. Gas: Limit. Signature: ECDSA.
# Transactions
print("=== 1. Transaction Structure ===")
print("""
Transaction:
- from
- to
- value
- data
- gas
- gasPrice
- nonce
- signature
Example:
{
'from': '0x...',
'to': '0x...',
'value': 1000000000000000000,
'data': '0x',
'gas': 21000
}
""")
print("\n=== 2. Types ===")
print("""
Types:
- Transfer: value
- Deploy: data (code)
- Call: data (function)
- Create2: deterministic
Example:
Transfer
โ value
""")
print("\n=== 3. Nonce ===")
print("""
Nonce:
- Transaction count
- Prevent replay
- Order
Example:
Nonce 0
โ 1
""")
print("\n=== 4. Gas Limit ===")
print("""
Gas Limit:
- Max gas
- Prevent infinite
- Refund
Example:
Gas limit: 21000
""")
print("\n=== 5. Gas Price ===")
print("""
Gas Price:
- Wei per gas
- EIP-1559
- Base + priority
Example:
50 gwei
""")
print("\n=== 6. Signature ===")
print("""
Signature:
- ECDSA
- secp256k1
- v, r, s
Example:
Sign
โ Signature
""")
print("\n=== 7. Python Transaction ===")
print("""
from eth_account import Account
from web3 import Web3
acct = Account.from_key('0x...')
tx = {
'to': '0x...',
'value': Web3.toWei(0.01, 'ether'),
'gas': 21000,
'gasPrice': Web3.toWei(50, 'gwei'),
'nonce': 0,
'chainId': 1
}
signed = acct.sign_transaction(tx)
print(signed.rawTransaction.hex())
""")
print("\n=== 8. Python Example ===")
print("""
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_KEY'))
# Send transaction
tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
print(f"TX Hash: {tx_hash.hex()}")
# Wait
receipt = w3.eth.waitForTransactionReceipt(tx_hash)
print(f"Status: {receipt.status}")
print(f"Gas used: {receipt.gasUsed}")
""")
print("\n=== 9. Transaction Types ===")
print(f"{'Type':<20} {'EIP':<15} {'Features':<30}")
print("-" * 65)
print(f"{'Legacy':<20} {'-':<15} {'gasPrice':<30}")
print(f"{'Type 1':<20} {'2930':<15} {'access list':<30}")
print(f"{'Type 2':<20} {'1559':<15} {'base + priority':<30}")
print(f"{'Type 3':<20} {'4844':<15} {'blob':<30}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Transfers
- Deploy
- Contract calls
- DeFi
""")โฝ Gas & Fees
๐ฏ Gas in Ethereum
Gas is the unit of computation in Ethereum. Every operation in the EVM costs gas. Users pay gas fees (base fee + priority fee) to execute transactions. Gas prevents spam and incentivizes validators.
Gas
Unit: Computation. Base Fee: Burned. Priority: Validator. Limit: Max. Refund: Unused. EIP-1559: Fee market.
# Gas & Fees
print("=== 1. What is Gas? ===")
print("""
Gas:
- Unit of computation
- Every op costs gas
- Prevent spam
Example:
Transfer: 21,000 gas
""")
print("\n=== 2. Gas Cost ===")
print("""
Cost:
- ADD: 3
- MUL: 5
- SLOAD: 2,100 (cold)
- SSTORE: 20,000 (new)
- CALL: 700
Example:
ADD
โ 3 gas
""")
print("\n=== 3. Gas Limit ===")
print("""
Limit:
- Max gas
- User sets
- Refund unused
Example:
Limit: 100,000
Used: 50,000
Refund: 50,000
""")
print("\n=== 4. Gas Price ===")
print("""
Price:
- Wei per gas
- EIP-1559
- Base + priority
Example:
Base: 10 gwei
Priority: 2 gwei
Total: 12 gwei
""")
print("\n=== 5. EIP-1559 ===")
print("""
EIP-1559:
- 2021
- Base fee
- Burned
- Priority fee
Example:
Base fee
โ Burned
""")
print("\n=== 6. Gas Refund ===")
print("""
Refund:
- Unused gas
- Returned
- 50% max
Example:
Unused
โ Refund
""")
print("\n=== 7. Python Gas ===")
print("""
def calculate_gas(gas_used, base_fee, priority_fee):
\"\"\"Calculate gas cost.\"\"\"
total = gas_used * (base_fee + priority_fee)
burned = gas_used * base_fee
tip = gas_used * priority_fee
return {
'total': total,
'burned': burned,
'tip': tip
}
# Example
# print(calculate_gas(21000, 10, 2))
""")
print("\n=== 8. Python Example ===")
print("""
from web3 import Web3
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_KEY'))
# Gas price
gas_price = w3.eth.gas_price
print(f"Gas price: {w3.fromWei(gas_price, 'gwei')} gwei")
# Estimate
gas_estimate = w3.eth.estimate_gas({
'to': '0x...',
'value': w3.toWei(1, 'ether')
})
print(f"Gas estimate: {gas_estimate}")
# Cost
cost = gas_estimate * gas_price
print(f"Cost: {w3.fromWei(cost, 'ether')} ETH")
""")
print("\n=== 9. Common Gas Costs ===")
print(f"{'Operation':<25} {'Gas':<15}")
print("-" * 40)
print(f"{'Transfer':<25} {'21,000':<15}")
print(f"{'ADD':<25} {'3':<15}")
print(f"{'MUL':<25} {'5':<15}")
print(f"{'SLOAD (cold)':<25} {'2,100':<15}")
print(f"{'SLOAD (warm)':<25} {'100':<15}")
print(f"{'SSTORE (new)':<25} {'20,000':<15}")
print(f"{'SSTORE (update)':<25} {'5,000':<15}")
print(f"{'CALL':<25} {'700':<15}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Transactions
- Smart contracts
- Optimization
- Layer 2
""")๐ป EVM Overview
๐ฏ The Ethereum Virtual Machine
The EVM is the runtime environment for executing smart contracts on Ethereum. It is a stack-based, Turing-complete virtual machine with ~140 opcodes, deterministic execution, and gas metering.
EVM
Stack: 1024 items. Word: 256-bit. Opcodes: ~140. Gas: Metered. Deterministic: Yes. Isolated: Sandboxed.
# EVM Overview
print("=== 1. What is the EVM? ===")
print("""
EVM:
- Ethereum Virtual Machine
- Runtime
- Stack-based
- 256-bit
- Gas metered
Example:
Solidity
โ Bytecode
โ EVM
""")
print("\n=== 2. Stack ===")
print("""
Stack:
- 1024 items
- 256-bit
- LIFO
Example:
PUSH 1
PUSH 2
ADD
โ 3
""")
print("\n=== 3. Memory ===")
print("""
Memory:
- Byte-addressable
- Expandable
- Gas cost
Example:
MSTORE
โ Memory
""")
print("\n=== 4. Storage ===")
print("""
Storage:
- Persistent
- Key-value
- 256-bit
Example:
SSTORE
โ Storage
""")
print("\n=== 5. Opcodes ===")
print("""
Opcodes:
- ~140
- 1 byte
- Gas
Example:
0x01: ADD
0x02: MUL
0x60: PUSH1
""")
print("\n=== 6. Gas ===")
print("""
Gas:
- Metered
- Prevent infinite
- Refund
Example:
ADD: 3 gas
SSTORE: 20,000 gas
""")
print("\n=== 7. Python EVM ===")
print("""
class EVM:
def __init__(self):
self.stack = []
self.memory = {}
self.storage = {}
self.pc = 0
self.gas = 1000000
def push(self, value):
self.stack.append(value)
def pop(self):
return self.stack.pop()
def add(self):
a = self.pop()
b = self.pop()
self.push(a + b)
def mul(self):
a = self.pop()
b = self.pop()
self.push(a * b)
def run(self, code):
for op in code:
if op == 'PUSH':
self.push(code[1])
elif op == 'ADD':
self.add()
elif op == 'MUL':
self.mul()
# Example
# evm = EVM()
# evm.push(1)
# evm.push(2)
# evm.add()
# print(evm.stack) # [3]
""")
print("\n=== 8. Python Example ===")
print("""
class EVM:
def __init__(self):
self.stack = []
self.gas = 1000000
def execute(self, opcode):
if opcode == 0x01: # ADD
a = self.stack.pop()
b = self.stack.pop()
self.stack.append(a + b)
self.gas -= 3
elif opcode == 0x02: # MUL
a = self.stack.pop()
b = self.stack.pop()
self.stack.append(a * b)
self.gas -= 5
elif opcode == 0x60: # PUSH1
self.stack.append(1)
self.gas -= 3
def run(self, code):
for op in code:
self.execute(op)
return self.stack
# Example
# evm = EVM()
# result = evm.run([0x60, 0x60, 0x01])
# print(result)
""")
print("\n=== 9. Components ===")
print(f"{'Component':<20} {'Size':<15} {'Gas':<15}")
print("-" * 50)
print(f"{'Stack':<20} {'1024':<15} {'Low':<15}")
print(f"{'Memory':<20} {'Expandable':<15} {'Medium':<15}")
print(f"{'Storage':<20} {'Persistent':<15} {'High':<15}")
print(f"{'Calldata':<20} {'Read-only':<15} {'Low':<15}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Smart contracts
- DeFi
- NFTs
- Layer 2
""")๐ง Opcodes
๐ฏ EVM Opcodes
Opcodes are the instructions that the EVM executes. There are ~140 opcodes, each with a unique byte value and gas cost. They manipulate the stack, memory, storage, and control flow.
Opcodes
Arithmetic: ADD, MUL. Stack: PUSH, POP. Memory: MLOAD, MSTORE. Storage: SLOAD, SSTORE. Control: JUMP, JUMPI. Call: CALL, DELEGATECALL.
# Opcodes
print("=== 1. Arithmetic ===")
print("""
Arithmetic:
- ADD: 0x01
- MUL: 0x02
- SUB: 0x03
- DIV: 0x04
- MOD: 0x06
- EXP: 0x0A
Example:
PUSH1 2
PUSH1 3
ADD
โ 5
""")
print("\n=== 2. Stack ===")
print("""
Stack:
- PUSH1-32: 0x60-0x7F
- POP: 0x50
- DUP1-16: 0x80-0x8F
- SWAP1-16: 0x90-0x9F
Example:
PUSH1 5
โ Stack: [5]
""")
print("\n=== 3. Memory ===")
print("""
Memory:
- MLOAD: 0x51
- MSTORE: 0x52
- MSTORE8: 0x53
- MSIZE: 0x59
Example:
MSTORE
โ Memory
""")
print("\n=== 4. Storage ===")
print("""
Storage:
- SLOAD: 0x54
- SSTORE: 0x55
Example:
SSTORE
โ Storage
""")
print("\n=== 5. Control Flow ===")
print("""
Control:
- JUMP: 0x56
- JUMPI: 0x57
- JUMPDEST: 0x5B
- PC: 0x58
Example:
JUMP
โ Jump
""")
print("\n=== 6. Call ===")
print("""
Call:
- CALL: 0xF1
- DELEGATECALL: 0xF4
- STATICCALL: 0xFA
- CREATE: 0xF0
- CREATE2: 0xF5
Example:
CALL
โ External call
""")
print("\n=== 7. Python Opcodes ===")
print("""
OPCODES = {
0x00: 'STOP',
0x01: 'ADD',
0x02: 'MUL',
0x03: 'SUB',
0x04: 'DIV',
0x50: 'POP',
0x51: 'MLOAD',
0x52: 'MSTORE',
0x54: 'SLOAD',
0x55: 'SSTORE',
0x56: 'JUMP',
0x57: 'JUMPI',
0x5B: 'JUMPDEST',
0x60: 'PUSH1',
0x61: 'PUSH2',
0x80: 'DUP1',
0x90: 'SWAP1',
0xF1: 'CALL',
0xF4: 'DELEGATECALL',
0xF0: 'CREATE',
}
# Example
# for op, name in OPCODES.items():
# print(f"0x{op:02x}: {name}")
""")
print("\n=== 8. Python Disassembler ===")
print("""
def disassemble(bytecode):
\"\"\"Disassemble EVM bytecode.\"\"\"
i = 0
while i < len(bytecode):
op = bytecode[i]
if op in OPCODES:
print(f"{i}: {OPCODES[op]}")
else:
print(f"{i}: UNKNOWN (0x{op:02x})")
i += 1
# Example
# bytecode = bytes([0x60, 0x01, 0x60, 0x02, 0x01])
# disassemble(bytecode)
""")
print("\n=== 9. Gas Costs ===")
print(f"{'Opcode':<15} {'Gas':<15} {'Description':<30}")
print("-" * 60)
print(f"{'ADD':<15} {'3':<15} {'Addition':<30}")
print(f"{'MUL':<15} {'5':<15} {'Multiplication':<30}")
print(f"{'SLOAD':<15} {'2,100':<15} {'Storage load (cold)':<30}")
print(f"{'SSTORE':<15} {'20,000':<15} {'Storage store (new)':<30}")
print(f"{'CALL':<15} {'700':<15} {'External call':<30}")
print(f"{'CREATE':<15} {'32,000':<15} {'Create contract':<30}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Smart contracts
- Bytecode
- Optimization
- Security
""")๐ Stack & Memory
๐ฏ Stack and Memory
The EVM uses a stack for computation and memory for temporary data. The stack is LIFO with 1024 items, each 256 bits. Memory is byte-addressable and expandable.
Stack & Memory
Stack: 1024 items. 256-bit: Word. LIFO: Yes. Memory: Byte-addressable. Expandable: Yes. Gas: Cost.
# Stack & Memory
print("=== 1. Stack ===")
print("""
Stack:
- 1024 items
- 256-bit
- LIFO
- Gas: 3
Example:
PUSH1 1
PUSH1 2
ADD
โ 3
""")
print("\n=== 2. Memory ===")
print("""
Memory:
- Byte-addressable
- Expandable
- Gas: 3 per word
Example:
MSTORE
โ Memory
""")
print("\n=== 3. Stack Operations ===")
print("""
Stack:
- PUSH
- POP
- DUP
- SWAP
Example:
PUSH1 5
DUP1
โ [5, 5]
""")
print("\n=== 4. Memory Operations ===")
print("""
Memory:
- MLOAD
- MSTORE
- MSTORE8
- MSIZE
Example:
MSTORE
โ Store
""")
print("\n=== 5. Stack Visualizer ===")
print("""
class Stack:
def __init__(self):
self.items = []
def push(self, value):
self.items.append(value)
def pop(self):
return self.items.pop()
def peek(self):
return self.items[-1]
def __repr__(self):
return f"Stack({self.items})"
# Example
# s = Stack()
# s.push(1)
# s.push(2)
# print(s) # Stack([1, 2])
""")
print("\n=== 6. Python Memory ===")
print("""
class Memory:
def __init__(self):
self.data = bytearray()
def store(self, offset, value):
while len(self.data) < offset + 32:
self.data.extend(b'\\x00' * 32)
self.data[offset:offset+32] = value.to_bytes(32, 'big')
def load(self, offset):
return int.from_bytes(self.data[offset:offset+32], 'big')
# Example
# m = Memory()
# m.store(0, 123)
# print(m.load(0))
""")
print("\n=== 7. Complete Example ===")
print("""
class EVMStack:
def __init__(self):
self.stack = []
self.memory = Memory()
self.gas = 1000000
def push(self, value):
self.stack.append(value)
self.gas -= 3
def pop(self):
return self.stack.pop()
def add(self):
a = self.pop()
b = self.pop()
self.push(a + b)
self.gas -= 3
def mstore(self, offset):
value = self.pop()
self.memory.store(offset, value)
self.gas -= 3
# Example
# evm = EVMStack()
# evm.push(1)
# evm.push(2)
# evm.add()
# print(evm.stack)
""")
print("\n=== 8. Stack Limits ===")
print(f"{'Limit':<20} {'Value':<15}")
print("-" * 40)
print(f"{'Max items':<20} {'1024':<15}")
print(f"{'Word size':<20} {'256-bit':<15}")
print(f"{'Push cost':<20} {'3 gas':<15}")
print(f"{'Pop cost':<20} {'2 gas':<15}")
print("\n=== 9. Memory Expansion ===")
print("""
def memory_cost(words):
\"\"\"Memory expansion cost.\"\"\"
return 3 * words + words ** 2 // 512
# Example
# print(memory_cost(1)) # 3
# print(memory_cost(10)) # 30
# print(memory_cost(100)) # 319
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- EVM execution
- Bytecode
- Optimization
""")๐พ Storage
๐ฏ Contract Storage
Storage is the persistent on-chain state of a contract. It's a key-value store where both keys and values are 256-bit words. Storage is expensive: 20,000 gas per new slot, 5,000 gas per update.
Storage
Persistent: On-chain. Key-value: 256-bit. Expensive: 20,000 gas. Slots: 2^256. Read: 2,100 gas. Write: 20,000 gas.
# Storage
print("=== 1. What is Storage? ===")
print("""
Storage:
- Persistent
- Key-value
- 256-bit
- Expensive
Example:
SSTORE
โ Storage
""")
print("\n=== 2. Storage Slots ===")
print("""
Slots:
- 2^256
- Key
- Value
Example:
slot 0: value
slot 1: value
""")
print("\n=== 3. Cost ===")
print("""
Cost:
- SLOAD: 2,100 (cold)
- SLOAD: 100 (warm)
- SSTORE: 20,000 (new)
- SSTORE: 5,000 (update)
- SSTORE: refund (delete)
Example:
SSTORE
โ 20,000 gas
""")
print("\n=== 4. Storage Layout ===")
print("""
Layout:
- Slot 0: first variable
- Slot 1: second
- Packed
Example:
uint256 a; // slot 0
uint256 b; // slot 1
""")
print("\n=== 5. Packing ===")
print("""
Packing:
- Multiple variables
- One slot
- Save gas
Example:
uint128 a; // slot 0
uint128 b; // slot 0
""")
print("\n=== 6. Python Storage ===")
print("""
class Storage:
def __init__(self):
self.slots = {}
def load(self, key):
return self.slots.get(key, 0)
def store(self, key, value):
self.slots[key] = value
def delete(self, key):
if key in self.slots:
del self.slots[key]
# Example
# s = Storage()
# s.store(0, 123)
# print(s.load(0))
""")
print("\n=== 7. Python Example ===")
print("""
class EVMStorage:
def __init__(self):
self.storage = {}
self.gas = 1000000
def sload(self, key):
if key in self.storage:
self.gas -= 100
return self.storage[key]
self.gas -= 2100
return 0
def sstore(self, key, value):
if key in self.storage:
self.gas -= 5000
else:
self.gas -= 20000
self.storage[key] = value
def __repr__(self):
return f"Storage({self.storage})"
# Example
# s = EVMStorage()
# s.sstore(0, 123)
# print(s.sload(0))
""")
print("\n=== 8. Storage vs Memory ===")
print(f"{'Feature':<20} {'Storage':<15} {'Memory':<15}")
print("-" * 50)
print(f"{'Persistence':<20} {'Yes':<15} {'No':<15}")
print(f"{'Cost':<20} {'High':<15} {'Low':<15}")
print(f"{'Size':<20} {'2^256':<15} {'Expandable':<15}")
print(f"{'Gas':<20} {'20,000':<15} {'3':<15}")
print("\n=== 9. Optimization ===")
print("""
Optimization:
- Pack variables
- Use memory
- Minimize SSTORE
Example:
uint128 a;
uint128 b;
โ 1 slot
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Smart contracts
- State
- Optimization
""")๐ฅ Calldata
๐ฏ Calldata
Calldata is the read-only input data of a transaction. It contains the function selector and arguments. Calldata is the cheapest data location: 4 gas per zero byte, 16 gas per non-zero byte.
Calldata
Read-only: Yes. Function selector: 4 bytes. Arguments: ABI-encoded. Cheapest: 4/16 gas. Immutable: Yes. External: Yes.
# Calldata
print("=== 1. What is Calldata? ===")
print("""
Calldata:
- Transaction input
- Read-only
- Function selector
- Arguments
Example:
0xa9059cbb000000000000000000000000...
""")
print("\n=== 2. Function Selector ===")
print("""
Selector:
- 4 bytes
- First 4 of keccak256
- Function signature
Example:
transfer(address,uint256)
โ 0xa9059cbb
""")
print("\n=== 3. ABI Encoding ===")
print("""
ABI:
- Application Binary Interface
- Encoding
- Arguments
Example:
transfer(address,uint256)
โ selector + args
""")
print("\n=== 4. Cost ===")
print("""
Cost:
- Zero byte: 4 gas
- Non-zero: 16 gas
- Cheapest
Example:
0x00
โ 4 gas
""")
print("\n=== 5. Python Calldata ===")
print("""
from eth_abi import encode
from web3 import Web3
# Encode
selector = Web3.keccak(text='transfer(address,uint256)')[:4]
args = encode(['address', 'uint256'], ['0x...', 1000])
calldata = selector + args
print(calldata.hex())
""")
print("\n=== 6. Python Example ===")
print("""
from eth_utils import function_signature_to_4byte_selector
# Selector
selector = function_signature_to_4byte_selector('transfer(address,uint256)')
print(f"Selector: 0x{selector.hex()}")
# Full calldata
from eth_abi import encode
args = encode(['address', 'uint256'], ['0x742d35Cc6634C0532925a3b844Bc454e4438f44e', 1000])
calldata = selector + args
print(f"Calldata: 0x{calldata.hex()}")
""")
print("\n=== 7. Comparison ===")
print(f"{'Data':<15} {'Cost':<15} {'Location':<15}")
print("-" * 45)
print(f"{'Calldata':<15} {'4/16':<15} {'External':<15}")
print(f"{'Memory':<15} {'3':<15} {'Temporary':<15}")
print(f"{'Storage':<15} {'20,000':<15} {'Persistent':<15}")
print("\n=== 8. Function Selector ===")
print("""
Common selectors:
- transfer(address,uint256): 0xa9059cbb
- approve(address,uint256): 0x095ea7b3
- balanceOf(address): 0x70a08231
- totalSupply(): 0x18160ddd
- transferFrom(address,address,uint256): 0x23b872dd
""")
print("\n=== 9. Python Encoding ===")
print("""
from eth_abi import encode
def encode_transfer(to, amount):
\"\"\"Encode transfer calldata.\"\"\"
selector = bytes.fromhex('a9059cbb')
args = encode(['address', 'uint256'], [to, amount])
return selector + args
# Example
# data = encode_transfer('0x742d35Cc6634C0532925a3b844Bc454e4438f44e', 1000)
# print(data.hex())
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Contract calls
- Transactions
- ABI encoding
""")๐ข Bytecode
๐ฏ EVM Bytecode
Bytecode is the compiled output of a smart contract. It's a sequence of opcodes that the EVM executes. Solidity compiles to bytecode, which is deployed to the blockchain.
Bytecode
Opcodes: 1 byte. Data: PUSH. Deploy: Constructor. Runtime: Deployed. Immutable: Yes. Size: 24KB max.
# Bytecode
print("=== 1. What is Bytecode? ===")
print("""
Bytecode:
- Compiled contract
- Opcodes
- EVM executes
- Deployed
Example:
0x6080604052...
""")
print("\n=== 2. Deploy vs Runtime ===")
print("""
Deploy:
- Constructor
- Init code
- Returns runtime
Runtime:
- Deployed code
- On-chain
- Executed
Example:
Deploy โ Runtime
""")
print("\n=== 3. Size Limit ===")
print("""
Limit:
- 24,576 bytes
- EIP-170
- Deploy fails
Example:
24KB
โ Limit
""")
print("\n=== 4. Python Bytecode ===")
print("""
# Simple bytecode: PUSH1 1 PUSH1 2 ADD
bytecode = bytes([0x60, 0x01, 0x60, 0x02, 0x01])
print(bytecode.hex())
# 6001600201
""")
print("\n=== 5. Python Disassembler ===")
print("""
OPCODES = {
0x00: 'STOP', 0x01: 'ADD', 0x02: 'MUL',
0x50: 'POP', 0x51: 'MLOAD', 0x52: 'MSTORE',
0x54: 'SLOAD', 0x55: 'SSTORE', 0x56: 'JUMP',
0x57: 'JUMPI', 0x5B: 'JUMPDEST',
0x60: 'PUSH1', 0x61: 'PUSH2',
0x80: 'DUP1', 0x90: 'SWAP1',
0xF1: 'CALL', 0xF4: 'DELEGATECALL',
}
def disassemble(bytecode):
i = 0
while i < len(bytecode):
op = bytecode[i]
name = OPCODES.get(op, f'UNKNOWN(0x{op:02x})')
print(f"{i}: {name}")
i += 1
# Example
# disassemble(bytes.fromhex('6001600201'))
""")
print("\n=== 6. Solidity to Bytecode ===")
print("""
// Solidity
pragma solidity ^0.8.0;
contract Simple {
uint256 public value;
function set(uint256 _value) public {
value = _value;
}
}
// Compile
// solc --bin Simple.sol
// โ 608060405234801561001057600080fd5b50...
""")
print("\n=== 7. Python Compile ===")
print("""
# pip install solc
import solcx
# Compile
compiled = solcx.compile_source('''
pragma solidity ^0.8.0;
contract Simple {
uint256 public value;
function set(uint256 _value) public {
value = _value;
}
}
''')
contract = compiled[':Simple']
print(f"Bytecode: {contract['bin']}")
print(f"ABI: {contract['abi']}")
""")
print("\n=== 8. Bytecode Structure ===")
print(f"{'Section':<20} {'Description':<40}")
print("-" * 60)
print(f"{'Deploy':<20} {'Init code':<40}")
print(f"{'Runtime':<20} {'Deployed code':<40}")
print(f"{'Metadata':<20} {'Compiler info':<40}")
print(f"{'Constructor':<20} {'Init logic':<40}")
print("\n=== 9. Python Analysis ===")
print("""
def bytecode_size(bytecode):
\"\"\"Bytecode size.\"\"\"
return len(bytecode)
def is_deployable(bytecode):
\"\"\"Check size limit.\"\"\"
return len(bytecode) <= 24576
# Example
# bc = bytes.fromhex('6001600201')
# print(f"Size: {bytecode_size(bc)}")
# print(f"Deployable: {is_deployable(bc)}")
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Smart contracts
- Deploy
- Analysis
- Security
""") ๐ณ Merkle Patricia Trie
๐ฏ Merkle Patricia Trie
The Merkle Patricia Trie (MPT) is Ethereum's core data structure for storing state, transactions, and receipts. It combines a Merkle tree (for verification) with a Patricia trie (for efficient key-value storage).
MPT
Merkle: Hash. Patricia: Trie. Key-value: Yes. Efficient: Yes. Root: State root. Proof: Merkle.
# Merkle Patricia Trie
print("=== 1. What is MPT? ===")
print("""
MPT:
- Merkle tree
- Patricia trie
- Key-value
- Efficient
Example:
State
โ MPT
โ Root
""")
print("\n=== 2. Node Types ===")
print("""
Nodes:
- Branch: 16 children
- Extension: shared prefix
- Leaf: value
Example:
Branch
โ 16
""")
print("\n=== 3. State Root ===")
print("""
Root:
- Hash
- Commitment
- Block header
Example:
State root
โ 0xabc...
""")
print("\n=== 4. Python MPT ===")
print("""
class MerklePatriciaTrie:
def __init__(self):
self.data = {}
def put(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key)
def root(self):
import hashlib
data = str(sorted(self.data.items()))
return hashlib.sha256(data.encode()).hexdigest()
# Example
# mpt = MerklePatriciaTrie()
# mpt.put('0x1234', 'account1')
# mpt.put('0x5678', 'account2')
# print(mpt.root())
""")
print("\n=== 5. Python Example ===")
print("""
import hashlib
class MPT:
def __init__(self):
self.data = {}
def put(self, key, value):
self.data[key] = value
def get(self, key):
return self.data.get(key)
def delete(self, key):
if key in self.data:
del self.data[key]
def root(self):
data = str(sorted(self.data.items()))
return hashlib.sha256(data.encode()).hexdigest()
def proof(self, key):
\"\"\"Generate Merkle proof.\"\"\"
if key not in self.data:
return None
return {
'key': key,
'value': self.data[key],
'root': self.root()
}
# Example
# mpt = MPT()
# mpt.put('0x1234', 'account1')
# mpt.put('0x5678', 'account2')
# print(mpt.proof('0x1234'))
""")
print("\n=== 6. Comparison ===")
print(f"{'Feature':<20} {'MPT':<15} {'Merkle':<15}")
print("-" * 50)
print(f"{'Key-value':<20} {'Yes':<15} {'No':<15}")
print(f"{'Efficient':<20} {'Yes':<15} {'No':<15}")
print(f"{'Proof':<20} {'Yes':<15} {'Yes':<15}")
print(f"{'Use':<20} {'State':<15} {'Tx':<15}")
print("\n=== 7. Trie Types ===")
print("""
Types:
- State trie: accounts
- Storage trie: contract storage
- Transaction trie: txs
- Receipt trie: receipts
Example:
State
โ State trie
""")
print("\n=== 8. Python Proof ===")
print("""
def verify_proof(key, value, root):
\"\"\"Verify Merkle proof.\"\"\"
computed = hashlib.sha256(f"{key}{value}".encode()).hexdigest()
return computed == root
# Example
# print(verify_proof('0x1234', 'account1', 'abc...'))
""")
print("\n=== 9. Use Cases ===")
print("""
Use cases:
- State
- Storage
- Transactions
- Receipts
- Light clients
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Ethereum
- State
- Proofs
- Light clients
""")๐ค Consensus (PoS)
๐ฏ Ethereum PoS
Ethereum transitioned from PoW to Proof of Stake (PoS) in September 2022 (The Merge). Validators stake 32 ETH to participate in consensus. Finality is achieved in ~12.8 minutes (2 epochs).
PoS
Validators: 32 ETH. Slots: 12 sec. Epochs: 32 slots. Finality: 2 epochs. Slashing: Penalty. Energy: 99.95% less.
# Consensus (PoS)
print("=== 1. The Merge ===")
print("""
Merge:
- 2022
- PoW โ PoS
- 99.95% less energy
Example:
Ethereum
โ PoS
""")
print("\n=== 2. Validators ===")
print("""
Validators:
- 32 ETH
- ~1M
- Active
Example:
32 ETH
โ Validator
""")
print("\n=== 3. Slots and Epochs ===")
print("""
Slots:
- 12 sec
- Block
- Proposer
Epochs:
- 32 slots
- 6.4 min
- Checkpoint
""")
print("\n=== 4. Finality ===")
print("""
Finality:
- 2 epochs
- ~12.8 min
- Reversible
Example:
Checkpoint
โ Finalized
""")
print("\n=== 5. Slashing ===")
print("""
Slashing:
- Double sign
- Surround
- Penalty
Example:
Double sign
โ Slashed
""")
print("\n=== 6. Python Validator ===")
print("""
class Validator:
def __init__(self, stake=32):
self.stake = stake
self.active = True
self.rewards = 0
self.slashed = False
def reward(self, apy=0.04):
if self.slashed:
return 0
return self.stake * apy
def slash(self, penalty=1):
self.stake -= penalty
self.slashed = True
# Example
# v = Validator()
# print(v.reward())
""")
print("\n=== 7. Python Consensus ===")
print("""
class EthereumPoS:
def __init__(self):
self.validators = []
self.slot = 0
self.epoch = 0
self.finalized = []
def add_validator(self, validator):
self.validators.append(validator)
def propose_block(self):
import random
return random.choice([v for v in self.validators if v.active])
def attest(self):
import random
return random.sample([v for v in self.validators if v.active], 128)
def finalize(self, checkpoint):
self.finalized.append(checkpoint)
# Example
# pos = EthereumPoS()
# pos.add_validator(Validator())
# print(pos.propose_block())
""")
print("\n=== 8. Comparison ===")
print(f"{'Feature':<20} {'PoW':<15} {'PoS':<15}")
print("-" * 50)
print(f"{'Energy':<20} {'High':<15} {'Low':<15}")
print(f"{'Stake':<20} {'N/A':<15} {'32 ETH':<15}")
print(f"{'Finality':<20} {'60 min':<15} {'12.8 min':<15}")
print(f"{'Attack':<20} {'51%':<15} {'33%':<15}")
print("\n=== 9. Python Example ===")
print("""
def finality_time(epochs=2):
\"\"\"Calculate finality time.\"\"\"
slot_time = 12
slots_per_epoch = 32
return epochs * slots_per_epoch * slot_time
# Example
# print(f"Finality: {finality_time()} seconds")
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Ethereum
- Staking
- Finality
- Layer 2
""")โก Layer 2
๐ฏ Layer 2 Scaling
Layer 2 solutions scale Ethereum by processing transactions off-chain while inheriting Ethereum's security. They include rollups (Optimistic and ZK), state channels, and sidechains.
Layer 2
Rollups: Optimistic, ZK. Sidechains: Polygon. Channels: Lightning. Scalability: 100x+. Security: Ethereum. Cost: Low.
# Layer 2
print("=== 1. What is Layer 2? ===")
print("""
Layer 2:
- Off-chain
- Ethereum security
- Scalability
- Low cost
Example:
Arbitrum
โ Rollup
""")
print("\n=== 2. Optimistic Rollups ===")
print("""
Optimistic:
- Assume valid
- Fraud proof
- 7-day challenge
- EVM compatible
Example:
Arbitrum
Optimism
""")
print("\n=== 3. ZK Rollups ===")
print("""
ZK:
- Validity proof
- Instant finality
- No challenge
- Complex
Example:
zkSync
StarkNet
Polygon zkEVM
""")
print("\n=== 4. Sidechains ===")
print("""
Sidechains:
- Independent
- Own consensus
- Bridge
- Fast
Example:
Polygon PoS
Gnosis
""")
print("\n=== 5. State Channels ===")
print("""
Channels:
- Off-chain
- Fast
- Cheap
- Two-party
Example:
Lightning
Raiden
""")
print("\n=== 6. Comparison ===")
print(f"{'Type':<20} {'Speed':<15} {'Security':<15} {'Example':<15}")
print("-" * 65)
print(f"{'Optimistic':<20} {'Fast':<15} {'High':<15} {'Arbitrum':<15}")
print(f"{'ZK':<20} {'Fast':<15} {'High':<15} {'zkSync':<15}")
print(f"{'Sidechain':<20} {'Very fast':<15} {'Medium':<15} {'Polygon':<15}")
print(f"{'Channels':<20} {'Very fast':<15} {'High':<15} {'Lightning':<15}")
print("\n=== 7. Python L2 ===")
print("""
class Rollup:
def __init__(self, name, type_):
self.name = name
self.type = type_
self.transactions = []
self.state_root = None
def add_transaction(self, tx):
self.transactions.append(tx)
def commit(self):
# Commit to L1
import hashlib
self.state_root = hashlib.sha256(str(self.transactions).encode()).hexdigest()
return self.state_root
# Example
# r = Rollup('Arbitrum', 'optimistic')
# r.add_transaction('tx1')
# print(r.commit())
""")
print("\n=== 8. Python Example ===")
print("""
class OptimisticRollup(Rollup):
def __init__(self, name):
super().__init__(name, 'optimistic')
self.challenge_period = 7 * 24 * 3600 # 7 days
def challenge(self, tx):
# Fraud proof
return True
class ZKRollup(Rollup):
def __init__(self, name):
super().__init__(name, 'zk')
self.proof = None
def generate_proof(self):
# ZK proof
self.proof = 'zk_proof'
# Example
# o = OptimisticRollup('Arbitrum')
# z = ZKRollup('zkSync')
""")
print("\n=== 9. Use Cases ===")
print("""
Use cases:
- DeFi
- Gaming
- NFTs
- Payments
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Scaling
- Low cost
- Fast
- DeFi
""")๐ dApps & DeFi
๐ฏ Decentralized Applications
dApps (Decentralized Applications) are applications that run on a blockchain. DeFi (Decentralized Finance) is the largest category of dApps, with $50B+ TVL.
dApps & DeFi
dApps: Smart contracts. DeFi: Finance. DEX: Uniswap. Lending: Aave. Stablecoins: USDC. TVL: $50B+.
# dApps & DeFi
print("=== 1. What are dApps? ===")
print("""
dApps:
- Decentralized
- Smart contracts
- Open source
- No downtime
Example:
Uniswap
โ dApp
""")
print("\n=== 2. DeFi ===")
print("""
DeFi:
- Decentralized Finance
- Lending
- DEX
- Yield
Examples:
Uniswap
Aave
Compound
MakerDAO
""")
print("\n=== 3. DEX ===")
print("""
DEX:
- Decentralized Exchange
- AMM
- Liquidity pools
Example:
Uniswap
โ AMM
""")
print("\n=== 4. Lending ===")
print("""
Lending:
- Borrow
- Lend
- Interest
Example:
Aave
โ Lending
""")
print("\n=== 5. Stablecoins ===")
print("""
Stablecoins:
- USD peg
- USDC
- USDT
- DAI
Example:
USDC
โ Stable
""")
print("\n=== 6. Yield Farming ===")
print("""
Yield:
- Farming
- Rewards
- APY
Example:
Compound
โ Yield
""")
print("\n=== 7. Python DEX ===")
print("""
class DEX:
def __init__(self):
self.pools = {}
def add_liquidity(self, token, amount):
self.pools[token] = self.pools.get(token, 0) + amount
def swap(self, from_token, to_token, amount):
# Simplified AMM
return amount * 0.997 # 0.3% fee
# Example
# dex = DEX()
# dex.add_liquidity('ETH', 1000)
# print(dex.swap('ETH', 'USDC', 1))
""")
print("\n=== 8. Python Example ===")
print("""
class AMM:
def __init__(self, token_a, token_b, reserve_a, reserve_b):
self.token_a = token_a
self.token_b = token_b
self.reserve_a = reserve_a
self.reserve_b = reserve_b
def get_price(self):
return self.reserve_b / self.reserve_a
def swap_a_for_b(self, amount_a):
# x * y = k
k = self.reserve_a * self.reserve_b
new_reserve_a = self.reserve_a + amount_a
new_reserve_b = k / new_reserve_a
amount_b = self.reserve_b - new_reserve_b
self.reserve_a = new_reserve_a
self.reserve_b = new_reserve_b
return amount_b
# Example
# amm = AMM('ETH', 'USDC', 100, 200000)
# print(amm.swap_a_for_b(1))
""")
print("\n=== 9. Top DeFi ===")
print(f"{'Protocol':<20} {'Category':<20} {'TVL':<15}")
print("-" * 60)
print(f"{'Uniswap':<20} {'DEX':<20} {'$5B+':<15}")
print(f"{'Aave':<20} {'Lending':<20} {'$10B+':<15}")
print(f"{'Lido':<20} {'Staking':<20} {'$20B+':<15}")
print(f"{'MakerDAO':<20} {'Stablecoin':<20} {'$8B+':<15}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- DeFi
- Trading
- Lending
- Stablecoins
- Yield
""")๐ผ๏ธ NFTs & Tokens
๐ฏ NFTs and Tokens
Tokens are digital assets on Ethereum. ERC-20 is the standard for fungible tokens, ERC-721 for NFTs, and ERC-1155 for multi-tokens.
NFTs & Tokens
ERC-20: Fungible. ERC-721: NFT. ERC-1155: Multi. USDC: ERC-20. CryptoPunks: ERC-721. OpenSea: Marketplace.
# NFTs & Tokens
print("=== 1. ERC-20 ===")
print("""
ERC-20:
- Fungible
- Standard
- USDC, USDT, DAI
Functions:
- transfer
- balanceOf
- approve
- transferFrom
""")
print("\n=== 2. ERC-721 ===")
print("""
ERC-721:
- NFT
- Unique
- CryptoPunks
Functions:
- ownerOf
- transferFrom
- tokenURI
""")
print("\n=== 3. ERC-1155 ===")
print("""
ERC-1155:
- Multi-token
- Fungible + NFT
- Gaming
Functions:
- balanceOf
- safeTransferFrom
""")
print("\n=== 4. Solidity ERC-20 ===")
print("""
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyToken {
string public name = "MyToken";
string public symbol = "MTK";
uint8 public decimals = 18;
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor(uint256 _supply) {
totalSupply = _supply;
balanceOf[msg.sender] = _supply;
}
function transfer(address to, uint256 value) public returns (bool) {
require(balanceOf[msg.sender] >= value);
balanceOf[msg.sender] -= value;
balanceOf[to] += value;
emit Transfer(msg.sender, to, value);
return true;
}
}
""")
print("\n=== 5. Solidity ERC-721 ===")
print("""
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract MyNFT {
string public name = "MyNFT";
string public symbol = "MNFT";
uint256 public totalSupply;
mapping(uint256 => address) public ownerOf;
mapping(address => uint256) public balanceOf;
mapping(uint256 => string) public tokenURI;
function mint(address to, string memory uri) public {
uint256 tokenId = totalSupply++;
ownerOf[tokenId] = to;
balanceOf[to]++;
tokenURI[tokenId] = uri;
}
}
""")
print("\n=== 6. Python ERC-20 ===")
print("""
class ERC20:
def __init__(self, name, symbol, supply):
self.name = name
self.symbol = symbol
self.total_supply = supply
self.balances = {}
self.allowances = {}
def transfer(self, from_addr, to_addr, amount):
if self.balances.get(from_addr, 0) >= amount:
self.balances[from_addr] -= amount
self.balances[to_addr] = self.balances.get(to_addr, 0) + amount
return True
return False
def approve(self, owner, spender, amount):
self.allowances[owner] = self.allowances.get(owner, {})
self.allowances[owner][spender] = amount
def transfer_from(self, spender, from_addr, to_addr, amount):
if self.allowances.get(from_addr, {}).get(spender, 0) >= amount:
self.allowances[from_addr][spender] -= amount
return self.transfer(from_addr, to_addr, amount)
return False
# Example
# token = ERC20('MyToken', 'MTK', 1000000)
# token.transfer('alice', 'bob', 100)
""")
print("\n=== 7. Python ERC-721 ===")
print("""
class ERC721:
def __init__(self, name, symbol):
self.name = name
self.symbol = symbol
self.owners = {}
self.balances = {}
self.token_uris = {}
self.total_supply = 0
def mint(self, to, uri):
token_id = self.total_supply
self.owners[token_id] = to
self.balances[to] = self.balances.get(to, 0) + 1
self.token_uris[token_id] = uri
self.total_supply += 1
return token_id
def owner_of(self, token_id):
return self.owners.get(token_id)
def transfer(self, from_addr, to_addr, token_id):
if self.owners.get(token_id) == from_addr:
self.owners[token_id] = to_addr
self.balances[from_addr] -= 1
self.balances[to_addr] = self.balances.get(to_addr, 0) + 1
return True
return False
# Example
# nft = ERC721('MyNFT', 'MNFT')
# nft.mint('alice', 'ipfs://...')
""")
print("\n=== 8. Comparison ===")
print(f"{'Standard':<15} {'Type':<20} {'Use':<20}")
print("-" * 55)
print(f"{'ERC-20':<15} {'Fungible':<20} {'Tokens':<20}")
print(f"{'ERC-721':<15} {'NFT':<20} {'Collectibles':<20}")
print(f"{'ERC-1155':<15} {'Multi':<20} {'Gaming':<20}")
print("\n=== 9. Top NFTs ===")
print(f"{'Collection':<20} {'Type':<15} {'Blockchain':<15}")
print("-" * 50)
print(f"{'CryptoPunks':<20} {'NFT':<15} {'Ethereum':<15}")
print(f"{'Bored Apes':<20} {'NFT':<15} {'Ethereum':<15}")
print(f"{'Art Blocks':<20} {'NFT':<15} {'Ethereum':<15}")
print(f"{'ENS':<20} {'NFT':<15} {'Ethereum':<15}")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- Collectibles
- Art
- Gaming
- Identity
- DeFi
""")๐ Solidity
๐ฏ Solidity Language
Solidity is a statically-typed, contract-oriented programming language for writing smart contracts on Ethereum. It compiles to EVM bytecode and is the most popular language for Ethereum development.
Solidity
Statically-typed: Yes. Contract-oriented: Yes. Compiles: Bytecode. EVM: Target. Popular: DeFi. Version: 0.8+.
# Solidity
print("=== 1. Hello World ===")
print("""
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract HelloWorld {
string public greeting = "Hello, World!";
function setGreeting(string memory _greeting) public {
greeting = _greeting;
}
function getGreeting() public view returns (string memory) {
return greeting;
}
}
""")
print("\n=== 2. Data Types ===")
print("""
Types:
- uint256
- address
- bool
- string
- bytes
- mapping
- array
- struct
Example:
uint256 public value;
address public owner;
""")
print("\n=== 3. Functions ===")
print("""
Functions:
- public
- private
- external
- internal
- view
- pure
- payable
Example:
function set(uint256 x) public {
value = x;
}
""")
print("\n=== 4. Events ===")
print("""
Events:
- Emit
- Logs
- Off-chain
Example:
event Transfer(address indexed from, address indexed to, uint256 value);
emit Transfer(msg.sender, to, value);
""")
print("\n=== 5. Modifiers ===")
print("""
Modifiers:
- Reusable
- Check
- Access control
Example:
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
""")
print("\n=== 6. Complete Contract ===")
print("""
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract SimpleStorage {
uint256 private value;
address public owner;
event ValueChanged(uint256 newValue);
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
constructor() {
owner = msg.sender;
}
function set(uint256 _value) public onlyOwner {
value = _value;
emit ValueChanged(_value);
}
function get() public view returns (uint256) {
return value;
}
}
""")
print("\n=== 7. Python Solidity ===")
print("""
# pip install solcx
import solcx
# Compile
compiled = solcx.compile_source('''
pragma solidity ^0.8.0;
contract Simple {
uint256 public value;
function set(uint256 _value) public {
value = _value;
}
}
''')
contract = compiled[':Simple']
print(f"Bytecode: {contract['bin']}")
print(f"ABI: {contract['abi']}")
""")
print("\n=== 8. Python Deploy ===")
print("""
from web3 import Web3
import solcx
# Compile
compiled = solcx.compile_source(source_code)
contract_interface = compiled[':Simple']
# Deploy
w3 = Web3(Web3.HTTPProvider('http://localhost:8545'))
Simple = w3.eth.contract(
abi=contract_interface['abi'],
bytecode=contract_interface['bin']
)
tx_hash = Simple.constructor().transact({'from': w3.eth.accounts[0]})
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
print(f"Contract: {tx_receipt.contractAddress}")
""")
print("\n=== 9. Best Practices ===")
print("""
Best practices:
- Use latest version
- Checks-effects-interactions
- Reentrancy guard
- Access control
- Gas optimization
- Testing
- Audit
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- DeFi
- NFTs
- DAOs
- Tokens
- dApps
""") ๐งฎ Gas Calculator
๐ฏ Interactive Gas Calculator
Calculate the cost of Ethereum transactions based on gas usage, base fee, and priority fee. See how EIP-1559 affects fees.
Calculator
Gas Used: Computation. Base Fee: Burned. Priority: Validator. Total: Cost. ETH Price: USD. EIP-1559: Fee market.
โ Ethereum Gas Calculator
Enter values and click "Calculate" to see the gas cost breakdown.
# Gas Calculator Code
print("""
# Ethereum Gas Calculator
Formula:
Total Fee = Gas Used ร (Base Fee + Priority Fee)
Where:
- Gas Used: Computation units
- Base Fee: Burned (removed from supply)
- Priority Fee: Tip to validator
Example:
Gas Used: 21,000
Base Fee: 10 gwei
Priority Fee: 2 gwei
Total: 21,000 ร (10 + 2) = 252,000 gwei = 0.000252 ETH
Burned: 21,000 ร 10 = 210,000 gwei = 0.00021 ETH
Tip: 21,000 ร 2 = 42,000 gwei = 0.000042 ETH
""")
print("\n=== JavaScript Implementation ===")
print("""
function calculateGas() {
const gasUsed = parseFloat(document.getElementById('gasUsed').value);
const baseFee = parseFloat(document.getElementById('baseFee').value);
const priorityFee = parseFloat(document.getElementById('priorityFee').value);
const ethPrice = parseFloat(document.getElementById('ethPrice').value);
// Calculate in gwei
const totalGwei = gasUsed * (baseFee + priorityFee);
const burnedGwei = gasUsed * baseFee;
const tipGwei = gasUsed * priorityFee;
// Convert to ETH
const totalETH = totalGwei / 1e9;
const burnedETH = burnedGwei / 1e9;
const tipETH = tipGwei / 1e9;
// Convert to USD
const totalUSD = totalETH * ethPrice;
document.getElementById('gasResult').innerHTML = `
Gas Used: ${gasUsed.toLocaleString()}
Base Fee: ${baseFee} gwei
Priority Fee: ${priorityFee} gwei
Total Fee: ${totalGwei.toLocaleString()} gwei
Total ETH: ${totalETH.toFixed(8)} ETH
Total USD: $${totalUSD.toFixed(2)}
๐ฅ Burned: ${burnedETH.toFixed(8)} ETH
๐ Validator Tip: ${tipETH.toFixed(8)} ETH
`;
}
""")
print("\n=== Common Gas Costs ===")
print("""
Operation Gas
----------------------
Transfer 21,000
ERC-20 transfer ~50,000
Uniswap swap ~150,000
NFT mint ~100,000
Contract deploy ~500,000+
""")
print("\n=== EIP-1559 ===")
print("""
EIP-1559:
- Base Fee: burned
- Priority Fee: tip
- Max Fee: limit
Formula:
Total = Gas ร (Base + Priority)
Max = Gas ร MaxFee
""")
print("\n=== Python Calculator ===")
print("""
def calculate_gas(gas_used, base_fee, priority_fee, eth_price=2500):
\"\"\"Calculate gas cost.\"\"\"
total_gwei = gas_used * (base_fee + priority_fee)
burned_gwei = gas_used * base_fee
tip_gwei = gas_used * priority_fee
total_eth = total_gwei / 1e9
burned_eth = burned_gwei / 1e9
tip_eth = tip_gwei / 1e9
return {
'total_gwei': total_gwei,
'total_eth': total_eth,
'total_usd': total_eth * eth_price,
'burned_eth': burned_eth,
'tip_eth': tip_eth
}
# Example
# result = calculate_gas(21000, 10, 2)
# print(f"Total: ${result['total_usd']:.2f}")
""")๐ Python EVM
๐ฏ Complete EVM Implementation
A complete, working Python implementation of a simplified EVM with stack, memory, storage, opcodes, and gas.
Python EVM
Stack: List. Memory: Bytearray. Storage: Dict. Opcodes: Execute. Gas: Meter. Complete: Yes.
# Complete EVM Implementation
print("=== 1. EVM Class ===")
print("""
class EVM:
def __init__(self):
self.stack = []
self.memory = bytearray()
self.storage = {}
self.gas = 1000000
self.pc = 0
self.returned = None
def push(self, value):
self.stack.append(value)
def pop(self):
return self.stack.pop()
def peek(self):
return self.stack[-1] if self.stack else 0
""")
print("\n=== 2. Opcodes ===")
print("""
OPCODES = {
0x00: 'STOP',
0x01: 'ADD',
0x02: 'MUL',
0x03: 'SUB',
0x04: 'DIV',
0x10: 'LT',
0x11: 'GT',
0x14: 'EQ',
0x15: 'ISZERO',
0x50: 'POP',
0x51: 'MLOAD',
0x52: 'MSTORE',
0x54: 'SLOAD',
0x55: 'SSTORE',
0x56: 'JUMP',
0x57: 'JUMPI',
0x5B: 'JUMPDEST',
0x60: 'PUSH1',
0x61: 'PUSH2',
0x80: 'DUP1',
0x90: 'SWAP1',
0xF1: 'CALL',
0xF3: 'RETURN',
}
""")
print("\n=== 3. Execute ===")
print("""
def execute(self, opcode):
\"\"\"Execute an opcode.\"\"\"
if opcode == 0x00: # STOP
return True
elif opcode == 0x01: # ADD
a = self.pop()
b = self.pop()
self.push((a + b) % 2**256)
self.gas -= 3
elif opcode == 0x02: # MUL
a = self.pop()
b = self.pop()
self.push((a * b) % 2**256)
self.gas -= 5
elif opcode == 0x03: # SUB
a = self.pop()
b = self.pop()
self.push((a - b) % 2**256)
self.gas -= 3
elif opcode == 0x50: # POP
self.pop()
self.gas -= 2
elif opcode == 0x51: # MLOAD
offset = self.pop()
value = int.from_bytes(self.memory[offset:offset+32], 'big')
self.push(value)
self.gas -= 3
elif opcode == 0x52: # MSTORE
offset = self.pop()
value = self.pop()
while len(self.memory) < offset + 32:
self.memory.extend(b'\\x00' * 32)
self.memory[offset:offset+32] = value.to_bytes(32, 'big')
self.gas -= 3
elif opcode == 0x54: # SLOAD
key = self.pop()
self.push(self.storage.get(key, 0))
self.gas -= 100
elif opcode == 0x55: # SSTORE
key = self.pop()
value = self.pop()
self.storage[key] = value
self.gas -= 20000
return False
""")
print("\n=== 4. Run ===")
print("""
def run(self, code):
\"\"\"Run bytecode.\"\"\"
self.pc = 0
while self.pc < len(code):
op = code[self.pc]
# PUSH1
if op == 0x60:
self.pc += 1
self.push(code[self.pc])
# PUSH2
elif op == 0x61:
self.pc += 1
value = (code[self.pc] << 8) | code[self.pc + 1]
self.push(value)
self.pc += 1
else:
if self.execute(op):
break
self.pc += 1
return self.stack
""")
print("\n=== 5. Complete Implementation ===")
print("""
class EVM:
def __init__(self):
self.stack = []
self.memory = bytearray()
self.storage = {}
self.gas = 1000000
self.pc = 0
def push(self, value):
self.stack.append(value)
def pop(self):
return self.stack.pop()
def execute(self, opcode):
if opcode == 0x00: # STOP
return True
elif opcode == 0x01: # ADD
self.push((self.pop() + self.pop()) % 2**256)
self.gas -= 3
elif opcode == 0x02: # MUL
self.push((self.pop() * self.pop()) % 2**256)
self.gas -= 5
elif opcode == 0x03: # SUB
a = self.pop()
b = self.pop()
self.push((a - b) % 2**256)
self.gas -= 3
elif opcode == 0x50: # POP
self.pop()
self.gas -= 2
elif opcode == 0x54: # SLOAD
self.push(self.storage.get(self.pop(), 0))
self.gas -= 100
elif opcode == 0x55: # SSTORE
key = self.pop()
value = self.pop()
self.storage[key] = value
self.gas -= 20000
return False
def run(self, code):
self.pc = 0
while self.pc < len(code):
op = code[self.pc]
if op == 0x60: # PUSH1
self.pc += 1
self.push(code[self.pc])
elif op == 0x61: # PUSH2
self.pc += 1
self.push((code[self.pc] << 8) | code[self.pc + 1])
self.pc += 1
else:
if self.execute(op):
break
self.pc += 1
return self.stack
# Example
evm = EVM()
# PUSH1 1, PUSH1 2, ADD
result = evm.run([0x60, 0x01, 0x60, 0x02, 0x01])
print(f"Result: {result}") # [3]
""")
print("\n=== 6. Testing ===")
print("""
import unittest
class TestEVM(unittest.TestCase):
def setUp(self):
self.evm = EVM()
def test_add(self):
result = self.evm.run([0x60, 0x01, 0x60, 0x02, 0x01])
self.assertEqual(result, [3])
def test_mul(self):
result = self.evm.run([0x60, 0x02, 0x60, 0x03, 0x02])
self.assertEqual(result, [6])
def test_sstore(self):
self.evm.run([0x60, 0x01, 0x60, 0x02, 0x55])
self.assertEqual(self.evm.storage[1], 2)
if __name__ == '__main__':
unittest.main()
""")
print("\n=== 7. Performance ===")
print("""
Performance:
- Opcode: O(1)
- Stack: O(1)
- Storage: O(1)
- Gas: O(1)
""")
print("\n=== 8. Libraries ===")
print("""
Libraries:
- py-evm
- eth-tester
- web3.py
- solcx
""")
print("\n=== 9. Use Cases ===")
print("""
Use cases:
- Learning
- Testing
- Prototyping
- Analysis
""")
print("\n=== 10. Complete Example ===")
print("""
# Full EVM simulation
evm = EVM()
# PUSH1 5, PUSH1 3, ADD
code = [0x60, 0x05, 0x60, 0x03, 0x01]
result = evm.run(code)
print(f"Result: {result}") # [8]
# PUSH1 2, PUSH1 4, MUL
code = [0x60, 0x02, 0x60, 0x04, 0x02]
result = evm.run(code)
print(f"Result: {result}") # [8]
# SSTORE
code = [0x60, 0x01, 0x60, 0x2a, 0x55]
evm.run(code)
print(f"Storage: {evm.storage}") # {1: 42}
""")๐ Web3.py
๐ฏ Web3.py
Web3.py is a Python library for interacting with Ethereum. It allows you to query the blockchain, send transactions, deploy contracts, and call functions.
Web3.py
Connect: Provider. Query: Balance, block. Send: Transaction. Contract: Deploy, call. Events: Logs. Complete: Yes.
# Web3.py
print("=== 1. Install ===")
print("""
pip install web3
""")
print("\n=== 2. Connect ===")
print("""
from web3 import Web3
# HTTP Provider
w3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/v3/YOUR_KEY'))
# Check connection
print(f"Connected: {w3.isConnected()}")
print(f"Block: {w3.eth.block_number}")
""")
print("\n=== 3. Query ===")
print("""
# Balance
balance = w3.eth.getBalance('0x742d35Cc6634C0532925a3b844Bc454e4438f44e')
print(f"Balance: {w3.fromWei(balance, 'ether')} ETH")
# Block
block = w3.eth.getBlock('latest')
print(f"Block: {block.number}")
print(f"Hash: {block.hash.hex()}")
# Transaction
tx = w3.eth.getTransaction('0x...')
print(f"From: {tx['from']}")
print(f"To: {tx['to']}")
""")
print("\n=== 4. Send Transaction ===")
print("""
from eth_account import Account
# Account
acct = Account.from_key('0x...')
# Build
tx = {
'to': '0x...',
'value': w3.toWei(0.01, 'ether'),
'gas': 21000,
'gasPrice': w3.toWei(50, 'gwei'),
'nonce': w3.eth.getTransactionCount(acct.address),
'chainId': 1
}
# Sign
signed = acct.sign_transaction(tx)
# Send
tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
print(f"TX: {tx_hash.hex()}")
""")
print("\n=== 5. Contract ===")
print("""
import json
# Load ABI
with open('abi.json') as f:
abi = json.load(f)
# Contract
address = '0x...'
contract = w3.eth.contract(address=address, abi=abi)
# Call (read)
name = contract.functions.name().call()
print(f"Name: {name}")
# Transact (write)
tx = contract.functions.transfer('0x...', 100).buildTransaction({
'from': acct.address,
'nonce': w3.eth.getTransactionCount(acct.address),
'gas': 100000,
'gasPrice': w3.toWei(50, 'gwei')
})
signed = acct.sign_transaction(tx)
tx_hash = w3.eth.sendRawTransaction(signed.rawTransaction)
""")
print("\n=== 6. Deploy Contract ===")
print("""
import solcx
# Compile
compiled = solcx.compile_source('''
pragma solidity ^0.8.0;
contract Simple {
uint256 public value;
function set(uint256 _value) public {
value = _value;
}
}
''')
contract_interface = compiled[':Simple']
# Deploy
Simple = w3.eth.contract(
abi=contract_interface['abi'],
bytecode=contract_interface['bin']
)
tx_hash = Simple.constructor().transact({'from': acct.address})
tx_receipt = w3.eth.waitForTransactionReceipt(tx_hash)
print(f"Contract: {tx_receipt.contractAddress}")
""")
print("\n=== 7. Events ===")
print("""
# Create filter
event_filter = contract.events.Transfer.createFilter(fromBlock='latest')
# Get events
events = event_filter.get_all_entries()
for event in events:
print(f"From: {event['args']['from']}")
print(f"To: {event['args']['to']}")
print(f"Value: {event['args']['value']}")
""")
print("\n=== 8. Complete Example ===")
print("""
from web3 import Web3
from eth_account import Account
import json
class EthereumClient:
def __init__(self, rpc_url, private_key=None):
self.w3 = Web3(Web3.HTTPProvider(rpc_url))
self.account = Account.from_key(private_key) if private_key else None
def get_balance(self, address):
balance = self.w3.eth.getBalance(address)
return self.w3.fromWei(balance, 'ether')
def send_eth(self, to, amount):
tx = {
'to': to,
'value': self.w3.toWei(amount, 'ether'),
'gas': 21000,
'gasPrice': self.w3.eth.gas_price,
'nonce': self.w3.eth.getTransactionCount(self.account.address),
'chainId': 1
}
signed = self.account.sign_transaction(tx)
return self.w3.eth.sendRawTransaction(signed.rawTransaction)
def load_contract(self, address, abi):
return self.w3.eth.contract(address=address, abi=abi)
# Example
# client = EthereumClient('https://mainnet.infura.io/v3/YOUR_KEY')
# print(client.get_balance('0x...'))
""")
print("\n=== 9. Best Practices ===")
print("""
Best practices:
- Use Infura/Alchemy
- Handle errors
- Gas estimation
- Nonce management
- Private key security
""")
print("\n=== 10. Use Cases ===")
print("""
Use cases:
- dApps
- Wallets
- Bots
- Analytics
- DeFi
""") โ๏ธ Comparison
๐ฏ Ethereum vs Others
Compare Ethereum with other blockchains: Bitcoin, Solana, Cardano, Polkadot, and Avalanche.
Comparison
Ethereum: Programmable. Bitcoin: Store of value. Solana: Speed. Cardano: Research. Polkadot: Interop. Avalanche: Subnets.
| Blockchain | Consensus | TPS | Smart Contracts | Best For |
|---|---|---|---|---|
| Ethereum | PoS | 15-30 | Yes (EVM) | dApps, DeFi |
| Bitcoin | PoW | 7 | Limited | Store of value |
| Solana | PoH + PoS | 65,000 | Yes | High speed |
| Cardano | PoS | 250 | Yes | Research |
| Polkadot | NPoS | 1,000 | Yes | Interoperability |
| Avalanche | Snowball | 4,500 | Yes (EVM) | Subnets |
| Polygon | PoS | 7,000 | Yes (EVM) | Layer 2 |
| BSC | PoSA | 160 | Yes (EVM) | Low fees |
# Decision Guide
print("=== Choose Blockchain by Use Case ===")
print("""
Programmable:
โ Ethereum
โ Solana
โ Avalanche
Store of value:
โ Bitcoin
High speed:
โ Solana
โ Avalanche
Interoperability:
โ Polkadot
โ Cosmos
Research:
โ Cardano
Low fees:
โ Polygon
โ BSC
โ Solana
Layer 2:
โ Arbitrum
โ Optimism
โ zkSync
""")
print("\n=== Speed Comparison ===")
print(f"{'Blockchain':<20} {'TPS':<15} {'Block Time':<15} {'Finality':<15}")
print("-" * 65)
print(f"{'Ethereum':<20} {'15-30':<15} {'12 sec':<15} {'12.8 min':<15}")
print(f"{'Bitcoin':<20} {'7':<15} {'10 min':<15} {'60 min':<15}")
print(f"{'Solana':<20} {'65,000':<15} {'400 ms':<15} {'1 sec':<15}")
print(f"{'Avalanche':<20} {'4,500':<15} {'1-2 sec':<15} {'1-2 sec':<15}")
print(f"{'Polygon':<20} {'7,000':<15} {'2 sec':<15} {'30 min':<15}")
print(f"{'BSC':<20} {'160':<15} {'3 sec':<15} {'15 sec':<15}")
print("\n=== When to Use Which ===")
print("""
USE Ethereum:
โ dApps
โ DeFi
โ NFTs
โ Web3
USE Bitcoin:
โ Store of value
โ Digital gold
USE Solana:
โ High speed
โ Low fees
USE Avalanche:
โ Subnets
โ Fast finality
USE Polygon:
โ Layer 2
โ Low fees
USE Polkadot:
โ Interoperability
""")โ FAQ
๐ฏ Frequently Asked Questions
Answers to common questions about Ethereum and the EVM.
What is Ethereum?
Ethereum is a decentralized, open-source blockchain with smart contract functionality. It is the second-largest cryptocurrency by market capitalization and the most programmable blockchain, enabling dApps, DeFi, NFTs, DAOs, and Web3.
What is the EVM?
The EVM (Ethereum Virtual Machine) is the runtime environment for executing smart contracts on Ethereum. It is a stack-based, Turing-complete virtual machine with ~140 opcodes, deterministic execution, and gas metering.
What is gas in Ethereum?
Gas is the unit of computation in Ethereum. Every operation in the EVM costs gas. Users pay gas fees (base fee + priority fee) to execute transactions. Gas prevents spam, allocates resources, and incentivizes validators. Simple transfers cost 21,000 gas.
What is Solidity?
Solidity is a statically-typed, contract-oriented programming language for writing smart contracts on Ethereum. It compiles to EVM bytecode. Solidity is the most popular language for Ethereum development, used by DeFi protocols, NFTs, and DAOs.
What is the difference between storage, memory, and calldata?
Storage is persistent on-chain state (expensive, 20,000 gas per slot). Memory is temporary, per-transaction data (cheap, 3 gas per word). Calldata is read-only input data from transactions (cheapest, 4/16 gas). Understanding these data locations is crucial for gas optimization.
What is the Merkle Patricia Trie?
The Merkle Patricia Trie (MPT) is Ethereum's core data structure for storing state, transactions, and receipts. It combines a Merkle tree (for verification) with a Patricia trie (for efficient key-value storage).
What is the difference between EOA and Contract accounts?
EOA (Externally Owned Account) is controlled by a private key and can initiate transactions. Contract Account is controlled by code and cannot initiate transactions. Both have a balance, nonce, storage, and code.
What is EIP-1559?
EIP-1559 is a fee market upgrade introduced in 2021. It introduced a base fee (burned) and a priority fee (tip to validators). This made gas fees more predictable and introduced ETH burning.
What is The Merge?
The Merge was Ethereum's transition from Proof of Work (PoW) to Proof of Stake (PoS) in September 2022. It reduced energy consumption by 99.95% and introduced validators (32 ETH stake).
What are Layer 2 solutions?
Layer 2 solutions scale Ethereum by processing transactions off-chain while inheriting Ethereum's security. They include rollups (Optimistic and ZK), sidechains, and state channels. Examples: Arbitrum, Optimism, zkSync, Polygon.
What is the difference between ERC-20, ERC-721, and ERC-1155?
ERC-20 is the standard for fungible tokens (USDC, USDT). ERC-721 is the standard for NFTs (CryptoPunks). ERC-1155 is a multi-token standard that supports both fungible and non-fungible tokens in one contract.
What is Web3.py?
Web3.py is a Python library for interacting with Ethereum. It allows you to query the blockchain, send transactions, deploy contracts, and call functions. It is the standard Python library for Ethereum development.
# Quick Reference
print("=== Quick Answers ===")
print("""
Q: What is Ethereum?
A: Programmable blockchain.
Q: What is EVM?
A: Ethereum Virtual Machine.
Q: What is gas?
A: Computation unit.
Q: What is Solidity?
A: Smart contract language.
Q: Storage vs memory?
A: Storage = persistent; memory = temporary.
Q: What is MPT?
A: Merkle Patricia Trie.
Q: EOA vs Contract?
A: EOA = private key; Contract = code.
Q: EIP-1559?
A: Base fee + priority fee.
Q: The Merge?
A: PoW โ PoS.
Q: Layer 2?
A: Off-chain scaling.
Q: ERC-20?
A: Fungible token.
Q: ERC-721?
A: NFT.
Q: Web3.py?
A: Python Ethereum library.
Q: Free?
A: Yes โ open source.
""")๐ Future
๐ฏ Where Ethereum Is Going
The future of Ethereum is Layer 2, sharding, account abstraction, zero-knowledge, AI, and global adoption.
Future Directions
Layer 2: Scaling. Sharding: Danksharding. Account: Abstraction. ZK: Privacy. AI: Integration. Global: Adoption.
# Future of Ethereum
print("=== 1. Layer 2 ===")
print("""
Trend: Layer 2
Current:
- 15-30 TPS
- L1
Future:
- 100,000+ TPS
- L2
- Rollups
Examples:
- Arbitrum
- Optimism
- zkSync
- StarkNet
Future:
- Scalable
- Cheap
- Fast
""")
print("\n=== 2. Sharding ===")
print("""
Trend: Sharding
Current:
- Single chain
Future:
- Danksharding
- Proto-danksharding
- Blobs
Examples:
- EIP-4844
- Dencun
Future:
- Scalable
- Data availability
- Cheap L2
""")
print("\n=== 3. Account Abstraction ===")
print("""
Trend: Account Abstraction
Current:
- EOA + Contract
Future:
- Smart accounts
- Social recovery
- Gasless
Examples:
- ERC-4337
- Safe
- Argent
Future:
- User-friendly
- Secure
- Flexible
""")
print("\n=== 4. Zero-Knowledge ===")
print("""
Trend: ZK
Current:
- ZK rollups
Future:
- ZK EVM
- Privacy
- Scalability
Examples:
- zkSync
- StarkNet
- Scroll
- Polygon zkEVM
Future:
- Private
- Scalable
- Efficient
""")
print("\n=== 5. AI ===")
print("""
Trend: AI
Ideas:
- AI agents
- AI contracts
- Prediction
Examples:
- Deep learning
- Neural networks
- AI
Future:
- AI-optimized
- Smart
- Efficient
""")
print("\n=== 6. Global Adoption ===")
print("""
Trend: Global
Current:
- Growing
Future:
- Mainstream
- Institutional
- Global
Examples:
- ETFs
- Banks
- Enterprises
Future:
- Mainstream
- Global
- Standard
""")
# TIMELINE
print("\n=== Timeline ===")
print("""
Past:
2013: Whitepaper
2015: Frontier
2016: DAO
2017: ICO
2020: DeFi
2021: NFTs, EIP-1559
2022: The Merge
2023: Shapella
2024: Dencun
Present:
2025: Layer 2
2026: Account abstraction
Future:
2030: Sharding
2035: ZK
2040: Global
""")
print("\n=== Final Thoughts ===")
print("""
Ethereum is:
- Programmable
- Decentralized
- Evolving
- The world computer
The future is:
- Layer 2
- Sharding
- Account abstraction
- Zero-knowledge
- AI
- Global adoption
"The world computer."
Keep exploring. Keep building.
""")