Complete reference for all exported interfaces, types, classes, and functions.
Factory function that creates a Router instance.
Parameters:
config—RouteConfigwith adapters, oracle, strategy, and constraints.
Returns: A Router with a single route() method.
Example:
const router = createRouter({
adapters: new Map([['base', baseAdapter]]),
feeOracle: oracle,
strategy: 'cheapest',
maxFeeAgeMs: 60_000,
});Select the best route and build a signed payment payload.
Parameters:
req— Payment requirement from a 402 response.signer— Signer instance for payload construction.
Returns: RouteResult with the selected chain, payload, fee, and all evaluated options.
Throws:
RouteExhaustedError— No eligible route found.PaymentConstructionError— Payload construction or validation failed.
type ChainId = 'base' | 'stellar' | 'solana' | 'polygon';interface RouteConfig {
readonly adapters: ReadonlyMap<ChainId, ChainAdapter>;
readonly feeOracle: FeeOracle;
readonly strategy: RoutingStrategy;
readonly maxFeeAgeMs: number;
readonly maxFeeUsd?: bigint;
readonly maxFinalityMs?: number;
readonly excludeChains?: readonly ChainId[];
readonly cloudApiKey?: string;
readonly enableBatching?: boolean;
}interface PaymentRequirement {
readonly acceptedChains: readonly AcceptedPayment[];
}interface AcceptedPayment {
readonly chainId: ChainId;
readonly payTo: string;
readonly amount: bigint;
readonly token: string;
readonly extra?: Readonly<Record<string, string>>;
}interface RouteResult {
readonly chainId: ChainId;
readonly payload: PaymentPayload;
readonly fee: FeeEstimate;
readonly evaluatedOptions: readonly RouteOption[];
}interface PaymentPayload {
readonly chainId: ChainId;
readonly to: string;
readonly amount: bigint;
readonly token: string;
readonly data: string;
}interface FeeEstimate {
readonly chainId: ChainId;
readonly feeAmount: bigint;
readonly feeUsd: bigint;
readonly finalityMs: number;
readonly confidence: FeeConfidence;
readonly timestamp: number;
}type FeeConfidence = 'high' | 'medium' | 'low';interface RouteOption {
readonly chainId: ChainId;
readonly payment: AcceptedPayment;
readonly fee: FeeEstimate;
readonly balance: bigint;
readonly score: number;
}interface TokenBalance {
readonly chainId: ChainId;
readonly token: string;
readonly balance: bigint;
readonly timestamp: number;
}interface Signer {
readonly address: string;
sign(data: Uint8Array): Promise<Uint8Array>;
signTypedData?(typedData: Record<string, unknown>): Promise<string>;
}interface ChainAdapter {
readonly chainId: ChainId;
getBalance(address: string, token: string): Promise<TokenBalance>;
estimateFee(payment: AcceptedPayment): Promise<FeeEstimate>;
buildPaymentPayload(payment: AcceptedPayment, signer: Signer): Promise<PaymentPayload>;
getFinality(): number;
}interface FeeOracle {
getFee(chainId: ChainId): Promise<FeeEstimate | undefined>;
getAllFees(): Promise<ReadonlyMap<ChainId, FeeEstimate>>;
start(): void;
stop(): void;
}type RoutingStrategy = 'cheapest' | 'fastest' | 'balanced' | CustomStrategy;interface CustomStrategy {
readonly type: 'custom';
readonly scorer: (options: readonly RouteOption[]) => readonly RouteOption[];
}interface RejectionReason {
readonly chainId: ChainId;
readonly reason: string;
readonly code: RejectionCode;
}type RejectionCode =
| 'NO_ADAPTER'
| 'INSUFFICIENT_BALANCE'
| 'FEE_TOO_HIGH'
| 'FINALITY_TOO_SLOW'
| 'CHAIN_EXCLUDED'
| 'STALE_FEE'
| 'FEE_UNAVAILABLE';Abstract base class for all Routex errors.
Thrown when no eligible route can be found. Contains rejections: RejectionReason[] explaining why each chain was ineligible.
Thrown when fee estimates are older than maxFeeAgeMs. Contains chainId, ageMs, and maxAgeMs.
Thrown when a chain has insufficient balance. Contains chainId, required (bigint), and available (bigint).
Thrown when payload construction fails. Contains chainId, phase, and detail (sanitized). Implements toJSON() for safe serialization.
Score by lowest fee. Formula: 1 / (feeUsd + 0.0001).
Score by lowest finality time. Formula: 1 / (finalityMs + 1).
Score by weighted combination. Formula: 0.6 * normFee + 0.4 * normFinality.
custom(scorer: CustomStrategy['scorer']): (options: readonly RouteOption[]) => readonly RouteOption[]
Wrap a user-provided scoring function.
Local fee oracle that polls chain adapters for fee estimates.
Constructor: new LocalFeeOracle(config: LocalFeeOracleConfig)
Parallel balance query manager with caching.
Constructor: new BalanceManager(config: BalanceManagerConfig)
Five-step routing pipeline (parse, filter, score, select, verify).
Constructor: new RouteSelector(config: RouteConfig)
Create a middleware instance for handling 402 responses.
Parameters:
config.routeConfig— FullRouteConfig.config.signer—Signerfor payload signing.config.onRouteSelected?— Callback on successful route.config.onRouteFailed?— Callback on routing failure.
Returns: RoutexMiddleware with handlePaymentRequired() and parseResponse() methods.
Cloud-hosted fee oracle with WebSocket streaming, REST polling fallback, and seamless degradation to a local oracle.
Config:
apiKey— Cloud API key (rtx_prefix)fallback—FeeOracleto use when cloud is unreachableendpoint?— Oracle URL (default:https://oracle.routex.dev)fallbackTimeoutMs?— Milliseconds before switching to fallback (default:5000)wsReconnectMaxMs?— Max reconnection delay (default:30000)restPollIntervalMs?— REST polling interval when WS is down (default:10000)
Behavior:
- Connects via WebSocket to
/v1/fees/stream(primary, lowest latency) - Falls back to REST polling (
GET /v1/fees) when WS reconnecting - If cloud unreachable for >5s, delegates to fallback
FeeOracle - Recovers automatically when cloud becomes available
import { CloudFeeOracle } from '@routexcc/cloud';
import { LocalFeeOracle } from '@routexcc/core';
const oracle = CloudFeeOracle({
apiKey: 'rtx_your_key',
fallback: new LocalFeeOracle(localConfig),
});
oracle.start();Reports route telemetry to the Routex analytics backend. Extracts only allowlisted fields from RouteResult — no private keys, addresses, or signer info.
Config:
apiKey— Cloud API keyendpoint?— Telemetry endpoint URLbufferSize?— Events to buffer before flushing (default:10)flushIntervalMs?— Periodic flush interval (default:5000)
Handle methods:
report(result: RouteResult): void— Queue a telemetry event (fire-and-forget)flush(): Promise<void>— Flush buffered events immediatelystop(): Promise<void>— Stop and flush remaining events
TelemetryEvent fields (strict allowlist):
chainId,amount,feeUsd,savingsUsd,timestamp
Batch settlement client (Phase 5 stub — no-op in current release).
When cloudApiKey is set in RouteConfig, createRouter() automatically:
- Wraps
feeOraclewithCloudFeeOracle(WebSocket streaming + fallback) - Creates
TelemetryReporterand firesreport()after each successful route - Falls back silently to local oracle if
@routexcc/cloudis not installed
Zero breaking changes from v1 — all existing code works unchanged.