@alkanes/ts-sdk API Reference

Complete TypeScript SDK reference for the Alkanes protocol

The @alkanes/ts-sdk provides a unified TypeScript interface for interacting with the Alkanes protocol. This page documents all available classes and their methods.

AlkanesProvider

The main entry point for all SDK functionality. Provides access to all sub-clients after initialization.

Basic usage:
import { AlkanesProvider } from '@alkanes/ts-sdk';

const provider = new AlkanesProvider({
  network: 'mainnet',           // 'mainnet' | 'testnet' | 'signet' | 'regtest' | 'local'
  rpcUrl?: string,              // Optional: Override RPC URL
  dataApiUrl?: string,          // Optional: Override Data API URL
  bitcoinNetwork?: Network,     // Optional: Custom bitcoinjs-lib network
});

// IMPORTANT: Must initialize before using
await provider.initialize();

// Access sub-clients
provider.esplora      // EsploraClient
provider.alkanes      // AlkanesRpcClient
provider.metashrew    // MetashrewClient
provider.lua          // LuaClient
provider.dataApi      // DataApiClient
provider.espo         // EspoClient
provider.bitcoin      // BitcoinRpcClient

Properties

PropertyTypeDescription
rpcUrlstringThe JSON-RPC endpoint URL
dataApiUrlstringThe Data API endpoint URL
networkNetworkbitcoinjs-lib network object
networkTypestringNetwork type: mainnet, testnet, signet, regtest
networkPresetstringThe network preset name used

Methods

initialize()

async initialize(): Promise<void>

Initialize the provider by loading the WASM module. Must be called before using any sub-clients.

Returns: Promise<void>
Example:
const provider = new AlkanesProvider({ network: 'mainnet' });
await provider.initialize();
// Now ready to use

getProvider()

async getProvider(): Promise<WebProvider>

Get the underlying WASM WebProvider instance. Automatically initializes if needed.

Returns: Promise<WebProvider> - The WASM provider instance

getBlockHeight()

async getBlockHeight(): Promise<number>

Convenience method to get the current blockchain height.

Returns: Promise<number> - Current block height
Example:
const height = await provider.getBlockHeight();
console.log('Current height:', height); // e.g., 927618

Typed Transaction Methods

alkanesExecuteTyped()

async alkanesExecuteTyped(params: {
  toAddresses: string[];
  inputRequirements: string;
  protostones: string;
  feeRate?: number;
  envelopeHex?: string;
  fromAddresses?: string[];
  changeAddress?: string;
  traceEnabled?: boolean;
  mineEnabled?: boolean;
  autoConfirm?: boolean;
}): Promise<TransactionBroadcast>

Execute an Alkanes contract call with full type safety. Returns a TransactionBroadcast object with transaction() for immediate tx info and receipt() for lazy-loaded traces.

Parameters:
  • toAddresses (string[]) – Recipient addresses
  • inputRequirements (string) – Token inputs required (e.g., '2:0:1000000')
  • protostones (string) – Protostone call format (e.g., '[2,0,77]:v0:v0')
  • feeRate (number) – Fee rate in sat/vB
  • envelopeHex (string) – WASM bytecode hex for contract deploy
  • traceEnabled (boolean) – Enable execution tracing
  • mineEnabled (boolean) – Auto-mine block (regtest only)
Returns: Promise<TransactionBroadcast> - { transaction(): Transaction, receipt(): Promise<Trace[]> }
Example:
const broadcast = await provider.alkanesExecuteTyped({
  toAddresses: [walletAddress],
  inputRequirements: '',
  protostones: '[2,0,77]:v0:v0',  // Mint DIESEL
  feeRate: 1,
  traceEnabled: true,
  mineEnabled: true,
});
const tx = broadcast.transaction();
console.log('TXID:', tx.txid);
const traces = await broadcast.receipt();

frbtcWrapTyped()

async frbtcWrapTyped(params: {
  amount: bigint | number;
  toAddress: string;
  fromAddress?: string;
  changeAddress?: string;
  feeRate?: number;
  traceEnabled?: boolean;
  mineEnabled?: boolean;
  autoConfirm?: boolean;
}): Promise<TransactionResult>

Wrap BTC to frBTC (the wrapped Bitcoin token on Alkanes). Essential for participating in Alkanes DeFi.

Parameters:
  • amount (bigint | number) – Amount in satoshis to wrap
  • toAddress (string) – Recipient address for frBTC
  • fromAddress (string) – Source address for BTC
  • feeRate (number) – Fee rate in sat/vB
  • mineEnabled (boolean) – Auto-mine block (regtest only)
Returns: Promise<TransactionResult> - Transaction details with txid
Example:
const result = await provider.frbtcWrapTyped({
  amount: BigInt(100000000), // 1 BTC
  toAddress: walletAddress,
  feeRate: 1,
  mineEnabled: true,
});
console.log('Wrapped! TXID:', result.reveal_txid);

alkanesInitPoolTyped()

async alkanesInitPoolTyped(params: {
  factoryId: { block: number; tx: number };
  token0: { block: number; tx: number };
  token1: { block: number; tx: number };
  amount0: string | number | bigint;
  amount1: string | number | bigint;
  minimumLp?: string | number | bigint;
  toAddress: string;
  fromAddress?: string;
  feeRate?: number;
  trace?: boolean;
  autoConfirm?: boolean;
}): Promise<string>

Initialize a new AMM liquidity pool with two tokens.

Parameters:
  • factoryId (AlkaneId) – AMM Factory contract ID
  • token0 (AlkaneId) – First token of the pair
  • token1 (AlkaneId) – Second token of the pair
  • amount0 (string) – Initial amount of token0
  • amount1 (string) – Initial amount of token1
  • minimumLp (string) – Minimum LP tokens (slippage protection)
Returns: Promise<string> - Transaction ID
Example:
const txid = await provider.alkanesInitPoolTyped({
  factoryId: { block: 4, tx: 65522 },
  token0: { block: 2, tx: 0 },    // DIESEL
  token1: { block: 32, tx: 0 },   // frBTC
  amount0: '300000000',
  amount1: '50000',
  toAddress: walletAddress,
  feeRate: 1,
});

alkanesSwapTyped()

async alkanesSwapTyped(params: {
  factoryId: { block: number; tx: number };
  path: Array<{ block: number; tx: number }>;
  inputAmount: string | number | bigint;
  minimumOutput: string | number | bigint;
  expires: number;
  toAddress: string;
  fromAddress?: string;
  feeRate?: number;
  trace?: boolean;
  autoConfirm?: boolean;
}): Promise<string>

Execute a token swap through AMM pools. Supports multi-hop routing.

Parameters:
  • factoryId (AlkaneId) – AMM Factory contract ID
  • path (AlkaneId[]) – Swap path from input to output token
  • inputAmount (string) – Amount of input token to swap
  • minimumOutput (string) – Minimum acceptable output (slippage protection)
  • expires (number) – Expiration block height
Returns: Promise<string> - Transaction ID
Example:
const txid = await provider.alkanesSwapTyped({
  factoryId: { block: 4, tx: 65522 },
  path: [
    { block: 2, tx: 0 },   // DIESEL (in)
    { block: 32, tx: 0 },  // frBTC (out)
  ],
  inputAmount: '100000000',
  minimumOutput: '10',
  expires: currentHeight + 10,
  toAddress: walletAddress,
  feeRate: 1,
});

EsploraClient

Client for Esplora-compatible Bitcoin block explorer API. Provides UTXO data, transaction information, and address balances.

Accessed via provider.esplora

getAddressUtxos()

async getAddressUtxos(address: string): Promise<UTXO[]>

Get all UTXOs for a Bitcoin address. Essential for calculating BTC balance and building transactions.

Parameters:
  • address (string) – Bitcoin address (any format)
Returns: Promise<UTXO[]> - Array of unspent transaction outputs
Example:
const utxos = await provider.esplora.getAddressUtxos('bc1q...');
const balance = utxos.reduce((sum, u) => sum + u.value, 0);
console.log('Balance:', balance, 'sats');

getAddressInfo()

async getAddressInfo(address: string): Promise<AddressInfo>

Get aggregated address information including transaction count and balances.

Parameters:
  • address (string) – Bitcoin address
Returns: Promise<AddressInfo> - Address statistics and balances

getAddressTxs()

async getAddressTxs(address: string): Promise<Transaction[]>

Get transaction history for an address.

Parameters:
  • address (string) – Bitcoin address
Returns: Promise<Transaction[]> - Array of transactions

getTx()

async getTx(txid: string): Promise<Transaction>

Get detailed transaction information by txid.

Parameters:
  • txid (string) – Transaction ID (hex)
Returns: Promise<Transaction> - Transaction details

getTxStatus()

async getTxStatus(txid: string): Promise<TxStatus>

Get confirmation status of a transaction.

Parameters:
  • txid (string) – Transaction ID
Returns: Promise<TxStatus> - Confirmation status and block info

getTxHex()

async getTxHex(txid: string): Promise<string>

Get raw transaction hex.

Parameters:
  • txid (string) – Transaction ID
Returns: Promise<string> - Raw transaction hex

getBlocksTipHeight()

async getBlocksTipHeight(): Promise<number>

Get the current blockchain tip height.

Returns: Promise<number> - Current block height

getBlocksTipHash()

async getBlocksTipHash(): Promise<string>

Get the current blockchain tip block hash.

Returns: Promise<string> - Block hash (hex)

broadcastTx()

async broadcastTx(txHex: string): Promise<string>

Broadcast a signed transaction to the network.

Parameters:
  • txHex (string) – Signed transaction hex
Returns: Promise<string> - Transaction ID if successful

AlkanesRpcClient

Client for Alkanes-specific RPC methods. Handles token balances, contract simulation, and protocol operations.

Accessed via provider.alkanes

getBalance()

async getBalance(address: string): Promise<AlkaneBalance[]>

Get all Alkane token balances for an address. Internally uses the protorunesbyaddress view function.

Parameters:
  • address (string) – Bitcoin address
Returns: Promise<AlkaneBalance[]> - Array of token balances
Example:
const balances = await provider.alkanes.getBalance('bc1q...');
for (const b of balances) {
  const id = `${b.alkane_id.block}:${b.alkane_id.tx}`;
  console.log(`${id}: ${b.balance}`);
}

getByAddress()

async getByAddress(address: string, blockTag?: string, protocolTag?: number): Promise<OutpointBalances>

Get detailed balance information by address with outpoint data. Returns balance sheets per UTXO.

Parameters:
  • address (string) – Bitcoin address
  • blockTag (string) – Block height or 'latest'
  • protocolTag (number) – Protocol tag (default: 1 for Alkanes)
Returns: Promise<OutpointBalances> - Balances organized by outpoint

getByOutpoint()

async getByOutpoint(outpoint: Outpoint, blockTag?: string, protocolTag?: number): Promise<BalanceSheet>

Get balance sheet for a specific UTXO outpoint.

Parameters:
  • outpoint (Outpoint) – { txid: string, vout: number }
  • blockTag (string) – Block height or 'latest'
  • protocolTag (number) – Protocol tag (default: 1)
Returns: Promise<BalanceSheet> - Token balances on the outpoint

getBytecode()

async getBytecode(alkaneId: AlkaneId, blockTag?: string): Promise<string>

Get the WASM bytecode of an Alkane contract.

Parameters:
  • alkaneId (AlkaneId) – { block: number, tx: number }
  • blockTag (string) – Block height or 'latest'
Returns: Promise<string> - Contract bytecode (hex)

simulate()

async simulate(contractId: AlkaneId, contextJson: string, blockTag?: string): Promise<SimulateResult>

Simulate a contract call without broadcasting. Used for read operations and gas estimation.

Parameters:
  • contractId (AlkaneId) – Target contract ID
  • contextJson (string) – JSON-encoded call context
  • blockTag (string) – Block height or 'latest'
Returns: Promise<SimulateResult> - Simulation result with return data
Example:
// Simulate a pool reserves query
const result = await provider.alkanes.simulate(
  { block: 2, tx: 77087 },
  JSON.stringify({ opcode: 101 }),  // getReserves
  'latest'
);

execute()

async execute(paramsJson: string): Promise<ExecuteResult>

Build a transaction that executes a contract call.

Parameters:
  • paramsJson (string) – JSON-encoded execution parameters
Returns: Promise<ExecuteResult> - Transaction data for signing

trace()

async trace(outpoint: Outpoint): Promise<TraceResult>

Trace the history of tokens on an outpoint.

Parameters:
  • outpoint (Outpoint) – { txid: string, vout: number }
Returns: Promise<TraceResult> - Token transfer history

view()

async view(contractId: AlkaneId, viewFn: string, params: unknown[], blockTag?: string): Promise<unknown>

Call a view function on a contract.

Parameters:
  • contractId (AlkaneId) – Target contract ID
  • viewFn (string) – View function name
  • params (unknown[]) – Function parameters
  • blockTag (string) – Block height or 'latest'
Returns: Promise<unknown> - View function result

getAllPools()

async getAllPools(factoryId?: AlkaneId): Promise<AlkaneId[]>

Get all AMM pools from a factory contract.

Parameters:
  • factoryId (AlkaneId) – Factory contract ID (optional)
Returns: Promise<AlkaneId[]> - Array of pool contract IDs

getAllPoolsWithDetails()

async getAllPoolsWithDetails(factoryId?: AlkaneId, chunkSize?: number, maxConcurrent?: number): Promise<PoolDetails[]>

Get all pools with their reserve and token details.

Parameters:
  • factoryId (AlkaneId) – Factory contract ID
  • chunkSize (number) – Batch size for queries
  • maxConcurrent (number) – Max concurrent requests
Returns: Promise<PoolDetails[]> - Array of pool details with reserves

getPendingUnwraps()

async getPendingUnwraps(blockTag?: string): Promise<PendingUnwrap[]>

Get pending BTC unwrap requests from the frBTC contract.

Parameters:
  • blockTag (string) – Block height or 'latest'
Returns: Promise<PendingUnwrap[]> - Array of pending unwrap requests

MetashrewClient

Low-level client for metashrew_view RPC calls. Provides direct access to indexer state queries.

Accessed via provider.metashrew

getHeight()

async getHeight(): Promise<number>

Get the current indexed blockchain height from the metashrew indexer.

Returns: Promise<number> - Current indexed height
Example:
const height = await provider.metashrew.getHeight();
console.log('Indexed height:', height);

getStateRoot()

async getStateRoot(height?: number): Promise<string>

Get the state root hash at a specific height.

Parameters:
  • height (number) – Block height (optional, defaults to latest)
Returns: Promise<string> - State root hash (hex)

getBlockHash()

async getBlockHash(height: number): Promise<string>

Get block hash at a specific height.

Parameters:
  • height (number) – Block height
Returns: Promise<string> - Block hash (hex)

view()

async view(viewFn: string, payload: string, blockTag?: string): Promise<string>

Execute a metashrew_view call. This is the low-level method for querying indexer state.

Parameters:
  • viewFn (string) – View function name (e.g., 'simulate', 'protorunesbyaddress')
  • payload (string) – Hex-encoded protobuf payload
  • blockTag (string) – Block height or 'latest'
Returns: Promise<string> - Hex-encoded response
Example:
// Query pool reserves
const response = await provider.metashrew.view(
  'simulate',
  '0x2096ce382a06029fda04e7073001',  // DIESEL/frBTC pool
  'latest'
);
// Parse the hex response...

LuaClient

Client for executing Lua scripts on the server. Supports automatic scripthash caching for improved performance.

Accessed via provider.lua

eval()

async eval(script: string, args?: unknown[]): Promise<LuaResult>

Execute a Lua script with automatic scripthash caching. This is the recommended method for Lua execution. It computes the SHA256 hash of the script and tries the cached version first (lua_evalsaved), falling back to full execution (lua_evalscript) if not cached.

Parameters:
  • script (string) – Lua script content
  • args (unknown[]) – Arguments passed to the script as 'args' global
Returns: Promise<LuaResult> - { calls: number, returns: any, runtime: number }
Example:
const result = await provider.lua.eval(`
  local height = tonumber(_RPC.metashrew_height()) or 0
  local params = args[1] or {}
  return {
    height = height,
    address = params[1]
  }
`, [['bc1q...']]);

console.log('Height:', result.returns.height);
console.log('RPC calls:', result.calls);
console.log('Runtime:', result.runtime, 'ms');

evalScript()

async evalScript(script: string): Promise<LuaResult>

Execute a Lua script directly without caching. Use this only when you need to bypass the scripthash cache (e.g., for one-time scripts).

Parameters:
  • script (string) – Lua script content
Returns: Promise<LuaResult> - { calls: number, returns: any, runtime: number }

DataApiClient

Client for the Data API endpoints. Provides market data, pool information, candles, and holder statistics.

Accessed via provider.dataApi

Market Data

getBitcoinPrice()

async getBitcoinPrice(): Promise<BitcoinPrice>

Get the current Bitcoin price in USD.

Returns: Promise<BitcoinPrice> - { usd: number, ... }
Example:
const price = await provider.dataApi.getBitcoinPrice();
console.log('BTC Price:', '$' + price.usd.toLocaleString());

getBitcoinMarketChart()

async getBitcoinMarketChart(days: number): Promise<MarketChart>

Get historical Bitcoin price data.

Parameters:
  • days (number) – Number of days of history
Returns: Promise<MarketChart> - Historical price data

Pool Data

getPools()

async getPools(factoryId?: string): Promise<Pool[]>

Get all pools from the data API.

Parameters:
  • factoryId (string) – Filter by factory (optional)
Returns: Promise<Pool[]> - Array of pool data

getReserves()

async getReserves(pool: string): Promise<Reserves>

Get current reserves for a pool.

Parameters:
  • pool (string) – Pool ID (e.g., '2:77087')
Returns: Promise<Reserves> - { reserve0: bigint, reserve1: bigint, ... }

getCandles()

async getCandles(pool: string, interval: string, startTime: number, endTime: number, limit?: number): Promise<Candle[]>

Get OHLCV candle data for a pool.

Parameters:
  • pool (string) – Pool ID
  • interval (string) – Candle interval (e.g., '1h', '1d')
  • startTime (number) – Start timestamp (seconds)
  • endTime (number) – End timestamp (seconds)
  • limit (number) – Max candles to return
Returns: Promise<Candle[]> - OHLCV data

getTrades()

async getTrades(pool: string, startTime?: number, endTime?: number, limit?: number): Promise<Trade[]>

Get trade history for a pool.

Parameters:
  • pool (string) – Pool ID
  • startTime (number) – Start timestamp (optional)
  • endTime (number) – End timestamp (optional)
  • limit (number) – Max trades to return
Returns: Promise<Trade[]> - Array of trades

Pool History

getPoolHistory()

async getPoolHistory(poolId: string, category: string, limit?: number, offset?: number): Promise<HistoryEntry[]>

Get pool history by category (swap, mint, burn, all).

Parameters:
  • poolId (string) – Pool ID
  • category (string) – 'swap' | 'mint' | 'burn' | 'all'
  • limit (number) – Max entries
  • offset (number) – Pagination offset
Returns: Promise<HistoryEntry[]> - History entries

getSwapHistory()

async getSwapHistory(poolId: string, limit?: number, offset?: number): Promise<SwapEntry[]>

Get swap history for a pool.

Parameters:
  • poolId (string) – Pool ID
  • limit (number) – Max entries
  • offset (number) – Pagination offset
Returns: Promise<SwapEntry[]> - Swap entries

getMintHistory()

async getMintHistory(poolId: string, limit?: number, offset?: number): Promise<MintEntry[]>

Get liquidity mint history for a pool.

Parameters:
  • poolId (string) – Pool ID
  • limit (number) – Max entries
  • offset (number) – Pagination offset
Returns: Promise<MintEntry[]> - Mint entries

getBurnHistory()

async getBurnHistory(poolId: string, limit?: number, offset?: number): Promise<BurnEntry[]>

Get liquidity burn history for a pool.

Parameters:
  • poolId (string) – Pool ID
  • limit (number) – Max entries
  • offset (number) – Pagination offset
Returns: Promise<BurnEntry[]> - Burn entries

Balance & Token Data

getAlkanesByAddress()

async getAlkanesByAddress(address: string): Promise<AlkaneBalance[]>

Get Alkane token balances for an address via the Data API.

Parameters:
  • address (string) – Bitcoin address
Returns: Promise<AlkaneBalance[]> - Token balances

getAddressBalances()

async getAddressBalances(address: string, includeOutpoints?: boolean): Promise<AddressBalances>

Get comprehensive address balances.

Parameters:
  • address (string) – Bitcoin address
  • includeOutpoints (boolean) – Include per-UTXO breakdown
Returns: Promise<AddressBalances> - Balance data

getHolders()

async getHolders(alkane: string, page?: number, limit?: number): Promise<Holder[]>

Get token holder list for an Alkane.

Parameters:
  • alkane (string) – Alkane ID (e.g., '2:0')
  • page (number) – Page number (0-indexed)
  • limit (number) – Results per page
Returns: Promise<Holder[]> - Array of holders

getHoldersCount()

async getHoldersCount(alkane: string): Promise<number>

Get total number of holders for an Alkane.

Parameters:
  • alkane (string) – Alkane ID
Returns: Promise<number> - Holder count

getKeys()

async getKeys(alkane: string, prefix: string, limit?: number): Promise<string[]>

Get storage keys for an Alkane contract.

Parameters:
  • alkane (string) – Alkane ID
  • prefix (string) – Key prefix filter
  • limit (number) – Max keys to return
Returns: Promise<string[]> - Array of storage keys

EspoClient

Client for the Espo indexer. Provides alkanes data and AMM analytics through two modules: Essentials (balances, holders, storage) and AMM Data (candles, trades, pools, swap routing).

Accessed via provider.espo

Essentials Module

ping()

async ping(): Promise<string>

Ping the Espo server to check connectivity.

Returns: Promise<string> - 'pong'
Example:
const response = await provider.espo.ping();
console.log(response); // 'pong'

getHeight()

async getHeight(): Promise<number>

Get the current block height processed by the Espo indexer.

Returns: Promise<number> - Current indexer height
Example:
const height = await provider.espo.getHeight();
console.log('Espo height:', height);

getAddressBalances()

async getAddressBalances(address: string, includeOutpoints?: boolean): Promise<any>

Get alkanes balances for a Bitcoin address with optional outpoint details.

Parameters:
  • address (string) – Bitcoin address
  • includeOutpoints (boolean) – Include detailed UTXO information (default: false)
Returns: Promise<any> - Balance data with optional outpoint breakdown
Example:
const balances = await provider.espo.getAddressBalances('bc1q...', true);
console.log(balances.balances); // { '840000:1': '1000000', ... }
console.log(balances.outpoints); // [{ outpoint: 'txid:0', entries: [...] }]

getAddressOutpoints()

async getAddressOutpoints(address: string): Promise<any>

Get all outpoints containing alkanes for an address.

Parameters:
  • address (string) – Bitcoin address
Returns: Promise<any> - Array of outpoints with alkane entries

getOutpointBalances()

async getOutpointBalances(outpoint: string): Promise<any>

Get alkanes balances at a specific UTXO outpoint.

Parameters:
  • outpoint (string) – Outpoint in format 'txid:vout'
Returns: Promise<any> - Alkane balances at the outpoint

getHolders()

async getHolders(alkaneId: string, page?: number, limit?: number): Promise<any>

Get paginated list of holders for an alkane token.

Parameters:
  • alkaneId (string) – Alkane ID in format 'block:tx'
  • page (number) – Page number (default: 0)
  • limit (number) – Items per page (default: 100)
Returns: Promise<any> - Paginated holder data
Example:
const holders = await provider.espo.getHolders('840000:1', 0, 50);
console.log('Total holders:', holders.total);
console.log('Page:', holders.items);

getHoldersCount()

async getHoldersCount(alkaneId: string): Promise<number>

Get the total number of unique holders for an alkane token.

Parameters:
  • alkaneId (string) – Alkane ID in format 'block:tx'
Returns: Promise<number> - Total holder count

getKeys()

async getKeys(alkaneId: string, page?: number, limit?: number): Promise<any>

Get storage keys for an alkane contract with pagination and UTF-8 decoding.

Parameters:
  • alkaneId (string) – Alkane ID in format 'block:tx'
  • page (number) – Page number (default: 0)
  • limit (number) – Items per page (default: 100)
Returns: Promise<any> - Paginated storage keys

AMM Data Module

ammdataPing()

async ammdataPing(): Promise<string>

Ping the AMM Data module to check connectivity.

Returns: Promise<string> - 'pong'

getCandles()

async getCandles(pool: string, timeframe?: string, side?: string, limit?: number, page?: number): Promise<any>

Get OHLCV candlestick data for a liquidity pool.

Parameters:
  • pool (string) – Pool ID in format 'block:tx'
  • timeframe (string) – Candle interval: '10m', '1h', '1d', '1w', '1M'
  • side (string) – Price side: 'base' or 'quote'
  • limit (number) – Number of candles (default: 100)
  • page (number) – Page number (default: 0)
Returns: Promise<any> - OHLCV candlestick data
Example:
const candles = await provider.espo.getCandles(
  '840100:5',
  '1h',
  'base',
  100,
  0
);
console.log(candles.candles); // [{ open, high, low, close, volume, ... }]

getTrades()

async getTrades(pool: string, limit?: number, page?: number, side?: string, filterSide?: string, sort?: string, dir?: string): Promise<any>

Get trade history for a pool with comprehensive filtering and sorting.

Parameters:
  • pool (string) – Pool ID in format 'block:tx'
  • limit (number) – Number of trades (default: 100)
  • page (number) – Page number (default: 0)
  • side (string) – Price side: 'base' or 'quote'
  • filterSide (string) – Filter by trade side: 'buy', 'sell', or 'all'
  • sort (string) – Sort field
  • dir (string) – Sort direction: 'asc' or 'desc'
Returns: Promise<any> - Paginated trade history

getPools()

async getPools(limit?: number, page?: number): Promise<any>

Get all AMM pools with pagination.

Parameters:
  • limit (number) – Number of pools (default: 100)
  • page (number) – Page number (default: 0)
Returns: Promise<any> - Paginated pool data

findBestSwapPath()

async findBestSwapPath(tokenIn: string, tokenOut: string, mode?: string, amountIn?: string, amountOut?: string, amountOutMin?: string, amountInMax?: string, availableIn?: string, feeBps?: number, maxHops?: number): Promise<any>

Find the optimal multi-hop swap path between two tokens using advanced routing algorithms.

Parameters:
  • tokenIn (string) – Input token ID
  • tokenOut (string) – Output token ID
  • mode (string) – Swap mode: 'exact_in', 'exact_out', or 'implicit'
  • amountIn (string) – Input amount (for exact_in mode)
  • amountOut (string) – Output amount (for exact_out mode)
  • amountOutMin (string) – Minimum acceptable output
  • amountInMax (string) – Maximum acceptable input
  • availableIn (string) – Available input amount
  • feeBps (number) – Fee in basis points (e.g., 30 = 0.3%)
  • maxHops (number) – Maximum number of hops (default: 3)
Returns: Promise<any> - Optimal swap route with hops and amounts
Example:
const path = await provider.espo.findBestSwapPath(
  '840000:1',
  '840000:2',
  'exact_in',
  '1000000',
  undefined,
  '900000',
  undefined,
  undefined,
  30,
  3
);
console.log('Amount out:', path.amount_out);
console.log('Hops:', path.hops);

getBestMevSwap()

async getBestMevSwap(token: string, feeBps?: number, maxHops?: number): Promise<any>

Find the best MEV (Maximal Extractable Value) arbitrage opportunity for a token across all available pools.

Parameters:
  • token (string) – Token ID to find arbitrage for
  • feeBps (number) – Fee in basis points (default: 30)
  • maxHops (number) – Maximum number of hops (default: 3)
Returns: Promise<any> - Best MEV opportunity with profit calculation
Example:
const mev = await provider.espo.getBestMevSwap('840000:1', 30, 3);
if (mev.profit > 0) {
  console.log('Profit:', mev.profit);
  console.log('Route:', mev.hops);
}

BitcoinRpcClient

Client for Bitcoin Core RPC methods. Provides block data, transaction broadcasting, and network information.

Accessed via provider.bitcoin

getBlockCount()

async getBlockCount(): Promise<number>

Get the current block count from Bitcoin Core.

Returns: Promise<number> - Block count

getBlockHash()

async getBlockHash(height: number): Promise<string>

Get block hash at a specific height.

Parameters:
  • height (number) – Block height
Returns: Promise<string> - Block hash

getBlock()

async getBlock(hash: string, raw?: boolean): Promise<Block>

Get block data by hash.

Parameters:
  • hash (string) – Block hash
  • raw (boolean) – Return raw hex instead of parsed
Returns: Promise<Block> - Block data

sendRawTransaction()

async sendRawTransaction(hex: string): Promise<string>

Broadcast a raw transaction.

Parameters:
  • hex (string) – Signed transaction hex
Returns: Promise<string> - Transaction ID

getTransaction()

async getTransaction(txid: string, blockHash?: string): Promise<Transaction>

Get transaction details.

Parameters:
  • txid (string) – Transaction ID
  • blockHash (string) – Block hash hint (optional)
Returns: Promise<Transaction> - Transaction data

getBlockchainInfo()

async getBlockchainInfo(): Promise<BlockchainInfo>

Get blockchain state information.

Returns: Promise<BlockchainInfo> - Chain info including sync status

getNetworkInfo()

async getNetworkInfo(): Promise<NetworkInfo>

Get network peer information.

Returns: Promise<NetworkInfo> - Network connectivity info

getMempoolInfo()

async getMempoolInfo(): Promise<MempoolInfo>

Get mempool statistics.

Returns: Promise<MempoolInfo> - Mempool size and fee info

estimateSmartFee()

async estimateSmartFee(target: number): Promise<FeeEstimate>

Estimate fee rate for confirmation target.

Parameters:
  • target (number) – Target blocks for confirmation
Returns: Promise<FeeEstimate> - Fee rate in sat/vB

generateToAddress()

async generateToAddress(nblocks: number, address: string): Promise<string[]>

Generate blocks (regtest only).

Parameters:
  • nblocks (number) – Number of blocks to generate
  • address (string) – Address for block rewards
Returns: Promise<string[]> - Generated block hashes

Types

Common types used throughout the SDK.

// Alkane identifier
interface AlkaneId {
  block: number;  // Block number where the alkane was created
  tx: number;     // Transaction index within the block
}

// Token balance
interface AlkaneBalance {
  alkane_id: AlkaneId;  // Or 'id' in some responses
  balance: string;       // Or 'amount' - raw balance (divide by 10^decimals)
  symbol?: string;
  name?: string;
}

// UTXO
interface UTXO {
  txid: string;
  vout: number;
  value: number;  // Satoshis
  status: {
    confirmed: boolean;
    block_height?: number;
    block_hash?: string;
    block_time?: number;
  };
}

// Outpoint reference
interface Outpoint {
  txid: string;
  vout: number;
}

// Lua execution result
interface LuaResult {
  calls: number;    // Number of RPC calls made
  returns: any;     // Script return value
  runtime: number;  // Execution time in ms
}

// Provider configuration
interface ProviderConfig {
  network: 'mainnet' | 'testnet' | 'signet' | 'regtest' | 'local';
  rpcUrl?: string;
  dataApiUrl?: string;
  bitcoinNetwork?: Network;  // bitcoinjs-lib network
}

// Network presets
const NETWORK_PRESETS = {
  mainnet: {
    networkType: 'mainnet',
    rpcUrl: 'https://mainnet.subfrost.io/v4/jsonrpc',
    dataApiUrl: 'https://mainnet.subfrost.io/v4/jsonrpc',
  },
  testnet: { ... },
  signet: { ... },
  regtest: { ... },
  local: { ... },
};

For usage examples and patterns, see the TS SDK Guide.