Fetching Alkane Data with alkanes-web-sys
This guide explains how we fetch DIESEL token statistics, pool data, and market metrics using the alkanes-web-sys bindings and Lua scripts for optimized page loads.
Overview
The alkanes.build dashboard displays real-time data including DIESEL price, market cap, total supply, and TVL (Total Value Locked). We use a combination of:
- metashrew_view RPC calls to query alkane contract state
- Lua scripts via lua_evalscript for batched queries
- Protobuf-encoded payloads for contract method invocation
Architecture
Data flows through these layers:
┌─────────────────────────────────────────────────────────────┐
│ React Components │
│ (DieselPriceCard, VaultPerformance) │
├─────────────────────────────────────────────────────────────┤
│ React Query Hooks │
│ (usePoolPrices, useMarketStats, useTvlStats) │
├─────────────────────────────────────────────────────────────┤
│ API Routes (Next.js) │
│ /api/pools, /api/pools/stats, /api/btc-price │
├─────────────────────────────────────────────────────────────┤
│ Pool Service Layer │
│ (getDashboardStats, getDieselMarketStats) │
├─────────────────────────────────────────────────────────────┤
│ Candle Fetcher Module │
│ (fetchDieselStats, STATS_LUA_SCRIPT) │
├─────────────────────────────────────────────────────────────┤
│ Subfrost RPC (metashrew) │
│ metashrew_view, lua_evalscript, simulate │
├─────────────────────────────────────────────────────────────┤
│ Bitcoin Network │
│ (Block data, Alkane contract state) │
└─────────────────────────────────────────────────────────────┘Fetching DIESEL Total Supply
The DIESEL token is the genesis alkane at position [2, 0]. To fetch its total supply, we call the GetTotalSupply opcode (101) via metashrew_view's simulate function.
- Build a protobuf payload encoding the alkane ID and opcode
- Call metashrew_view with the 'simulate' view function
- Parse the u128 little-endian response
Building the Protobuf Payload
The payload format follows the alkanes-web-sys protobuf schema. For DIESEL's GetTotalSupply:
// lib/pools/candle-fetcher.ts
export const DIESEL_TOKEN = {
block: 2,
tx: 0,
id: '2:0',
symbol: 'DIESEL',
decimals: 8,
// Protobuf payload for GetTotalSupply opcode (101)
// Format: 0x20 <version> 2a <len> 02 <block> 00 <tx> 65 <opcode 101> 30 01
// Obtained via: mainnet-cli.sh alkanes simulate 2:0:101
totalSupplyPayload: '0x20e3ce382a030200653001',
} as const;This encodes: version byte, alkane ID [2, 0], opcode 101 (0x65), and execution flags.
Finding Opcodes with CLI
Use the alkanes CLI to discover available opcodes and generate payloads:
# Fuzz an alkane to discover valid opcodes
mainnet-cli.sh alkanes inspect 2:0 --fuzz --fuzz-ranges 0-200
# Simulate a specific opcode to get the payload
mainnet-cli.sh alkanes simulate 2:0:101
# Output shows the protobuf payload:
# Method: metashrew_view, Params: ["simulate", "0x20e3ce382a030200653001", "latest"]
# Result: 0x0a121a10a03b944b483400000000000000000000108a8803// Source: alkanes/alkanes-std-genesis-alkane/src/lib.rs
#[derive(MessageDispatch)]
enum GenesisAlkaneMessage {
#[opcode(0)]
Initialize,
#[opcode(77)]
Mint,
#[opcode(99)]
#[returns(String)]
GetName,
#[opcode(100)]
#[returns(String)]
GetSymbol,
#[opcode(101)]
#[returns(u128)]
GetTotalSupply, // <-- We use this opcode
}Parsing the Response
The response contains a protobuf wrapper with the u128 value in little-endian format:
// Response: 0x0a121a10a03b944b483400000000000000000000108a8803
// Structure: 0a <outer_len> 1a <inner_len> <u128 LE value> 10 <varint>
// The u128 value: a03b944b48340000 0000000000000000
function parseTotalSupplyResponse(resultHex: string): bigint | null {
let hex = resultHex.startsWith('0x') ? resultHex.slice(2) : resultHex;
// Find the inner data after "1a" marker
const marker1a = hex.indexOf('1a');
if (marker1a === -1) return null;
const valueStart = marker1a + 4; // Skip "1a" and length byte
const valueEnd = hex.indexOf('10', valueStart);
if (valueEnd === -1) return null;
const valueHex = hex.slice(valueStart, valueEnd).padEnd(32, '0');
// Reverse byte pairs for little-endian
let reversed = '';
for (let i = valueHex.length - 2; i >= 0; i -= 2) {
reversed += valueHex.slice(i, i + 2);
}
return BigInt('0x' + reversed);
}
// Result: 57485110295456n (574,851.10 DIESEL with 8 decimals)Fetching Pool Data
AMM pool reserves are fetched by calling opcode 1000 on pool contracts. Each pool returns:
reserve0– Amount of token0 (e.g., DIESEL)reserve1– Amount of token1 (e.g., frBTC)totalSupply– LP token total supply
Pool payloads follow the same pattern with different alkane IDs:
// Pool alkane IDs and payloads
export const POOL_CONFIGS = {
DIESEL_FRBTC: {
id: '79247:0', // Alkane ID [79247, 0]
payload: '0x2096ce382a06029fda04e7073001', // opcode 1000
token0: { symbol: 'DIESEL', decimals: 8 },
token1: { symbol: 'frBTC', decimals: 8 },
},
DIESEL_BUSD: {
id: '76505:0', // Alkane ID [76505, 0]
payload: '0x2096ce382a0602d99604e7073001', // opcode 1000
token0: { symbol: 'DIESEL', decimals: 8 },
token1: { symbol: 'bUSD', decimals: 8 },
},
} as const;Optimized Fetching with Lua Scripts
To minimize RPC round-trips, we use a Lua script that fetches all data in a single call:
export const STATS_LUA_SCRIPT = `
-- Fetch DIESEL stats and pool TVL in a single call
local results = {
diesel = {},
pools = {},
height = 0
}
-- Helper to parse little-endian u128 from hex string
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
-- 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 DIESEL/frBTC pool reserves
local frbtc_response = _RPC.metashrew_view(
"simulate",
"0x2096ce382a06029fda04e7073001",
"latest"
)
if frbtc_response then
-- Parse reserves from response
results.pools.DIESEL_FRBTC = {
reserve_a = parse_u128_le(inner_hex, 64),
reserve_b = parse_u128_le(inner_hex, 80),
total_supply = parse_u128_le(inner_hex, 96)
}
end
-- Fetch DIESEL/bUSD pool reserves
local busd_response = _RPC.metashrew_view(
"simulate",
"0x2096ce382a0602d99604e7073001",
"latest"
)
-- ... parse similarly
return cjson.encode(results)
`;Advantages of Lua scripts:
- Single RPC call instead of multiple parallel calls
- Atomic snapshot of data at the same block height
- Server-side JSON encoding for efficient response
The Lua script is executed via lua_evalscript:
const response = await fetch(rpcUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'lua_evalscript',
params: [STATS_LUA_SCRIPT],
}),
});
const json = await response.json();
const luaResult = JSON.parse(json.result);
// luaResult contains:
// {
// diesel: { total_supply: 57485110295456 },
// pools: {
// DIESEL_FRBTC: { reserve_a: 259032503803, reserve_b: 12392199, total_supply: 1719377281 },
// DIESEL_BUSD: { reserve_a: 378956334102, reserve_b: 1630422433262, total_supply: ... }
// },
// height: 927587
// }Price and TVL Calculations
With the fetched data, we calculate:
DIESEL Price
Calculated from pool reserves using the constant product formula:
// DIESEL price in frBTC (from DIESEL/frBTC pool)
const dieselPriceBtc = reserve1 / reserve0;
// = 12392199 / 259032503803 = 0.00004784 BTC
// DIESEL price in USD
const dieselPriceUsd = dieselPriceBtc * btcPriceUsd;
// = 0.00004784 * 92146.60 = $4.41Total Value Locked
Sum of both sides of each pool valued in USD:
// TVL = both sides of pool valued in USD
// For constant product AMM, both sides have equal value
export function calculatePoolTvl(
reserve0: bigint,
reserve1: bigint,
decimals0: number,
decimals1: number,
token1PriceUsd: number
): { tvlToken0: number; tvlToken1: number; tvlUsd: number } {
const tvlToken0 = Number(reserve0) / Math.pow(10, decimals0);
const tvlToken1 = Number(reserve1) / Math.pow(10, decimals1);
// TVL = 2 * value of one side (both sides equal in constant product)
const tvlUsd = tvlToken1 * token1PriceUsd * 2;
return { tvlToken0, tvlToken1, tvlUsd };
}
// DIESEL/frBTC: 2 * 0.124 BTC * $92,146 = $22,838
// DIESEL/bUSD: 2 * 16,304 bUSD * $1 = $32,608
// Total TVL: $55,446Market Cap
Total supply multiplied by current price:
const totalSupply = 574851.10; // DIESEL (with 8 decimals applied)
const priceUsd = 4.41;
const marketCap = totalSupply * priceUsd;
// = 574,851.10 * 4.41 = $2,535,093Integration in Next.js
The data fetching is implemented in lib/pools/candle-fetcher.ts and lib/pools/pool-service.ts:
// Optimized: Single Lua script call for all data
export async function getDashboardStats(): Promise<DashboardStats> {
const cacheKey = 'dashboard:stats';
// Try cache first
const cached = await cacheGet<SerializedDashboardStats>(cacheKey);
if (cached) return deserialize(cached);
// Fetch all data with single Lua script call
const [stats, btcPrice] = await Promise.all([
fetchDieselStats(config), // Lua script: DIESEL supply + both pools
getBitcoinPrice(), // External API call
]);
// Calculate market stats
const dieselPriceBtc = calculatePrice(
stats.pools.DIESEL_FRBTC.reserve0,
stats.pools.DIESEL_FRBTC.reserve1,
8, 8
);
const dieselPriceUsd = dieselPriceBtc * btcPrice.usd;
const totalSupplyFormatted = Number(stats.dieselTotalSupply) / 1e8;
const marketCapUsd = totalSupplyFormatted * dieselPriceUsd;
// Calculate TVL for each pool
const tvlFrbtc = calculatePoolTvl(..., btcPrice.usd);
const tvlBusd = calculatePoolTvl(..., 1); // bUSD = $1
const totalTvlUsd = tvlFrbtc.tvlUsd + tvlBusd.tvlUsd;
// Cache and return
await cacheSet(cacheKey, serialize(result), CACHE_TTL_STATS);
return result;
}Caching Strategy
Results are cached in Redis with appropriate TTLs:
- Pool prices: 30 seconds
- Market stats: 60 seconds
- TVL stats: 60 seconds
- BTC price: 60 seconds
Testing
Integration tests verify the data fetching works correctly against live RPC:
describe("Live DIESEL Stats Integration Tests", () => {
it("should fetch DIESEL total supply via metashrew_view", async () => {
const totalSupply = await getDieselTotalSupply(rpcConfig);
expect(totalSupply).toBeGreaterThan(BigInt(0));
const formatted = Number(totalSupply) / 1e8;
expect(formatted).toBeGreaterThan(500000); // ~574,851 DIESEL
});
it("should fetch all stats in a single RPC call", async () => {
const stats = await fetchDieselStats(rpcConfig);
expect(stats.dieselTotalSupply).toBeGreaterThan(BigInt(0));
expect(stats.pools.DIESEL_FRBTC).not.toBeNull();
expect(stats.pools.DIESEL_BUSD).not.toBeNull();
expect(stats.height).toBeGreaterThan(900000);
});
it("should calculate all dashboard stats correctly", async () => {
const stats = await fetchDieselStats(rpcConfig);
const btcPrice = await fetchBitcoinPrice(priceConfig);
// Verify all values
expect(dieselPriceUsd).toBeGreaterThan(0);
expect(marketCapUsd).toBeGreaterThan(0);
expect(totalTvlUsd).toBeGreaterThan(0);
});
});
// Run with: RUN_INTEGRATION=true pnpm vitest run tests/integration/live-rpc.test.tsResources
- alkanes-rs GitHub - Alkanes protocol implementation
- alkanes-std-genesis-alkane - DIESEL token source code
- Subfrost API - Hosted RPC endpoint