alkanes-std Library Reference

Core traits, macros, and utilities for building Alkanes smart contracts

The alkanes-std library provides essential building blocks for Alkanes smart contracts. This reference covers the core traits, storage patterns, and macros you'll use when building contracts.

Overview

The Alkanes runtime is split across several crates that work together:

alkanes-runtime- Core runtime with AlkaneResponder trait, storage, and external calls
alkanes-support- Types like Context, CallResponse, AlkaneId, and Cellpack
alkanes-macros- Procedural macros including MessageDispatch and declare_alkane!
alkanes-std-factory-support- MintableToken trait for token implementations
metashrew-support- Low-level storage utilities like KeyValuePointer

AlkaneResponder Trait

Every contract must implement the AlkaneResponder trait. It provides access to context, storage, and external calls.

use alkanes_runtime::runtime::AlkaneResponder;

#[derive(Default)]
pub struct MyContract(());

impl AlkaneResponder for MyContract {}

// Now MyContract has access to all AlkaneResponder methods:
// - context(), height(), fuel(), sequence()
// - call(), staticcall(), delegatecall()
// - load(), store()
// - observe_initialization()

Core Methods

MethodReturnsDescription
context()Result<Context>Get the current execution context (caller, inputs, incoming alkanes)
observe_initialization()Result<()>Mark contract as initialized (fails if already initialized)
height()u64Get current blockchain height
fuel()u64Get remaining execution fuel/gas
sequence()u128Get next sequence number for factory spawns
balance(who, what)u128Query balance of an alkane for an address
transaction()Vec<u8>Get raw transaction bytes
transaction_id()Result<Txid>Get the current transaction ID
block()Vec<u8>Get raw block bytes

External Call Methods

MethodReturnsDescription
call(cellpack, alkanes, fuel)Result<CallResponse>Call another contract (state changes persist)
staticcall(cellpack, alkanes, fuel)Result<CallResponse>Call without state changes (read-only)
delegatecall(cellpack, alkanes, fuel)Result<CallResponse>Call with caller's context (for proxies)

Storage Methods

MethodReturnsDescription
load(key)Vec<u8>Load raw bytes from storage
store(key, value)()Store raw bytes to storage

MessageDispatch Macro

The #[derive(MessageDispatch)] macro generates opcode routing for your contract's messages.

use alkanes_runtime::message::MessageDispatch;

#[derive(MessageDispatch)]
pub enum MyMessage {
    // Simple opcode with no parameters
    #[opcode(0)]
    Initialize,

    // Opcode with parameters (decoded from inputs)
    #[opcode(1)]
    Transfer { to: u128, amount: u128 },

    // Opcode that returns data
    #[opcode(99)]
    #[returns(String)]
    GetName,

    // Opcode returning numeric value
    #[opcode(101)]
    #[returns(u128)]
    GetTotalSupply,
}
#[opcode(N)]- Map this variant to opcode N (0-255)
#[returns(Type)]- Mark this opcode as returning Type in the response data
Variant { field: Type }- Opcode parameters are decoded from inputs

declare_alkane! Macro

The declare_alkane! macro generates the WASM entry point that connects your contract to the runtime.

use alkanes_runtime::declare_alkane;

// This macro generates:
// - __execute() entry point for WASM
// - __meta() for ABI export
// - Opcode routing and error handling

declare_alkane! {
    impl AlkaneResponder for MyContract {
        type Message = MyMessage;
    }
}

Context Structure

The Context provides information about the current execution:

FieldTypeDescription
myselfAlkaneIdThis contract's ID (block:tx format)
callerAlkaneIdThe calling contract's ID (or 0:0 for EOA)
inputsVec<u128>Input parameters after the opcode
incoming_alkanesAlkaneTransferParcelTokens sent with this call
voutu32Output index in the transaction
fn my_method(&self) -> Result<CallResponse> {
    let context = self.context()?;

    // Access caller info
    let caller = &context.caller;
    let my_id = &context.myself;

    // Access input parameters
    let first_param = context.inputs.get(0).unwrap_or(&0);

    // Access incoming tokens
    for transfer in &context.incoming_alkanes.0 {
        println!("Received {} of {:?}", transfer.value, transfer.id);
    }

    Ok(CallResponse::forward(&context.incoming_alkanes))
}

CallResponse Structure

Every opcode handler returns a CallResponse:

FieldTypeDescription
dataVec<u8>Return data (used for #[returns(Type)] values)
alkanesAlkaneTransferParcelTokens to send back to caller
fn get_name(&self) -> Result<CallResponse> {
    let context = self.context()?;

    // Forward any incoming alkanes back to caller
    let mut response = CallResponse::forward(&context.incoming_alkanes);

    // Set return data (for #[returns(String)])
    response.data = b"MyToken".to_vec();

    Ok(response)
}

fn mint(&self, amount: u128) -> Result<CallResponse> {
    let context = self.context()?;
    let mut response = CallResponse::forward(&context.incoming_alkanes);

    // Add minted tokens to response
    response.alkanes.0.push(AlkaneTransfer {
        id: context.myself.clone(),
        value: amount,
    });

    Ok(response)
}

StoragePointer

StoragePointer provides a convenient way to manage contract storage:

from_keyword("/path")- Create pointer from a string path
.select(&key)- Create sub-pointer by appending key bytes
.get()- Load value as Arc<Vec<u8>>
.set(Arc::new(value))- Store value
.get_value::<T>()- Load and deserialize as type T
.set_value::<T>(v)- Serialize and store type T
use alkanes_runtime::storage::StoragePointer;
use metashrew_support::index_pointer::KeyValuePointer;
use std::sync::Arc;

// Simple key-value storage
fn total_supply_pointer() -> StoragePointer {
    StoragePointer::from_keyword("/totalsupply")
}

fn get_total_supply(&self) -> u128 {
    total_supply_pointer().get_value::<u128>()
}

fn set_total_supply(&self, value: u128) {
    total_supply_pointer().set_value::<u128>(value);
}

// Hierarchical storage with .select()
fn balance_pointer(&self, user: &[u8]) -> StoragePointer {
    StoragePointer::from_keyword("/balances/").select(user)
}

fn get_balance(&self, user: &[u8]) -> u128 {
    self.balance_pointer(user).get_value::<u128>()
}

// Store complex data
fn set_data(&self, key: &str, data: Vec<u8>) {
    let mut ptr = StoragePointer::from_keyword(key);
    ptr.set(Arc::new(data));
}

AuthenticatedResponder Trait

For contracts that need owner-only functions, implement AuthenticatedResponder:

deploy_auth_token(units)- Deploy an auth token during initialization
only_owner()- Require auth token in incoming_alkanes (reverts if not present)
auth_token()- Get the auth token AlkaneId
set_auth_token(id)- Set the auth token (usually done automatically)
use alkanes_runtime::auth::AuthenticatedResponder;

#[derive(Default)]
pub struct OwnedContract(());

impl AlkaneResponder for OwnedContract {}
impl AuthenticatedResponder for OwnedContract {}

impl OwnedContract {
    fn initialize(&self, auth_units: u128) -> Result<CallResponse> {
        self.observe_initialization()?;
        let context = self.context()?;
        let mut response = CallResponse::forward(&context.incoming_alkanes);

        // Deploy auth token and add to response
        response.alkanes.0.push(self.deploy_auth_token(auth_units)?);

        Ok(response)
    }

    fn admin_only_function(&self) -> Result<CallResponse> {
        // This will revert if auth token not in incoming_alkanes
        self.only_owner()?;

        // Only executes if caller has auth token
        let context = self.context()?;
        Ok(CallResponse::forward(&context.incoming_alkanes))
    }
}

MintableToken Trait

For token contracts, MintableToken provides standard token functionality:

name() / symbol()- Get token name and symbol from storage
set_name_and_symbol_str(name, symbol)- Set name and symbol during init
total_supply()- Get current total supply
increase_total_supply(v) / decrease_total_supply(v)- Modify total supply (for mint/burn)
mint(context, value)- Create a mint transfer
use alkanes_std_factory_support::MintableToken;

#[derive(Default)]
pub struct MyToken(());

impl MintableToken for MyToken {}
impl AlkaneResponder for MyToken {}

impl MyToken {
    fn initialize(&self, name: String, symbol: String, initial_supply: u128) -> Result<CallResponse> {
        self.observe_initialization()?;
        let context = self.context()?;

        // Set token metadata
        self.set_name_and_symbol_str(name, symbol);

        // Mint initial supply
        let mut response = CallResponse::forward(&context.incoming_alkanes);
        let transfer = <Self as MintableToken>::mint(self, &context, initial_supply)?;
        response.alkanes.0.push(transfer);

        Ok(response)
    }

    fn get_total_supply(&self) -> Result<CallResponse> {
        let context = self.context()?;
        let mut response = CallResponse::forward(&context.incoming_alkanes);
        response.data = self.total_supply().to_le_bytes().to_vec();
        Ok(response)
    }
}

Cellpack Structure

A Cellpack represents a call to another contract:

use alkanes_support::cellpack::Cellpack;
use alkanes_support::id::AlkaneId;

// Call another contract
let cellpack = Cellpack {
    target: AlkaneId { block: 2, tx: 12345 },  // Target contract
    inputs: vec![99],  // Opcode 99 (GetName)
};

let response = self.staticcall(
    &cellpack,
    &AlkaneTransferParcel::default(),  // No tokens sent
    self.fuel(),  // Use remaining fuel
)?;

// Call with parameters
let cellpack = Cellpack {
    target: AlkaneId { block: 2, tx: 12345 },
    inputs: vec![
        1,           // Opcode 1 (Transfer)
        recipient,   // First parameter
        amount,      // Second parameter
    ],
};

// Call with token transfer
let response = self.call(
    &cellpack,
    &AlkaneTransferParcel(vec![
        AlkaneTransfer {
            id: AlkaneId { block: 2, tx: 0 },  // DIESEL
            value: 1000000,
        }
    ]),
    self.fuel(),
)?;

AlkaneId Structure

Every contract has a unique AlkaneId with block and tx components:

RangeDescription
[2, N]Regular deployed contracts (sequence-based)
[4, N]Factory templates deployed at specific tx
[6, N]Clone operations from template N
[3, N]Deploy new contract from tx N
use alkanes_support::id::AlkaneId;

// Reference a deployed contract
let diesel = AlkaneId { block: 2, tx: 0 };

// Reference a factory template
let token_factory = AlkaneId { block: 4, tx: 1 };

// Clone from template (opcode prefix)
let clone_op = AlkaneId { block: 6, tx: 1 };

// Deploy new contract (opcode prefix)
let deploy_op = AlkaneId { block: 3, tx: 12345 };

// Access current contract's ID
let context = self.context()?;
let my_id = context.myself;  // e.g., AlkaneId { block: 2, tx: 77 }

Standard Opcodes

Common opcode conventions across Alkanes contracts:

OpcodeNameDescription
0InitializeContract initialization (usually called once)
77MintMint new tokens (if applicable)
88BurnBurn tokens
99GetNameReturn token/contract name
100GetSymbolReturn token symbol
101GetTotalSupplyReturn total supply

Complete Example

A minimal token contract using all the key patterns:

src/lib.rs
use alkanes_runtime::runtime::AlkaneResponder;
use alkanes_runtime::{auth::AuthenticatedResponder, declare_alkane, message::MessageDispatch};
use alkanes_std_factory_support::MintableToken;
use alkanes_support::{context::Context, parcel::AlkaneTransfer, response::CallResponse};
use anyhow::Result;

#[derive(Default)]
pub struct MyToken(());

// Implement required traits
impl MintableToken for MyToken {}
impl AuthenticatedResponder for MyToken {}
impl AlkaneResponder for MyToken {}

// Define message opcodes
#[derive(MessageDispatch)]
enum MyTokenMessage {
    #[opcode(0)]
    Initialize {
        auth_units: u128,
        initial_supply: u128,
        name: String,
        symbol: String,
    },

    #[opcode(77)]
    Mint { amount: u128 },

    #[opcode(88)]
    Burn,

    #[opcode(99)]
    #[returns(String)]
    GetName,

    #[opcode(100)]
    #[returns(String)]
    GetSymbol,

    #[opcode(101)]
    #[returns(u128)]
    GetTotalSupply,
}

impl MyToken {
    fn initialize(
        &self,
        auth_units: u128,
        initial_supply: u128,
        name: String,
        symbol: String,
    ) -> Result<CallResponse> {
        self.observe_initialization()?;
        let context = self.context()?;

        // Set token metadata
        self.set_name_and_symbol_str(name, symbol);

        // Build response
        let mut response = CallResponse::forward(&context.incoming_alkanes);

        // Deploy auth token for owner
        response.alkanes.0.push(self.deploy_auth_token(auth_units)?);

        // Mint initial supply
        let transfer = <Self as MintableToken>::mint(self, &context, initial_supply)?;
        response.alkanes.0.push(transfer);

        Ok(response)
    }

    fn mint(&self, amount: u128) -> Result<CallResponse> {
        self.only_owner()?;  // Require auth token

        let context = self.context()?;
        let mut response = CallResponse::forward(&context.incoming_alkanes);

        let transfer = <Self as MintableToken>::mint(self, &context, amount)?;
        response.alkanes.0.push(transfer);

        Ok(response)
    }

    fn burn(&self) -> Result<CallResponse> {
        let context = self.context()?;

        // Find our token in incoming alkanes
        let burn_amount: u128 = context.incoming_alkanes.0
            .iter()
            .filter(|t| t.id == context.myself)
            .map(|t| t.value)
            .sum();

        // Decrease total supply
        self.decrease_total_supply(burn_amount)?;

        // Return any other tokens (but not our burned tokens)
        let mut response = CallResponse::default();
        for transfer in &context.incoming_alkanes.0 {
            if transfer.id != context.myself {
                response.alkanes.0.push(transfer.clone());
            }
        }

        Ok(response)
    }

    fn get_name(&self) -> Result<CallResponse> {
        let context = self.context()?;
        let mut response = CallResponse::forward(&context.incoming_alkanes);
        response.data = self.name().into_bytes();
        Ok(response)
    }

    fn get_symbol(&self) -> Result<CallResponse> {
        let context = self.context()?;
        let mut response = CallResponse::forward(&context.incoming_alkanes);
        response.data = self.symbol().into_bytes();
        Ok(response)
    }

    fn get_total_supply(&self) -> Result<CallResponse> {
        let context = self.context()?;
        let mut response = CallResponse::forward(&context.incoming_alkanes);
        response.data = self.total_supply().to_le_bytes().to_vec();
        Ok(response)
    }
}

// Register contract entry point
declare_alkane! {
    impl AlkaneResponder for MyToken {
        type Message = MyTokenMessage;
    }
}