Pool Pricing & Candles with Lua
Learn how to fetch AMM pool reserves, calculate prices, and build OHLC candle data using Lua scripts with the Subfrost API. This guide covers both server-side Lua execution and client-side integration with alkanes-web-sys.
Overview
The Subfrost API provides powerful Lua scripting capabilities that allow you to batch multiple RPC calls into a single request. This is particularly useful for fetching historical pool data to build price charts and candles.
Key Concepts
lua_evalscript
Execute Lua scripts server-side with access to all RPC methods via the _RPC global table
metashrew_view
Query historical blockchain state at any block height using prebuilt protobuf payloads
Pool Reserves
AMM pools store token reserves (reserve_a, reserve_b) which determine the exchange rate
OHLC Candles
Open-High-Low-Close price data points aggregated over time intervals
Pool Configuration
Each pool has a unique protobuf payload used for querying its state. These payloads are generated by the alkanes-cli and can be used directly with metashrew_view:
// Pool configurations with protobuf payloads
const POOL_CONFIGS = {
DIESEL_FRBTC: {
id: '2:77087',
name: 'DIESEL/frBTC',
protobufPayload: '0x208bce382a06029fda04e7073001',
token0Decimals: 6, // DIESEL
token1Decimals: 8, // frBTC
},
DIESEL_BUSD: {
id: '2:68441',
name: 'DIESEL/bUSD',
protobufPayload: '0x208bce382a0602d99604e7073001',
token0Decimals: 6, // DIESEL
token1Decimals: 6, // bUSD
},
};Lua Script for Pool Candles
This Lua script fetches pool reserves at multiple block heights and retrieves actual block timestamps from Bitcoin block headers:
-- Pool candles: Fetch pool reserves at multiple block heights
-- Args: params[1]=pool_payload, params[2]=start_height, params[3]=end_height, params[4]=interval
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 -- Default: ~1 day
if not pool_payload or not start_height or not end_height then
return { error = "Missing required arguments" }
end
-- 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 -- 16 bytes = 32 hex chars
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 actual block timestamp from Bitcoin block header
local function get_block_timestamp(height)
local success, block_hash = pcall(function()
return _RPC.btc_getblockhash(height)
end)
if not success or not block_hash then return nil end
local success2, block = pcall(function()
return _RPC.btc_getblock(block_hash, 1)
end)
if not success2 or not block then return nil end
return block.time or block.mediantime
end
local results = { data_points = {} }
-- Query pool state at each interval
for height = start_height, end_height, interval do
local block_tag = tostring(height)
local success, response = pcall(function()
return _RPC.metashrew_view("simulate", pool_payload, block_tag)
end)
if success and response and type(response) == "string" then
local data_hex = response
if data_hex:sub(1, 2) == "0x" then
data_hex = data_hex:sub(3)
end
-- Find inner data after protobuf wrapper
local marker_pos = data_hex:find("1a")
if marker_pos then
local len_byte = tonumber(data_hex:sub(marker_pos + 2, marker_pos + 3), 16) or 0
local inner_start = marker_pos + (len_byte < 128 and 4 or 6)
if #data_hex >= inner_start + 223 then
local inner_hex = data_hex:sub(inner_start)
-- Parse reserves (at byte offsets 64, 80, 96)
local reserve_a = parse_u128_le(inner_hex, 64)
local reserve_b = parse_u128_le(inner_hex, 80)
local total_supply = parse_u128_le(inner_hex, 96)
if reserve_a and reserve_b and total_supply then
local timestamp = get_block_timestamp(height)
table.insert(results.data_points, {
height = height,
timestamp = timestamp,
reserve_a = reserve_a,
reserve_b = reserve_b,
total_supply = total_supply
})
end
end
end
end
end
results.count = #results.data_points
return resultsScript Breakdown
Calling from curl
You can execute the Lua script directly via the JSON-RPC API:
curl -X POST https://mainnet.subfrost.io/v4/jsonrpc \
-H "Content-Type: application/json" \
-d '{
"jsonrpc": "2.0",
"id": 1,
"method": "lua_evalscript",
"params": [
"<lua_script_here>",
["0x208bce382a06029fda04e7073001", "920000", "927000", "144"]
]
}'
# Response structure:
{
"jsonrpc": "2.0",
"result": {
"calls": 56,
"returns": {
"data_points": [
{ "height": 920000, "timestamp": 1733000000, "reserve_a": 1000000, "reserve_b": 50000000 },
...
],
"count": 8
},
"runtime": 1234
},
"id": 1
}JavaScript/TypeScript Integration
Here's how to call the Lua script from your application:
const RPC_URL = 'https://mainnet.subfrost.io/v4/jsonrpc';
// Or with your API key:
// const RPC_URL = 'https://mainnet.subfrost.io/v4/YOUR_API_KEY';
interface PoolDataPoint {
height: number;
timestamp?: number;
reserve0: bigint;
reserve1: bigint;
totalSupply: bigint;
}
async function fetchPoolDataPoints(
poolPayload: string,
startHeight: number,
endHeight: number,
interval: number = 144
): Promise<PoolDataPoint[]> {
const response = await fetch(RPC_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0',
id: 1,
method: 'lua_evalscript',
params: [
POOL_CANDLES_LUA_SCRIPT,
[poolPayload, startHeight.toString(), endHeight.toString(), interval.toString()],
],
}),
});
const json = await response.json();
// lua_evalscript returns { calls, returns, runtime }
const luaResult = json.result?.returns;
if (luaResult?.error) {
throw new Error(`Lua script error: ${luaResult.error}`);
}
const dataPoints = luaResult?.data_points || [];
return dataPoints.map(dp => ({
height: dp.height,
timestamp: dp.timestamp,
reserve0: BigInt(Math.floor(dp.reserve_a)),
reserve1: BigInt(Math.floor(dp.reserve_b)),
totalSupply: BigInt(Math.floor(dp.total_supply)),
}));
}Calculating Prices
Once you have the reserves, calculate the price by adjusting for token decimals:
function calculatePrice(
reserve0: bigint,
reserve1: bigint,
decimals0: number,
decimals1: number
): number {
if (reserve0 === BigInt(0)) return 0;
// Adjust for decimal places
const adjusted0 = Number(reserve0) / Math.pow(10, decimals0);
const adjusted1 = Number(reserve1) / Math.pow(10, decimals1);
// Price = reserve1 / reserve0 (how much token1 per token0)
return adjusted1 / adjusted0;
}
// Example: DIESEL/frBTC pool
const price = calculatePrice(
BigInt("1000000000"), // 1000 DIESEL (6 decimals)
BigInt("50000000"), // 0.5 frBTC (8 decimals)
6, // DIESEL decimals
8 // frBTC decimals
);
// price = 0.0000005 frBTC per DIESELBuilding Candles
Aggregate price data points into OHLC candles:
interface Candle {
timestamp: number; // Unix milliseconds
open: number;
high: number;
low: number;
close: number;
}
function buildCandles(
dataPoints: PoolDataPoint[],
decimals0: number,
decimals1: number,
candleBlocks: number = 144
): Candle[] {
if (dataPoints.length === 0) return [];
const sorted = [...dataPoints].sort((a, b) => a.height - b.height);
const candles: Candle[] = [];
let candleStartBlock = sorted[0].height;
let candleStartTimestamp = sorted[0].timestamp
? sorted[0].timestamp * 1000
: Date.now();
let candlePrices: number[] = [];
for (const dp of sorted) {
const price = calculatePrice(dp.reserve0, dp.reserve1, decimals0, decimals1);
if (dp.height >= candleStartBlock + candleBlocks) {
// Close current candle
if (candlePrices.length > 0) {
candles.push({
timestamp: candleStartTimestamp,
open: candlePrices[0],
high: Math.max(...candlePrices),
low: Math.min(...candlePrices),
close: candlePrices[candlePrices.length - 1],
});
}
// Start new candle
candleStartBlock = Math.floor(dp.height / candleBlocks) * candleBlocks;
candleStartTimestamp = dp.timestamp ? dp.timestamp * 1000 : Date.now();
candlePrices = [price];
} else {
candlePrices.push(price);
}
}
// Don't forget the last candle
if (candlePrices.length > 0) {
candles.push({
timestamp: candleStartTimestamp,
open: candlePrices[0],
high: Math.max(...candlePrices),
low: Math.min(...candlePrices),
close: candlePrices[candlePrices.length - 1],
});
}
return candles;
}Fetching Bitcoin Price
To convert token prices to USD, fetch the current Bitcoin price from the Data API:
const DATA_API_URL = 'https://mainnet.subfrost.io/v4/api';
// Or with your API key:
// const DATA_API_URL = 'https://mainnet.subfrost.io/v4/YOUR_API_KEY';
interface BitcoinPrice {
usd: number;
timestamp: number;
}
async function fetchBitcoinPrice(): Promise<BitcoinPrice> {
const response = await fetch(`${DATA_API_URL}/get-bitcoin-price`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const json = await response.json();
// Response: { statusCode: 200, data: { bitcoin: { usd: 92310.54 } } }
const usd = json.data?.bitcoin?.usd;
if (typeof usd !== 'number') {
throw new Error('Invalid BTC price response');
}
return { usd, timestamp: Date.now() };
}
// Usage
const btcPrice = await fetchBitcoinPrice();
console.log(`BTC: $${btcPrice.usd.toLocaleString()}`);DIESEL Price Metrics Example
Combine pool prices with BTC price to get comprehensive DIESEL metrics:
interface DieselPriceMetrics {
dieselFrbtcPrice: number; // DIESEL in frBTC
dieselBusdPrice: number; // DIESEL in bUSD
btcUsdPrice: number; // BTC in USD
dieselUsdViaFrbtc: number; // DIESEL in USD (calculated)
timestamp: number;
}
async function getDieselMetrics(): Promise<DieselPriceMetrics> {
// 1. Get current block height
const heightResponse = await fetch(RPC_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
jsonrpc: '2.0', id: 1, method: 'metashrew_height', params: []
}),
});
const currentHeight = parseInt((await heightResponse.json()).result, 10);
// 2. Fetch pool data for both pools (in parallel)
const [frbtcData, busdData, btcPrice] = await Promise.all([
fetchPoolDataPoints(POOL_CONFIGS.DIESEL_FRBTC.protobufPayload, currentHeight, currentHeight, 1),
fetchPoolDataPoints(POOL_CONFIGS.DIESEL_BUSD.protobufPayload, currentHeight, currentHeight, 1),
fetchBitcoinPrice(),
]);
// 3. Calculate prices
const dieselFrbtcPrice = calculatePrice(
frbtcData[0].reserve0, frbtcData[0].reserve1, 6, 8
);
const dieselBusdPrice = calculatePrice(
busdData[0].reserve0, busdData[0].reserve1, 6, 6
);
// 4. Calculate DIESEL/USD via frBTC
// frBTC is 1:1 with BTC, so: DIESEL/frBTC * BTC/USD = DIESEL/USD
const dieselUsdViaFrbtc = dieselFrbtcPrice * btcPrice.usd;
return {
dieselFrbtcPrice,
dieselBusdPrice,
btcUsdPrice: btcPrice.usd,
dieselUsdViaFrbtc,
timestamp: Date.now(),
};
}
// Usage
const metrics = await getDieselMetrics();
console.log(`DIESEL/frBTC: ${metrics.dieselFrbtcPrice.toFixed(8)}`);
console.log(`DIESEL/bUSD: ${metrics.dieselBusdPrice.toFixed(4)}`);
console.log(`BTC/USD: $${metrics.btcUsdPrice.toLocaleString()}`);
console.log(`DIESEL/USD: $${metrics.dieselUsdViaFrbtc.toFixed(4)}`);Best Practices
- Cache historical data aggressively - past block data never changes
- Use intervals of 144 blocks (~1 day) for daily candles
- Batch multiple height queries in a single Lua script call
- Handle rate limits gracefully with exponential backoff
- Store timestamps as Unix seconds from block headers for accuracy
Example Lua Scripts
Find more Lua script examples in the public/lua-examples directory:
| Script | Description |
|---|---|
| pool_candles.lua | Fetch pool reserves and build candle data |
| balances.lua | Query token balances for addresses |
| multicall.lua | Batch multiple RPC calls efficiently |
| spendable_utxos.lua | Find spendable UTXOs for an address |
Get an API Key
To use the Subfrost API in production, sign up for an API key at api.subfrost.io