Vyper Programming Language
Overview
Vyper is a Python-like language for Ethereum smart contracts that prioritizes security and simplicity. It restricts certain Solidity features to eliminate common vulnerability patterns.
âšī¸
Vyper follows a "less is more" philosophy. Features like inheritance, function overloading, and infinite loops are deliberately omitted to enhance security.
Language Comparison
Vyper Syntax Basics
# SPDX-License-Identifier: MIT
# @version ^0.3.9
# State variables
owner: public(address)
total_supply: public(uint256)
balances: public(HashMap[address, uint256])
# Events
event Transfer:
sender: indexed(address)
receiver: indexed(address)
amount: uint256
# Constants
MAX_SUPPLY: constant(uint256) = 1000000
# Constructor
@external
def __init__():
self.owner = msg.sender
# External function
@external
@view
def balance_of(account: address) -> uint256:
return self.balances[account]
# State-modifying function
@external
def transfer(to: address, amount: uint256) -> bool:
assert to != empty(address), "Invalid address"
assert self.balances[msg.sender] >= amount, "Insufficient balance"
self.balances[msg.sender] -= amount
self.balances[to] += amount
log Transfer(msg.sender, to, amount)
return True
# Internal function
@internal
def _mint(to: address, amount: uint256):
assert to != empty(address), "Invalid address"
assert self.total_supply + amount <= MAX_SUPPLY, "Exceeds max supply"
self.total_supply += amount
self.balances[to] += amount
Decorators
Vyper uses decorators for function attributes:
# @version ^0.3.9
owner: public(address)
# @external - Can be called externally
# @view - Read-only, no state modification
# @pure - No state access at all
# @nonreentrant("lock") - Prevents reentrancy
# @payable - Can receive ETH
@external
@view
def get_owner() -> address:
return self.owner
@external
@nonreentrant("lock")
def withdraw(amount: uint256):
assert msg.sender == self.owner, "Not owner"
assert self.balance >= amount, "Insufficient balance"
send(msg.sender, amount)
@external
@payable
def deposit():
pass # Accept ETH
@external
@pure
def add(a: uint256, b: uint256) -> uint256:
return a + b
Decorator Reference
| Decorator | Purpose | Gas Impact |
|---|---|---|
| @external | External call only | None |
| @view | Read-only | None |
| @pure | No state access | None |
| @nonreentrant | Reentrancy guard | ~2,600 gas |
| @payable | Accept ETH | None |
| @initializable | Upgradeable init | None |
Security Features
Built-in Security Mechanisms
# @version ^0.3.9
# Automatic overflow/underflow protection
@external
def unsafe_add(a: uint256, b: uint256) -> uint256:
# Vyper automatically checks for overflow
return a + b # Reverts on overflow
# Reentrancy protection
@external
@nonreentrant("lock")
def withdraw():
# Cannot be called reentrantly
send(msg.sender, self.balance)
# No access to private variables from other contracts
owner: private(address) # Only accessible within this contract
# Type safety
@external
def process(value: uint256): # Must be uint256
pass
# Explicit visibility
@external # External only
@internal # Internal only
@private # Private to this contract
Security Comparison with Solidity
| Feature | Vyper | Solidity |
|---|---|---|
| Overflow Protection | Built-in | 0.8.x built-in, older needs SafeMath |
| Reentrancy Guard | @nonreentrant decorator | Manual implementation |
| Integer Overflow | Automatic revert | Manual checks required |
| Access Control | Explicit decorators | Requires modifier implementation |
| Infinite Loops | Not allowed | Allowed (gas limited) |
| Function Overloading | Not allowed | Allowed |
Gas Efficiency
Vyper Gas Optimization
# @version ^0.3.9
# Storage packing is automatic
# Vyper packs variables into storage slots efficiently
# These are automatically packed into fewer slots:
a: public(uint128)
b: public(uint128) # Same slot as a
c: public(uint64)
d: public(uint64) # Same slot as c
e: public(uint64) # Same slot as c and d
# External vs public functions
@external
def external_func(): # Saves ~21 gas per call
pass
@public
def public_func(): # Costs more
pass
# Use calldata for read-only parameters
@external
def process(data: Bytes[1024]): # calldata (cheaper)
pass
Gas Comparison: Vyper vs Solidity
| Operation | Vyper | Solidity | Difference |
|---|---|---|---|
| Storage Write | ~5,000 | ~5,000 | Same |
| Function Call | ~2,100 | ~2,100 | Same |
| Loops | N/A | Variable | N/A |
| Complex Logic | Higher | Lower | Vyper slower |
| Simple Logic | Similar | Similar | Same |
Real-World Examples
Simple Token in Vyper
# @version ^0.3.9
name: public(String[32])
symbol: public(String[8])
decimals: public(uint8)
total_supply: public(uint256)
balances: public(HashMap[address, uint256])
allowances: public(HashMap[address, HashMap[address, uint256]])
event Transfer:
sender: indexed(address)
receiver: indexed(address)
amount: uint256
event Approval:
owner: indexed(address)
spender: indexed(address)
amount: uint256
@external
def __init__(name: String[32], symbol: String[8], decimals: uint8, initial_supply: uint256):
self.name = name
self.symbol = symbol
self.decimals = decimals
self.total_supply = initial_supply * 10 ** convert(decimals, uint256)
self.balances[msg.sender] = self.total_supply
@external
@view
def balance_of(account: address) -> uint256:
return self.balances[account]
@external
def transfer(to: address, amount: uint256) -> bool:
assert to != empty(address), "Transfer to zero address"
assert self.balances[msg.sender] >= amount, "Insufficient balance"
self.balances[msg.sender] -= amount
self.balances[to] += amount
log Transfer(msg.sender, to, amount)
return True
@external
def approve(spender: address, amount: uint256) -> bool:
assert spender != empty(address), "Approve to zero address"
self.allowances[msg.sender][spender] = amount
log Approval(msg.sender, spender, amount)
return True
@external
def transfer_from(sender: address, receiver: address, amount: uint256) -> bool:
assert receiver != empty(address), "Transfer to zero address"
assert self.balances[sender] >= amount, "Insufficient balance"
assert self.allowances[sender][msg.sender] >= amount, "Insufficient allowance"
self.allowances[sender][msg.sender] -= amount
self.balances[sender] -= amount
self.balances[receiver] += amount
log Transfer(sender, receiver, amount)
return True
DEX Contract in Vyper
# @version ^0.3.9
struct Pool:
token0: address
token1: address
reserve0: uint256
reserve1: uint256
total_supply: uint256
fee: uint256
pools: public(HashMap[uint256, Pool])
pool_count: public(uint256)
event PoolCreated:
pool_id: indexed(uint256)
token0: indexed(address)
token1: indexed(address)
event Swap:
pool_id: indexed(uint256)
sender: indexed(address)
amount_in: uint256
amount_out: uint256
@external
def create_pool(token0: address, token1: address, fee: uint256) -> uint256:
assert token0 != empty(address), "Invalid token0"
assert token1 != empty(address), "Invalid token1"
assert token0 != token1, "Identical tokens"
assert fee > 0 and fee <= 10000, "Invalid fee"
pool_id = self.pool_count
self.pools[pool_id] = Pool({
token0: token0,
token1: token1,
reserve0: 0,
reserve1: 0,
total_supply: 0,
fee: fee
})
self.pool_count += 1
log PoolCreated(pool_id, token0, token1)
return pool_id
@external
@nonreentrant("lock")
def swap(pool_id: uint256, amount_in: uint256, min_amount_out: uint256) -> uint256:
pool: Pool = self.pools[pool_id]
assert pool.total_supply > 0, "Pool doesn't exist"
# Constant product formula: x * y = k
reserve_in: uint256 = pool.reserve0
reserve_out: uint256 = pool.reserve1
# Apply fee
amount_in_with_fee: uint256 = amount_in * (10000 - pool.fee)
amount_out: uint256 = (amount_in_with_fee * reserve_out) / (reserve_in * 10000 + amount_in_with_fee)
assert amount_out >= min_amount_out, "Slippage exceeded"
# Update reserves
self.pools[pool_id].reserve0 = reserve_in + amount_in
self.pools[pool_id].reserve1 = reserve_out - amount_out
log Swap(pool_id, msg.sender, amount_in, amount_out)
return amount_out
Use Cases
When to Use Vyper
| Use Case | Why Vyper | Example |
|---|---|---|
| Security-critical contracts | Built-in security | Token contracts |
| Simple logic | Simplicity advantage | Payment splitting |
| Formal verification | Better support | Financial instruments |
| Education | Easier to learn | Teaching smart contracts |
When to Use Solidity
| Use Case | Why Solidity | Example |
|---|---|---|
| Complex systems | More features | DeFi protocols |
| Upgradability | Proxy patterns | DAOs |
| Large ecosystem | More tools/libraries | NFT marketplaces |
| Performance | Assembly access | High-frequency trading |
Limitations
# @version ^0.3.9
# LIMITATION 1: No inheritance
# Cannot do: contract Child(Parent)
# Must copy-paste or use imports
# LIMITATION 2: No function overloading
# Cannot have multiple functions with same name
# Must use different names: transfer, transfer_to, etc.
# LIMITATION 3: No infinite loops
# while True: # NOT ALLOWED
# pass
# LIMITATION 4: No custom errors with data
# assert condition, "Error message" only
# LIMITATION 5: Limited string operations
# No string concatenation, limited methods
# LIMITATION 6: No inline assembly
# Cannot optimize with low-level EVM code
# LIMITATION 7: No complex data structures
# Limited to basic types and mappings
# LIMITATION 8: No multiple return values from external functions
# Must use struct or multiple functions
Comparison Table
| Feature | Vyper | Solidity | Recommendation |
|---|---|---|---|
| Learning Curve | Easy | Moderate | Vyper for beginners |
| Security | Built-in | Manual | Vyper for critical apps |
| Ecosystem | Growing | Mature | Solidity for production |
| Tooling | Basic | Extensive | Solidity for complex projects |
| Formal Verification | Better | Limited | Vyper for verification |
| Performance | Good | Better | Solidity for optimization |
| Documentation | Good | Extensive | Solidity for resources |
| Community | Smaller | Large | Solidity for support |
Trade-offs
| Decision | Option A | Option B | Recommendation |
|---|---|---|---|
| Language | Vyper (secure) | Solidity (flexible) | Vyper for security-critical |
| Features | Limited (Vyper) | Full (Solidity) | Match to project needs |
| Ecosystem | Growing (Vyper) | Mature (Solidity) | Consider support needs |
| Gas | Similar | Similar | Choose based on other factors |
Interview Questions
-
What are the key security features built into Vyper that are not present in Solidity?
Vyper includes: automatic overflow/underflow protection, @nonreentrant decorator for reentrancy prevention, no inheritance (eliminating related vulnerabilities), no function overloading, and limited loop constructs. These features reduce the attack surface by design.
-
Explain why Vyper chose to eliminate inheritance. What are the trade-offs?
Vyper eliminates inheritance to prevent issues like the "diamond problem," fragile base class problem, and unexpected behavior from deep inheritance chains. The trade-off is code duplication and less reuse, but this is considered acceptable for enhanced security.
-
When would you choose Vyper over Solidity for a production project?
Choose Vyper for: security-critical contracts (token standards, financial instruments), contracts requiring formal verification, simple logic contracts, and projects prioritizing security over flexibility. Choose Solidity for: complex DeFi protocols, upgradable contracts, and projects needing extensive ecosystem support.
Quiz Questions
-
What decorator prevents reentrancy attacks in Vyper?
- A) @external
- B) @view
- C) @nonreentrant
- D) @payable
Answer: C - The @nonreentrant decorator implements a mutex lock to prevent reentrant calls.
-
Which of the following is NOT allowed in Vyper?
- A) While loops
- B) For loops
- C) Functions
- D) Events
Answer: A - Vyper does not allow while loops (infinite loops) to prevent gas limit issues.
-
What is the primary advantage of Vyper's approach to data types?
- A) More flexible
- B) Better performance
- C) Stronger type safety
- D) Smaller bytecode
Answer: C - Vyper's strict type system prevents type-related vulnerabilities by design.