@todayapp/avantis-sdk
Version:
Unofficial TypeScript SDK for Avantis DEX - Decentralized perpetual futures trading (BETA)
1,791 lines (1,769 loc) • 79.5 kB
text/typescript
import Decimal$1, { Decimal } from 'decimal.js';
import { WalletClient, PublicClient, Account, Transport, Chain, TransactionRequest, Hash, TransactionReceipt, Log } from 'viem';
import { EventEmitter } from 'eventemitter3';
import { z } from 'zod';
/**
* Platform Fee Management Types
*
* These types enable platforms to collect fees on trades,
* offer discounts, and share revenue with referrers.
*/
/**
* Platform fee configuration for the SDK
*/
interface PlatformFeeConfig {
/** Platform wallet address to receive fees */
platformWallet: string;
/** Base fee percentage (e.g., 0.001 = 0.1%) */
baseFeePercent: number;
/** Percentage of platform fee that goes to referrer (0-100) */
referralSplitPercent?: number;
/** Whether platform fees are enabled */
enabled: boolean;
}
/**
* Fee parameters for a specific trade
*/
interface PlatformFeeParams {
/** Whether to collect platform fee on this trade */
enabled: boolean;
/** Discount percentage on platform fee (0-100) */
discountPercent?: number;
/** Referral address to receive fee split */
referralAddress?: string;
}
/**
* Calculated fee breakdown
*/
interface FeeBreakdown {
/** Base platform fee before discount */
baseFee: Decimal;
/** Discount amount */
discount: Decimal;
/** Final platform fee after discount */
platformFee: Decimal;
/** Amount going to referrer */
referralFee: Decimal;
/** Amount going to platform */
platformReceives: Decimal;
/** Total amount user pays in fees */
totalFee: Decimal;
}
/**
* Transaction call data for Multicall bundling
*/
interface CallData {
/** Target contract address */
target: string;
/** Whether to allow this call to fail */
allowFailure: boolean;
/** Encoded function call data */
callData: string;
/** ETH value to send (if any) */
value?: bigint;
}
/**
* Bundled transaction for Multicall3
*/
interface BundledTransaction {
/** Multicall3 contract address */
to: string;
/** Encoded multicall data */
data: string;
/** Total ETH value (if any) */
value: bigint;
/** Estimated gas limit */
gasLimit?: bigint;
/** Human-readable description of operations */
description: string[];
}
/**
* Result of a bundled transaction
*/
interface BundledTransactionResult {
/** Transaction hash */
hash: string;
/** Whether all calls succeeded */
success: boolean;
/** Individual call results */
results: {
success: boolean;
returnData: string;
}[];
/** Gas used */
gasUsed: bigint;
/** Effective gas price */
effectiveGasPrice: bigint;
}
declare enum PositionSide {
LONG = "long",
SHORT = "short"
}
declare enum OrderType {
MARKET = "market",
STOP_LIMIT = "stop_limit",
LIMIT = "limit",
MARKET_ZERO_FEE = "market_zero_fee"
}
declare enum OrderTypeValue {
MARKET = 0,
STOP_LIMIT = 1,
LIMIT = 2,
MARKET_ZERO_FEE = 3
}
declare enum PositionStatus {
OPEN = "open",
CLOSED = "closed",
LIQUIDATED = "liquidated",
PENDING = "pending"
}
interface TradingPair {
id: string;
symbol: string;
base: string;
quote: string;
feedId: string;
minSize: Decimal$1;
maxSize: Decimal$1;
maxLeverage: number;
decimals: number;
isActive: boolean;
category: "crypto" | "forex" | "commodity" | "index";
}
interface OpenPositionParams {
pair: string;
side: PositionSide;
size: Decimal$1 | number | string;
leverage: number;
orderType?: OrderType;
openPrice?: Decimal$1 | number | string;
stopLoss?: Decimal$1 | number | string;
takeProfit?: Decimal$1 | number | string;
slippage?: number;
referrer?: string;
platformFee?: PlatformFeeParams;
}
interface ClosePositionParams {
positionId: string;
size?: Decimal$1 | number | string;
collateralAmount?: Decimal$1 | number | string;
slippage?: number;
platformFee?: PlatformFeeParams;
}
interface UpdatePositionParams {
positionId: string;
stopLoss?: Decimal$1 | number | string | null;
takeProfit?: Decimal$1 | number | string | null;
autofetchPrices?: boolean;
priceUpdateData?: string[];
}
interface CancelLimitOrderParams {
pairIndex: number;
orderIndex: number;
}
interface UpdateLimitOrderParams {
pairIndex: number;
orderIndex: number;
price: Decimal$1 | number | string;
slippage?: number;
takeProfit?: Decimal$1 | number | string;
stopLoss?: Decimal$1 | number | string;
}
interface PendingLimitOrder {
id: string;
trader: string;
pairIndex: number;
orderIndex: number;
pair?: string;
positionSize: Decimal$1;
buy: boolean;
leverage: number;
openPrice: Decimal$1;
tp?: Decimal$1;
sl?: Decimal$1;
slippageP?: number;
block?: number;
timestamp: Date;
orderType: OrderType;
}
interface Position {
id: string;
owner: string;
pair: string;
side: PositionSide;
size: Decimal$1;
collateral: Decimal$1;
leverage: number;
entryPrice: Decimal$1;
markPrice: Decimal$1;
liquidationPrice: Decimal$1;
unrealizedPnl: Decimal$1;
unrealizedPnlPercent: number;
realizedPnl: Decimal$1;
stopLoss?: Decimal$1;
takeProfit?: Decimal$1;
margin: Decimal$1;
maintenanceMargin: Decimal$1;
status: PositionStatus;
openedAt: Date;
closedAt?: Date;
lastUpdated: Date;
}
interface TradeResponse {
success: boolean;
transactionHash: string;
position?: Position;
gasUsed: bigint;
effectiveGasPrice: bigint;
error?: string;
}
interface PendingTrade {
id: string;
type: "open" | "close" | "update";
params: OpenPositionParams | ClosePositionParams | UpdatePositionParams;
status: "pending" | "submitted" | "confirmed" | "failed";
transactionHash?: string;
createdAt: Date;
error?: string;
}
interface TradingFees {
openFee: Decimal$1;
closeFee: Decimal$1;
borrowFee: Decimal$1;
fundingFee: Decimal$1;
}
interface AccountInfo {
address: string;
balance: Decimal$1;
usdcBalance: Decimal$1;
tradingAllowance: Decimal$1;
totalCollateral: Decimal$1;
freeCollateral: Decimal$1;
marginUsed: Decimal$1;
unrealizedPnl: Decimal$1;
realizedPnl: Decimal$1;
positions: Position[];
marginLevel: number;
}
interface MarketStats {
pair: string;
price: Decimal$1;
volume24h: Decimal$1;
high24h: Decimal$1;
low24h: Decimal$1;
change24h: Decimal$1;
changePercent24h: number;
openInterest: Decimal$1;
fundingRate: Decimal$1;
nextFundingTime: Date;
}
declare enum MarginUpdateType {
ADD = 0,
REMOVE = 1
}
interface UpdateMarginParams {
pairIndex: number;
positionIndex: number;
type: MarginUpdateType;
amount: Decimal$1 | number | string;
autofetchPrices?: boolean;
priceUpdateData?: string[];
}
declare enum LimitOrderType {
TP = 0,// Take Profit
SL = 1,// Stop Loss
LIQ = 2,// Liquidation
OPEN = 3
}
interface ExecuteLimitOrderParams {
orderType: LimitOrderType;
trader: string;
pairIndex: number;
index: number;
priceUpdateData?: string[];
}
type ChainId = 8453 | 84531;
interface NetworkConfig {
chainId: ChainId;
name: string;
rpcUrl: string;
explorerUrl: string;
nativeCurrency: {
name: string;
symbol: string;
decimals: number;
};
contracts: {
trading: string;
tradingStorage?: string;
tradingCallbacks?: string;
pairInfos?: string;
pairStorage?: string;
priceAggregator?: string;
vaultManager?: string;
usdc: string;
priceFeed: string;
vault: string;
router: string;
avnt?: string;
multicall?: string;
referral?: string;
};
websocketUrl?: string;
}
interface SignerConfig {
type: "privateKey" | "mnemonic" | "jsonRpc" | "injected" | "viemClient" | "privyClient";
privateKey?: string;
mnemonic?: string;
path?: string;
provider?: any;
client?: WalletClient;
privyClient?: any;
privyWalletId?: string;
}
interface TransactionConfig {
gasLimit?: bigint;
gasPrice?: bigint;
maxFeePerGas?: bigint;
maxPriorityFeePerGas?: bigint;
nonce?: number;
value?: bigint;
}
interface TransactionResult {
hash: string;
blockNumber?: number;
blockHash?: string;
timestamp?: number;
from: string;
to: string;
value: bigint;
gasUsed: bigint;
effectiveGasPrice: bigint;
status: "success" | "failed" | "pending";
logs?: any[];
}
interface ContractCall {
contract: string;
method: string;
args: any[];
value?: bigint;
gasLimit?: bigint;
}
interface EventFilter {
address?: string | string[];
topics?: (string | string[] | null)[];
fromBlock?: number | string;
toBlock?: number | string;
}
interface BlockchainEvent {
address: string;
topics: string[];
data: string;
blockNumber: number;
transactionHash: string;
transactionIndex: number;
blockHash: string;
logIndex: number;
removed: boolean;
}
type ProviderType = PublicClient;
type SignerType = WalletClient;
type AccountType = Account;
type TransportType = Transport;
type ChainType = Chain;
type TransactionRequestType = TransactionRequest;
type TransactionResponseType = Hash;
type TransactionReceiptType = TransactionReceipt;
type LogType = Log;
interface PriceFeedData {
pair: string;
price: Decimal$1;
bid: Decimal$1;
ask: Decimal$1;
timestamp: Date;
confidence: number;
expo: number;
}
interface PriceUpdate {
feedId: string;
price: Decimal$1;
publishTime: Date;
prevPrice?: Decimal$1;
emaPrice?: Decimal$1;
}
interface OrderBook {
pair: string;
bids: OrderBookEntry[];
asks: OrderBookEntry[];
timestamp: Date;
}
interface OrderBookEntry {
price: Decimal$1;
size: Decimal$1;
}
interface Candle {
time: Date;
open: Decimal$1;
high: Decimal$1;
low: Decimal$1;
close: Decimal$1;
volume: Decimal$1;
}
interface MarketHours {
pair: string;
isOpen: boolean;
nextOpen?: Date;
nextClose?: Date;
timezone: string;
}
type PriceSubscriptionCallback = (data: PriceFeedData) => void;
type MarketEventCallback = (event: MarketEvent) => void;
interface MarketEvent {
type: 'trade' | 'liquidation' | 'funding' | 'orderbook_update';
pair: string;
data: any;
timestamp: Date;
}
interface FundingRate {
pair: string;
rate: Decimal$1;
nextFundingTime: Date;
timestamp: Date;
}
interface LiquidationEvent {
positionId: string;
pair: string;
side: 'long' | 'short';
size: Decimal$1;
price: Decimal$1;
timestamp: Date;
}
interface TradeEvent {
pair: string;
price: Decimal$1;
size: Decimal$1;
side: 'buy' | 'sell';
timestamp: Date;
}
declare enum TimeInterval {
M1 = "1m",
M5 = "5m",
M15 = "15m",
M30 = "30m",
H1 = "1h",
H4 = "4h",
D1 = "1d",
W1 = "1w"
}
interface PairStorageData {
pairIndex: number;
feed: {
maxOpenDeviationP: number;
maxCloseDeviationP: number;
feedId: string;
};
backupFeed: {
maxDeviationP: number;
feedId: string;
};
spreadP: number;
pnlSpreadP: number;
leverages: {
minLeverage: number;
maxLeverage: number;
pnlMinLeverage: number;
pnlMaxLeverage: number;
};
priceImpactMultiplier: number;
skewImpactMultiplier: number;
groupIndex: number;
feeIndex: number;
values: {
maxGainP: number;
maxSlP: number;
maxLongOiP: number;
maxShortOiP: number;
groupOpenInterestPecentage: number;
maxWalletOI: number;
isUSDCAligned: boolean;
};
}
interface PairInfosData {
name: string;
from: string;
to: string;
feed: string;
spreadP: number;
groupIndex: number;
feeIndex: number;
minLeverage: number;
maxLeverage: number;
minPositionSize: Decimal$1;
maxPositionSize: Decimal$1;
maxOpenInterestLong: Decimal$1;
maxOpenInterestShort: Decimal$1;
}
interface MarketData {
pairIndex: number;
name: string;
from: string;
to: string;
pythFeedId: string;
spreadPercent: number;
minLeverage: number;
maxLeverage: number;
minPositionSizeUSDC: Decimal$1;
maxPositionSizeUSDC: Decimal$1;
maxOpenInterestLong: Decimal$1;
maxOpenInterestShort: Decimal$1;
groupIndex: number;
feeIndex: number;
priceImpactMultiplier: number;
skewImpactMultiplier: number;
isUSDCAligned: boolean;
currentPrice?: {
price: string;
confidence: string;
expo: number;
publishTime: number;
};
}
declare const NETWORKS: Record<"base" | "base-sepolia", NetworkConfig>;
declare const TRADING_PAIRS: {
"BTC/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"ETH/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"LINK/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"MATIC/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"DOGE/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"SOL/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"ADA/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"AVAX/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"ATOM/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"DOT/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"FTM/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"NEAR/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"ALGO/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"XRP/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"LTC/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"BCH/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"ICP/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"ETC/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"XLM/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"FIL/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"UNI/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"APE/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"SHIB/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"ARB/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"OP/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "crypto";
};
"EUR/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"GBP/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"USD/JPY": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"USD/CHF": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"AUD/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"USD/CAD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"NZD/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"EUR/GBP": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"EUR/JPY": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"GBP/JPY": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "forex";
};
"XAU/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "commodity";
};
"XAG/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "commodity";
};
"WTI/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "commodity";
};
"BRENT/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "commodity";
};
"SPX500/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "index";
};
"NAS100/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "index";
};
"US30/USD": {
feedId: string;
minSize: number;
maxSize: number;
maxLeverage: number;
decimals: number;
category: "index";
};
};
declare const FEES: {
openPositionFee: number;
closePositionFee: number;
borrowFeePerHour: number;
fundingFeeMax: number;
liquidationFee: number;
};
declare const DEFAULTS: {
slippage: number;
gasLimit: bigint;
confirmations: number;
timeout: number;
maxRetries: number;
};
/**
* Client for interacting with PriceAggregator and PairInfos contracts
* Provides access to price feeds and pair configuration
*/
interface PairInfo {
id: number;
name: string;
from: string;
to: string;
feed: string;
spreadP: number;
groupIndex: number;
feeIndex: number;
minLeverage: number;
maxLeverage: number;
minPositionSize: Decimal$1;
maxPositionSize: Decimal$1;
maxOpenInterestLong: Decimal$1;
maxOpenInterestShort: Decimal$1;
}
interface PriceData {
price: Decimal$1;
timestamp: Date;
confidence: number;
}
declare class PriceClient {
private blockchain;
private priceAggregatorContract?;
private pairInfosContract?;
private network;
private pairInfoCache;
private allPairsCache;
private cacheTimestamp;
private readonly CACHE_TTL_MS;
constructor(networkName?: keyof typeof NETWORKS, customRpcUrl?: string);
/**
* Initializes smart contract instances
*/
private initializeContracts;
/**
* Gets the current price for a pair
*/
getPrice(pairIndex: number): Promise<PriceData>;
/**
* Gets prices for multiple pairs
*/
getMultiplePrices(pairIndices: number[]): Promise<Map<number, PriceData>>;
/**
* Gets pair information
*/
getPairInfo(pairIndex: number, useCache?: boolean): Promise<PairInfo>;
/**
* Gets all pair infos dynamically from the contract
* Note: This uses the blockchain provider to access PairStorage for the count
* @param useCache - Whether to use cached data (default: true)
* @param onProgress - Optional callback to track progress
*/
getAllPairInfos(useCache?: boolean, onProgress?: (current: number, total: number) => void): Promise<PairInfo[]>;
/**
* Clears the pair info cache and forces a refresh on next request
*/
clearCache(): void;
/**
* Refreshes all pair info from the contract
*/
refreshPairInfos(onProgress?: (current: number, total: number) => void): Promise<PairInfo[]>;
/**
* Gets pair info from PairInfos contract by index
* Note: PairInfos contract on Avantis stores fee/rollover data, not pair names
* Pair names are derived from pair index
*/
getPairInfosData(pairIndex: number): Promise<any>;
/**
* Gets trading fees for a pair
*/
getTradingFees(pairIndex: number): Promise<{
openFee: number;
closeFee: number;
oracleFee: number;
triggerOrderFee: number;
}>;
/**
* Checks if oracle prices are valid
*/
isPriceValid(pairIndex: number): Promise<boolean>;
/**
* Gets the network configuration
*/
getNetwork(): NetworkConfig;
/**
* Disconnects from the blockchain
*/
disconnect(): void;
}
/**
* PythClient - Client for interacting with Pyth Network price oracles
*
* Pyth Network provides real-time price feeds for various assets.
* This client fetches price update data from the Pyth Hermes API,
* which is required by Avantis trading contracts.
*
* Hermes API: https://hermes.pyth.network
*/
interface PythPriceUpdate {
feedId: string;
price: string;
conf: string;
expo: number;
publishTime: number;
}
interface FormattedPythPrice {
feedId: string;
price: number;
rawPrice: string;
confidence: number;
expo: number;
publishTime: number;
}
interface PythClientConfig {
hermesUrl?: string;
network?: "mainnet" | "testnet";
socketApiUrl?: string;
}
declare class PythClient {
private readonly hermesUrl;
private readonly socketApiUrl;
private marketCache?;
private cacheTimestamp;
private readonly CACHE_TTL_MS;
private cacheRefreshPromise?;
/**
* Creates a new PythClient instance
* @param config - Configuration options
*/
constructor(config?: PythClientConfig);
/**
* Fetches price update data for a single trading pair
* Dynamically fetches the feed ID from Socket API
* @param pair - The trading pair name (e.g., 'BTC/USD', 'TRUMP/USD')
* @returns Price update data as bytes array
*/
getPriceUpdateData(pair: string): Promise<string[]>;
/**
* Fetches price update data for multiple trading pairs
* Dynamically fetches feed IDs from Socket API
* @param pairs - Array of trading pair names
* @returns Price update data as bytes array
*/
getPriceUpdateDataForPairs(pairs: string[]): Promise<string[]>;
/**
* Fetches price update data by feed IDs
* @param feedIds - Array of Pyth price feed IDs
* @returns Price update data as bytes array
*/
getPriceUpdateDataByFeedIds(feedIds: string[]): Promise<string[]>;
/**
* Gets the latest price for a trading pair (for display/informational purposes)
* Note: This does NOT return update data needed for transactions
* This method dynamically fetches the feed ID from Socket API
* @param pair - The trading pair name (e.g., 'BTC/USD', 'TRUMP/USD')
* @returns Price information
*/
getLatestPrice(pair: string): Promise<PythPriceUpdate>;
/**
* Dynamically fetches the Pyth feed ID for a trading pair from Socket API
* Uses caching to minimize API calls
* @param pair - The trading pair name (e.g., 'BTC/USD')
* @returns The Pyth feed ID
*/
private getFeedIdForPair;
/**
* Refreshes the market cache from Socket API
* @private
*/
private refreshMarketCache;
/**
* Formats a raw Pyth price by applying the exponent
* @param priceUpdate - Raw price update from Pyth
* @returns Formatted price with exponent applied
*/
formatPythPrice(priceUpdate: PythPriceUpdate): FormattedPythPrice;
/**
* Gets the latest price by Pyth feed ID (for display/informational purposes)
* This method accepts feed IDs directly from contracts
* @param feedId - The Pyth feed ID (bytes32 hex string)
* @returns Price information
*/
getLatestPriceByFeedId(feedId: string): Promise<PythPriceUpdate>;
/**
* Gets the latest formatted price by Pyth feed ID
* Returns the price with exponent already applied for easy display
* @param feedId - The Pyth feed ID (bytes32 hex string)
* @returns Formatted price information
*/
getFormattedPriceByFeedId(feedId: string): Promise<FormattedPythPrice>;
/**
* Gets latest prices for multiple feed IDs
* Useful for batch fetching prices from contract-provided feed IDs
* @param feedIds - Array of Pyth feed IDs (bytes32 hex strings)
* @returns Map of feed ID to price data
*/
getLatestPricesByFeedIds(feedIds: string[]): Promise<Map<string, PythPriceUpdate>>;
/**
* Gets the configured Hermes URL
*/
getHermesUrl(): string;
}
declare class TraderClient extends EventEmitter {
private blockchain;
private tradingContract?;
private usdcContract;
private network;
private positions;
private feeManager?;
private multicallBundler?;
private pythClient;
private socketAPI;
private marketConfigCache?;
private marketCacheTimestamp;
private readonly MARKET_CACHE_TTL_MS;
constructor(networkName?: keyof typeof NETWORKS, customRpcUrl?: string);
/**
* Initializes smart contract instances
*/
private initializeContracts;
/**
* Sets the signer for transactions
*/
setSigner(config: SignerConfig): Promise<void>;
/**
* Gets the current account address
*/
getAddress(): Promise<string>;
/**
* Gets the network configuration
*/
getNetwork(): NetworkConfig;
/**
* Gets the Pyth client for advanced price oracle operations
*/
getPythClient(): PythClient;
/**
* Gets account information
*/
getAccountInfo(): Promise<AccountInfo>;
/**
* Gets USDC balance
*/
getUSDCBalance(address?: string): Promise<Decimal$1>;
/**
* Gets USDC allowance for trading
*/
getTradingAllowance(address?: string): Promise<Decimal$1>;
/**
* Approves USDC for trading
*/
approveUSDCForTrading(amount?: Decimal$1 | number | string): Promise<TradeResponse>;
/**
* Approves maximum USDC for trading (one-time approval for unlimited trading)
* This approves the maximum uint256 value, so you never need to approve again
*/
approveMaxUSDC(): Promise<TradeResponse>;
/**
* Opens a new trading position (market or limit order)
*/
openPosition(params: OpenPositionParams): Promise<TradeResponse>;
/**
* Closes an existing position
*/
closePosition(params: ClosePositionParams): Promise<TradeResponse>;
/**
* Updates position stop loss and take profit
*/
updatePosition(params: UpdatePositionParams): Promise<TradeResponse>;
/**
* Gets a specific position from TradingStorage
*/
getPosition(pairIndex: number, positionIndex: number, trader?: string): Promise<Position | null>;
/**
* Gets all positions for the current account
*/
getPositions(address?: string): Promise<Position[]>;
/**
* Parses position data from contract and enriches with calculations
*/
private parsePositionData;
/**
* Cancels a pending limit order
*/
cancelLimitOrder(params: CancelLimitOrderParams): Promise<TradeResponse>;
/**
* Updates a pending limit order
*/
updateLimitOrder(params: UpdateLimitOrderParams): Promise<TradeResponse>;
/**
* Gets the pair index for a given pair name (DEPRECATED - uses hardcoded mapping)
* @deprecated Use getPairIndexFromAPI() instead for accurate pair indices
*/
getPairIndex(pairName: string): number;
/**
* Gets the pair name for a given index (DEPRECATED - uses hardcoded mapping)
* @deprecated Use getPairNameFromAPI() instead for accurate pair names
*/
getPairName(index: number): string;
/**
* Gets all available trading pairs (DEPRECATED - uses hardcoded mapping)
* @deprecated Use getAllPairsFromAPI() instead for all 89+ pairs
*/
getAllPairs(): string[];
/**
* Gets pairs by category (DEPRECATED - uses hardcoded mapping)
* @deprecated Use Socket API methods via AvantisSDK.getMarketsByType() instead
*/
getPairsByCategory(category: "crypto" | "forex" | "commodity" | "index"): string[];
/**
* Gets the pair index for a given pair name from Socket API (dynamic, accurate)
* @param pairName - The pair name (e.g., "ETH/USD", "BTC/USD")
* @returns The pair index or throws error if not found
*/
getPairIndexFromAPI(pairName: string): Promise<number>;
/**
* Gets market configuration by pair index from Socket API with caching
* @param pairIndex - The pair index
* @returns Market configuration with dynamic limits
*/
private getMarketConfigByPairIndex;
/**
* Refreshes the market cache from Socket API
*/
private refreshMarketCache;
/**
* Gets market configuration from Socket API with caching (dynamic, accurate)
* Provides real-time min/max position sizes, leverage limits, and spread
* @param pairName - The pair name (e.g., "ETH/USD", "BTC/USD")
* @returns Market configuration with dynamic limits
*/
getMarketConfig(pairName: string): Promise<any>;
/**
* Gets the pair name for a given index from Socket API (dynamic, accurate)
* @param index - The pair index
* @returns The pair name or throws error if not found
*/
getPairNameFromAPI(index: number): Promise<string>;
/**
* Gets all available trading pairs from Socket API (89+ pairs)
* @returns Array of all pair names
*/
getAllPairsFromAPI(): Promise<string[]>;
/**
* Sets platform fee configuration
*/
setPlatformFeeConfig(config: Partial<PlatformFeeConfig>): void;
/**
* Gets current platform fee configuration
*/
getPlatformFeeConfig(): PlatformFeeConfig | null;
/**
* Calculates fee breakdown for a trade
*/
calculateFeeBreakdown(tradeSize: Decimal$1 | number | string, params?: PlatformFeeParams): FeeBreakdown | null;
/**
* Opens a position with platform fees (bundled transaction)
*/
openPositionWithFees(params: OpenPositionParams): Promise<TradeResponse>;
/**
* Closes a position with platform fees (bundled transaction)
*/
closePositionWithFees(params: ClosePositionParams): Promise<TradeResponse>;
/**
* Updates margin for an open position (add or remove collateral)
*/
updateMargin(params: UpdateMarginParams): Promise<TradeResponse>;
/**
* Executes a limit order (for keepers/bots)
*/
executeLimitOrder(params: ExecuteLimitOrderParams): Promise<TradeResponse>;
/**
* Gets all pending limit orders for the current account
* Uses the custom Avantis Multicall contract for efficient data fetching
*/
getPendingLimitOrders(address?: string): Promise<PendingLimitOrder[]>;
/**
* Disconnects from the blockchain
*/
disconnect(): void;
}
interface PriceFeedConfig {
apiUrl?: string;
websocketUrl?: string;
apiKey?: string;
network?: keyof typeof NETWORKS;
}
declare class FeedClient extends EventEmitter {
private ws?;
private http;
private subscriptions;
private marketEventCallbacks;
private priceCache;
private config;
private reconnectAttempts;
private isConnected;
constructor(config?: PriceFeedConfig);
/**
* Connects to the price feed WebSocket
*/
connect(): Promise<void>;
/**
* Disconnects from the price feed WebSocket
*/
disconnect(): void;
/**
* Subscribes to price updates for a trading pair
*/
subscribeToPrice(pair: string, callback: PriceSubscriptionCallback): () => void;
/**
* Gets the latest price for a trading pair
* @deprecated This method attempts to fetch from a non-existent Avantis price API.
* Use Pyth Network integration instead: sdk.pyth.getLatestPriceByFeedId()
*/
getLatestPrice(pair: string): Promise<PriceFeedData>;
/**
* Gets multiple price feeds at once
*/
getMultiplePrices(pairs: string[]): Promise<Map<string, PriceFeedData>>;
/**
* Gets market statistics for a trading pair
* @deprecated This method is not functional as Avantis does not provide a public stats API.
* Use Socket API for open interest data or Pyth Network for current prices instead.
*/
getMarketStats(pair: string): Promise<MarketStats>;
/**
* Gets historical candle data
* @deprecated This method is not functional as Avantis does not provide a public candles API.
* Consider using on-chain event queries or third-party indexers for historical data.
*/
getCandles(pair: string, interval: TimeInterval, limit?: number): Promise<Candle[]>;
/**
* Gets market hours for a trading pair
*/
getMarketHours(pair: string): Promise<MarketHours>;
/**
* Gets the current funding rate
*/
getFundingRate(pair: string): Promise<FundingRate>;
/**
* Subscribes to market events
*/
onMarketEvent(callback: MarketEventCallback): () => void;
/**
* Sets up WebSocket event handlers
*/
private setupWebSocketHandlers;
/**
* Handles incoming WebSocket messages
*/
private handleWebSocketMessage;
/**
* Handles price updates from WebSocket
*/
private handlePriceUpdate;
/**
* Handles trade events from WebSocket
*/
private handleTradeEvent;
/**
* Handles liquidation events from WebSocket
*/
private handleLiquidationEvent;
/**
* Handles funding rate updates
*/
private handleFundingUpdate;
/**
* Notifies price subscribers
*/
private notifyPriceSubscribers;
/**
* Notifies market event callbacks
*/
private notifyMarketEventCallbacks;
/**
* Subscribes to all active price feeds
*/
private subscribeToAllFeeds;
/**
* Gets trading pair from feed ID
*/
private getPairFromFeedId;
/**
* Gets next forex market open time
*/
private getNextForexOpen;
/**
* Gets next forex market close time
*/
private getNextForexClose;
}
/**
* Client for interacting with TradingStorage and PairStorage contracts
* Provides read-only access to trading data and pair information
*/
declare class StorageClient {
private blockchain;
private tradingStorageContract?;
private pairStorageContract?;
private network;
constructor(networkName?: keyof typeof NETWORKS, customRpcUrl?: string);
/**
* Initializes smart contract instances
*/
private initializeContracts;
/**
* Gets all trades for a specific trader
*/
getTrades(trader: string): Promise<any[]>;
/**
* Gets all pending limit orders for a trader
*/
getPendingLimitOrders(trader: string): Promise<PendingLimitOrder[]>;
/**
* Gets maximum open interest for a pair
*/
getMaxOpenInterest(pairIndex: number): Promise<Decimal$1>;
/**
* Gets current open interest for a pair
*/
getOpenInterest(pairIndex: number, isLong: boolean): Promise<Decimal$1>;
/**
* Gets borrowing fees for a pair
*/
getBorrowingFees(pairIndex: number, isLong: boolean): Promise<Decimal$1>;
/**
* Gets pair spread
*/
getPairSpread(pairIndex: number): Promise<number>;
/**
* Checks if a pair is listed
*/
isPairListed(pairIndex: number): Promise<boolean>;
/**
* Gets the total number of pairs available
*/
getPairsCount(): Promise<number>;
/**
* Gets full pair data from the PairStorage contract
* This includes feed IDs, leverage limits, spreads, etc.
*/
getPairData(pairIndex: number): Promise<PairStorageData>;
/**
* Gets all pair data from the contract dynamically
* Only returns pairs with valid Pyth feed IDs
*/
getAllPairsData(): Promise<PairStorageData[]>;
/**
* Gets the network configuration
*/
getNetwork(): NetworkConfig;
/**
* Disconnects from the blockchain
*/
disconnect(): void;
}
/**
* Client for interacting with Avantis Socket API
* Provides access to complete market data including all 91 trading pairs
*/
declare class SocketAPIClient {
private readonly apiUrl;
private cache;
private allMarketsCache;
private cacheTimestamp;
private readonly CACHE_TTL_MS;
constructor(apiUrl?: string);
/**
* Fetches raw data from Avantis Socket API
*/
private fetchSocketData;
/**
* Converts Socket API pair info to MarketData format
*/
private convertToMarketData;
/**
* Gets all available markets from the Socket API
* @param useCache - Whether to use cached data (default: true)
*/
getAllMarkets(useCache?: boolean): Promise<MarketData[]>;
/**
* Gets a specific market by pair index
* @param pairIndex - The pair index to fetch
* @param useCache - Whether to use cached data (default: true)
*/
getMarket(pairIndex: number, useCache?: boolean): Promise<MarketData | null>;
/**
* Gets markets by asset type (crypto, forex, stocks, etc.)
* @param assetType - The asset type to filter by
*/
getMarketsByType(assetType: string): Promise<MarketData[]>;
/**
* Gets all available asset types
*/
getAssetTypes(): Promise<string[]>;
/**
* Clears the cache
*/
clearCache(): void;
/**
* Gets the total open interest across all markets
*/
getTotalOpenInterest(): Promise<{
long: number;
short: number;
}>;
/**
* Gets the data version from the API
*/
getDataVersion(): Promise<string>;
}
declare class AvantisSDK {
readonly trader: TraderClient;
readonly feed: FeedClient;
readonly storage: StorageClient;
readonly price: PriceClient;
readonly pyth: PythClient;
readonly socketAPI: SocketAPIClient;
private readonly networkName;
/**
* Creates a new instance of the Avantis SDK
* @param networkName - The network to connect to ('base', 'base-sepolia', etc.)
* @param customRpcUrl - Optional custom RPC URL
*/
constructor(networkName?: keyof typeof NETWORKS, customRpcUrl?: string);
/**
* Sets the signer for all clients
* @param config - The signer configuration
*/
setSigner(config: SignerConfig): Promise<void>;
/**
* Gets the current network name
*/
getNetwork(): string;
/**
* Gets the current account address from the trader client
*/
getAddress(): Promise<string>;
/**
* Disconnects all clients
*/
disconnect(): void;
/**
* Gets all pending limit orders for the current account
*/
getPendingLimitOrders(): Promise<any[]>;
/**
* Gets all available markets from the contract dynamically
* Combines data from PairStorage (feed IDs, leverage) and PairInfos (names)
* @param useCache - Whether to use cached data (default: true)
* @param onProgress - Optional callback to track progress
*/
getAllMarkets(useCache?: boolean, onProgress?: (current: number, total: number) => void): Promise<MarketData[]>;
/**
* Gets all markets with their current prices from Pyth
* @param useCache - Whether to use cached pair data (default: true)
* @param onProgress - Optional callback to track progress
*/
getAllMarketsWithPrices(useCache?: boolean, onProgress?: (current: number, total: number) => void): Promise<MarketData[]>;
/**
* Gets all markets from the Avantis Socket API (recommended)
* This method fetches all 91 trading pairs with complete metadata
* @param useCache - Whether to use cached data (default: true)
*/
getAllMarketsFromAPI(useCache?: boolean): Promise<MarketData[]>;
/**
* Gets all markets from the Socket API with current Pyth prices
* @param useCache - Whether to use cached market data (default: true)
*/
getAllMarketsFromAPIWithPrices(useCache?: boolean): Promise<MarketData[]>;
/**
* Gets markets by asset type (crypto, forex, stocks, etc.)
* @param assetType - The asset type to filter by (e.g., 'Crypto', 'Forex', 'Stocks')
*/
getMarketsByType(assetType: string): Promise<MarketData[]>;
/**
* Gets all available asset types
*/
getAssetTypes(): Promise<string[]>;
/**
* Gets a specific market by pair index from the Socket API
* @param pairIndex - The pair index
* @param useCache - Whether to use cached data (default: true)
*/
getMarketByIndex(pairIndex: number, useCache?: boolean): Promise<MarketData | null>;
/**
* Gets the total open interest across all markets
*/
getTotalOpenInterest(): Promise<{
long: number;
short: number;
}>;
/**
* Refreshes market data from the contract (bypasses cache)
*/
refreshMarkets(onProgress?: (current: number, total: number) => void): Promise<PairInfo[]>;
/**
* Clears all cached market data (both on-chain and API)
*/
clearMarketCache(): void;
/**
* Gets the SDK version
*/
getVersion(): string;
/**
* Gets the pair index for a given pair name from the Socket API
* @param pairName - The pair name (e.g., "ETH/USD", "BTC/USD")
* @param useCache - Whether to use cached data (default: true)
* @returns The pair index or null if not found
*/
getPairIndexByName(pairName: string, useCache?: boolean): Promise<number | null>;
/**
* Gets the pair name for a given index from the Socket API
* @param pairIndex - The pair index
* @param useCache - Whether to use cached data (default: true)
* @returns The pair name or null if not found
*/
getPairNameByIndex(pairIndex: number, useCache?: boolean): Promise<string | null>;
/**
* Gets all pair names from the Socket API
* @param useCache - Whether to use cached data (default: true)
* @returns Array of all pair names
*/
getAllPairNames(useCache?: boolean): Promise<string[]>;
}
/**
* FeeManager - Handles platform fee calculations and distributions
*/
declare class FeeManager {
private config;
constructor(config?: Partial<PlatformFeeConfig>);
/**
* Validates the fee configuration
*/
private validateConfig;
/**
* Updates the fee configuration
*/
updateConfig(config: Partial<PlatformFeeConfig>): void;
/**
* Gets the current configuration
*/
getConfig(): PlatformFeeConfig;
/**
* Checks if fees are enabled
*/
isEnabled(): boolean;
/**
* Calculates platform fee for a trade
*/
calculatePlatformFee(tradeSize: Decimal$1 | number | string, discountPercent?: number): Decimal$1;
/**
* Applies a discount to a fee amount
*/
applyDiscount(fee: Decimal$1, discountPercent: number): Decimal$1;
/**
* Calculates the fee split between platform and referrer
*/
splitFeeForReferral(totalFee: Decimal$1): {
platform: Decimal$1;
referral: Decimal$1;
};
/**
* Calculates complete fee breakdown for a trade
*/
calculateFeeBreakdown(tradeSize: Decimal$1 | number | string, params?: PlatformFeeParams): FeeBreakdown;
/**
* Validates fee parameters for a trade
*/
validateFeeParams(params: PlatformFeeParams): void;
/**
* Formats fee breakdown for display
*/
formatFeeBreakdown(breakdown: FeeBreakdown): string[];
}
/**
* MulticallBundler - Handles bundling multiple transactions into a single Multicall3 transaction
*/
declare class MulticallBundler {
private multicallAddress;
constructor(multicallAddress?: string);
/**
* Creates a USDC approval call
*/
createApprovalCall(usdcAddress: string, spender: string, amount: bigint): CallData;
/**
* Creates a USDC transfer call
*/
createTransferCall(usdcAddress: string, recipient: string, amount: bigint): CallData;
/**
* Creates an openTrade call
*/
createOpenTradeCall(tradingAddress: string, tradeStruct: any, orderTypeValue: number, slippageUnits: bigint, executionFee: bigint): CallData;
/**
* Creates a closeTradeMarket call
*/
createCloseTradeCall(tradingAddress: string, pairIndex: number, positionIndex: number, amount: bigint, executionFee: bigint): CallData;
/**
* Bundles multiple calls into a single Multicall3 transaction
*/
bundleCalls(calls: CallData[], description?: string[]): BundledTransaction;
/**
* Bundles a trade with platform fees
*/
bundleTradeWithFees(params: {
usdcAddress: string;
tradingAddress: string;
platformWallet: string;
referralAddress?: string;
totalAmount: bigint;
platformFeeAmount: bigint;
referralFeeAmount?: bigint;
tradeStruct: any;
orderTypeValue: number;
slippageUnits: bigint;
executionFee: bigint;
}): BundledTransaction;
/**
* Bundles a close position with platform fees
*/
bundleCloseWithFees(params: {
usdcAddress: string;
tradingAddress: string;
platformWallet: string;
referralAddress?: string;
platformFeeAmount: bigint;
referralFeeAmount?: bigint;
pairIndex: number;
positionIndex: number;
closeAmount: bigint;
executionFee: bigint;
}): BundledTransaction;
/**
* Decodes the result of a multicall transaction
* Note: viem provides better utilities for this, but keeping for compatibility
*/
decodeMulticallResult(data: string): {
success: boolean;
results: Array<{
success: boolean;
returnData: string;
}>;
};
/**
* Generates default descriptions for calls
*/
private generateDefaultDescriptions;
}
/**
* Default constants for platform fee management
*/
/**
* Minimum platform fee percentage (0.01%)
*/
declare const MIN_PLATFORM_FEE_PERCENT = 0.0001;
/**
* Maximum platform fee percentage (5%)
*/
declare const MAX_PLATFORM_FEE_PERCENT = 0.05;
/**
* Default platform fee percentage (0.1%)
*/
declare const DEFAULT_PLATFORM_FEE_PERCENT = 0.001;
/**
* Default referral split percentage (50%)
*/
declare const DEFAULT_REFERRAL_SPLIT_PERCENT = 50;
/**
* Maximum discount percentage (100% - free)
*/
declare const MAX_DISCOUNT_PERCENT = 100;
/**
* Multicall3 contract address on Base mainnet
*/
declare const MULTICALL3_ADDRESS = "0x7A829c5C97A2Bf8BeFB4b01d96A282E4763848d8";
declare class BlockchainProvider {
private publicClient;
private walletClient?;
private account?;
private network;