### Initialization and Setup Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt Examples demonstrating how to initialize the SDK and set up necessary configurations. ```typescript import { FlashTradeSDK } from "@flash-trade/sdk"; const sdk = new FlashTradeSDK({ // Configuration options }); ``` -------------------------------- ### One-time Setup for Flash Trade SDK Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/examples/readme.md This snippet outlines the necessary steps to set up your environment for using the Flash Trade SDK. It includes creating a keypair, funding the wallet, and installing dependencies. ```bash solana-keygen new --outfile localPublicKey.json solana airdrop 0.2 $(solana-keygen pubkey ./localPublicKey.json) cp .env.example .env yarn ``` -------------------------------- ### Example: Get LP Token Statistics Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-data-client.md Demonstrates how to build a price map and use it to retrieve LP token statistics, then log them to the console. ```typescript // Build price map from oracle data const pricesMap = new Map(); for (const custody of custodies) { const oraclePrice = await fetchOraclePrice(custody.mint); pricesMap.set(custody.symbol, { price: oraclePrice, emaPrice: oraclePrice // Use spot price for demo }); } const lpStats = poolDataClient.getLpStats(pricesMap); console.log(`LP Token Price: $${lpStats.priceUi}`); console.log(`Pool AUM: $${lpStats.totalPoolValueUsdUi}`); console.log(`Stablecoin %: ${lpStats.stableCoinPercentage}%`); ``` -------------------------------- ### Complete SDK Initialization Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md A comprehensive example demonstrating the initialization of the PerpetualsClient, including setting up the connection, provider, wallet, program IDs, and configuring transaction parameters like prioritization fee and commitment. ```typescript import { PerpetualsClient, PoolConfig, } from "flash-sdk"; import { AnchorProvider } from "@coral-xyz/anchor"; import { Connection, clusterApiUrl, PublicKey } from "@solana/web3.js"; async function initializeSDK() { // Setup connection const connection = new Connection( clusterApiUrl("mainnet-beta"), "confirmed" ); // Get wallet from browser const wallet = window.solana; if (!wallet?.isConnected) { throw new Error("Wallet not connected"); } // Create provider const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed", preflightCommitment: "confirmed", skipPreflight: true, }); // Initialize PerpetualsClient const programId = new PublicKey( "9Z8r9hzAeFYAKQKqMSB8YajhWk8dVwxeKp6GZw3dVFy6" ); const composabilityProgramId = new PublicKey( "CPgnYYBKvzohpMHZJvNNq4m2xh7EKt5txL7kUQXdGzxu" ); const fbNftRewardProgramId = new PublicKey( "DGkRuNmGdB5VKzQiHiJdHjDU4FfvxR8wJqJeYu7LHFVS" ); const rewardDistributionProgramId = new PublicKey( "5u7eV2LVWHjMfkRbV5kQGN7fVYqQDavQ5gqcKt5Cyt8Y" ); const perpClient = new PerpetualsClient( provider, programId, composabilityProgramId, fbNftRewardProgramId, rewardDistributionProgramId, { postSendTxCallback: ({ txid }) => { console.log(`✓ Tx: ${txid}`); }, prioritizationFee: 50000, txConfirmationCommitment: "confirmed", } ); // Load pool configuration const poolConfig = PoolConfig.fromIdsByName( "Crypto.1", "mainnet-beta" ); // Pre-load address lookup tables await perpClient.loadAddressLookupTable(poolConfig); console.log("✓ SDK initialized"); console.log(`✓ Pool: ${poolConfig.poolName}`); console.log(`✓ Wallet: ${wallet.publicKey.toBase58()}`); return { perpClient, poolConfig, provider }; } // Usage const { perpClient, poolConfig, provider } = await initializeSDK(); ``` -------------------------------- ### Install Flash Trade SDK Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/README.md Install the SDK using npm. This is the first step to begin using the library. ```bash npm install flash-sdk ``` -------------------------------- ### Run Local Devnet and Tests Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/README.md Commands to start a local Solana devnet environment and run tests using the Anchor framework. Ensure Anchor CLI is installed and configured. ```bash anchor localnet anchor test ``` -------------------------------- ### Install Flash SDK Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/SDK/readme.md Install the Flash SDK using npm or yarn. ```bash npm i flash-sdk ``` ```bash yarn add flash-sdk ``` -------------------------------- ### Getting Account Data Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt Examples for accessing account-specific information. ```typescript const accountData = await sdk.account.getData(address); ``` -------------------------------- ### Verify SDK Setup for Production Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md A helper function to verify critical setup parameters before deploying to production. It checks wallet connectivity, balance, program ID, pool configuration, and address lookup tables. ```typescript // Verification helper async function verifySetup( perpClient: PerpetualsClient, poolConfig: PoolConfig ): Promise { try { // Check wallet const wallet = perpClient.provider.wallet; console.log(`✓ Wallet: ${wallet.publicKey.toBase58()}`); // Check connection const balance = await perpClient.provider.connection.getBalance( wallet.publicKey ); if (balance === 0) { console.error("✗ Wallet balance is 0"); return false; } console.log(`✓ Balance: ${balance / 1e9} SOL`); // Check program const program = perpClient.program; console.log(`✓ Program: ${program.programId.toBase58()}`); // Check pool const pool = await perpClient.getPool(poolConfig.poolName); console.log(`✓ Pool: ${pool.name}`); // Check ALTs await perpClient.loadAddressLookupTable(poolConfig); console.log(`✓ ALTs loaded: ${poolConfig.addressLookupTableAddresses.length}`); return true; } catch (error) { console.error("✗ Verification failed:", error); return false; } } // Usage const isReady = await verifySetup(perpClient, poolConfig); ``` -------------------------------- ### OraclePrice scale_to_exponent Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Shows how to scale an OraclePrice to a target exponent, for example, -6. ```typescript const scaledPrice = oraclePrice.scale_to_exponent(new BN(-6)); ``` -------------------------------- ### Transaction Flow Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt A complete example illustrating a typical transaction flow within the SDK. ```typescript // Example of a complete transaction flow // (Specific code omitted for brevity, refer to detailed examples) ``` -------------------------------- ### Install Flash SDK using npm or yarn Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Install the Flash SDK using either npm or yarn package managers. Ensure you have the required dependencies installed. ```bash npm install flash-sdk # or yarn add flash-sdk ``` -------------------------------- ### Complete Pool Analysis with PoolDataClient Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-data-client.md This snippet shows how to load pool configurations, fetch on-chain data, and use the PoolDataClient to get LP and custody statistics. It requires setup with Solana web3.js and SPL token functionalities, and fetches price data from Pyth oracles. ```typescript import { PoolDataClient, PoolConfig, PoolAccount } from 'flash-sdk'; import { Connection, PublicKey } from '@solana/web3.js'; import { getMint } from '@solana/spl-token'; const connection = new Connection('https://api.mainnet-beta.solana.com'); // 1. Load pool configuration const poolConfig = PoolConfig.fromIdsByName('Crypto.1', 'mainnet-beta'); // 2. Fetch on-chain pool account const poolAccount = PoolAccount.from( poolConfig.poolAddress, await perpClient.getPool('Crypto.1') ); // 3. Fetch LP token mint data const lpMintInfo = await getMint( connection, poolConfig.stakedLpTokenMint ); // 4. Fetch all custody data const custodyPromises = poolConfig.custodies.map(custody => perpClient.program.account.custody.fetch(custody.custodyAccount) ); const custodyDatas = await Promise.all(custodyPromises); const custodies = custodyDatas.map((data, i) => CustodyAccount.from( poolConfig.custodies[i].custodyAccount, data ) ); // 5. Create PoolDataClient const poolDataClient = new PoolDataClient( poolConfig, poolAccount, lpMintInfo, custodies ); // 6. Fetch current oracle prices (example using Pyth) const pricesMap = new Map(); for (const custody of custodies) { const pythPrice = await fetchPythPrice(custody.mint); pricesMap.set( poolConfig.custodies[poolConfig.custodies.findIndex( c => c.custodyAccount.equals(custody.publicKey) )].symbol, { price: pythPrice, emaPrice: pythPrice } ); } // 7. Get statistics const lpStats = poolDataClient.getLpStats(pricesMap); const custodyStats = poolDataClient.getCustodyStats(pricesMap); console.log('=== LP Token Stats ==='); console.log(`Supply: ${lpStats.lpTokenSupply}`); console.log(`Price: $${lpStats.priceUi}`); console.log(`Pool AUM: $${lpStats.totalPoolValueUsdUi}`); console.log(`Stablecoin %: ${lpStats.stableCoinPercentage}%`); console.log(' === Custody Stats ==='); custodyStats.forEach(stats => { console.log(` ${stats.symbol}:`); console.log(` Price: $${stats.priceUi}`); console.log(` Owned: ${stats.assetsOwnedAmountUi} ${stats.symbol}`); console.log(` Ratio: ${stats.currentRatioUi}% (Target: ${stats.targetRatioUi}%)`); console.log(` Available to Add: ${stats.availableToAddAmountUi} ${stats.symbol}`); console.log(` Available to Remove: ${stats.availableToRemoveAmountUi} ${stats.symbol}`); }); ``` -------------------------------- ### Example: Get Custody Token Statistics Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-data-client.md Iterates through custody statistics, logging details such as symbol, price, current ratio, available amount to add, and utilization for each token. ```typescript const custodyStats = poolDataClient.getCustodyStats(pricesMap); custodyStats.forEach(stats => { console.log(`${stats.symbol}:`); console.log(` Price: $${stats.priceUi}`); console.log(` Current Ratio: ${stats.currentRatioUi}%`); console.log(` Available to Add: ${stats.availableToAddAmountUi} ${stats.symbol}`); console.log(` Utilization: ${stats.utilizationUi}%`); }); ``` -------------------------------- ### OraclePrice Comparison Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Demonstrates how to use the cmp method to compare two OraclePrice instances. ```typescript const priceA = new OraclePrice({ price: new BN(35000e9), exponent: new BN(-9), confidence: BN_ZERO }); const priceB = new OraclePrice({ price: new BN(36000e9), exponent: new BN(-9), confidence: BN_ZERO }); if (priceA.cmp(priceB) < 0) { console.log('Price A is lower'); } ``` -------------------------------- ### Close Position Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Shows how to close an existing long BTC/USDC position. This example includes an option to convert WSOL back to SOL upon closing. The method returns transaction instructions and required signers. ```typescript const { instructions, additionalSigners } = await perpClient.closePosition( 'BTC', 'USDC', { price: new BN(36000e9), exponent: -9 }, poolConfig, Side.Long, true // convert WSOL to SOL ); ``` -------------------------------- ### Fetching Positions Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt Code examples for retrieving details of open positions. ```typescript const positions = await sdk.perpetuals.fetchPositions(); ``` -------------------------------- ### Node.js Wallet Setup for Scripting Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Illustrates how to create and use a wallet in a Node.js environment for scripting purposes. It involves generating a keypair and wrapping it with Anchor's `NodeWallet`. ```typescript import { Keypair } from "@solana/web3.js"; import { NodeWallet } from "@coral-xyz/anchor"; const keypair = Keypair.generate(); const wallet = new NodeWallet(keypair); const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed", }); ``` -------------------------------- ### Browser Wallet Setup with React Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Demonstrates how to set up a browser wallet connection within a React component using the `@solana/wallet-adapter-react` library. It shows how to obtain wallet details and initialize an Anchor provider. ```typescript import { useWallet } from "@solana/wallet-adapter-react"; // In React component const { wallet, publicKey, signTransaction } = useWallet(); const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed", }); const perpClient = new PerpetualsClient( provider, programId, // ... other params ); ``` -------------------------------- ### Connect SDK Locally Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/SDK/readme.md Connect to a local instance of the SDK using AnchorProvider. This example demonstrates setting up the provider, initializing the PerpetualsClient, and configuring pool settings. ```typescript import { AnchorProvider } from "@coral-xyz/anchor"; import { ComputeBudgetProgram , PublicKey, TransactionInstruction } from '@solana/web3.js' const provider : AnchorProvider = AnchorProvider.local(clusterUrl, { commitment: "confirmed", preflightCommitment: "confirmed", skipPreflight: true }); const perpClient = new PerpetualsClient(provider, programId); // NOTE: choose the correct POOL_CONFIG based on the pool you want to interact // flp.1 const POOL_CONFIG = PoolConfig.fromIdsByName('Crypto.1','mainnet-beta') // flp.2 // const POOL_CONFIG = PoolConfig.fromIdsByName('Virtual.1','mainnet-beta') // flp.3 // const POOL_CONFIG = PoolConfig.fromIdsByName('Governance.1','mainnet-beta') // flp.4 // const POOL_CONFIG = PoolConfig.fromIdsByName('Community.1','mainnet-beta') // flp.5 // const POOL_CONFIG = PoolConfig.fromIdsByName('Community.2','mainnet-beta') // flp.7 // const POOL_CONFIG = PoolConfig.fromIdsByName('Trump.1','mainnet-beta') // flp.8 // const POOL_CONFIG = PoolConfig.fromIdsByName('Ore.1','mainnet-beta') // flp.r // const POOL_CONFIG = PoolConfig.fromIdsByName('Remora.1','mainnet-beta') const poolAddress = POOL_CONFIG.poolAddress.toBase58() const backupOracleData: any = await (await fetch(`https://flash.trade/api/backup-oracle?poolAddress=${poolAddress}`)).json() const backUpOracleInstruction = new TransactionInstruction({ keys: backupOracleData.keys, programId: new PublicKey(backupOracleData.programId), data: Buffer.from(backupOracleData.data), }) const USDC_TOKEN = POOL_CONFIG.tokens.find((t) => t.symbol == 'USDC')! const BTC_TOKEN = POOL_CONFIG.tokens.find((t) => t.symbol == 'BTC')! const tokenMint = new PublicKey('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v') const USDC_TOKEN = POOL_CONFIG.tokens.find((t) => t.mintKey.equals(tokenMint))! await perpClient.loadAddressLookupTable(POOL_CONFIG) const payTokenSymbol = 'USDC'; // 'SOL' , 'BTC', 'ETH' const { instructions : addLiqInstructions, additionalSigners : addLiqAdditionalSigners } = await perpClient.addLiquidityAndStake( payTokenSymbol, tokenAmountIn, minLpAmountOut, // new BN(0) POOL_CONFIG ) const setCULimitIx = ComputeBudgetProgram.setComputeUnitLimit({ units: 600_000 }) let addresslookupTables: AddressLookupTableAccount[] = ( await flashClient.getOrLoadAddressLookupTable(POOL_CONFIG) ).addressLookupTables const txid = perpClient.sendTransaction([backUpOracleInstruction, setCULimitIx, ...addLiqInstructions ], { addLiqAdditionalSigners, alts: addresslookupTables, }) const payTokenSymbol = 'USDC'; // 'SOL' , 'BTC', 'ETH' const { instructions : addCompLiqInstructions, additionalSigners : addCompLiqAdditionalSigners } = await perpClient.addCompoundingLiquidity( tokenAmountIn, payTokenSymbol, minLpAmountOut, // new BN(0) USDC_TOKEN.mintKey, POOL_CONFIG ) const setCULimitIx = ComputeBudgetProgram.setComputeUnitLimit({ units: 600_000 }) const txid = perpClient.sendTransaction([backUpOracleInstruction, setCULimitIx, ...addCompLiqInstructions ], { addCompLiqAdditionalSigners, alts: perpClient.addressLookupTables, }) const recieveTokenSymbol = 'USDC'; // 'SOL' , 'BTC', 'ETH' const { instructions : removeCompLiqInstructions, additionalSigners : removeCompLiqAdditionalSigners } = await await perpClient.removeCompoundingLiquidity( lpAmountIn, minTokenAmountOut, // new BN(0) recieveTokenSymbol, USDC_TOKEN.mintKey, POOL_CONFIG, true ) const setCULimitIx = ComputeBudgetProgram.setComputeUnitLimit({ units: 600_000 }) let addresslookupTables: AddressLookupTableAccount[] = ( await flashClient.getOrLoadAddressLookupTable(POOL_CONFIG) ).addressLookupTables const txid = perpClient.sendTransaction([backUpOracleInstruction, setCULimitIx, ...removeCompLiqInstructions ], { removeCompLiqAdditionalSigners, alts: addresslookupTables, }) ``` -------------------------------- ### Staking LP Tokens Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt Examples for staking LP tokens to earn rewards. ```typescript await sdk.staking.stake({ // Staking details }); ``` -------------------------------- ### OraclePrice getTokenAmount Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Calculates the equivalent token amount for $1000 USD using a BTC oracle price and 8 token decimals. ```typescript const btcPrice = new OraclePrice({ price: new BN(35000e9), exponent: new BN(-9), confidence: BN_ZERO }); const oneThousandUsd = new BN(1000e6); const btcAmount = btcPrice.getTokenAmount(oneThousandUsd, 8); // btcAmount ≈ 0.02857 BTC (in satoshis) ``` -------------------------------- ### getOpenPositionQuote Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Simulate opening a position and get entry price, fees, and liquidation price. This method is useful for understanding the potential outcomes before committing to a trade. ```APIDOC ## getOpenPositionQuote ### Description Simulate opening a position and get entry price, fees, and liquidation price. ### Method `async` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |---|---|---| | targetSymbol | string | Trading pair symbol | | collateralSymbol | string | Collateral token symbol | | collateralAmount | BN | Collateral in native decimals | | leverage | BN | Leverage multiplier (9 decimals) | | side | Side | Long or Short | | poolConfig | PoolConfig | Pool configuration | ### Returns Quote with entry price, fees, liquidation price ### Request Example ```typescript // Example usage (assuming PerpetualsClient instance and necessary types are available) const quote = await client.getOpenPositionQuote("BTC-USD", "USDC", new BN(1000000000000), new BN(1000000000), Side.Buy, poolConfig); ``` ### Response #### Success Response - **OpenPositionQuoteData**: Contains entry price, fees, and liquidation price. #### Response Example ```json { "entryPrice": "...", "fees": "...", "liquidationPrice": "..." } ``` ``` -------------------------------- ### Open Position Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Demonstrates how to open a leveraged long position for BTC/USDC. Ensure correct pool configuration and provide necessary price and size details. The function returns transaction instructions and additional signers. ```typescript const poolConfig = PoolConfig.fromIdsByName('Crypto.1', 'mainnet-beta'); const btcToken = poolConfig.tokens.find(t => t.symbol === 'BTC'); const usdcToken = poolConfig.tokens.find(t => t.symbol === 'USDC'); const { instructions, additionalSigners } = await perpClient.openPosition( 'BTC', 'USDC', { price: new BN(35000e9), exponent: -9 }, usdcAmount, sizeInUsd, Side.Long, poolConfig, Privilege.None ); ``` -------------------------------- ### Load All Pool Configurations Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-config.md Loads all available pool configurations for a given Solana cluster. Use this to get a list of all pools. ```typescript static getAllPoolConfigs(cluster: Cluster): PoolConfig[] ``` ```typescript const allPools = PoolConfig.getAllPoolConfigs('mainnet-beta'); ``` -------------------------------- ### OraclePrice getAssetAmountUsd Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Calculates the USD value of 1 BTC using a BTC oracle price and 8 token decimals. ```typescript const oneBtc = new BN(1e8); // 1 BTC in satoshis const usdValue = btcPrice.getAssetAmountUsd(oneBtc, 8); // usdValue ≈ 35000e6 USD ``` -------------------------------- ### Flash SDK Import Guide Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/types.md Imports essential enums, account types, price types, quote types, and utility functions from the flash-sdk. ```typescript import { // Enums Side, Privilege, OracleType, FeesMode, FeesAction, // Account Types Position, Order, Pool, Custody, Market, FlpStake, TokenStake, TokenVault, // Price Types OraclePrice, ContractOraclePrice, // Quote Types OpenPositionQuoteData, ClosePositionQuoteData, AddLiquidityAmountAndFee, RemoveLiquidityAmountAndFee, // Utility isVariant, isOneOfVariant, DEFAULT_POSITION, } from 'flash-sdk'; ``` -------------------------------- ### PoolDataClient Integration with PerpetualsClient Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-data-client.md This example demonstrates how to use the PoolDataClient by integrating it with the PerpetualsClient to fetch and analyze pool data. It includes steps for retrieving pool configuration, account data, custody data, and LP mint information, culminating in the creation of a PoolDataClient instance and the retrieval of LP and custody statistics. ```APIDOC ## analyzePool ### Description Fetches and analyzes data for a given perpetual finance pool using PerpetualsClient and PoolDataClient. ### Method Signature `async function analyzePool(perpClient: PerpetualsClient, poolName: string)` ### Parameters - **perpClient** (`PerpetualsClient`) - An instance of the PerpetualsClient. - **poolName** (`string`) - The name of the pool to analyze. ### Returns An object containing `lpStats` and `custodyStats`. ### Example Usage ```typescript import { PerpetualsClient, PoolDataClient } from 'flash-sdk'; async function analyzePool(perpClient: PerpetualsClient, poolName: string) { const poolConfig = PoolConfig.fromIdsByName(poolName, 'mainnet-beta'); // Fetch pool data const poolData = await perpClient.getPool(poolName); const poolAccount = PoolAccount.from(poolConfig.poolAddress, poolData); // Fetch custody data const custodyPromises = poolConfig.custodies.map(c => perpClient.program.account.custody.fetch(c.custodyAccount) ); const custodyDatas = await Promise.all(custodyPromises); const custodies = custodyDatas.map((data, i) => CustodyAccount.from( poolConfig.custodies[i].custodyAccount, data ) ); // Fetch LP mint const lpMintInfo = await connection.getParsedAccountInfo( poolConfig.stakedLpTokenMint ); // Create client const poolDataClient = new PoolDataClient( poolConfig, poolAccount, lpMintInfo.value?.parsed?.info, custodies ); // Get stats const lpStats = poolDataClient.getLpStats(pricesMap); return { lpStats, custodyStats: poolDataClient.getCustodyStats(pricesMap) }; } ``` ``` -------------------------------- ### PerpetualsClient Methods - Quotes/Simulations Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/README.md Methods for simulating trades and liquidity operations to get quotes. ```APIDOC ## PerpetualsClient Quotes/Simulations ### Description Methods for simulating trade and liquidity operations to obtain quotes before execution. - `getOpenPositionQuote` - Simulate opening position - `getClosePositionQuote` - Simulate closing position - `getAddLiquidityAmountAndFeeView` - Liquidity simulation - `getRemoveLiquidityAmountAndFeeView` - Liquidity withdrawal simulation ``` -------------------------------- ### OraclePrice withMultiplier Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Applies a borrow rate multiplier to an OraclePrice to calculate an effective price. ```typescript const borrowRate = new BN(50e6); // 0.05 (5%) const effectivePrice = oraclePrice.withMultiplier(borrowRate); ``` -------------------------------- ### Configure Post-Transaction Callback Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Set a callback function to execute after a transaction is sent. This example also shows setting a prioritization fee and transaction confirmation commitment. ```typescript const client = new PerpetualsClient( provider, programId, composabilityProgramId, fbNftRewardProgramId, rewardDistributionProgramId, { postSendTxCallback: ({ txid }) => { console.log(`Transaction sent: ${txid}`); }, prioritizationFee: 50000, txConfirmationCommitment: 'confirmed' } ); ``` -------------------------------- ### Usage of Decimal Precision Constants Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/utilities.md Example demonstrating how to use decimal precision constants with BN.js for creating precise numerical values. ```typescript import { USD_DECIMALS, BPS_DECIMALS, RATE_DECIMALS } from 'flash-sdk'; import { BN } from '@coral-xyz/anchor'; const oneUsd = new BN(10 ** USD_DECIMALS); // 1,000,000 const tenBps = new BN(10 * 10 ** BPS_DECIMALS); // 100,000 (0.01%) const fivePercent = new BN(5e8); // 500,000,000 in RATE_DECIMALS ``` -------------------------------- ### Access Token Information by Symbol Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Retrieves token information using its symbol. Shows how to get decimals, mint address, and stablecoin status. ```typescript // Get token by symbol const usdcToken = poolConfig.getTokenFromSymbol("USDC"); console.log("USDC decimals:", usdcToken.decimals); // 6 console.log("USDC mint:", usdcToken.mintKey.toBase58()); console.log("Is stable:", usdcToken.isStable); // true ``` -------------------------------- ### Get Token Configuration by Mint String Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-config.md Retrieves the Token configuration object using the token's mint address as a string. ```typescript getTokenFromMintString(mint: string): Token ``` -------------------------------- ### Connect to Local Validator Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Set up a connection to a local Solana validator for testing purposes. This can be done using the standard Anchor test command or a custom connection setup. ```typescript // Use local validator with Anchor anchor test // Or with custom setup const connection = new Connection( "http://127.0.0.1:8899", "confirmed" ); ``` -------------------------------- ### Accessing Raw and UI-Formatted Custody Statistics Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-data-client.md This example illustrates accessing raw and UI-formatted statistics for individual custodies within a pool. The 'currentRatioUi' and 'utilizationUi' provide percentage values suitable for display. ```typescript // Similar for custody stats custodyStats[0].currentRatioUi; // "25.50" (as percentage) custodyStats[0].utilizationUi; // "45.30" (as percentage) ``` -------------------------------- ### Custom Connection Options Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Configures a Solana `Connection` with specific options, including block commitment level and transaction confirmation timeouts. This example uses a standard public endpoint. ```typescript const connection = new Connection( "https://api.mainnet-beta.solana.com", { commitment: "confirmed", // Block commitment httpAgent: undefined, // Custom HTTP agent (Node.js) confirmTransactionInitialTimeout: 60000, // Confirm timeout (ms) } ); ``` -------------------------------- ### Initialize Perpetuals Client Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/README.md Set up the connection to Solana and initialize the Perpetuals client with program and pool IDs. Ensure your provider and wallet are correctly configured. ```typescript import { PerpetualsClient, PoolConfig } from "flash-sdk"; import { AnchorProvider } from "@coral-xyz/anchor"; import { Connection, clusterApiUrl, PublicKey } from "@solana/web3.js"; // Setup connection and wallet const connection = new Connection(clusterApiUrl("mainnet-beta"), "confirmed"); const wallet = window.solana; // or your wallet const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed" }); // Initialize client const programId = new PublicKey("9Z8r9hzAeFYAKQKqMSB8YajhWk8dVwxeKp6GZw3dVFy6"); const perpClient = new PerpetualsClient( provider, programId, new PublicKey("CPgnYYBKvzohpMHZJvNNq4m2xh7EKt5txL7kUQXdGzxu"), new PublicKey("DGkRuNmGdB5VKzQiHiJdHjDU4FfvxR8wJqJeYu7LHFVS"), new PublicKey("5u7eV2LVWHjMfkRbV5kQGN7fVYqQDavQ5gqcKt5Cyt8Y"), { prioritizationFee: 50000 } ); // Load pool const poolConfig = PoolConfig.fromIdsByName("Crypto.1", "mainnet-beta"); await perpClient.loadAddressLookupTable(poolConfig); ``` -------------------------------- ### Calculate Entry Price and Fee (Sync V2) Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Synchronously calculates the entry price, fees, and liquidation price for opening a new position. Requires custody accounts, price with slippage, collateral amount, size delta, and side. ```typescript getEntryPriceAndFeeSyncV2( targetCustodyAccount: CustodyAccount, collateralCustodyAccount: CustodyAccount, priceWithSlippage: OraclePrice, collateralUsd: BN, sizeDeltaUsd: BN, side: Side ): EntryPriceAndFeeV2 ``` -------------------------------- ### Get Compounding LP Token Price Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/SDK/readme.md This snippet shows how to call a view function to get the compounding LP token price. It requires the pool address and pool configuration. ```typescript const compoundingLPTokenPrice = await perpClient.getCompoundingLPTokenPrice(POOL_CONFIG.poolAddress, POOL_CONFIG) ``` -------------------------------- ### Import Everything Pattern Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/EXPORTS.md Demonstrates how to import all exports from the 'flash-sdk' package using a wildcard import. ```typescript import * from 'flash-sdk' ``` -------------------------------- ### Closing a Position Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt Examples for closing existing leveraged positions. ```typescript await sdk.perpetuals.closePosition({ // Position details }); ``` -------------------------------- ### Initialize Anchor Provider Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Set up the Anchor Provider by creating a Solana connection and providing wallet details. This is a prerequisite for initializing the PerpetualsClient. ```typescript import { AnchorProvider } from "@coral-xyz/anchor"; import { Connection, clusterApiUrl } from "@solana/web3.js"; // Create connection const connection = new Connection( clusterApiUrl("mainnet-beta"), "confirmed" ); // Create wallet (using default wallet from browser/Phantom) const wallet = window.solana; // or your wallet implementation // Create provider const provider = new AnchorProvider(connection, wallet, { commitment: "confirmed", preflightCommitment: "confirmed", skipPreflight: true, }); ``` -------------------------------- ### RemoveCollateralQuoteData Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/types.md Represents the data returned when getting a quote for removing collateral. ```APIDOC ## RemoveCollateralQuoteData ### Description Represents the data returned when getting a quote for removing collateral from a position. This interface includes details on the updated collateral, leverage, liquidation price, collateral received, and fees. ### Fields - **newCollateralUsd** (BN) - The new collateral amount in USD after removal. - **newLeverage** (BN) - The new leverage after removing collateral. - **newLiquidationPrice** (OraclePrice) - The new liquidation price after removing collateral. - **collateralAmountReceived** (BN) - The amount of collateral received. - **fees** (object) - Details about the fees for removing collateral. - **feeUsd** (BN) - The fee in USD. - **feeAmount** (BN) - The fee amount. ``` -------------------------------- ### AddCollateralQuoteData Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/types.md Represents the data returned when getting a quote for adding collateral. ```APIDOC ## AddCollateralQuoteData ### Description Represents the data returned when getting a quote for adding collateral to a position. This interface provides information on the new collateral amount, leverage, liquidation price, and associated fees. ### Fields - **newCollateralUsd** (BN) - The new collateral amount in USD. - **newLeverage** (BN) - The new leverage after adding collateral. - **newLiquidationPrice** (OraclePrice) - The new liquidation price after adding collateral. - **fees** (object) - Details about the fees for adding collateral. - **feeUsd** (BN) - The fee in USD. - **feeAmount** (BN) - The fee amount. ``` -------------------------------- ### ClosePositionQuoteData Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/types.md Represents the data returned when getting a quote for closing a position. ```APIDOC ## ClosePositionQuoteData ### Description Represents the data returned when getting a quote for closing a position. This interface includes exit price, profit/loss, and fees. ### Fields - **exitPrice** (OraclePrice) - The exit price for the position. - **pnl** (object) - The profit or loss details for the position. - **profitUsd** (BN) - The profit in USD. - **lossUsd** (BN) - The loss in USD. - **fees** (object) - Details about the fees associated with closing the position. - **exitFeeUsd** (BN) - The exit fee in USD. - **exitFeeAmount** (BN) - The exit fee amount. - **borrowFeeUsd** (BN) - The borrow fee in USD. - **borrowFeeAmount** (BN) - The borrow fee amount. ``` -------------------------------- ### OpenPositionQuoteData Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/types.md Represents the data returned when getting a quote for opening a position. ```APIDOC ## OpenPositionQuoteData ### Description Represents the data returned when getting a quote for opening a position. This interface provides details about entry price, fees, liquidation price, size, and leverage. ### Fields - **entryPrice** (OraclePrice) - The entry price for the position. - **fees** (object) - Details about the fees associated with opening the position. - **openFeeUsd** (BN) - The opening fee in USD. - **openFeeAmount** (BN) - The opening fee amount. - **openFeeUsdAfterDiscount** (BN) - The opening fee in USD after any applicable discounts. - **openFeeAmountAfterDiscount** (BN) - The opening fee amount after any applicable discounts. - **liquidationPrice** (OraclePrice) - The liquidation price for the position. - **sizeUsd** (BN) - The size of the position in USD. - **sizeAmount** (BN) - The size of the position in amount. - **leverage** (BN) - The leverage applied to the position. ``` -------------------------------- ### from (static) Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Creates a new PositionAccount instance from public key and parsed position data. ```APIDOC ## Method: from (static) ### Signature ```typescript static from(publicKey: PublicKey, parseData: Position): PositionAccount ``` ``` -------------------------------- ### OraclePrice toUiPrice Example Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Formats an OraclePrice object into a string with two decimal places. ```typescript const priceStr = oraclePrice.toUiPrice(2); // "35000.50" ``` -------------------------------- ### constructor Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Initializes a new instance of the PositionAccount class. ```APIDOC ## Method: constructor ### Signature ```typescript constructor(publicKey: PublicKey, parseData: Position) ``` ``` -------------------------------- ### Get Non-Stable Custody Accounts Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-config.md Retrieves an array of PublicKey objects for all non-stable custody accounts. ```typescript getNonStableCustodies(): PublicKey[] ``` -------------------------------- ### Get Non-Stable Token Mints Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-config.md Retrieves an array of PublicKey objects for all non-stable token mints. ```typescript getNonStableTokens(): PublicKey[] ``` ```typescript const volatileTokens = poolConfig.getNonStableTokens(); ``` -------------------------------- ### getEntryPriceAndFeeSyncV2 Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Synchronously calculates the entry price and opening fees for a new position, considering slippage and collateral. This is a V2 method for accurate pre-trade calculations. ```APIDOC ## getEntryPriceAndFeeSyncV2 ### Description Calculate entry price and opening fees for a position. ### Method Signature ```typescript getEntryPriceAndFeeSyncV2( targetCustodyAccount: CustodyAccount, collateralCustodyAccount: CustodyAccount, priceWithSlippage: OraclePrice, collateralUsd: BN, sizeDeltaUsd: BN, side: Side ): EntryPriceAndFeeV2 ``` ### Returns - Entry price, fees, liquidation price ``` -------------------------------- ### Get All Custody Account Addresses Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-config.md Retrieves an array containing the PublicKey objects for all active custody accounts. ```typescript getAllCustodies(): PublicKey[] ``` -------------------------------- ### Environment Variables for SDK Configuration Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Configure SDK connection and program IDs using a .env file. Load these variables into your application using the dotenv library. ```bash # Connection SOLANA_CLUSTER=mainnet-beta SOLANA_RPC_URL=https://api.mainnet-beta.solana.com # Default Programs FLASH_PROGRAM_ID=9Z8r9hzAeFYAKQKqMSB8YajhWk8dVwxeKp6GZw3dVFy6 FLASH_COMPOSABILITY_PROGRAM_ID=CPgnYYBKvzohpMHZJvNNq4m2xh7EKt5txL7kUQXdGzxu FLASH_NFT_REWARD_PROGRAM_ID=DGkRuNmGdB5VKzQiHiJdHjDU4FfvxR8wJqJeYu7LHFVS FLASH_REWARD_DISTRIBUTION_PROGRAM_ID=5u7eV2LVWHjMfkRbV5kQGN7fVYqQDavQ5gqcKt5Cyt8Y # Transaction Settings PRIORITIZATION_FEE=50000 CONFIRMATION_COMMITMENT=confirmed ``` -------------------------------- ### Get Assets Under Management Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Asynchronously retrieves the total assets under management (AUM) for a specific pool. The AUM is returned as a string. ```typescript getAssetsUnderManagement = async ( poolKey: PublicKey, poolConfig: PoolConfig ): Promise ``` -------------------------------- ### Fetch All Pool Accounts Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Asynchronously fetches data for all available pool accounts. This is useful for getting an overview of all trading pools. ```typescript getPools = async (): Promise ``` -------------------------------- ### Import Specific Classes Pattern Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/EXPORTS.md Shows how to import specific client and account classes from the 'flash-sdk'. ```typescript import { PerpetualsClient, PoolConfig, PoolAccount, PositionAccount, CustodyAccount, OraclePrice } from 'flash-sdk' ``` -------------------------------- ### Get All and Filter Tokens Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/configuration.md Fetches all available tokens within a pool configuration and demonstrates filtering for stable and volatile tokens. ```typescript // Get all tokens const allTokens = poolConfig.tokens; const stableTokens = allTokens.filter(t => t.isStable); const volatileTokens = allTokens.filter(t => !t.isStable); ``` -------------------------------- ### Adding Liquidity Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt Demonstrates how to add liquidity to a pool. ```typescript await sdk.liquidity.add({ // Liquidity details }); ``` -------------------------------- ### Initialize Pool Configuration Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/pool-config.md Loads a pool configuration by name and environment. Accesses available tokens and market public keys. ```typescript import { PoolConfig } from 'flash-sdk'; // Load Crypto.1 pool configuration for mainnet const poolConfig = PoolConfig.fromIdsByName('Crypto.1', 'mainnet-beta'); // Access available tokens const tokens = poolConfig.tokens; console.log('Available tokens:', tokens.map(t => t.symbol)); // Access available markets const markets = poolConfig.getAllMarketPks(); console.log('Number of markets:', markets.length); ``` -------------------------------- ### MarketAccount Static from Method Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/account-classes.md Creates a MarketAccount instance from public key and parsed market data. ```typescript static from(publicKey: PublicKey, parseData: Market): MarketAccount ``` -------------------------------- ### Check and Calculate Position Metrics Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/README.md Fetch user positions and calculate metrics like PnL and liquidation price. This involves retrieving position data and using the client to compute real-time metrics. ```typescript // Fetch position const positions = await perpClient.getUserPositions( provider.wallet.publicKey, poolConfig ); positions.forEach(pos => { console.log(`Size: $${pos.sizeUsd}`); console.log(`Collateral: $${pos.collateralUsd}`); console.log(`Entry: ${pos.entryPrice.price}`); }); // Calculate metrics const currentPrice = new BN(36000e9); const metrics = perpClient.getPositionMetrics( positions[0], targetCustodyAccount, currentPrice ); console.log(`PnL: ${metrics.pnl.profitUsd}`); console.log(`Liquidation: ${metrics.liquidationPrice}`); ``` -------------------------------- ### getClosePositionQuote Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Simulate closing a position and get exit price and fees. This helps in estimating the cost and return of closing an existing position. ```APIDOC ## getClosePositionQuote ### Description Simulate closing a position and get exit price and fees. ### Method `async` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Description | |---|---|---| | targetSymbol | string | Trading pair symbol | | collateralSymbol | string | Collateral token symbol | | poolConfig | PoolConfig | Pool configuration | | side | Side | Long or Short | ### Returns Quote with exit price and fees ### Request Example ```typescript // Example usage (assuming PerpetualsClient instance and necessary types are available) const quote = await client.getClosePositionQuote("BTC-USD", "USDC", poolConfig, Side.Buy); ``` ### Response #### Success Response - **ClosePositionQuoteData**: Contains exit price and fees. #### Response Example ```json { "exitPrice": "...", "fees": "..." } ``` ``` -------------------------------- ### Get Current Unix Timestamp Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/utilities.md Retrieves the current Unix timestamp in seconds since the epoch. This is a simple utility function with no parameters. ```typescript import { getUnixTs } from 'flash-sdk'; const now = getUnixTs(); console.log(`Current time: ${now}`); ``` -------------------------------- ### Running Flash Trade SDK Scripts Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/examples/readme.md Commands to execute the different scripts provided by the Flash Trade SDK. These scripts cover trading, liquidity management, and revenue reading. ```bash npx ts-node src/trade.ts ``` ```bash npx ts-node src/liquidity.ts ``` ```bash npx ts-node src/revenue.ts ``` -------------------------------- ### Environment Configuration for Flash Trade SDK Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/examples/readme.md Configuration details for the .env file, specifying the wallet and RPC URL. The LAZER_PROXY_URL is optional. ```env ANCHOR_WALLET=localPublicKey.json RPC_URL=https://your-mainnet-rpc.example.com # LAZER_PROXY_URL is optional — defaults to https://pyth-lazer-proxy-3.dourolabs.app ``` -------------------------------- ### Import Utilities Pattern Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/EXPORTS.md Illustrates importing various utility functions for number conversions, account checks, and variant checks from the SDK. ```typescript import { nativeToUiDecimals, uiDecimalsToNative, validateNumberString, checkIfAccountExists, getUnixTs, isVariant, isOneOfVariant } from 'flash-sdk' ``` -------------------------------- ### Fetch Pool Account Data Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/api-reference/perpetuals-client.md Asynchronously fetches the on-chain data for a specific pool account. Use this to get detailed information about a pool. ```typescript getPool = async (name: string): Promise ``` -------------------------------- ### Pool Configuration Lookup Source: https://github.com/flash-trade/flash-trade-sdk/blob/main/_autodocs/SUMMARY.txt Demonstrates how to look up pool configurations by various identifiers. ```typescript const poolConfig = await sdk.pools.getPoolConfigById("poolId"); ```