Example Contracts
Overview
Section titled “Overview”The contracts/ directory contains production-ready reference implementations covering DeFi primitives, oracles, cross-chain messaging, and utilities. All contracts are written in Zig using the Ashen SDK.
Tokens
Section titled “Tokens”SFT Token (sft_v1) — Rust
Section titled “SFT Token (sft_v1) — Rust”A feature-rich fungible token with modular capabilities:
- Core: mint, burn, transfer
- Roles: owner, minter, blacklister, fee manager
- Allowances: approve/transferFrom pattern
- Blacklist: address blocking
- Fees: configurable transfer fees
- Recovery: owner can recover stuck tokens
Optional features (compile-time): pause, whitelist, limits, locking, snapshots, governance, multisig, flash loans, compliance hooks.
# Build with default featuresjust contract-build --manifest-path contracts/sft_v1/Cargo.toml
# Build with all featurescargo build --manifest-path contracts/sft_v1/Cargo.toml --features fullKey functions: mint, burn, transfer, approve, transfer_from, set_fee
DeFi Primitives
Section titled “DeFi Primitives”AMM Pool (amm_pool_v1)
Section titled “AMM Pool (amm_pool_v1)”A constant-product automated market maker (x × y = k) with:
- 0.3% default fee (configurable by owner)
- K-invariant verification using u256 arithmetic
- Slippage protection and minimum output checks
# Buildcd contracts/amm_pool_v1 && zig build -Doptimize=ReleaseSmallKey functions: swap_x_for_y, swap_y_for_x, add_liquidity, remove_liquidity
Concentrated Liquidity (concentrated_liquidity_v1)
Section titled “Concentrated Liquidity (concentrated_liquidity_v1)”Bin-based fixed-price liquidity pool (similar to Trader Joe v2):
- Discrete price bins with configurable bin step
- Capital-efficient concentrated positions
- Active bin tracking for swaps
Key functions: add_liquidity, remove_liquidity, swap, get_active_bin
Stable Swap (stable_swap_v1)
Section titled “Stable Swap (stable_swap_v1)”StableSwap invariant AMM optimized for pegged assets:
- Low slippage for like-kind swaps
- Configurable amplification coefficient
- Multi-asset support
Key functions: exchange, add_liquidity, remove_liquidity, get_dy
Order Book (order_book_v1)
Section titled “Order Book (order_book_v1)”Central limit order book (CLOB) with price-time priority:
- Sorted storage keys for efficient bid/ask iteration
- Partial fills and order cancellation
- Market and limit order types
Key functions: place_order, cancel_order, match_orders, get_best_bid, get_best_ask
DEX Router (dex_router_v1)
Section titled “DEX Router (dex_router_v1)”Multi-hop swap router demonstrating cross-contract calls:
- Chained swaps across multiple pools
- Access list hints for state key warming
- Slippage protection across the full path
Key functions: swap_exact_in, swap_exact_out, get_amounts_out
Lending Market (lending_market_v1)
Section titled “Lending Market (lending_market_v1)”Single-asset money market with:
- Supply/withdraw with share-based accounting
- Borrow/repay with interest accrual
- Liquidation with configurable thresholds
Key functions: supply, withdraw, borrow, repay, liquidate
Vault (vault_v1 / vault_strategy_v1)
Section titled “Vault (vault_v1 / vault_strategy_v1)”ERC-4626 style tokenized vault:
- Deposit/withdraw with share accounting
- Pluggable yield strategies
- Performance fee collection
Key functions: deposit, withdraw, harvest, report
Staking (stake_pool_v1 / reward_gauge_v1)
Section titled “Staking (stake_pool_v1 / reward_gauge_v1)”Staking and rewards distribution:
- Time-weighted reward accumulation
- Multiple reward tokens
- Gauge voting for emissions
Key functions: stake, unstake, claim_rewards, vote
Governance (timelock_governor_v1)
Section titled “Governance (timelock_governor_v1)”On-chain governance with timelock:
- Proposal creation and voting
- Configurable voting period and quorum
- Timelock delay for execution
Key functions: propose, vote, queue, execute
Oracles
Section titled “Oracles”Price Oracle (price_oracle_v1)
Section titled “Price Oracle (price_oracle_v1)”Push/pull price oracle with TWAP:
- Signed price updates from authorized publishers
- Circular buffer for time-weighted averaging
- Staleness checks
Key functions: update_price, get_price, get_twap
Pyth Oracle (pyth_oracle_v1)
Section titled “Pyth Oracle (pyth_oracle_v1)”Pyth-style ed25519 price attestation verification:
- Publisher set management with threshold
- Direct signature verification (not via Wormhole)
- Price confidence intervals
Key functions: verify_attestation, update_publisher_set, get_price
RedStone Oracle (redstone_oracle_v1)
Section titled “RedStone Oracle (redstone_oracle_v1)”RedStone data package verification:
- ECDSA signature verification
- Multi-signer threshold support
- Timestamp validation
Key functions: verify_data_package, get_price
Chainlink OCR2 (chainlink_ocr2_v1)
Section titled “Chainlink OCR2 (chainlink_ocr2_v1)”Chainlink Off-Chain Reporting v2 verification:
- Multi-signature report verification
- Configurable signer set
- Report decoding
Key functions: verify_report, set_config, latest_answer
Cross-Chain
Section titled “Cross-Chain”Wormhole Core (wormhole_core_v1)
Section titled “Wormhole Core (wormhole_core_v1)”Wormhole VAA (Verified Action Approval) verification:
- Guardian signature verification
- Message parsing and validation
- Replay protection
Key functions: verify_vaa, parse_vaa, update_guardian_set
Axelar GMP (axelar_gmp_v1)
Section titled “Axelar GMP (axelar_gmp_v1)”Axelar General Message Passing:
- Cross-chain message execution
- Operator set management
- Batch processing
Key functions: execute, initialize, update_operators
Hyperlane ISM (hyperlane_ism_v1)
Section titled “Hyperlane ISM (hyperlane_ism_v1)”Hyperlane Interchain Security Module:
- Validator-based message verification
- Configurable threshold per origin
- Message routing
Key functions: verify_message, update_validator_set
Infrastructure
Section titled “Infrastructure”Light Client (light_client_v1)
Section titled “Light Client (light_client_v1)”On-chain light client for finality verification:
- MMR (Merkle Mountain Range) proof verification
- BLS signature aggregation
- Header chain validation
Key functions: verify_finality_proof, update_header, get_root
Fee Sponsor (fee_sponsor_v1)
Section titled “Fee Sponsor (fee_sponsor_v1)”Third-party gas sponsorship:
- Sponsor agreements with spending limits
- Per-user and per-contract policies
- Expiration and revocation
Key functions: create_agreement, sponsor_tx, revoke, withdraw
Source Registry (source_registry_v1)
Section titled “Source Registry (source_registry_v1)”Contract source code registry:
- On-chain source verification
- Version management
- Metadata storage
Key functions: register, verify, get_source
Testing & Development
Section titled “Testing & Development”Mock Pool (mock_pool_v1)
Section titled “Mock Pool (mock_pool_v1)”Deterministic AMM for testing:
- Configurable reserves and fees
- Predictable swap outputs
- DEX router integration testing
Gas Burner (gas_burner_v1)
Section titled “Gas Burner (gas_burner_v1)”Gas throughput stress testing:
- Pure compute workload (ALU-heavy)
- Storage-write workload
- Mixed DeFi-like operations
- Parallel execution testing
# Run stress testjust gas-stress --scenario mixed --duration 60Zig Fixture (zig_fixture)
Section titled “Zig Fixture (zig_fixture)”Minimal contract template for testing the SDK and toolchain.
Building Contracts
Section titled “Building Contracts”All Zig contracts follow the same build pattern:
# Build a single contractcd contracts/<name> && zig build -Doptimize=ReleaseSmall
# Build all contractsjust contract-build-allContract Structure
Section titled “Contract Structure”Each contract directory contains:
contracts/<name>/├── build.zig # Build configuration├── linker.ld # Linker script for RISC-V├── src/│ └── main.zig # Contract implementation└── zig-out/ # Build output (gitignored)Reference Implementation
Section titled “Reference Implementation”For a complete, well-documented example, see amm_pool_v1 which demonstrates:
- Full SDK usage (storage, events, math, guards)
- Proper error handling
- Gas-efficient patterns
- Comprehensive testing