Skip to content

Example Contracts

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.

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.

Terminal window
# Build with default features
just contract-build --manifest-path contracts/sft_v1/Cargo.toml
# Build with all features
cargo build --manifest-path contracts/sft_v1/Cargo.toml --features full

Key functions: mint, burn, transfer, approve, transfer_from, set_fee


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
Terminal window
# Build
cd contracts/amm_pool_v1 && zig build -Doptimize=ReleaseSmall

Key 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


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


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


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


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


ERC-4626 style tokenized vault:

  • Deposit/withdraw with share accounting
  • Pluggable yield strategies
  • Performance fee collection

Key functions: deposit, withdraw, harvest, report


Staking and rewards distribution:

  • Time-weighted reward accumulation
  • Multiple reward tokens
  • Gauge voting for emissions

Key functions: stake, unstake, claim_rewards, vote


On-chain governance with timelock:

  • Proposal creation and voting
  • Configurable voting period and quorum
  • Timelock delay for execution

Key functions: propose, vote, queue, execute

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-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 data package verification:

  • ECDSA signature verification
  • Multi-signer threshold support
  • Timestamp validation

Key functions: verify_data_package, get_price


Chainlink Off-Chain Reporting v2 verification:

  • Multi-signature report verification
  • Configurable signer set
  • Report decoding

Key functions: verify_report, set_config, latest_answer

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 General Message Passing:

  • Cross-chain message execution
  • Operator set management
  • Batch processing

Key functions: execute, initialize, update_operators


Hyperlane Interchain Security Module:

  • Validator-based message verification
  • Configurable threshold per origin
  • Message routing

Key functions: verify_message, update_validator_set

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


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


Contract source code registry:

  • On-chain source verification
  • Version management
  • Metadata storage

Key functions: register, verify, get_source

Deterministic AMM for testing:

  • Configurable reserves and fees
  • Predictable swap outputs
  • DEX router integration testing

Gas throughput stress testing:

  • Pure compute workload (ALU-heavy)
  • Storage-write workload
  • Mixed DeFi-like operations
  • Parallel execution testing
Terminal window
# Run stress test
just gas-stress --scenario mixed --duration 60

Minimal contract template for testing the SDK and toolchain.

All Zig contracts follow the same build pattern:

Terminal window
# Build a single contract
cd contracts/<name> && zig build -Doptimize=ReleaseSmall
# Build all contracts
just contract-build-all

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)

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