@btr-supply/swap
Version:
Generic Bridge+Swap aggregator for compatible EVMs
489 lines (485 loc) • 19.8 kB
TypeScript
// Generated by dts-bundle-generator v9.5.1
/** Basic interface for objects that can be reliably converted to a string. */
export interface Stringifiable {
toString(): string;
}
/** Enumeration of supported DEX aggregators. */
export declare enum AggId {
LIFI = "LIFI",
SOCKET = "SOCKET",
SQUID = "SQUID",
RANGO = "RANGO",
UNIZEN = "UNIZEN",
ROCKETX = "ROCKETX",// Currently commented out in src/index.ts
ONE_INCH = "ONE_INCH",
ZERO_X = "ZERO_X",
PARASWAP = "PARASWAP",
ODOS = "ODOS",
KYBERSWAP = "KYBERSWAP",
OPENOCEAN = "OPENOCEAN",
FIREBIRD = "FIREBIRD",
BEBOP = "BEBOP",// Currently commented out in src/index.ts
DEBRIDGE = "DEBRIDGE",
COWSWAP = "COWSWAP",
HASHFLOW = "HASHFLOW",
AIRSWAP = "AIRSWAP",
ONE_INCH_FUSION = "ONE_INCH_FUSION",
PARASWAP_DELTA = "PARASWAP_DELTA",
UNIZEN_GASLESS = "UNIZEN_GASLESS"
}
declare enum ProtocolType {
DEX = "DEX",
CEX = "CEX",
OTC = "OTC",
AGGREGATOR = "AGGREGATOR",
BRIDGE = "BRIDGE"
}
declare enum StepType {
SWAP = "SWAP",
BRIDGE = "BRIDGE",
CROSS_CHAIN_SWAP = "CROSS_CHAIN_SWAP",// swap + bridge or bridge + swap
CONTRACT_CALL = "CONTRACT_CALL",
TRANSFER = "TRANSFER"
}
declare enum OpStatus {
WAITING = "WAITING",
PENDING = "PENDING",
DONE = "DONE",
FAILED = "FAILED",
SUCCESS = "SUCCESS",
NEEDS_GAS = "NEEDS_GAS",
ONGOING = "ON_GOING",// Consistent casing
PARTIAL_SUCCESS = "PARTIAL_SUCCESS",
NOT_FOUND = "NOT_FOUND"
}
export declare enum SerializationMode {
JSON = "JSON",
CSV = "CSV",
TABLE = "TABLE",
SQLITE = "SQLITE"
}
export declare enum DisplayMode {
ALL = "ALL",
BEST = "BEST",
ALL_COMPACT = "ALL_COMPACT",// { nonce, value, to, data } json or nonce,value,to,data csv
BEST_COMPACT = "BEST_COMPACT",// same as above, array
RANK = "RANK"
}
/** Tuple type representing basic token information: [address, symbol, decimals] */
export type TokenInfoTuple = [
address: string,
symbol: string,
decimals?: number
];
/** Common token representation used across different aggregators. */
export interface IToken {
chainId: number;
address?: string;
name: string;
symbol?: string;
decimals: number;
priceUsd?: string;
logo?: string;
}
/** Details about the specific tool (protocol/DEX) used in a swap step. */
export interface IProtocol {
id: string;
name: string;
description?: string;
type?: ProtocolType;
logo?: string;
}
/** Represents a blockchain transaction request, compatible with ethers.js/viem structures. */
export type TransactionRequest = {
to?: string;
from?: string;
nonce?: bigint | string | Stringifiable;
gasLimit?: bigint | string | Stringifiable;
gasPrice?: bigint | string | Stringifiable;
data?: Uint8Array | string;
value?: bigint | string | Stringifiable;
chainId?: number;
type?: number;
maxPriorityFeePerGas?: bigint | string | Stringifiable;
maxFeePerGas?: bigint | string | Stringifiable;
aggId?: AggId;
approveTo?: string;
customData?: Record<string, any>;
latencyMs?: number;
};
/** Represents a custom contract call to be potentially included in a swap route. */
export interface ICustomContractCall {
toAddress?: string;
callData: string;
gasLimit?: string;
inputPos?: number;
}
/** Core parameters required for fetching a swap quote or transaction. */
export interface IBtrSwapParams {
aggIds?: AggId[];
input: IToken;
output: IToken;
inputAmountWei: string | number | bigint | Stringifiable;
outputAmountWei?: string | number | bigint | Stringifiable;
payer: string;
testPayer?: string;
receiver?: string;
integrator?: string;
referrer?: string;
maxSlippage?: number;
customContractCalls?: ICustomContractCall[];
bridgeBlacklist?: string[];
exchangeBlacklist?: string[];
sendGas?: boolean;
overloaded?: boolean;
expiryMs?: number;
}
/** Extended parameters for CLI operations. */
export interface IBtrSwapCliParams extends IBtrSwapParams {
apiKeys?: Record<string, string>;
integratorIds?: Record<string, string>;
referrerCodes?: Record<string, string | number>;
feesBps?: Record<string, number>;
displayModes?: DisplayMode[];
serializationMode?: SerializationMode;
envFile?: string;
executable?: string;
verbose?: number;
/** Optional path to log file for rank/best performance */
logFile?: string;
/** Mode for logging output (JSON or SQLITE) */
logMode?: SerializationMode;
}
/** Estimate details for a swap step. */
export interface ISwapEstimate {
exchangeRate?: string | number;
input?: string | number;
inputWei?: string | bigint;
output?: string | number;
outputWei?: string | bigint;
slippage?: string | number;
priceImpact?: string | number;
}
/** Consolidated gas and fee estimates for a transaction. */
export interface ICostEstimate {
gasCostUsd: number;
gasCostWei: bigint;
feeCostUsd: number;
feeCostWei: bigint;
feeToken?: IToken;
}
/** Represents a single step within a complex swap route (e.g., swap, bridge). */
export interface ISwapStep {
id?: string;
type: StepType;
description?: string;
input?: IToken;
output?: IToken;
inputChainId?: number;
outputChainId?: number;
payer?: string;
receiver?: string;
protocol?: IProtocol;
estimates?: ISwapEstimate & ICostEstimate;
}
/** Extends the base TransactionRequest with swap-specific estimates and details. */
export interface ITransactionRequestWithEstimate extends TransactionRequest {
params: IBtrSwapParams;
steps: ISwapStep[];
globalEstimates: ISwapEstimate & ICostEstimate;
latencyMs: number;
}
/** Performance metrics for a quote/transaction request. */
export interface IQuotePerformance {
aggId: string;
exchangeRate: number;
output: number;
gasCostUsd: number;
feeCostUsd: number;
latencyMs: number;
steps: number;
protocols: string[];
}
/** Parameters for fetching the status of a transaction. */
export interface IStatusParams {
aggId?: AggId;
inputChainId?: string;
outputChainId?: string;
txHash?: string;
txId: string;
}
/** Response structure for transaction status requests. */
export interface IStatusResponse {
id: string;
status: OpStatus;
txHash?: string;
receivingTx?: string;
sendingTx?: string;
substatus?: string;
substatusMessage?: string;
}
declare abstract class BaseAggregator {
/** Unique identifier for the aggregator (e.g., "lifi", "socket"). */
readonly id: AggId;
/** API key, if required by the aggregator's service. Read from config. */
readonly apiKey: string;
/** Base URL for the aggregator's API. Read from config. */
readonly baseApiUrl: string;
/** Default integrator identifier used in API requests. Read from config or defaults to "astrolab". */
readonly integrator: string;
/** Optional referrer address for fee sharing or tracking. Read from config. */
readonly referrer?: string | `0x${string}`;
/** Optional fee percentage in basis points (e.g., 50 for 0.5%) applied by BTR. Read from config. */
readonly feeBps: number;
/** Mapping of chain IDs to the aggregator's primary router contract address for that chain. */
routerByChainId: {
[chainId: number]: string;
};
/** Mapping of chain IDs to the alias used by the aggregator's API (e.g., "eth", "1", "polygon"). */
aliasByChainId: {
[chainId: number]: string | number;
};
/** Mapping of chain IDs to the required approval (spender) address for token allowances. Often the same as the router. */
approvalAddressByChainId: {
[chainId: number]: string;
};
/** Mapping of chain IDs to signature receiver addresses for EIP-712/1271 gasless signatures, specific to the aggregator's contracts. */
signatureReceiverByChainId: {
[chainId: number]: string;
};
/**
* Initializes common properties for an aggregator instance.
* Reads configuration values like API root, API key, integrator ID, referrer, and fee BPS
* from the global configuration.
* @param aggId - The unique identifier for this aggregator (e.g., `AggId.LIFI`).
* @throws {Error} If configuration is missing or incomplete (e.g., missing `apiRoot`) for the specified `aggId`.
*/
constructor(aggId: AggId);
/**
* Overloads, validates, and sets default values for BTR Swap parameters.
* - Ensures basic parameter validity (addresses, chain IDs, amounts) using `validateParams`.
* - Sets default `output.chainId` to `input.chainId` for same-chain swaps if not provided.
* - Sets default `receiver` to `payer` if not provided.
* - Ensures the current aggregator's ID is included in `aggIds`.
* - Sets default `maxSlippage` to `MAX_SLIPPAGE_BPS` (from `../constants`) if not provided.
* - Marks the parameters as overloaded to prevent redundant processing.
*
* Subclasses may override this to add aggregator-specific validation or defaults,
* but should typically call `super.overloadParams(p)` first.
*
* @param p - The input {@link IBtrSwapParams}.
* @returns The validated and potentially modified {@link IBtrSwapParams}.
* @throws {Error} If basic parameter validation fails via `validateParams`.
*/
protected overloadParams: (p: IBtrSwapParams) => IBtrSwapParams;
/**
* Gets the base API root URL for a specific chain.
* The default implementation returns the `baseApiUrl` stored in the instance.
* Subclasses should override this if the aggregator uses different base URLs per chain
* (e.g., subdomains like `polygon.api.aggregator.xyz`).
* Ensures the chain is supported before returning.
* @param chainId - The chain ID for which to get the API root.
* @returns The base API root URL string for the specified chain.
* @throws {Error} If the chain ID is not supported by this aggregator (checked via `ensureChainSupported`).
*/
protected getApiRoot(chainId: number): string;
/**
* Abstract method to convert standardized {@link IBtrSwapParams} into the format
* expected by the specific aggregator's API for quote or transaction requests.
* Must be implemented by subclasses.
* @param params - Standardized BTR Swap parameters.
* @returns An object containing parameters formatted for the aggregator's API, or `undefined` if conversion is not possible.
*/
protected abstract convertParams(params: IBtrSwapParams): Record<string, any> | undefined;
/**
* Abstract method to fetch a price quote from the aggregator's API.
* This typically involves calling an endpoint like `/quote` or `/price`.
* The implementation should handle parameter conversion, API request, response parsing,
* and basic validation of the quote response.
* Must be implemented by subclasses.
* @param params - Standardized BTR Swap parameters, typically processed by `overloadParams`.
* @returns A promise resolving to the aggregator's specific quote response structure (e.g., `ILifiBestQuote`), or `undefined` if the quote fails.
*/
abstract getQuote(params: IBtrSwapParams): Promise<any | undefined>;
/**
* Abstract method to fetch the necessary transaction request data from the aggregator's API
* to execute the swap. This might involve fetching a quote first and then using that
* quote to build the transaction data (e.g., via a `/swap` or `/build-tx` endpoint).
* The implementation should return a standardized {@link ITransactionRequestWithEstimate}.
* Must be implemented by subclasses.
* @param params - Standardized BTR Swap parameters, typically processed by `overloadParams`.
* @returns A promise resolving to the formatted {@link ITransactionRequestWithEstimate}, including details like `to`, `data`, `value`, `steps`, and `globalEstimates`, or `undefined` if the request fails.
*/
abstract getTransactionRequest(params: IBtrSwapParams): Promise<ITransactionRequestWithEstimate | undefined>;
/**
* Fetches the transaction request using `getTransactionRequest` and measures the execution time.
* Adds the measured latency in milliseconds to the `latencyMs` property of the returned transaction request.
* @param params - Standard BTR Swap parameters.
* @returns A promise resolving to the {@link ITransactionRequestWithEstimate} with added `latencyMs`, or `undefined` if `getTransactionRequest` fails.
* @see {@link withLatency}
*/
getTimedTr(params: IBtrSwapParams): Promise<ITransactionRequestWithEstimate | undefined>;
/**
* Fetches the status of a previously executed transaction from the aggregator's API.
* This is primarily relevant for cross-chain swaps where status tracking is crucial.
* The default implementation logs a warning and returns `undefined`, indicating it's not supported.
* Subclasses supporting status checks (like LiFi, Socket) must override this method.
* @param params - Parameters identifying the transaction, typically including `txHash` and chain IDs ({@link IStatusParams}).
* @returns A promise resolving to a standardized {@link IStatusResponse} object, or `undefined` if status checking is not supported or the request fails.
*/
getStatus(_params: IStatusParams): Promise<IStatusResponse | undefined>;
/**
* Checks if a given chain ID is supported by this aggregator.
* Support is determined by the presence of the chain ID in either the `routerByChainId`
* or `aliasByChainId` mappings defined in the subclass constructor.
* @param chainId - The chain ID to check.
* @returns `true` if the chain is supported, `false` otherwise.
*/
isChainSupported(chainId: number): boolean;
/**
* Ensures that a given chain ID is supported by this aggregator by calling `isChainSupported`.
* @param chainId - The chain ID to check.
* @throws {Error} if the chain ID is not supported by this aggregator.
*/
ensureChainSupported(chainId: number): void;
/**
* Handles errors encountered during aggregator operations (e.g., API requests, parameter conversion).
* Logs the error message and optionally the stack trace to the console, prefixed with the aggregator ID and context.
* Subclasses can override this to implement more specific error handling or reporting logic,
* potentially re-throwing errors or returning specific error codes.
* The default implementation does not re-throw the error.
* @param error - The error object or value caught.
* @param context - A string providing context about the operation where the error occurred (e.g., "getQuote", "getTransactionRequest").
*/
handleError(error: unknown, context: string): void;
/**
* Gets the primary router contract address for a given chain ID, if defined for this aggregator.
* Retrieves the address from the `routerByChainId` map.
* @param chainId - The chain ID.
* @returns The router address as a string, or `undefined` if no router is defined for the chain.
*/
getRouterAddress(chainId: number): string | undefined;
/**
* Gets the required approval (spender) address for token allowances on a specific chain ID.
* It first checks the `approvalAddressByChainId` map. If no specific approval address is found,
* it falls back to the router address for that chain obtained via `getRouterAddress`.
* @param chainId - The chain ID.
* @returns The approval address as a string, or `undefined` if neither a specific approval address nor a router address is defined for the chain.
*/
getApprovalAddress(chainId: number): string | undefined;
}
/**
* Interface for an aggregator's configuration.
*/
export interface AggregatorConfig {
apiRoot: string;
apiKey: string | null;
integrator: string;
referrer: string | number | null;
feeBps: number;
}
/**
* Main configuration object holding config objects for each supported aggregator.
*/
declare const c: Record<AggId, AggregatorConfig>;
/** Default list of aggregators to query when none are specified and no custom calls are needed. */
export declare const defaultAggregators: AggId[];
/**
* Slippage constants for DEX aggregators
*/
export declare const MAX_SLIPPAGE_BPS = 500;
/**
* Type alias for header configuration in table/CSV generation.
* Can be either a string array or a Record mapping data keys to display names.
*/
export type HeaderConfig = string[] | Record<string, string>;
/**
* Configuration options for serialization across different formats.
*/
export type SerializationOptions = {
/** Serialization mode (JSON, CSV, or TABLE). */
mode?: SerializationMode;
/** Number of spaces for JSON indentation. */
spaces?: number;
/** Optional header configuration for CSV/TABLE modes. */
headers?: HeaderConfig;
/** Whether to include headers in CSV/TABLE output. */
includeHeaders?: boolean;
/** Separator character for CSV mode. */
separator?: string;
/** Column widths for TABLE mode. */
columnWidths?: number | number[];
/** Cell padding for TABLE mode. */
padding?: number;
};
/**
* Converts an object to a JSON string with sanitized values.
* @param o - The object to convert
* @param spaces - The number of spaces to use for formatting
* @returns The JSON string
*/
export declare const toJSON: (o: any, spaces?: number) => string;
/**
* Serializes an object to JSON, CSV, or TABLE format.
* @param o - Object to serialize
* @param options - Serialization options
* @returns Serialized string in the specified format
*/
export declare function serialize(o: any, options?: SerializationOptions): string;
/**
* Converts a token format to an IToken object.
* @param t - The token as symbol, address, cli format (chainId:address(:symbol(:decimals))) or TokenInfoTuple
* @param chainId - The chain ID
* @returns The IToken object
*/
export declare const getToken: (t: TokenInfoTuple | string, chainId?: number) => IToken;
/**
* Creates compact transaction request objects for an array of transactions.
* @param trs - Array of transaction request objects to compact
* @returns Array of compact transaction request objects
*/
export declare const compactTrs: (trs: TransactionRequest[]) => TransactionRequest[];
/**
* Extracts performance metrics from a transaction request with estimate.
* @param tr - The transaction request with estimate
* @returns Performance metrics object
*/
export declare function getPerformance(tr: ITransactionRequestWithEstimate): IQuotePerformance;
/**
* Creates a performance table from an array of transaction requests.
* @param trs - Array of transaction requests with estimates
* @returns Formatted table string with performance metrics
*/
export declare function getPerformanceTable(trs: ITransactionRequestWithEstimate[]): string;
/** Mapping of AggId to its corresponding Aggregator implementation instance. */
export declare const aggregatorById: Partial<{
[key in AggId]: BaseAggregator;
}>;
/**
* Fetches the best transaction request and extracts its calldata.
* Useful for scenarios where only the transaction calldata is needed.
* @param o - BTR Swap parameters.
* @returns A promise resolving to the transaction calldata string, or an empty string if no data is found.
*/
export declare function getCallData(o: IBtrSwapParams): Promise<string>;
/**
* Fetches transaction requests concurrently from multiple specified aggregators.
* Sorts the successful results by the best estimated output amount (exchange rate).
* Includes a timeout mechanism for each aggregator request.
* @param o - BTR Swap parameters.
* @returns Array of successful transaction requests sorted by rate, or undefined if none succeed.
* @throws {Error} If no viable routes are found.
*/
export declare function getAllTimedTr(params: IBtrSwapParams): Promise<ITransactionRequestWithEstimate[]>;
/**
* Fetches the single best transaction request from the available aggregators.
* It determines the "best" request based on the highest estimated output amount after fetching from all specified aggregators.
* Uses `getAllTimedTr` internally.
* @param o - BTR Swap parameters.
* @returns A promise resolving to the best transaction request, or undefined if none found.
*/
export declare const getBestTransactionRequest: (o: IBtrSwapParams) => Promise<ITransactionRequestWithEstimate | undefined>;
export {
c as config,
};
export {};