Testing Contracts
Test your Alkanes smart contracts before deployment
Testing Alkanes contracts involves both unit tests in Rust and integration tests using the CLI simulator. This guide covers testing strategies, test utilities, and best practices.
Testing Approaches
There are three main approaches to testing Alkanes contracts:
CLI Simulation
Use alkanes-cli simulate to test contract calls without deploying. Fast feedback loop for testing opcodes and state changes.
Regtest Integration
Deploy to a local regtest environment and test actual on-chain behavior. Required for testing transaction flows and token transfers.
Unit Tests
Test individual functions in isolation using Rust's #[test] framework. Good for testing pure logic and edge cases.
Using the CLI Simulator
The alkanes-cli simulate command lets you test contract calls without creating transactions:
# Simulate syntax: alkanes-cli simulate <alkane_id>:<opcode> [--args "..."]
# alkane_id format: block:tx (e.g., 2:100 for deployed contract)
# Basic simulation - call opcode 99 on contract 2:100
alkanes-cli -p regtest simulate 2:100:99
# Simulation with arguments
alkanes-cli -p regtest simulate 2:100:103 --args "bcrt1q..."
# Simulation with detailed trace
alkanes-cli -p regtest simulate 2:100:99 --trace
# Simulation returning raw bytes
alkanes-cli -p regtest simulate 2:100:99 --rawSimulation Examples
Query a token name (opcode 99):
alkanes-cli -p regtest simulate 2:100:99Query token balance for an address:
alkanes-cli -p regtest simulate 2:100:103 --args "bcrt1q..."Simulate with trace for debugging:
alkanes-cli -p regtest simulate 2:100:99 --traceTest genesis alkane (subfrost public key):
alkanes-cli -p regtest simulate 32:0:103Regtest Integration Testing
For full integration tests, deploy contracts to regtest and execute real transactions:
#!/bin/bash
set -e
WALLET="--wallet-file ~/.alkanes/wallet.json --passphrase test"
NETWORK="-p regtest"
# 1. Deploy the token contract
echo "Deploying token contract..."
alkanes-cli $NETWORK $WALLET alkanes deploy \
--wasm ./target/wasm32-unknown-unknown/release/my_token.wasm \
--cellpack "[3,0]:100:0" \
--auto-confirm
# Mine a block to confirm
alkanes-cli $NETWORK $WALLET bitcoind generatetoaddress 1 "p2tr:0"
# 2. Simulate to verify deployment
echo "Verifying deployment..."
NAME=$(alkanes-cli $NETWORK simulate 4:1:99)
echo "Token name: $NAME"
# 3. Test mint operation
echo "Testing mint..."
alkanes-cli $NETWORK $WALLET alkanes execute \
--to "[4,1]:1" \
--cellpack "[4,1]:1000000:p2tr:0" \
--auto-confirm
alkanes-cli $NETWORK $WALLET bitcoind generatetoaddress 1 "p2tr:0"
# 4. Verify balance
echo "Checking balance..."
BALANCE=$(alkanes-cli $NETWORK simulate 4:1:103 --args "$(alkanes-cli $NETWORK wallet address)")
echo "Balance: $BALANCE"
# 5. Test transfer
echo "Testing transfer..."
alkanes-cli $NETWORK $WALLET alkanes execute \
--inputs "4:1:500000" \
--cellpack "[4,1]:500000:bcrt1q...recipient" \
--auto-confirm
echo "All tests passed!"Debugging with Traces
The --trace flag provides detailed execution traces for debugging:
- Call stack showing contract-to-contract calls
- Gas consumption at each step
- Storage reads and writes
- Return values and error messages
[TRACE] alkanes-cli simulate 2:100:1 --trace --args "1000"
CallContext {
target: AlkaneId { block: 2, tx: 100 },
opcode: 1,
incoming_alkanes: [],
args: [0x03e8] // 1000 in hex
}
[0] CALL to 2:100 opcode=1
fuel: 100000000
[1] STORAGE_READ key="/balances/caller"
value: 5000000
[2] STORAGE_WRITE key="/balances/caller"
old: 5000000
new: 5001000
[3] STORAGE_WRITE key="/total_supply"
old: 10000000
new: 10001000
ReturnContext {
success: true,
data: [],
fuel_remaining: 99998500,
alkanes_returned: []
}Rust Unit Tests
Test pure functions and logic in isolation using standard Rust tests:
#[cfg(test)]
mod tests {
use super::*;
// Test pure functions that don't need the runtime
#[test]
fn test_amount_calculation() {
// Test fee calculation logic
let amount = 1000u128;
let fee_bps = 30u128; // 0.3%
let fee = (amount * fee_bps) / 10000;
assert_eq!(fee, 3);
}
#[test]
fn test_price_impact() {
// Test AMM price calculation
let reserve_a = 1000000u128;
let reserve_b = 1000000u128;
let amount_in = 10000u128;
// With 0.3% fee
let amount_in_with_fee = amount_in * 997;
let numerator = amount_in_with_fee * reserve_b;
let denominator = reserve_a * 1000 + amount_in_with_fee;
let amount_out = numerator / denominator;
assert!(amount_out < amount_in); // Should get less due to fees
assert_eq!(amount_out, 9870); // Expected output
}
#[test]
fn test_storage_key_generation() {
// Test that storage keys are generated correctly
use metashrew_support::index_pointer::KeyValuePointer;
let ptr = StoragePointer::from_keyword("/balances/");
let key = ptr.select(b"user1").keyword();
assert!(key.starts_with(b"/balances/"));
}
#[test]
#[should_panic(expected = "overflow")]
fn test_overflow_protection() {
let max = u128::MAX;
let result = max.checked_add(1).expect("overflow");
}
}Test Utilities
The alkanes-rs codebase provides test helpers in crates/alkanes/src/tests/helpers.rs:
| Function | Description |
|---|---|
| init_with_multiple_cellpacks | Create a test block with multiple contract deployments |
| create_cellpack_with_witness | Build a transaction with WASM payload |
| assert_binary_deployed_to_id | Verify contract was deployed to expected AlkaneId |
| get_sheet_for_outpoint | Get balance sheet for a specific UTXO |
| assert_return_context | Assert the contract returned expected data |
| assert_revert_context | Assert the contract reverted with expected error |
Mock Provider for CLI Tests
For testing CLI operations without a live node, use MockProvider:
use alkanes_cli_common::mock_provider::MockProvider;
use alkanes_cli_common::traits::{AlkanesProvider, WalletProvider};
use bitcoin::{Amount, Network, OutPoint, TxOut};
#[tokio::test]
async fn test_with_mock_provider() -> anyhow::Result<()> {
// Create mock provider for regtest
let mut provider = MockProvider::new(Network::Regtest);
// Create mock UTXOs
let txid = bitcoin::Txid::from_str(
"8a6465187b53d05405f49851a13d44a1e95b2803835b132145540c89a70af83d"
)?;
let outpoint = OutPoint::new(txid, 0);
let address = WalletProvider::get_address(&provider).await?;
let script_pubkey = address.script_pubkey();
// Add a 1 BTC UTXO
provider.utxos.lock().unwrap().push((
outpoint,
TxOut {
value: Amount::from_sat(100_000_000),
script_pubkey: script_pubkey.clone(),
}
));
// Set up alkane balances
use alkanes_cli_common::alkanes::protorunes::*;
use std::collections::HashMap;
let mut balances = HashMap::new();
balances.insert(
AlkaneId { block: 2, tx: 1 },
5u128 // 5 units of alkane 2:1
);
provider.set_protorunes_response(
txid.to_string(),
0,
ProtoruneOutpointResponse {
outpoint: outpoint.to_string(),
balance_sheet: BalanceSheet {
cached: Balances { balances },
},
},
);
// Now test operations against the mock
// ...
Ok(())
}Testing Token Balances
Verify token balances after transactions:
use crate::tests::helpers::*;
use alkanes_support::id::AlkaneId;
use protorune_support::balance_sheet::BalanceSheet;
#[test]
fn test_token_balance_after_mint() -> anyhow::Result<()> {
clear(); // Reset test state
// Create test block with deploy + mint
let wasm = get_token_wasm();
let deploy_cellpack = Cellpack::new(vec![3, 0], vec![100, 0]); // Deploy
let mint_cellpack = Cellpack::new(vec![4, 1], vec![1, 1000000]); // Mint 1M
let test_block = init_with_cellpack_pairs(vec![
BinaryAndCellpack::new(wasm, deploy_cellpack),
BinaryAndCellpack::cellpack_only(mint_cellpack),
]);
// Index the block
index_block(&test_block)?;
// Check balance at output 0 of last tx
let sheet = get_last_outpoint_sheet(&test_block)?;
let token_id = AlkaneId { block: 4, tx: 1 };
assert_eq!(
sheet.get(&token_id.into()),
Some(&1000000u128),
"Should have 1M tokens"
);
Ok(())
}Testing with Trace Events
Assert on specific trace events for detailed verification:
use crate::tests::helpers::*;
use alkanes_support::trace::TraceResponse;
#[test]
fn test_contract_returns_expected_data() -> anyhow::Result<()> {
clear();
// Deploy and call contract
let test_block = setup_test_contract()?;
index_block(&test_block)?;
// Get the outpoint we want to check
let outpoint = OutPoint {
txid: test_block.txdata.last().unwrap().compute_txid(),
vout: 0,
};
// Assert the contract returned "MyToken"
assert_return_context(&outpoint, |response: TraceResponse| {
let name = String::from_utf8(response.inner.data.clone())?;
assert_eq!(name, "MyToken");
Ok(())
})?;
Ok(())
}
#[test]
fn test_unauthorized_call_reverts() -> anyhow::Result<()> {
clear();
// Try to call admin function without authorization
let test_block = setup_unauthorized_call()?;
index_block(&test_block)?;
let outpoint = OutPoint {
txid: test_block.txdata.last().unwrap().compute_txid(),
vout: 0,
};
// Assert the contract reverted with expected message
assert_revert_context(&outpoint, "unauthorized")?;
Ok(())
}CI/CD Integration
Run tests in your CI pipeline:
name: Test Contracts
on:
push:
branches: [main]
pull_request:
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Rust
uses: dtolnay/rust-action@stable
with:
targets: wasm32-unknown-unknown
- name: Run unit tests
run: cargo test --lib
- name: Build WASM contracts
run: cargo build --release --target wasm32-unknown-unknown
- name: Start regtest environment
run: |
docker-compose up -d
sleep 30 # Wait for services
- name: Run integration tests
run: |
cargo build --release -p alkanes-cli
export PATH="$PATH:$(pwd)/target/release"
./scripts/run-tests.sh
- name: Stop regtest
if: always()
run: docker-compose downTesting Best Practices
Test edge cases
Test zero amounts, max values, empty strings, unauthorized callers
Test error paths
Verify your contract reverts with appropriate messages for invalid inputs
Test authorization
Ensure only authorized callers can execute privileged operations
Test storage limits
Verify behavior when approaching storage limits or with large data
Use simulation first
Test with simulate before deploying to catch errors early
Test multi-call sequences
Verify state is consistent across multiple contract calls