alkanes-web-sys Integration

alkanes-web-sys provides WebAssembly bindings for interacting with Alkanes from both browser and Node.js environments. This guide covers installation, configuration, and common use cases including wallet management, transaction signing, and RPC communication.

For a higher-level TypeScript interface, see the @alkanes/ts-sdk which wraps alkanes-web-sys with typed client classes. View TS SDK API Reference →

Installation

Install the package using your preferred package manager:

# npm
npm install @aspect/alkanes-web-sys

# pnpm
pnpm add @aspect/alkanes-web-sys

# yarn
yarn add @aspect/alkanes-web-sys

Key Features

WASM Performance

High-performance WebAssembly backend for cryptographic operations

HD Wallet Support

BIP32/BIP39/BIP44 hierarchical deterministic wallets

Transaction Signing

Sign Bitcoin and Alkanes transactions locally

Cross-Platform

Works in browsers, Node.js, and edge runtimes

Basic Setup

Initialize the WASM module and create a provider:

import { initWasm, WebProvider } from '@aspect/alkanes-web-sys';

// Initialize WASM module (required once at startup)
await initWasm();

// Create a provider instance
const provider = new WebProvider({
  rpcUrl: 'https://mainnet.subfrost.io/v4/jsonrpc',
  dataApiUrl: 'https://mainnet.subfrost.io/v4/api',
});

Provider Configuration

Configure the provider with your RPC endpoints:

// Configuration options
interface ProviderConfig {
  rpcUrl: string;       // JSON-RPC endpoint
  dataApiUrl?: string;  // Data API endpoint (optional)
  network?: 'mainnet' | 'signet' | 'regtest';
  timeout?: number;     // Request timeout in ms
}

// With API key (for production)
const provider = new WebProvider({
  rpcUrl: 'https://mainnet.subfrost.io/v4/YOUR_API_KEY',
  dataApiUrl: 'https://mainnet.subfrost.io/v4/YOUR_API_KEY',
  network: 'mainnet',
  timeout: 30000,
});

// Public endpoints (rate limited)
const publicProvider = new WebProvider({
  rpcUrl: 'https://mainnet.subfrost.io/v4/jsonrpc',
  dataApiUrl: 'https://mainnet.subfrost.io/v4/api',
});

Wallet Management

Create and manage HD wallets:

import { Wallet, generateMnemonic } from '@aspect/alkanes-web-sys';

// Generate a new mnemonic
const mnemonic = generateMnemonic(12); // 12 or 24 words
console.log('Mnemonic:', mnemonic);

// Create wallet from mnemonic
const wallet = Wallet.fromMnemonic(mnemonic, {
  network: 'mainnet',
  addressType: 'p2wpkh', // Native SegWit
});

// Get addresses
const address = wallet.getAddress();
const publicKey = wallet.getPublicKey();

console.log('Address:', address);
console.log('Public Key:', publicKey);

// Derive child keys (BIP44 path)
const childWallet = wallet.derive("m/84'/0'/0'/0/0");

Making RPC Calls

Use the provider to make JSON-RPC calls:

// Generic RPC call
const blockHeight = await provider.call('metashrew_height', []);
console.log('Current height:', blockHeight);

// Get Bitcoin block info
const blockHash = await provider.call('btc_getblockhash', [blockHeight]);
const block = await provider.call('btc_getblock', [blockHash, 1]);

// Query address UTXOs
const utxos = await provider.call('esplora_address::utxo', ['bc1q...']);

// Get Alkanes token balances
const balances = await provider.call('alkanes_protorunesbyaddress', ['bc1q...']);

// Query pool state with metashrew_view
const poolState = await provider.call('metashrew_view', [
  'simulate',
  '0x208bce382a06029fda04e7073001',  // DIESEL/frBTC pool payload
  blockHeight.toString()
]);

These RPC methods are wrapped with TypeScript types in the @alkanes/ts-sdk. For example, alkanes_protorunesbyaddress is available as provider.alkanes.getBalance(). AlkanesRpcClient →

Executing Lua Scripts

Run Lua scripts using lua_evalscript:

// Execute a Lua script
const luaScript = `
  local height = _RPC.btc_getblockcount()
  local hash = _RPC.btc_getblockhash(height)
  return { height = height, hash = hash }
`;

const result = await provider.call('lua_evalscript', [luaScript, []]);
// result = { calls: 2, returns: { height: 927500, hash: "000..." }, runtime: 5 }

console.log('Block height:', result.returns.height);
console.log('Block hash:', result.returns.hash);

// With arguments
const scriptWithArgs = `
  local params = args[1] or {}
  local address = params[1]
  local utxos = _RPC.esplora_addressutxo(address)
  return { count = #utxos, utxos = utxos }
`;

const utxoResult = await provider.call('lua_evalscript', [
  scriptWithArgs,
  [['bc1q...']]  // args[1] = ['bc1q...']
]);

Fetching Pool Data

Complete example of fetching pool candle data:

import { initWasm, WebProvider } from '@aspect/alkanes-web-sys';

// Pool candle fetcher using alkanes-web-sys
async function fetchPoolCandles(
  provider: WebProvider,
  poolPayload: string,
  startHeight: number,
  endHeight: number,
  interval: number = 144
) {
  const luaScript = `
    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

    if not pool_payload or not start_height or not end_height then
      return { error = "Missing required arguments" }
    end

    local function parse_u128_le(hex_str, byte_offset)
      local hex_offset = byte_offset * 2
      local hex_len = 32
      if #hex_str < hex_offset + hex_len then return nil end
      local hex_slice = hex_str:sub(hex_offset + 1, hex_offset + hex_len)
      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 or not hash then return nil end
      local ok2, block = pcall(function() return _RPC.btc_getblock(hash, 1) end)
      if not ok2 or not block 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 and type(response) == "string" then
        local hex = response:sub(1, 2) == "0x" and response:sub(3) or response
        local marker = hex:find("1a")
        if marker then
          local len_byte = tonumber(hex:sub(marker + 2, marker + 3), 16) or 0
          local inner_start = marker + (len_byte < 128 and 4 or 6)
          if #hex >= inner_start + 223 then
            local inner = hex:sub(inner_start)
            local ra = parse_u128_le(inner, 64)
            local rb = parse_u128_le(inner, 80)
            local ts = parse_u128_le(inner, 96)
            if ra and rb and ts then
              table.insert(results.data_points, {
                height = height,
                timestamp = get_block_timestamp(height),
                reserve_a = ra,
                reserve_b = rb,
                total_supply = ts
              })
            end
          end
        end
      end
    end
    results.count = #results.data_points
    return results
  `;

  const result = await provider.call('lua_evalscript', [
    luaScript,
    [[poolPayload, startHeight.toString(), endHeight.toString(), interval.toString()]]
  ]);

  if (result.returns?.error) {
    throw new Error(result.returns.error);
  }

  return result.returns?.data_points || [];
}

// Usage
async function main() {
  await initWasm();

  const provider = new WebProvider({
    rpcUrl: 'https://mainnet.subfrost.io/v4/jsonrpc',
  });

  // Get current height
  const height = await provider.call('metashrew_height', []);
  const currentHeight = parseInt(height, 10);

  // Fetch DIESEL/frBTC candles for last 7 days
  const candles = await fetchPoolCandles(
    provider,
    '0x208bce382a06029fda04e7073001',  // DIESEL/frBTC
    currentHeight - 7 * 144,
    currentHeight,
    144
  );

  console.log(`Fetched ${candles.length} data points`);
  for (const dp of candles) {
    const price = (dp.reserve_b / 1e8) / (dp.reserve_a / 1e6);
    console.log(`Block ${dp.height}: ${price.toFixed(8)} frBTC/DIESEL`);
  }
}

main().catch(console.error);

Browser Usage

Special considerations for browser environments:

// Next.js / React setup
// next.config.js
module.exports = {
  webpack: (config) => {
    config.experiments = {
      ...config.experiments,
      asyncWebAssembly: true,
    };
    return config;
  },
};

// React component
import { useEffect, useState } from 'react';

function PriceWidget() {
  const [price, setPrice] = useState<number | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    async function fetchPrice() {
      const { initWasm, WebProvider } = await import('@aspect/alkanes-web-sys');
      await initWasm();

      const provider = new WebProvider({
        rpcUrl: 'https://mainnet.subfrost.io/v4/jsonrpc',
      });

      // Fetch current DIESEL price...
      const height = await provider.call('metashrew_height', []);
      // ... rest of price fetching logic

      setPrice(calculatedPrice);
      setLoading(false);
    }

    fetchPrice();
  }, []);

  if (loading) return <div>Loading...</div>;
  return <div>DIESEL: ${price?.toFixed(4)}</div>;
}

Node.js Usage

Using alkanes-web-sys in Node.js applications:

// server.ts - Node.js usage
import { initWasm, WebProvider } from '@aspect/alkanes-web-sys';

// Initialize once at startup
let provider: WebProvider;

async function init() {
  await initWasm();
  provider = new WebProvider({
    rpcUrl: process.env.RPC_URL || 'https://mainnet.subfrost.io/v4/jsonrpc',
    dataApiUrl: process.env.DATA_API_URL || 'https://mainnet.subfrost.io/v4/api',
  });
}

// API route handler
export async function GET(request: Request) {
  if (!provider) await init();

  const height = await provider.call('metashrew_height', []);

  return Response.json({ height: parseInt(height, 10) });
}

// Express.js example
import express from 'express';

const app = express();

app.get('/api/height', async (req, res) => {
  if (!provider) await init();
  const height = await provider.call('metashrew_height', []);
  res.json({ height: parseInt(height, 10) });
});

app.listen(3000);

Troubleshooting

WASM not loading

Ensure your bundler supports WASM imports. For webpack, add the experiments.asyncWebAssembly option.

Memory errors

Large responses may exceed WASM memory limits. Process data in chunks or increase memory.

Cross-origin errors

WASM files must be served with correct CORS headers in browser environments.

Get an API Key

For production use with higher rate limits, sign up at api.subfrost.io