API Reference

Complete reference for all public exports from @taurusswap/sdk. Every function, type, and constant is covered.

TaurusClient

The high-level entry point. Owns an Algod client, Indexer client, and a pool-state cache. Import and instantiate once per app.

import { TaurusClient } from '@taurusswap/sdk';
const client = new TaurusClient(config?: TaurusClientConfig);

TaurusClientConfig

interface TaurusClientConfig {
  algodUrl?:    string;  // default: https://testnet-api.algonode.cloud
  algodToken?:  string;  // default: '' (public AlgoNode)
  algodPort?:   number;
  indexerUrl?:  string;  // default: https://testnet-idx.algonode.cloud
  indexerToken?: string;
  poolAppId?:   number;  // default: 758284478 (testnet)
  cacheTtlMs?:  number;  // pool-state cache TTL ms; default 10 000; 0 = no cache
}

Methods

MethodReturnsDescription
getPoolState(forceRefresh?)Promise<PoolState>Fetch pool state; results cached for cacheTtlMs
invalidateCache()voidForce-evict cached pool state
getPosition(address, tickId)Promise<PositionInfo | null>Read LP position and compute claimable fees
quote(params)Promise<SwapQuote>Off-chain swap quote
getAllPrices(baseTokenIdx?)Promise<number[]>Spot price of every token relative to base
buildSwapTxns(params)Promise<Transaction[]>Build unsigned swap transaction group
buildAddLiquidityTxns(params)Promise<{ txns, depositPerTokenRaw, tickId }>Build unsigned add-tick transaction group
buildRemoveLiquidityTxns(params)Promise<Transaction[]>Build unsigned remove-liquidity group
buildClaimFeesTxns(params)Promise<Transaction[]>Build unsigned claim-fees group
computeZap(sourceIdx, totalAmountRaw)Promise<ZapPlan>Plan single-token deposit (pure, no extra calls)
buildZapTxns(params)Promise<{ swapTxnGroups, addLiquidityTxns, plan }>Build all groups for a zap operation
tickParamsFromDepegPrice(depegPrice, depositRaw)Promise<{ r, k }>Convert depeg price + deposit to (r, k)
getCapitalEfficiency(depegPrice, tickRadius)Promise<{ k, efficiency, depositPerToken }>Capital efficiency multiplier for a tick config
estimateRemoval(address, tickId, shares)Promise<EstimateRemovalResult>Preview principal + fees before removing
estimateAPR(depegPrice, depositPerTokenRaw)Promise<EstimateAPRResult>Estimate annualised yield (requires indexer)
getPoolStats()Promise<PoolStats>24h stats from Indexer: volume, fees, TVL
getTransactions(options?)Promise<AMMTransaction[]>Recent swap/LP transactions from Indexer

Pool Functions (standalone)

readPoolState

async function readPoolState(
  client:  algosdk.Algodv2,
  appId:   number,
): Promise<PoolState>

Reads global state, reserves box, fee_growth box, tick boxes, and token boxes.

readPosition

async function readPosition(
  client:     algosdk.Algodv2,
  appId:      number,
  address:    string,
  tickId:     number,
  n:          number,
  feeGrowth:  bigint[],
  tick:       Tick,
): Promise<PositionInfo | null>

Returns null if no pos: box exists for (address, tickId).

getSwapQuote

function getSwapQuote(           // synchronous
  poolState:    PoolState,
  tokenInIdx:   number,
  tokenOutIdx:  number,
  amountInRaw:  bigint,
): SwapQuote

buildSwapTxns

async function buildSwapTxns(
  client:       algosdk.Algodv2,
  poolAppId:    number,
  sender:       string,
  poolState:    PoolState,
  tokenInIdx:   number,
  tokenOutIdx:  number,
  amountInRaw:  bigint,
  slippageBps?: number,           // default 50 (0.5%)
): Promise<algosdk.Transaction[]>

executeSwap

async function executeSwap(
  client:      algosdk.Algodv2,
  poolAppId:   number,
  sender:      string,
  tokenInIdx:  number,
  tokenOutIdx: number,
  amountInRaw: bigint,
  slippageBps: number,
  signer:      (txns: algosdk.Transaction[]) => Promise<Uint8Array[]>,
): Promise<{ txId: string; amountOut: bigint }>

tickParamsFromDepegPrice

function tickParamsFromDepegPrice(
  depegPrice:            number,   // e.g. 0.99
  totalDepositPerTokenRaw: bigint, // raw microunits
  n:                     number,
  sqrtN:                 bigint,
  invSqrtN:              bigint,
): { r: bigint; k: bigint }        // both in AMOUNT_SCALE units

computeDepositPerToken

function computeDepositPerToken(
  r:       bigint,  // AMOUNT_SCALE units
  k:       bigint,  // AMOUNT_SCALE units
  n:       number,
  sqrtN:   bigint,
  invSqrtN: bigint,
): bigint  // raw microunits per token

addLiquidity

async function addLiquidity(params: AddLiquidityParams): Promise<AddLiquidityResult>

interface AddLiquidityParams {
  client:   algosdk.Algodv2;
  poolAppId: number;
  sender:   string;
  r:        bigint;   // AMOUNT_SCALE units
  k:        bigint;   // AMOUNT_SCALE units
  signer:   (txns: algosdk.Transaction[]) => Promise<Uint8Array[]>;
}

interface AddLiquidityResult {
  txId:              string;
  tickId:            number;  // ID assigned to the new tick
  depositPerTokenRaw: bigint; // raw microunits deposited per token
}

removeLiquidity

async function removeLiquidity(params: RemoveLiquidityParams): Promise<{ txId: string }>

interface RemoveLiquidityParams {
  client:   algosdk.Algodv2;
  poolAppId: number;
  sender:   string;
  tickId:   number;
  shares:   bigint;  // pass tick.totalShares for full exit
  signer:   (txns: algosdk.Transaction[]) => Promise<Uint8Array[]>;
}

claimFees

async function claimFees(params: ClaimFeesParams): Promise<{ txId: string }>

interface ClaimFeesParams {
  client:   algosdk.Algodv2;
  poolAppId: number;
  sender:   string;
  tickId:   number;
  signer:   (txns: algosdk.Transaction[]) => Promise<Uint8Array[]>;
}

computeZap

function computeZap(               // synchronous
  pool:           PoolState,
  sourceTokenIdx: number,
  totalAmountRaw: bigint,
): ZapPlan

interface ZapPlan {
  swaps:          ZapSwap[];
  depositPerToken: bigint;   // min received across all token swaps (raw microunits)
  avgPriceImpact: number;
}

interface ZapSwap {
  fromIdx:     number;
  toIdx:       number;
  amountIn:    bigint;  // raw microunits
  amountOut:   bigint;  // raw microunits (off-chain quote)
  priceImpact: number;
}

Types

// Pool snapshot
interface PoolState {
  appId:             number;
  n:                 number;
  sqrtN:             bigint;     // PRECISION-scaled
  invSqrtN:          bigint;     // PRECISION-scaled
  sumX:              bigint;     // AMOUNT_SCALE units
  sumXSq:            bigint;     // AMOUNT_SCALE² units
  virtualOffset:     bigint;     // AMOUNT_SCALE units
  rInt:              bigint;     // AMOUNT_SCALE units
  sBound:            bigint;     // AMOUNT_SCALE units
  kBound:            bigint;     // AMOUNT_SCALE units
  totalR:            bigint;     // AMOUNT_SCALE units
  feeBps:            bigint;     // e.g. 30n = 0.30%
  feeGrowth:         bigint[];   // [n] PRECISION-scaled accumulators
  actualReservesRaw: bigint[];   // [n] raw microunits (use for TVL / display)
  reserves:          bigint[];   // [n] math-space (actualRaw/1000 + virtualOffset)
  numTicks:          number;
  ticks:             Tick[];
  tokenAsaIds:       number[];
  tokenDecimals:     number[];
}

// Tick
interface Tick {
  id:          number;
  r:           bigint;     // AMOUNT_SCALE units
  k:           bigint;     // AMOUNT_SCALE units
  state:       TickState;  // INTERIOR = 0, BOUNDARY = 1
  totalShares: bigint;
}
enum TickState { INTERIOR = 0, BOUNDARY = 1 }

// LP position
interface PositionInfo {
  tickId:        number;
  shares:        bigint;
  positionR:     bigint;    // AMOUNT_SCALE units
  claimableFees: bigint[];  // [n] raw microunits
}

// Swap quote
interface SwapQuote {
  amountIn:           bigint;
  amountOut:          bigint;
  priceImpact:        number;   // 0.01 = 1%
  instantaneousPrice: number;
  effectivePrice:     number;
  ticksCrossed:       number;
  route:              TradeSegment[];
}

// Indexer stats
interface PoolStats {
  tvlUsd:       number;
  volume24hUsd: number;
  fees24hUsd:   number;
  swapCount24h: number;
  activeTicks:  number;
  feeBps:       number;
}

interface AMMTransaction {
  id:           string;
  type:         'swap' | 'add' | 'remove' | 'claim';
  timestamp:    number;  // ms since epoch
  wallet:       string;
  tokenInIdx?:  number;
  tokenOutIdx?: number;
  amountIn?:    bigint;  // raw microunits
  amountOut?:   bigint;  // raw microunits
}

// APR estimate
interface EstimateAPRResult {
  apr:                number;   // e.g. 0.12 = 12%
  dailyFeeUsd:        number;
  efficiencyMultiplier: number;
  tickRadius:         bigint;
}

interface EstimateRemovalResult {
  receivePerTokenRaw: bigint[];  // principal amounts, raw microunits
  claimableFeesRaw:   bigint[];  // fee amounts, raw microunits
}

Error Classes

// Base class
class TaurusError extends Error {
  readonly code: string; // machine-readable error code
}

class SwapTooSmallError         extends TaurusError { code = 'SWAP_TOO_SMALL' }
class InsufficientLiquidityError extends TaurusError { code = 'INSUFFICIENT_LIQUIDITY' }
class TickNotFoundError          extends TaurusError { code = 'TICK_NOT_FOUND' }
class InvalidTickParamsError     extends TaurusError { code = 'INVALID_TICK_PARAMS' }
class InvalidSlippageError       extends TaurusError { code = 'INVALID_SLIPPAGE' }
class ZapAmountTooSmallError     extends TaurusError { code = 'ZAP_TOO_SMALL' }
class IndexerNotConfiguredError  extends TaurusError { code = 'INDEXER_NOT_CONFIGURED' }

Constants

import {
  PRECISION,            // 1_000_000_000n  — 10⁹ scaling for feeGrowth and prices
  PRECISION_SQ,         // PRECISION²
  AMOUNT_SCALE,         // 1_000n          — raw microunits / AMOUNT_SCALE = math units
  TOLERANCE,            // 1_000n          — invariant residual tolerance

  SQRT_TABLE,           // Record<number, bigint> — floor(√n × 10⁹) for n = 2..100
  INV_SQRT_TABLE,       // Record<number, bigint> — floor(1/√n × 10⁹)

  MAX_NEWTON_ITERATIONS, // 50  — Newton-bisection solver cap
  MAX_BISECTION_STEPS,   // 80
  MAX_BRACKET_SAMPLES,   // 64
  MAX_TICK_CROSSINGS,    // 20  — safety cap on crossings per trade

  DEFAULT_SLIPPAGE_BPS,  // 50  — 0.50%
  ALGO_MICRO,            // 1_000_000n
  MIN_TXN_FEE,           // 1_000n
  OPCODE_BUDGET_PER_TXN, // 700
} from '@taurusswap/sdk';

Math Exports

These are exported for advanced use cases. Normal integrations should use the pool-level functions above.

// Sphere invariant (single-tick, no crossings)
function sphereInvariant(reserves: bigint[], rInt: bigint, n: number): bigint
function getPrice(reserves: bigint[], rInt: bigint, i: number, j: number): bigint
function equalPricePoint(r: bigint, invSqrtN: bigint): bigint  // q in AMOUNT_SCALE units
function solveSwapSphere(...): bigint

// Torus invariant (multi-tick composite)
function torusInvariant(sumX: bigint, sumXSq: bigint, n: number,
                        rInt: bigint, sBound: bigint, kBound: bigint,
                        sqrtN: bigint, invSqrtN: bigint): bigint
function isValidState(poolState: PoolState): boolean

// Newton-bisection solver
function solveSwapNewton(effectiveInScaled: bigint, tokenInIdx: number,
                         tokenOutIdx: number, reserves: bigint[], n: number,
                         sqrtN: bigint, invSqrtN: bigint, rInt: bigint): bigint

// Tick consolidation
function consolidateTicks(ticks: Tick[], sqrtN: bigint):
  { rInt: bigint; sBound: bigint; kBound: bigint }

// Tick geometry
function kFromDepegPrice(depegPrice: number, r: bigint, n: number,
                         sqrtN: bigint, invSqrtN: bigint): bigint
function capitalEfficiency(r: bigint, k: bigint, n: number,
                            sqrtN: bigint, invSqrtN: bigint): number
function xMin(r: bigint, k: bigint, n: number, sqrtN: bigint): bigint
function xMax(r: bigint, n: number, invSqrtN: bigint): bigint

// BigInt utilities
function sqrt(n: bigint): bigint
function abs(n: bigint): bigint
function min(a: bigint, b: bigint): bigint
function max(a: bigint, b: bigint): bigint