### Install OrbitFlare SDK for Go Source: https://docs.orbitflare.com/sdk/go-jetstream Install the OrbitFlare SDK for Go using the go get command. This is the first step to using the JetStream client. ```bash go get github.com/orbitflare/orbitflare-sdk-go ``` -------------------------------- ### Clone Jetstream Client Example (Bash) Source: https://docs.orbitflare.com/data-streaming/jetstream Clone the basic Rust client example repository to get started with Jetstream. ```bash git clone https://github.com/orbitflare/jetstream-client-example cd jetstream-client-example ``` -------------------------------- ### Get SOL Supply with web3.js Source: https://docs.orbitflare.com/rpc/methods/getSupply Shows how to use the web3.js library to get the SOL supply. This example includes a function to also analyze the supply data, converting lamports to SOL and calculating percentages. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get supply const supply = await connection.getSupply(); console.log('Supply:', supply); // Get supply with analysis async function getSupplyWithAnalysis( config?: { commitment?: string; excludeNonCirculatingAccountsList?: boolean } ) { const supply = await connection.getSupply(config); return { supply, analysis: { totalInSOL: supply.total / 1e9, circulatingInSOL: supply.circulating / 1e9, nonCirculatingInSOL: supply.nonCirculating / 1e9, circulatingPercentage: (supply.circulating / supply.total) * 100, metadata: { timestamp: Date.now(), commitment: config?.commitment } } }; } ``` -------------------------------- ### Install from Source Source: https://docs.orbitflare.com/agents/skills Installs the OrbitFlare skills by cloning the repository and running the install script. Supports the same flags as the npm installer. ```bash git clone https://github.com/orbitflare/orbitflare-skills cd orbitflare-skills/orbitflare ./install.sh # same flags: --project, --cursor, --codex, --path ``` -------------------------------- ### Get Program Accounts with web3.js Source: https://docs.orbitflare.com/rpc/methods/getProgramAccounts Demonstrates how to fetch all program accounts and filtered program accounts using the web3.js library. Ensure you have the '@solana/web3.js' package installed. ```typescript import { Connection, PublicKey } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get all program accounts const accounts = await connection.getProgramAccounts( new PublicKey('PROGRAM_ID') ); console.log('Accounts:', accounts); // Get filtered program accounts async function getFilteredProgramAccounts( programId: PublicKey, filters: any[] ) { const accounts = await connection.getProgramAccounts(programId, { filters }); return accounts.map(({ pubkey, account }) => ({ pubkey: pubkey.toBase58(), data: account.data, lamports: account.lamports, owner: account.owner.toBase58(), executable: account.executable })); } ``` -------------------------------- ### Stake Activation with web3.js Source: https://docs.orbitflare.com/rpc/methods/getStakeActivation Shows how to use the web3.js library to get stake activation details. The second example includes a function to analyze the activation data, calculating total stake, active percentage, and including metadata. ```typescript import { Connection, PublicKey } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get stake activation const stakeAccount = new PublicKey('4vJ9JU1bJJE96FWSJKvHsmmFADCg4gpZQff4P3bkLZj'); const activation = await connection.getStakeActivation(stakeAccount); console.log('Stake activation:', activation); ``` ```typescript async function getStakeActivationWithAnalysis( stakeAccount: PublicKey, config?: { commitment?: string; epoch?: number } ) { const activation = await connection.getStakeActivation(stakeAccount, config); return { activation, analysis: { totalStake: activation.active + activation.inactive, activePercentage: (activation.active / (activation.active + activation.inactive)) * 100, state: activation.state, metadata: { timestamp: Date.now(), epoch: config?.epoch, commitment: config?.commitment } } }; } ``` -------------------------------- ### Using web3.js to getBlock Source: https://docs.orbitflare.com/rpc/methods/getBlock Example of fetching block data using the web3.js library. Requires installation of `@solana/web3.js` and an active connection to the RPC endpoint. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); const slot = 430; const block = await connection.getBlock( slot, { maxSupportedTransactionVersion: 0 } ); ``` -------------------------------- ### Start Local Development Server Source: https://docs.orbitflare.com/development Navigate to your project's docs directory and run this command to start a local preview server. The documentation will be available at http://localhost:3000. ```bash mintlify dev ``` -------------------------------- ### Get Fee for Message using web3.js Source: https://docs.orbitflare.com/rpc/methods/getFeeForMessage This TypeScript example demonstrates how to use the web3.js library to connect to the Orbitflare RPC and retrieve the fee for a message. Ensure you have the @solana/web3.js package installed. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('http://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); const message = 'AQABAyRn/PA8jzJtN6oAyB3VR0nfOF0xnfkYaKwY4Ir3nrHFJGqhAQICAAEDAgABDAIAAAAEAAAAAAAA'; const fee = await connection.getFeeForMessage(message); console.log(fee); ``` -------------------------------- ### Install Project Template Source: https://docs.orbitflare.com/agents/cli Scaffold a new project using a specified template (e.g., 'solana-copy-trader') into a target directory. ```bash orbitflare template --install solana-copy-trader --dir ./bot ``` -------------------------------- ### Full Network and Wallet Interaction Example Source: https://docs.orbitflare.com/sdk/go-rpc This Go program demonstrates how to connect to the Orbitflare network, fetch the latest slot and blockhash, retrieve a wallet's SOL balance, and list recent transactions. ```go package main import ( "context" "encoding/json" "fmt" "log" "time" "github.com/orbitflare/orbitflare-sdk-go/rpc" ) func main() { client, err := rpc.NewBuilder(). URL("http://ny.rpc.orbitflare.com"). FallbackURL("http://fra.rpc.orbitflare.com"). Commitment("confirmed"). Build() if err != nil { log.Fatal(err) } ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) defer cancel() wallet := "CKs1E69a2e9TmH4mKKLrXFF8kD3ZnwKjoEuXa6sz9WqX" slot, _ := client.GetSlot(ctx) blockhash, _, _ := client.GetLatestBlockhash(ctx) fmt.Printf("network slot: %d\nblockhash: %s\n", slot, blockhash) balance, _ := client.GetBalance(ctx, wallet) fmt.Printf("\n%s\n SOL: %.4f\n", wallet, float64(balance)/1_000_000_000) sigs, _ := client.GetSignaturesForAddress(ctx, wallet, 5) fmt.Println("\nrecent transactions:") for _, raw := range sigs { var sig struct { Signature string `json:"signature"` Slot uint64 `json:"slot"` Err any `json:"err"` } json.Unmarshal(raw, &sig) status := "ok" if sig.Err != nil { status = "failed" } fmt.Printf(" %d %s %s\n", sig.Slot, status, sig.Signature[:20]) } } ``` -------------------------------- ### Get Node Version with web3.js Source: https://docs.orbitflare.com/rpc/methods/getVersion This TypeScript example demonstrates how to use the web3.js library to get the node version. It also includes a function to perform basic analysis on the version information. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get version const version = await connection.getVersion(); console.log('Node version:', version); // Get version with analysis async function getVersionWithAnalysis() { const version = await connection.getVersion(); return { version, analysis: { timestamp: Date.now(), isLatest: await checkLatestVersion(version['solana-core']) } }; } async function checkLatestVersion(currentVersion: string): Promise { // Implementation to check if current version is latest // This would typically involve calling an external API return true; } ``` -------------------------------- ### Full Example: Monitoring Script Source: https://docs.orbitflare.com/cn/sdk/typescript-websocket A complete example demonstrating how to monitor slot updates and USDC account changes in real-time by setting up multiple subscriptions. ```APIDOC import { WsClientBuilder } from '@orbitflare/sdk/ws'; async function main() { const client = await new WsClientBuilder() .url('ws://ny.rpc.orbitflare.com') .build(); const slots = await client.slotSubscribe(); const usdc = await client.accountSubscribe( 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', 'confirmed', ); console.log('watching slots and USDC mint account...'); slots.on((slot) => { const s = slot?.slot ?? 0; const parent = slot?.parent ?? 0; console.log(`slot ${s} (parent ${parent})`); }); usdc.on((acct) => { const lamports = acct?.lamports ?? 0; const data = acct?.data?.[0]; const dataLen = typeof data === 'string' ? data.length : 0; console.log(`USDC mint updated: ${lamports} lamports, ${dataLen} bytes`); }); // Keep the script running indefinitely await new Promise(() => {}); } void main(); ``` -------------------------------- ### Get Largest Accounts (Filtered) Source: https://docs.orbitflare.com/rpc/methods/getLargestAccounts This example shows how to filter the results to only include circulating accounts. ```APIDOC ## GET /getLargestAccounts (Filtered) ### Description Retrieves the top 20 accounts by lamport balance, sorted in descending order, and filters for circulating accounts only. ### Method POST ### Endpoint / (RPC Endpoint) ### Parameters #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version. - **id** (number) - Required - The ID of the request. - **method** (string) - Required - The method to call, which is "getLargestAccounts". - **params** (array) - Optional - An array containing parameters for the method. - **filter** (string) - Optional - Filters the accounts. Accepted values: "circulating", "nonCirculating". ### Request Example ```json { "jsonrpc": "2.0", "id": 1, "method": "getLargestAccounts", "params": [ { "filter": "circulating" } ] } ``` ### Response #### Success Response (200) - **result** (array) - An array of account objects, each containing 'address' and 'lamports'. - **error** (object) - An error object if the request failed. - **id** (number) - The ID of the response. #### Response Example ```json { "jsonrpc": "2.0", "result": [ { "address": "3f59p24f44444444444444444444444444444444", "lamports": 1000000000000000000 } ], "id": 1 } ``` ``` -------------------------------- ### Get Largest Accounts (Basic) Source: https://docs.orbitflare.com/rpc/methods/getLargestAccounts This example demonstrates how to call the getLargestAccounts method without any filters. ```APIDOC ## GET /getLargestAccounts ### Description Retrieves the top 20 accounts by lamport balance, sorted in descending order. ### Method POST ### Endpoint / (RPC Endpoint) ### Parameters #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version. - **id** (number) - Required - The ID of the request. - **method** (string) - Required - The method to call, which is "getLargestAccounts". ### Request Example ```json { "jsonrpc": "2.0", "id": 1, "method": "getLargestAccounts" } ``` ### Response #### Success Response (200) - **result** (array) - An array of account objects, each containing 'address' and 'lamports'. - **error** (object) - An error object if the request failed. - **id** (number) - The ID of the response. #### Response Example ```json { "jsonrpc": "2.0", "result": [ { "address": "3f59p24f44444444444444444444444444444444", "lamports": 1000000000000000000 } ], "id": 1 } ``` ``` -------------------------------- ### Full WebSocket Monitoring Program Example Source: https://docs.orbitflare.com/sdk/go-websocket A complete Go program demonstrating how to connect to the WebSocket, subscribe to slot updates and account changes, and print a live feed of events. It includes error handling, automatic reconnection, and proper resource management. ```go package main import ( "context" "encoding/json" "fmt" "log" "github.com/orbitflare/orbitflare-sdk-go/ws" ) func main() { ctx := context.Background() client, err := ws.NewBuilder(). URL("ws://ny.rpc.orbitflare.com"). Build(ctx) if err != nil { log.Fatal(err) } defer client.Close() slots, err := client.SlotSubscribe(ctx) if err != nil { log.Fatal(err) } defer slots.Unsubscribe() fmt.Println("watching slots...") for { event, ok := slots.Next(ctx) if !ok { return } var slot struct { Slot uint64 `json:"slot"` Parent uint64 `json:"parent"` } json.Unmarshal(event, &slot) fmt.Printf("slot %d (parent %d)\n", slot.Slot, slot.Parent) } } ``` -------------------------------- ### Get Slot using web3.js Source: https://docs.orbitflare.com/rpc/methods/getSlot This example shows how to use the web3.js library to interact with the getSlot RPC method. It includes functions for getting the current slot and the slot with a specified commitment level. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get current slot const slot = await connection.getSlot(); console.log('Current slot:', slot); // Get slot with commitment async function getSlotWithCommitment( commitment: 'processed' | 'confirmed' | 'finalized' = 'confirmed' ) { const slot = await connection.getSlot(commitment); return { slot, commitment, timestamp: Date.now() }; } ``` -------------------------------- ### Full Example: Monitor Slot and Account Updates Source: https://docs.orbitflare.com/cn/sdk/typescript-websocket A complete example demonstrating how to subscribe to slot updates and USDC account changes, printing a live stream of events. It uses event listeners for continuous updates. ```typescript import { WsClientBuilder } from '@orbitflare/sdk/ws'; async function main() { const client = await new WsClientBuilder() .url('ws://ny.rpc.orbitflare.com') .build(); const slots = await client.slotSubscribe(); const usdc = await client.accountSubscribe( 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', 'confirmed', ); console.log('watching slots and USDC mint account...'); slots.on((slot) => { const s = slot?.slot ?? 0; const parent = slot?.parent ?? 0; console.log(`slot ${s} (parent ${parent})`); }); usdc.on((acct) => { const lamports = acct?.lamports ?? 0; const data = acct?.data?.[0]; const dataLen = typeof data === 'string' ? data.length : 0; console.log(`USDC mint updated: ${lamports} lamports, ${dataLen} bytes`); }); await new Promise(() => {}); } void main(); ``` -------------------------------- ### Delegate Account Planning with TypeScript Source: https://docs.orbitflare.com/rpc/methods/getTokenAccountsByDelegate This example demonstrates how to plan delegate accounts by fetching all associated token accounts and generating recommendations for consolidation or diversification. It requires the PublicKey and Connection objects from the Solana SDK. ```typescript interface DelegateAccountPlan { delegate: string; currentAccounts: Array<{ pubkey: string; mint: string; balance: string; }>; recommendations: Array<{ type: 'consolidate' | 'diversify' | 'rebalance'; accounts: string[]; reason: string; }>; metadata: { timestamp: number; }; } class DelegateAccountPlanner { private readonly minBalancePerAccount = BigInt(1000000); // 1 token private readonly maxAccountsPerMint = 5; async planDelegateAccounts( delegate: PublicKey, config: { programId: PublicKey; commitment?: string } ): Promise { const accounts = await connection.getTokenAccountsByDelegate(delegate, config); const byMint = accounts.value.reduce((acc, account) => { const mint = account.account.data.parsed.info.mint; if (!acc[mint]) { acc[mint] = []; } acc[mint].push(account); return acc; }, {} as Record); const recommendations: Array<{ type: 'consolidate' | 'diversify' | 'rebalance'; accounts: string[]; reason: string; }> = []; Object.entries(byMint).forEach(([mint, mintAccounts]) => { // Check for accounts with low balances const lowBalanceAccounts = mintAccounts.filter(account => BigInt(account.account.data.parsed.info.tokenAmount.amount) < this.minBalancePerAccount ); if (lowBalanceAccounts.length > 0) { recommendations.push({ type: 'consolidate', accounts: lowBalanceAccounts.map(account => account.pubkey), reason: `Accounts with balances below minimum threshold for mint ${mint}` }); } // Check for too many accounts per mint if (mintAccounts.length > this.maxAccountsPerMint) { recommendations.push({ type: 'consolidate', accounts: mintAccounts.map(account => account.pubkey), reason: `Too many accounts (${mintAccounts.length}) for mint ${mint}` }); } }); return { delegate: delegate.toBase58(), currentAccounts: accounts.value.map(account => ({ pubkey: account.pubkey, mint: account.account.data.parsed.info.mint, balance: account.account.data.parsed.info.tokenAmount.amount })), recommendations, metadata: { timestamp: Date.now() } }; } } ``` -------------------------------- ### Using web3.js to Get Slot Leader Source: https://docs.orbitflare.com/rpc/methods/getSlotLeader Utilize the web3.js library to interact with the RPC endpoint and retrieve the slot leader. This example shows how to get the slot leader with and without a specified commitment level. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get current slot leader const slotLeader = await connection.getSlotLeader(); console.log('Current slot leader:', slotLeader); // Get slot leader with commitment async function getSlotLeaderWithCommitment( commitment: 'processed' | 'confirmed' | 'finalized' = 'confirmed' ) { const slotLeader = await connection.getSlotLeader(commitment); return { slotLeader, commitment, timestamp: Date.now() }; } ``` -------------------------------- ### View and Install Project Templates Source: https://docs.orbitflare.com/cli View details of a specific template using --view or install a template into a directory using --install. Templates are fetched from the orbitflare/templates repository and cached locally. ```bash # View template details orbitflare template --view solana-copy-trader ``` ```bash # Install a template orbitflare template --install solana-copy-trader --dir ./my-bot ``` -------------------------------- ### Clone Solana Wallet Tracker Example (Bash) Source: https://docs.orbitflare.com/data-streaming/jetstream Clone the production-ready wallet tracker example for a more comprehensive reference. ```bash git clone https://github.com/orbitflare/solana-wallet-tracker cd solana-wallet-tracker ``` -------------------------------- ### Get Transaction using web3.js Source: https://docs.orbitflare.com/rpc/methods/getTransaction This example shows how to fetch transaction data using the web3.js library. ```APIDOC ## Get Transaction with web3.js ### Description Retrieves transaction details using the `getTransaction` method from the `@solana/web3.js` library. ### Method Signature `connection.getTransaction(signature: string, options?: { commitment?: string; encoding?: string }): Promise` ### Parameters - **signature** (string) - Required - The signature of the transaction to retrieve. - **options** (object) - Optional - Configuration options for fetching the transaction. - **commitment** (string) - Optional - The commitment level for the query. - **encoding** (string) - Optional - The encoding format for the transaction data (e.g., 'jsonParsed'). ### Request Example ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); const signature = '5VERv8NMvzbJMEkV8xnrLkUaQwJJ9C9zV5uZ6cKf7Kq9'; // Get transaction const transaction = await connection.getTransaction(signature, { encoding: 'jsonParsed' }); console.log('Transaction:', transaction); ``` ### Response - **Transaction** (object | null) - An object containing the transaction details if found, otherwise null. The structure of the transaction object depends on the `encoding` option used. ``` -------------------------------- ### Get Transaction using curl Source: https://docs.orbitflare.com/rpc/methods/getTransaction This example demonstrates how to retrieve transaction details using a direct RPC call with curl. ```APIDOC ## Get Transaction ### Description Retrieves the details of a specific transaction using its signature. ### Method POST ### Endpoint `https://fra.rpc.orbitflare.com` ### Parameters #### Query Parameters - **api_key** (string) - Required - Your Orbitflare API key. #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version, should be "2.0". - **id** (integer) - Required - An identifier for the request. - **method** (string) - Required - The method to call, which is "getTransaction". - **params** (array) - Required - An array containing the transaction signature and optional configuration. - **0** (string) - Required - The transaction signature. - **1** (object) - Optional - Configuration object. - **encoding** (string) - Optional - The encoding format for the transaction data (e.g., "jsonParsed"). ### Request Example ```json { "jsonrpc": "2.0", "id": 1, "method": "getTransaction", "params": [ "5VERv8NMvzbJMEkV8xnrLkUaQwJJ9C9zV5uZ6cKf7Kq9", { "encoding": "jsonParsed" } ] } ``` ### Response #### Success Response (200) - **result** (object) - Contains the transaction details. - **error** (object) - Contains error details if the request failed. - **id** (integer) - The identifier for the response. #### Response Example (Response structure depends on the encoding and transaction details. Refer to Orbitflare RPC documentation for specific response formats.) ``` -------------------------------- ### getRecentBlockhash RPC Request with Commitment (Legacy) Source: https://docs.orbitflare.com/rpc/methods/getRecentBlockhash Example of a JSON-RPC request to get the most recent blockhash with a specified commitment level. ```bash curl https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY -X POST -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0", "id": 1, "method": "getRecentBlockhash", "params": [ { "commitment": "confirmed" } ] }' ``` -------------------------------- ### Request with Configuration Source: https://docs.orbitflare.com/rpc/methods/getSignaturesForAddress An example demonstrating how to use optional parameters like `limit`, `before`, and `commitment` for more specific queries. ```APIDOC ## POST /?api_key={api_key} ### Description Retrieves confirmed transaction signatures for a given address with pagination and commitment options. ### Method POST ### Endpoint `/?api_key={api_key}` ### Parameters #### Request Body - **jsonrpc** (string) - Required - Specifies the JSON-RPC version. - **id** (integer) - Required - The ID of the request. - **method** (string) - Required - The method to call, which is `getSignaturesForAddress`. - **params** (array) - Required - An array containing the address and optional configuration. - **address** (string) - Required - The address to query signatures for. - **config** (object) - Optional - Configuration object for the query. - **limit** (integer) - Optional - The maximum number of signatures to return (default: 100). - **before** (string) - Optional - Signature to paginate before. - **commitment** (string) - Optional - Commitment level (`processed`, `confirmed`, `finalized`). ### Request Example ```json { "jsonrpc": "2.0", "id": 1, "method": "getSignaturesForAddress", "params": [ "ADDRESS", { "limit": 100, "before": "SIGNATURE", "commitment": "confirmed" } ] } ``` ### Response #### Success Response (200) - **result** (array) - An array of signature objects. - **signature** (string) - The transaction signature. - **slot** (integer) - The slot in which the transaction was processed. - **err** (object | null) - An error object if the transaction failed, otherwise null. - **confirmationStatus** (string) - The confirmation status of the transaction. - **blockTime** (integer | null) - The block timestamp if available. #### Response Example ```json { "jsonrpc": "2.0", "result": [ { "signature": "ANOTHER_SIGNATURE", "slot": 123456780, "err": null, "confirmationStatus": "confirmed", "blockTime": 1678886300 } ], "id": 1 } ``` ``` -------------------------------- ### Basic getRecentBlockhash RPC Request (Legacy) Source: https://docs.orbitflare.com/rpc/methods/getRecentBlockhash Example of a basic JSON-RPC request to get the most recent blockhash using curl. ```bash curl https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY -X POST -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0", "id": 1, "method": "getRecentBlockhash", "params": [] }' ``` -------------------------------- ### Install OrbitFlare CLI from Source Source: https://docs.orbitflare.com/cli Install the OrbitFlare CLI by cloning the repository and building from source. Requires Git and Rust. ```bash git clone https://github.com/orbitflare/orbit-cli.git cd orbit-cli cargo install --path . ``` -------------------------------- ### OpenAPI Configuration Examples Source: https://docs.orbitflare.com/essentials/settings Configure OpenAPI paths using absolute URLs, relative paths, or an array for multiple sources. ```json "openapi": "https://example.com/openapi.json" ``` ```json "openapi": "/openapi.json" ``` ```json "openapi": ["https://example.com/openapi1.json", "/openapi2.json", "/openapi3.json"] ``` -------------------------------- ### Get Largest Accounts using web3.js Source: https://docs.orbitflare.com/rpc/methods/getLargestAccounts Example of how to use the web3.js library to fetch the largest accounts, with and without filters. ```APIDOC ## Get Largest Accounts with web3.js ### Description This example demonstrates how to use the `@solana/web3.js` library to interact with the `getLargestAccounts` RPC method. ### Method Signature `connection.getLargestAccounts(options?: { filter?: 'circulating' | 'nonCirculating' }): Promise>` ### Parameters - **options** (object) - Optional. Configuration options for the call. - **filter** (string) - Optional. Filters the accounts. Accepted values: "circulating", "nonCirculating". ### Code Example ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get all largest accounts const largestAccounts = await connection.getLargestAccounts(); console.log('Largest accounts:', largestAccounts); // Get circulating accounts only const circulatingAccounts = await connection.getLargestAccounts({ filter: 'circulating' }); console.log('Largest circulating accounts:', circulatingAccounts); ``` ### Response The method returns a Promise that resolves to an array of account objects. Each object contains: - **address** (string): The public key of the account. - **lamports** (bigint): The balance of the account in lamports. ``` -------------------------------- ### Scaffold a Project with Orbitflare CLI Source: https://docs.orbitflare.com/cli Install a project template, such as 'solana-copy-trader', into a specified directory. Replace './my-bot' with your desired project path. ```bash orbitflare template --install solana-copy-trader --dir ./my-bot ``` -------------------------------- ### Request Airdrop with web3.js Source: https://docs.orbitflare.com/rpc/methods/requestAirdrop This web3.js example demonstrates how to request an airdrop and optionally wait for its confirmation. Ensure you have the @solana/web3.js library installed. ```typescript import { Connection, PublicKey } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Request airdrop const signature = await connection.requestAirdrop( new PublicKey('83astBRguLMdt2h5U1Tpdq5tjFoJ6noeGwaY3mDLVcri'), 1000000000 // 1 SOL ); console.log('Airdrop signature:', signature); // Request airdrop with confirmation async function requestAirdropWithConfirmation( pubkey: string, lamports: number, config: { commitment?: string } ) { const signature = await connection.requestAirdrop( new PublicKey(pubkey), lamports, config ); // Wait for confirmation const confirmation = await connection.confirmTransaction(signature); return { signature, confirmation: { status: confirmation.value.err ? 'failed' : 'success', slot: confirmation.context.slot }, request: { pubkey, lamports, formatted: lamports / 1e9 + ' SOL' }, metadata: { timestamp: Date.now(), commitment: config.commitment } }; } ``` -------------------------------- ### Build Jetstream Client (Bash) Source: https://docs.orbitflare.com/data-streaming/jetstream Build the Rust client example in release mode. ```bash cargo build --release ``` -------------------------------- ### Get Transaction Count with web3.js Source: https://docs.orbitflare.com/rpc/methods/getTransactionCount Shows how to use the web3.js library to fetch the transaction count. Includes an example of fetching with a specific commitment level. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get transaction count const count = await connection.getTransactionCount(); console.log('Transaction count:', count); // Get transaction count with analysis async function getTransactionCountWithAnalysis( config: { commitment?: string } ) { const count = await connection.getTransactionCount(config); return { count, analysis: { timestamp: Date.now(), commitment: config.commitment } }; } ``` -------------------------------- ### Using web3.js Source: https://docs.orbitflare.com/rpc/methods/getProgramAccounts Examples of using the web3.js library to fetch program accounts, both with and without filters. ```APIDOC ## getProgramAccounts with web3.js ### Description Demonstrates how to use the `@solana/web3.js` library to fetch program accounts. Includes examples for fetching all accounts and for applying filters. ### Usage ```typescript import { Connection, PublicKey } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get all program accounts const programId = new PublicKey('PROGRAM_ID'); const allAccounts = await connection.getProgramAccounts(programId); console.log('All Accounts:', allAccounts); // Get filtered program accounts async function getFilteredProgramAccounts( programId: PublicKey, filters: any[] ) { const filteredAccounts = await connection.getProgramAccounts(programId, { filters }); return filteredAccounts.map(({ pubkey, account }) => ({ pubkey: pubkey.toBase58(), data: account.data, lamports: account.lamports, owner: account.owner.toBase58(), executable: account.executable })); } // Example usage of filtered accounts: // const filters = [ // { dataSize: 165 }, // { // memcmp: { // offset: 0, // bytes: 'BASE58_ENCODED_BYTES', // } // } // ]; // const filtered = await getFilteredProgramAccounts(programId, filters); // console.log('Filtered Accounts:', filtered); ``` ### Parameters for `getProgramAccounts` (web3.js) - **programId** (PublicKey) - The public key of the program. - **options** (object, optional) - Configuration options. - **filters** (array, optional) - An array of filter objects. Each object can be: - `{ dataSize: number }` - Filters accounts by their data size. - `{ memcmp: { offset: number, bytes: string } }` - Filters accounts based on memory comparison. `bytes` should be base-58 encoded. ### Response Structure (web3.js) Each account object in the returned array has the following structure: - **pubkey** (PublicKey) - The public key of the account. - **account** (object) - The account details. - **data** (Buffer) - The account data. - **executable** (boolean) - Whether the account is executable. - **lamports** (number) - The account balance in lamports. - **owner** (PublicKey) - The owner of the account. - **rentEpoch** (number) - The epoch at which the account will next owe rent. ``` -------------------------------- ### Get Signature Statuses with web3.js Source: https://docs.orbitflare.com/rpc/methods/getSignatureStatuses Shows how to fetch signature statuses using the web3.js library. This example requires the '@solana/web3.js' package and an active RPC connection. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('http://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); const signatures = [ '5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW', '5j7s6NiJS3JAkvgkoc18WVAsiSaci2pxB2A6ueCJP4tprA2TFg9wSyTLeYouxPBJEMzJinENTkpA52YStRW5Dia7' ]; const statuses = await connection.getSignatureStatuses(signatures); console.log(statuses); ``` -------------------------------- ### Install OrbitFlare Rust SDK Source: https://docs.orbitflare.com/agents/sdk Install the Rust SDK with specific features for RPC, WebSocket, Yellowstone gRPC, or Jetstream. Features can be combined as needed. ```bash cargo add orbitflare-sdk # RPC only cargo add orbitflare-sdk --features ws # + WebSocket cargo add orbitflare-sdk --features grpc # + Yellowstone gRPC cargo add orbitflare-sdk --features jetstream # + Jetstream ``` -------------------------------- ### Get Signatures using web3.js Source: https://docs.orbitflare.com/rpc/methods/getSignaturesForAddress This TypeScript example demonstrates how to fetch transaction signatures for an address using the web3.js library. It includes a function for paginated retrieval of signatures. ```typescript import { Connection, PublicKey } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get signatures for address const signatures = await connection.getSignaturesForAddress( new PublicKey('ADDRESS') ); console.log('Signatures:', signatures); // Get paginated signatures async function getPaginatedSignatures( address: PublicKey, limit: number = 100, before?: string ) { const signatures = await connection.getSignaturesForAddress(address, { limit, before }); return signatures.map(signature => ({ signature: signature.signature, slot: signature.slot, success: !signature.err, timestamp: signature.blockTime, status: signature.confirmationStatus })); } ``` -------------------------------- ### getSignaturesForAddress Request with Configuration Source: https://docs.orbitflare.com/rpc/methods/getSignaturesForAddress This example shows how to make a request with additional parameters like 'limit', 'before', and 'commitment' for pagination and specific confirmation status. Replace 'YOUR-API-KEY', 'ADDRESS', and 'SIGNATURE' accordingly. ```bash curl https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY -X POST -H "Content-Type: application/json" -d '{ "jsonrpc": "2.0", "id": 1, "method": "getSignaturesForAddress", "params": [ "ADDRESS", { "limit": 100, "before": "SIGNATURE", "commitment": "confirmed" } ] }' ``` -------------------------------- ### Get Identity using Python Source: https://docs.orbitflare.com/rpc/methods/getIdentity Illustrates how to fetch the identity public key using the solana-py library. This example requires the solana.rpc.api Client to be initialized with the RPC endpoint. ```python from solana.rpc.api import Client client = Client("http://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY") response = client.get_identity() print(response) ``` -------------------------------- ### Build Minimal RPC Client Source: https://docs.orbitflare.com/sdk/go-rpc Construct a minimal RPC client using only the essential URL configuration. ```go client, err := rpc.NewBuilder(). URL("http://ny.rpc.orbitflare.com"). Build() ``` -------------------------------- ### Get Epoch Info using web3.js Source: https://docs.orbitflare.com/rpc/methods/getEpochInfo This TypeScript example demonstrates how to fetch epoch information using the web3.js library. It initializes a connection and calls the getEpochInfo method. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('http://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); const epochInfo = await connection.getEpochInfo(); console.log(epochInfo); ``` -------------------------------- ### Full Network Interaction Example Source: https://docs.orbitflare.com/sdk/typescript-rpc A comprehensive script demonstrating common RPC operations: checking network state, fetching wallet balances and token holdings, and retrieving recent transactions. Requires the RpcClientBuilder to be imported. ```typescript import { RpcClientBuilder } from '@orbitflare/sdk'; async function main() { const client = new RpcClientBuilder() .url('http://ny.rpc.orbitflare.com') .fallbackUrl('http://fra.rpc.orbitflare.com') .commitment('confirmed') .build(); const wallet = 'CKs1E69a2e9TmH4mKKLrXFF8kD3ZnwKjoEuXa6sz9WqX'; const slot = await client.getSlot(); const { blockhash } = await client.getLatestBlockhash(); console.log(`network slot: ${slot}`); console.log(`blockhash: ${blockhash}`); const balance = await client.getBalance(wallet); console.log(` ${wallet}`); console.log(` SOL: ${(balance / 1_000_000_000).toFixed(4)}`); const tokens = await client.getTokenAccountsByOwner(wallet); for (const token of tokens) { const info = token?.account?.data?.parsed?.info; const mint = info?.mint ?? 'unknown'; const amount = info?.tokenAmount?.uiAmountString ?? '0'; if (amount !== '0') console.log(` ${mint}: ${amount}`); } const sigs = await client.getSignaturesForAddress(wallet, 5); console.log(' recent transactions:'); for (const sig of sigs) { const signature = sig?.signature ?? '?'; const status = sig?.err == null ? 'ok' : 'failed'; console.log(` ${sig?.slot ?? 0} ${status} ${signature.slice(0, 20)}`); } const fees = await client.getRecentPrioritizationFees([wallet]); const total = fees.reduce( (acc: number, f: any) => acc + (typeof f?.prioritizationFee === 'number' ? f.prioritizationFee : 0), 0, ); const avg = total / Math.max(fees.length, 1); console.log(` avg priority fee: ${avg.toFixed(0)} micro-lamports`); } void main(); ``` -------------------------------- ### Get Block Time with web3.js Source: https://docs.orbitflare.com/rpc/methods/getBlockTime This TypeScript example demonstrates how to use the web3.js library to fetch the block time for a single slot and how to process multiple slots concurrently. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get block time const blockTime = await connection.getBlockTime(100000000); if (blockTime !== null) { console.log('Block time:', new Date(blockTime * 1000)); } else { console.log('Block not available'); } // Get multiple block times async function getBlockTimes(slots: number[]) { const times = await Promise.all( slots.map(slot => connection.getBlockTime(slot)) ); return times.map((time, index) => ({ slot: slots[index], time: time ? new Date(time * 1000) : null })); } ``` -------------------------------- ### Get Early Token Transactions Source: https://docs.orbitflare.com/cn/fetching-data/getTransactionsForAddress Retrieve the earliest transactions for a token mint to identify first minters and early holders. Use `sortOrder: 'asc'` to start from the beginning. ```typescript const earlyActivity = await getTransactionsForAddress(tokenMintAddress, { sortOrder: 'asc', limit: 100, transactionDetails: 'full', filters: { tokenAccounts: 'all', }, }); ``` -------------------------------- ### Minimal gRPC client setup Source: https://docs.orbitflare.com/sdk/rust-grpc Initialize a GeyserClient with only the essential URL configuration. ```rust let client = GeyserClientBuilder::new() .url("http://ny.rpc.orbitflare.com:10000") .build()?; ``` -------------------------------- ### Install OrbitFlare SDK Source: https://docs.orbitflare.com/sdk/typescript-rpc Install the OrbitFlare SDK using npm. This package provides the RPC client functionality. ```bash npm install @orbitflare/sdk ``` -------------------------------- ### Get Inflation Rate with web3.js Source: https://docs.orbitflare.com/rpc/methods/getInflationRate Shows how to retrieve the inflation rate and calculate staking APY using the web3.js library. This example requires an active connection to the RPC endpoint. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('https://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); // Get current inflation rate const inflationRate = await connection.getInflationRate(); console.log('Total inflation:', inflationRate.total); console.log('Validator inflation:', inflationRate.validator); console.log('Foundation inflation:', inflationRate.foundation); console.log('Current epoch:', inflationRate.epoch); // Calculate staking APY async function calculateStakingAPY(totalStaked: number, totalSupply: number) { const inflationRate = await connection.getInflationRate(); const validatorAPY = (inflationRate.validator * totalSupply) / totalStaked; return { validatorAPY, totalInflation: inflationRate.total, validatorInflation: inflationRate.validator, foundationInflation: inflationRate.foundation, epoch: inflationRate.epoch }; } ``` -------------------------------- ### Build Minimal WebSocket Client Source: https://docs.orbitflare.com/sdk/go-websocket Create a WebSocket client with only the essential URL configuration. The Build method establishes the connection immediately. ```go client, err := ws.NewBuilder(). URL("ws://ny.rpc.orbitflare.com"). Build(ctx) ``` -------------------------------- ### Get Inflation Reward with web3.js Source: https://docs.orbitflare.com/rpc/methods/getInflationReward Shows how to retrieve inflation rewards for a list of addresses using the web3.js library. This example queries for epoch 2 and logs the rewards to the console. ```typescript import { Connection } from '@solana/web3.js'; const connection = new Connection('http://fra.rpc.orbitflare.com?api_key=YOUR-API-KEY'); const addresses = [ '6dmNQ5jwLeLk5REvio1JcMshcbvkYMwy26sJ8pbkvStu', 'BGsqMegLpV6n6Ve146sSX2dTjUMj3M92HnU8BbNRMhF2' ]; const rewards = await connection.getInflationReward(addresses, 2); console.log(rewards); ```