@alkanes/ts-sdk Guide

Working examples from the alkanes.build codebase

This guide documents how alkanes.build uses the @alkanes/ts-sdk to fetch blockchain data, execute Lua scripts, and build a complete DeFi dashboard. All examples are from working production code.

Installation

Install the SDK from the alkanes package registry. The URL below is pinned to the latest commit on the develop branch:

Fetching latest version...

Or configure npm to use the alkanes registry:

# Configure npm registry (alternative)
npm config set @alkanes:registry https://pkg.alkanes.build/
npm install @alkanes/ts-sdk

Architecture Overview

The SDK provides a unified TypeScript interface over WASM bindings. See the full API Reference for complete method documentation.

// SDK Structure
import { AlkanesProvider } from '@alkanes/ts-sdk';

const provider = new AlkanesProvider({ network: 'mainnet' });
await provider.initialize();

// Sub-clients available after initialization:
provider.esplora      // EsploraClient - UTXOs, transactions
provider.alkanes      // AlkanesRpcClient - token balances, contract calls
provider.metashrew    // MetashrewClient - low-level metashrew_view
provider.lua          // LuaClient - Lua script execution
provider.dataApi      // DataApiClient - market data, BTC price
provider.bitcoin      // BitcoinRpcClient - bitcoind RPC calls

Creating the Provider

The AlkanesProvider is the main entry point. Here's how alkanes.build initializes it:

lib/alkanes-client.ts
import { AlkanesProvider } from '@alkanes/ts-sdk';

// Network presets available: 'mainnet', 'testnet', 'signet', 'regtest'
const provider = new AlkanesProvider({
  network: 'mainnet',
  // Optional: Override RPC URL
  rpcUrl: process.env.ALKANES_RPC_URL || 'https://mainnet.subfrost.io/v4/jsonrpc',
});

// IMPORTANT: Must call initialize() before using the provider
// This loads the WASM module (works in both Node.js and browser)
await provider.initialize();

Singleton Client Pattern

We use a singleton pattern for the provider to avoid repeated WASM initialization:

lib/alkanes-client.ts (singleton pattern)
class AlkanesClient {
  private provider: AlkanesProvider | null = null;
  private initPromise: Promise<void> | null = null;
  private rpcUrl: string;

  constructor() {
    this.rpcUrl = process.env.ALKANES_RPC_URL || 'https://mainnet.subfrost.io/v4/jsonrpc';
  }

  // Lazy, singleton initialization
  private async ensureProvider(): Promise<AlkanesProvider> {
    if (this.provider) return this.provider;

    if (!this.initPromise) {
      this.initPromise = (async () => {
        this.provider = new AlkanesProvider({
          network: 'mainnet',
          rpcUrl: this.rpcUrl,
        });
        await this.provider.initialize();
      })();
    }

    await this.initPromise;
    return this.provider!;
  }

  // Example method using the provider
  async getCurrentHeight(): Promise<number> {
    const provider = await this.ensureProvider();
    return provider.getBlockHeight();
  }
}

// Export singleton instance
export const alkanesClient = new AlkanesClient();

Getting Block Height

Fetch the current blockchain height using the provider:

Getting current block height
// Using the convenience method
const height = await provider.getBlockHeight();
console.log('Current height:', height); // e.g., 927618

// Or using the metashrew client directly
const height = await provider.metashrew.getHeight();

Fetching Wallet Balances

Get BTC balance and Alkane token holdings for an address:

Fetching wallet balances
// Get BTC UTXOs
const utxos = await provider.esplora.getAddressUtxos(address);
const btcBalance = utxos.reduce((sum, utxo) => sum + utxo.value, 0);
console.log('BTC Balance:', btcBalance, 'sats');

// Get Alkane token balances
const balances = await provider.alkanes.getBalance(address);
console.log('Token balances:', balances);
// Returns: [{ alkane_id: { block: 2, tx: 0 }, balance: 444121520576, ... }]

// Format balances with known token metadata
const KNOWN_TOKENS = {
  '2:0': { symbol: 'DIESEL', decimals: 8 },
  '32:0': { symbol: 'frBTC', decimals: 8 },
  '2:56801': { symbol: 'bUSD', decimals: 8 },
};

for (const b of balances) {
  const id = `${b.alkane_id.block}:${b.alkane_id.tx}`;
  const token = KNOWN_TOKENS[id] || { symbol: id, decimals: 8 };
  const formatted = Number(b.balance) / Math.pow(10, token.decimals);
  console.log(`${token.symbol}: ${formatted.toLocaleString()}`);
}

Fetching Bitcoin Price

Get the current BTC/USD price from the Data API:

Fetching Bitcoin price
// Using the Data API client
const result = await provider.dataApi.getBitcoinPrice();

// Response structure varies, handle multiple formats:
const price = result?.data?.bitcoin?.usd
           ?? result?.bitcoin?.usd
           ?? result?.price
           ?? result?.usd;

if (typeof price === 'number' && price > 0) {
  console.log('BTC Price:', '$' + price.toLocaleString());
}

Metashrew View Calls

Call alkane contracts using metashrew_view for pool reserves and token data:

Fetching pool reserves via metashrew_view
// Pool configurations with protobuf payloads
const POOLS = {
  DIESEL_FRBTC: {
    name: 'DIESEL/frBTC',
    protobufPayload: '0x2096ce382a06029fda04e7073001',
    alkaneId: { block: 2, tx: 77087 },
  },
  DIESEL_BUSD: {
    name: 'DIESEL/bUSD',
    protobufPayload: '0x2096ce382a0602d99604e7073001',
    alkaneId: { block: 2, tx: 68441 },
  },
};

// Call metashrew_view with 'simulate' view function
const hex = await provider.metashrew.view(
  'simulate',
  POOLS.DIESEL_FRBTC.protobufPayload,
  'latest'  // or a specific block height as string
);

// Parse the response (little-endian u128 values)
function parsePoolReserves(hex: string) {
  const data = hex.startsWith('0x') ? hex.slice(2) : hex;
  // Find inner data after protobuf wrapper
  const marker = data.indexOf('1a');
  if (marker === -1) return null;

  const lenByte = parseInt(data.slice(marker + 2, marker + 4), 16);
  const innerStart = marker + (lenByte < 128 ? 4 : 6);
  const inner = data.slice(innerStart);

  // Pool layout: token_a[32], token_b[32], reserve_a[16], reserve_b[16], total_supply[16]
  return {
    reserve0: parseU128LE(inner, 64),
    reserve1: parseU128LE(inner, 80),
    totalSupply: parseU128LE(inner, 96),
  };
}

// Helper: parse little-endian u128
function parseU128LE(hex: string, byteOffset: number): bigint {
  const slice = hex.slice(byteOffset * 2, byteOffset * 2 + 32);
  let reversed = '';
  for (let i = slice.length - 2; i >= 0; i -= 2) {
    reversed += slice.slice(i, i + 2);
  }
  return BigInt('0x' + (reversed || '0'));
}

Lua Script Execution

Execute Lua scripts for batched queries with automatic scripthash caching:

  • Single RPC round-trip for multiple queries
  • Atomic data snapshot at the same block height
  • Automatic scripthash caching (lua_evalsaved fallback)
  • Server-side JSON encoding
Executing Lua scripts with provider.lua.eval()
// The LuaClient automatically handles scripthash caching:
// 1. Computes SHA256 hash of script
// 2. Tries lua_evalsaved (cached) first
// 3. Falls back to lua_evalscript if not cached

const STATS_LUA_SCRIPT = `
-- Fetch DIESEL stats in a single RPC call
local results = { diesel = {}, pools = {}, height = 0 }

-- Get current height
results.height = tonumber(_RPC.metashrew_height()) or 0

-- Fetch DIESEL total supply (opcode 101)
local diesel_response = _RPC.metashrew_view(
    "simulate",
    "0x20e3ce382a030200653001",
    "latest"
)
if diesel_response then
    results.diesel.total_supply = parse_total_supply(diesel_response)
end

-- Fetch pool reserves
local frbtc_response = _RPC.metashrew_view(
    "simulate",
    "0x2096ce382a06029fda04e7073001",
    "latest"
)
-- Parse and add to results...

return results
`;

// Execute the script
const result = await provider.lua.eval(STATS_LUA_SCRIPT, []);

// Result structure: { calls: number, returns: any, runtime: number }
console.log('RPC calls made:', result.calls);
console.log('Runtime (ms):', result.runtime);
console.log('Data:', result.returns);

Fetching Pool Candle Data

Complete example of fetching historical pool data for charts:

lib/pools/candle-fetcher.ts
// Lua script for fetching historical pool data
export const CANDLES_LUA_SCRIPT = `
local params = args[1] or {}
local pool_payload = params[1]
local start_height = tonumber(params[2])
local end_height = tonumber(params[3])
local interval = tonumber(params[4]) or 144  -- ~1 day in blocks

local function parse_u128_le(hex_str, byte_offset)
    -- Little-endian u128 parsing
    local hex_offset = byte_offset * 2
    local hex_slice = hex_str:sub(hex_offset + 1, hex_offset + 32)
    local reversed = ""
    for i = #hex_slice - 1, 1, -2 do
        reversed = reversed .. hex_slice:sub(i, i + 1)
    end
    return tonumber(reversed, 16) or 0
end

local function get_block_timestamp(height)
    local ok, hash = pcall(function() return _RPC.btc_getblockhash(height) end)
    if not ok then return nil end
    local ok2, block = pcall(function() return _RPC.btc_getblock(hash, 1) end)
    if not ok2 then return nil end
    return block.time
end

local results = { data_points = {} }

for height = start_height, end_height, interval do
    local ok, response = pcall(function()
        return _RPC.metashrew_view("simulate", pool_payload, tostring(height))
    end)

    if ok and response then
        local hex = response:sub(1, 2) == "0x" and response:sub(3) or response
        -- Parse reserves from response...
        table.insert(results.data_points, {
            height = height,
            timestamp = get_block_timestamp(height),
            reserve_a = parse_u128_le(inner, 64),
            reserve_b = parse_u128_le(inner, 80),
            total_supply = parse_u128_le(inner, 96)
        })
    end
end

results.count = #results.data_points
return results
`;

// Execute and process results
export async function fetchPoolDataPoints(
  poolKey: 'DIESEL_FRBTC' | 'DIESEL_BUSD',
  startHeight: number,
  endHeight: number,
  interval: number = 144
) {
  const pool = POOLS[poolKey];
  const provider = await ensureProvider();

  const result = await provider.lua.eval(CANDLES_LUA_SCRIPT, [
    [pool.protobufPayload, startHeight.toString(), endHeight.toString(), interval.toString()]
  ]);

  // Convert to typed data points
  return result.returns.data_points.map(dp => ({
    height: dp.height,
    timestamp: dp.timestamp,
    reserve0: BigInt(dp.reserve_a),
    reserve1: BigInt(dp.reserve_b),
    totalSupply: BigInt(dp.total_supply),
  }));
}

Wallet Operations

The SDK provides wallet management through the rawProvider. Create wallets, load mnemonics, and get addresses:

Wallet management with rawProvider
import { AlkanesProvider } from '@alkanes/ts-sdk';

const provider = new AlkanesProvider({
  network: 'regtest',
  rpcUrl: 'http://127.0.0.1:18888'
});
await provider.initialize();

// Access the raw WASM provider for wallet operations
const rawProvider = provider.rawProvider;

// Create a new wallet
const walletInfo = rawProvider.walletCreate();
console.log('Mnemonic:', walletInfo.mnemonic);
console.log('Address:', walletInfo.address);

// Load an existing wallet from mnemonic
rawProvider.walletLoadMnemonic('your twelve word mnemonic phrase here ...');

// Get addresses (type: 'p2tr' | 'p2wpkh' | 'p2sh-p2wpkh')
const addresses = rawProvider.walletGetAddresses('p2tr', 0, 5);
addresses.forEach((addr, i) => {
  console.log(`Address ${i}: ${addr.address}`);
});

Regtest Development

For local development, connect to a regtest node and use Bitcoin RPC for block generation:

Regtest setup and block generation
import { AlkanesProvider } from '@alkanes/ts-sdk';

const provider = new AlkanesProvider({
  network: 'regtest',
  rpcUrl: process.env.RPC_URL || 'http://127.0.0.1:18888'
});
await provider.initialize();

// Check if node is running
const height = await provider.bitcoin.getBlockCount();
console.log('Regtest node running at height:', height);

// Fund a wallet by mining blocks
const walletAddress = 'bcrt1q...';  // Your regtest address

// Mine 101 blocks to mature coinbase
await provider.bitcoin.generateToAddress(101, walletAddress);

// Check wallet UTXOs
const utxos = await provider.esplora.getAddressUtxos(walletAddress);
console.log('Wallet has', utxos.length, 'UTXOs');

// Get total balance
const totalSats = utxos.reduce((sum, u) => sum + u.value, 0);
console.log('Balance:', totalSats / 100_000_000, 'BTC');

Contract Deployment

Deploy WASM contracts using protostones. This pattern is from the alkanes-rs deploy-regtest-bindgen.ts script:

Deploy a WASM contract
import { readFileSync } from 'fs';
import { AlkanesProvider } from '@alkanes/ts-sdk';

// Read WASM file as hex
function readWasmAsHex(wasmPath: string): string {
  const buffer = readFileSync(wasmPath);
  return buffer.toString('hex');
}

async function deployContract(
  provider: AlkanesProvider,
  walletAddress: string,
  wasmPath: string,
  targetTx: number,
  initArgs: string = ''
): Promise<string> {
  // Read WASM as hex for envelope
  const envelopeHex = readWasmAsHex(wasmPath);

  // Build protostone for deployment
  // Format: [3,targetTx,initArgs...]:v0:v0
  // [3,...] = deploy opcode, creates contract at [4,targetTx]
  const protostone = initArgs
    ? `[3,${targetTx},${initArgs}]:v0:v0`
    : `[3,${targetTx}]:v0:v0`;

  console.log('Deploying with protostone:', protostone);
  console.log('WASM size:', envelopeHex.length / 2, 'bytes');

  // Execute deployment
  const result = await provider.alkanesExecuteTyped({
    toAddresses: [walletAddress],
    inputRequirements: '',
    protostones: protostone,
    feeRate: 1,
    envelopeHex: envelopeHex,
    fromAddresses: [walletAddress],
    changeAddress: walletAddress,
    traceEnabled: true,
    autoConfirm: true,
    mineEnabled: true,  // Auto-mine on regtest
  });

  console.log('Deployed to [4,', targetTx, ']');
  return result.reveal_txid || result.txid;
}

// Example: Deploy a token contract at [4, 0x1234]
await deployContract(
  provider,
  walletAddress,
  './contracts/my_token.wasm',
  0x1234,
  '0,1000000000'  // Init args: owner=0, total_supply=1B
);

Transaction Execution

Execute alkane transactions with full type safety using alkanesExecuteTyped. This method returns a TransactionBroadcast object that provides immediate access to transaction info and lazy-loaded execution traces:

Execute alkane transactions
// Call a contract method (e.g., mint DIESEL tokens)
const mintResult = await provider.alkanesExecuteTyped({
  toAddresses: [walletAddress],
  inputRequirements: '',
  // [2,0,77] = call DIESEL contract (2:0) with opcode 77 (mint)
  protostones: '[2,0,77]:v0:v0',
  feeRate: 1,
  fromAddresses: [walletAddress],
  changeAddress: walletAddress,
  traceEnabled: true,
  autoConfirm: true,
  mineEnabled: true,
});

// Transfer tokens between addresses
const transferResult = await provider.alkanesExecuteTyped({
  toAddresses: [recipientAddress],
  // Input requirements specify token amounts needed
  inputRequirements: '2:0:1000000',  // Need 1M units of 2:0 (DIESEL)
  protostones: '',  // No contract call, just transfer
  feeRate: 2,
  fromAddresses: [walletAddress],
  changeAddress: walletAddress,
  autoConfirm: true,
});

// Create a liquidity pool
const poolResult = await provider.alkanesExecuteTyped({
  toAddresses: [walletAddress],
  inputRequirements: '2:0:300000000,32:0:50000',  // DIESEL + frBTC
  // Call factory contract to create pool
  protostones: `[4,${FACTORY_ID},1,2,0,32,0]:v0:v0`,
  feeRate: 1,
  fromAddresses: [walletAddress],
  changeAddress: walletAddress,
  traceEnabled: true,
  autoConfirm: true,
  mineEnabled: true,
});

Wrapping BTC to frBTC

Use frbtcWrapTyped to convert BTC to frBTC (the wrapped Bitcoin token on Alkanes). This is essential for participating in Alkanes DeFi:

Wrap BTC to frBTC
// Wrap BTC to frBTC using the typed method
const result = await provider.frbtcWrapTyped({
  // Amount in satoshis to wrap
  amount: BigInt(100000000), // 1 BTC = 100,000,000 sats
  toAddress: walletAddress,
  fromAddress: walletAddress,
  feeRate: 1,
  traceEnabled: true,
  mineEnabled: true,   // Auto-mine on regtest
  autoConfirm: true,
});

console.log('Wrap transaction:', result.reveal_txid);

// Verify frBTC balance after wrap
const balances = await provider.alkanes.getBalance(walletAddress);
const frbtc = balances.find(b =>
  b.alkane_id.block === 32 && b.alkane_id.tx === 0
);
console.log('frBTC balance:', frbtc?.balance);

Creating AMM Pools

Use alkanesInitPoolTyped to create new liquidity pools. This example is from the deploy-regtest-bindgen.ts script:

Create AMM liquidity pool
// Initialize a new AMM pool with two tokens
const txid = await provider.alkanesInitPoolTyped({
  // Factory contract ID (where to create the pool)
  factoryId: { block: 4, tx: 65522 },  // AMM Factory

  // Token pair for the pool
  token0: { block: 2, tx: 0 },    // DIESEL
  token1: { block: 32, tx: 0 },   // frBTC

  // Initial liquidity amounts (in smallest units)
  amount0: '300000000',  // 3 DIESEL (8 decimals)
  amount1: '50000',      // 0.0005 frBTC

  // Minimum LP tokens to receive (optional, for slippage protection)
  minimumLp: '0',

  toAddress: walletAddress,
  fromAddress: walletAddress,
  feeRate: 1,
  trace: true,
  autoConfirm: true,
});

console.log('Pool created! TXID:', txid);

// The pool will be created at a new alkane ID
// Query the factory to find the pool ID

Executing Swaps

Use alkanesSwapTyped to execute token swaps through AMM pools:

Execute token swap
// Swap tokens through an AMM pool
const txid = await provider.alkanesSwapTyped({
  // Factory to route through
  factoryId: { block: 4, tx: 65522 },

  // Swap path: array of token IDs from input to output
  path: [
    { block: 2, tx: 0 },   // DIESEL (input)
    { block: 32, tx: 0 },  // frBTC (output)
  ],

  // Amount of input token to swap
  inputAmount: '100000000',  // 1 DIESEL

  // Minimum output (slippage protection)
  minimumOutput: '10',  // Minimum frBTC to receive

  // Expiration block height (deadline for swap)
  expires: currentHeight + 10,

  toAddress: walletAddress,
  fromAddress: walletAddress,
  feeRate: 1,
  trace: true,
  autoConfirm: true,
});

console.log('Swap executed! TXID:', txid);

// For multi-hop swaps, extend the path:
// path: [tokenA, tokenB, tokenC]  // A -> B -> C

Contract Verification

Verify a contract was deployed successfully by checking its bytecode:

Verify contract deployment
async function verifyDeployment(
  provider: AlkanesProvider,
  contractId: string  // Format: "4:1234"
): Promise<boolean> {
  // Retry a few times as indexer may lag
  for (let i = 0; i < 3; i++) {
    try {
      const bytecode = await provider.alkanes.getBytecode(contractId);

      if (bytecode && bytecode.length > 0) {
        console.log(`Contract ${contractId} verified!`);
        console.log(`Bytecode size: ${bytecode.length / 2} bytes`);
        return true;
      }
    } catch {
      // Ignore and retry
    }

    console.log('Waiting for indexer...');
    await new Promise(r => setTimeout(r, 2000));
  }

  console.error(`Contract ${contractId} not found`);
  return false;
}

// Verify after deployment
await verifyDeployment(provider, '4:0x1234');

// Get contract storage
const storage = await provider.alkanes.getStorageSlot(
  '4:0x1234',  // Contract ID
  '0x00'       // Storage key
);
console.log('Storage value:', storage);

Integration Testing

Our integration tests verify the SDK works correctly against live RPC:

tests/integration/live-rpc.test.ts
import { describe, it, expect } from "vitest";
import { AlkanesProvider } from "@alkanes/ts-sdk";

const TEST_ADDRESS = "bc1puvfmy5whzdq35nd2trckkm09em9u7ps6lal564jz92c9feswwrpsr7ach5";

describe("Live SDK Integration", () => {
  it("should fetch wallet balances", async () => {
    const provider = new AlkanesProvider({
      network: "mainnet",
      rpcUrl: "https://mainnet.subfrost.io/v4/jsonrpc"
    });
    await provider.initialize();

    // Get UTXOs
    const utxos = await provider.esplora.getAddressUtxos(TEST_ADDRESS);
    expect(Array.isArray(utxos)).toBe(true);
    expect(utxos.length).toBeGreaterThan(0);

    // Get alkane balances
    const balances = await provider.alkanes.getBalance(TEST_ADDRESS);
    expect(balances).toBeDefined();
    console.log('Found', balances.length, 'token balances');
  }, 60000);

  it("should execute Lua scripts", async () => {
    const provider = new AlkanesProvider({ network: "mainnet" });
    await provider.initialize();

    const result = await provider.lua.eval(`
      local height = tonumber(_RPC.metashrew_height()) or 0
      return { height = height }
    `, []);

    expect(result.returns.height).toBeGreaterThan(900000);
  }, 60000);
});

// Run with: RUN_INTEGRATION=true pnpm vitest run tests/integration/

Troubleshooting

WASM not loading in Node.js

Ensure you call provider.initialize() before using any methods. The SDK handles cross-platform WASM loading automatically.

Empty responses from Lua scripts

Check that your Lua script returns a value. The SDK uses JSON.parse internally to deserialize the response.

RPC timeout errors

Lua scripts that make many RPC calls may timeout. Reduce the number of block heights queried or increase the interval.

Resources