### Install switchboard-on-demand dependency Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/README.md Add the library to your Cargo.toml file to begin using it in your project. ```toml [dependencies] switchboard-on-demand = "0.8.0" ``` -------------------------------- ### Install Firebase CLI Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/DOCS.md Use this command to install or upgrade the Firebase CLI tool. ```bash curl -sL https://firebase.tools | upgrade=true bash ``` -------------------------------- ### use_feed_data Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md An example of how to load and validate a PullFeedAccountData account within a Solana Anchor instruction. ```APIDOC ## use_feed_data ### Description This function demonstrates how to load a `PullFeedAccountData` account, extract the current price, and validate the data freshness and sample count. ### Signature `pub fn use_feed_data(ctx: Context) -> Result<()>` ### Parameters - **ctx** (Context) - Required - The Anchor context containing the `feed` account loader. ### Logic - Loads the `PullFeedAccountData` from the account loader. - Retrieves the current price from `last_update.value()`. - Validates that the data age (in slots) does not exceed the `staleness_threshold`. - Validates that the `num_samples` meets the `min_responses` requirement. ``` -------------------------------- ### Generate and Deploy Documentation Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/DOCS.md Commands to generate the documentation site locally or deploy it to Firebase. ```bash # Generates the docs site and opens locally. pnpm docgen --open # Generates the docs site and tries to deploy to Firebase. # # Note that you will need to be logged into the Firebase CLI (See above). pnpm docgen:deploy ``` -------------------------------- ### View SDK File Structure Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/INDEX.md Displays the directory layout of the documentation workspace. ```text /workspace/home/output/ ├── README.md ........................... Start here ├── INDEX.md ............................ This file ├── configuration.md .................... Feature flags & env vars ├── types.md ............................ Type definitions ├── errors.md ........................... Error reference └── api-reference/ ├── quote-verifier.md ............... QuoteVerifier builder & verification ├── oracle-quote.md ................. Verified quote data access ├── oracle-account.md ............... Oracle account & TEE attestation ├── pull-feed.md .................... Aggregated oracle results ├── decimal.md ...................... Decimal number types └── sysvar-utilities.md ............. System variable helpers ``` -------------------------------- ### Get current slot from Clock sysvar Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/sysvar-utilities.md Extracts the current slot number from a provided Solana Clock sysvar reference. ```rust pub fn get_slot(clock: &Clock) -> u64 ``` ```rust use switchboard_on_demand::clock; use solana_program::sysvar::clock::Clock; let clock = Clock::get()?; let current_slot = clock::get_slot(&clock); ``` -------------------------------- ### Get Pull Feed Account Size Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md Retrieves the total byte size of a pull feed account, including the 8-byte discriminator. ```rust let account_size = PullFeedAccountData::size(); ``` -------------------------------- ### Configure Client-V3 Feature Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Enables the client feature using Solana v3 crates. ```toml [dependencies] switchboard-on-demand = { version = "0.10.0", features = ["client-v3"] } ``` -------------------------------- ### Configure Default Dependencies Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Basic configuration for including the crate with default features and CPI support. ```toml [dependencies] switchboard-on-demand = { version = "0.10.0", features = ["default", "cpi"] } ``` -------------------------------- ### Configure Solana-V3 Feature Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Explicitly enables Solana SDK v3 and CPI support. ```toml switchboard-on-demand = { version = "0.10.0", features = ["solana-v3", "cpi"] } ``` -------------------------------- ### Configure Solana-V2 Feature Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Explicitly enables Solana SDK v2 and CPI support. ```toml switchboard-on-demand = { version = "0.10.0", features = ["solana-v2", "cpi"] } ``` -------------------------------- ### Configure Anchor Integration Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Enables Anchor framework support with Solana SDK v2. ```toml switchboard-on-demand = { version = "0.10.0", features = ["anchor", "solana-v2"] } ``` -------------------------------- ### On-Chain Pull Feed Parsing Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md Demonstrates how to load a Pull Feed account, extract the price, and validate data freshness and sample counts. ```rust use switchboard_on_demand::prelude::*; #[derive(Accounts)] pub struct UsePullFeed<'info> { pub feed: AccountLoader<'info, PullFeedAccountData>, } pub fn use_feed_data(ctx: Context) -> Result<()> { let feed = ctx.accounts.feed.load()?; // Get current price let price = feed.last_update.value() .ok_or(OnDemandError::StaleResult)?; // Validate freshness let clock = Clock::get()?; let age = clock.slot - feed.last_update.slot.unwrap_or(0); if age > feed.staleness_threshold { return Err(OnDemandError::StaleResult.into()); } // Validate sample count if feed.last_update.num_samples < feed.min_responses { return Err(OnDemandError::NotEnoughSamples.into()); } msg!("Feed price: {}, age: {} slots", price, age); Ok(()) } ``` -------------------------------- ### Configure Devnet Deployment Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Sets the crate to use devnet program IDs for off-chain interactions. ```toml [target.'cfg(not(target_os = "solana"))'.dependencies] switchboard-on-demand = { version = "0.10.0", features = ["client", "devnet"] } ``` -------------------------------- ### Integrate OracleAccountData with QuoteVerifier Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Demonstrates loading oracle data, verifying queue membership, checking enclave status, and performing quote verification. ```rust let oracle_data = OracleAccountData::new(&oracle_info)?; // Verify oracle is on the correct queue assert_eq!(oracle_data.queue, queue.key()); // Verify oracle is currently verified let clock = Clock::get()?; assert!(oracle_data.enclave.is_verified(&clock)); // Then verify the oracle quote let quote = QuoteVerifier::new() .queue(&queue_account) // ... other builder methods .verify_account(&oracle_info)?; ``` -------------------------------- ### List Firebase Projects Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/DOCS.md Verify access to the required Firebase project by listing available projects. ```bash ❯ firebase projects:list ✔ Preparing the list of your Firebase projects ┌────────────────────────┬────────────────────────┬────────────────┬──────────────────────┐ │ Project Display Name │ Project ID │ Project Number │ Resource Location ID │ ├────────────────────────┼────────────────────────┼────────────────┼──────────────────────┤ │ Switchboard Docs │ switchboard-docs │ 659732266249 │ [Not specified] │ └────────────────────────┴────────────────────────┴────────────────┴──────────────────────┘ ``` -------------------------------- ### Define SDK Version Constants Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/types.md Constants for tracking the current SDK version, name, and compatibility requirements. ```rust pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub const SDK_NAME: &str = "switchboard-on-demand"; pub const SUPPORTED_PROGRAM_VERSIONS: &[&str] = &["0.7.0"]; pub const MIN_SOLANA_VERSION: &str = "1.18.0"; ``` -------------------------------- ### Configure Pinocchio Optimization Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Enables Pinocchio for optimized account deserialization. ```toml switchboard-on-demand = { version = "0.10.0", features = ["cpi", "pinocchio"] } ``` -------------------------------- ### Integrate with the quote program Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/README.md Use the QUOTE_PROGRAM_ID and QuoteVerifier to verify quotes directly from oracle accounts. ```rust use switchboard_on_demand::{QUOTE_PROGRAM_ID, QuoteVerifier}; // The quote program ID is available as a constant let quote_program = QUOTE_PROGRAM_ID; // Verify quotes from oracle accounts let verified_quote = QuoteVerifier::new() .queue(&queue_account) .slothash_sysvar(&slothash_sysvar) .ix_sysvar(&instructions_sysvar) .clock_slot(clock_slot) .max_age(150) .verify_account(&oracle_account)?; ``` -------------------------------- ### Process Pull Feed Account Data in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md Demonstrates parsing account data, accessing aggregated values, checking data freshness, and iterating over oracle submissions. ```rust use switchboard_on_demand::PullFeedAccountData; use rust_decimal::Decimal; pub fn process_pull_feed(account_data: &[u8]) -> Result<()> { // Parse account data (skip 8-byte discriminator) let feed: &PullFeedAccountData = bytemuck::from_bytes(&account_data[8..]); // Access current result let current = &feed.last_update; // Get aggregated values as Decimals if let Some(value) = current.value() { msg!("Current price: {}", value); } if let Some(mean) = current.mean() { msg!("Mean: {}", mean); } if let Some(std_dev) = current.std_dev() { msg!("Std Dev: {}", std_dev); } // Check data freshness if let Some(slot) = current.result_slot() { msg!("Result slot: {}", slot); let current_slot = Clock::get()?.slot; let staleness = current_slot - slot; if staleness > feed.staleness_threshold { return Err(OnDemandError::StaleResult.into()); } } // Iterate over submissions for submission in &feed.submissions { if submission.oracle == Pubkey::default() { continue; // Empty slot } msg!( "Oracle {} submitted {} at slot {}", submission.oracle, submission.value, submission.slot ); } // Access historical results for (i, historical) in feed.historical_results.iter().enumerate().take(10) { msg!("History[{}] - Mean: {}, Slot: {}", i, historical.mean, historical.slot); } Ok(()) } ``` -------------------------------- ### Verify Oracle Quote Workflow Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Demonstrates a complete quote verification process using the QuoteVerifier builder pattern. ```rust use anchor_lang::prelude::*; use switchboard_on_demand::QuoteVerifier; #[derive(Accounts)] pub struct VerifyQuoteCtx<'info> { pub queue: AccountLoader<'info, QueueAccountData>, pub slothashes: Sysvar<'info, SlotHashes>, pub instructions: Sysvar<'info, Instructions>, pub clock: Sysvar<'info, Clock>, } pub fn verify_oracle_quote(ctx: Context) -> Result<()> { let clock_slot = switchboard_on_demand::clock::get_slot(&ctx.accounts.clock); let quote = QuoteVerifier::new() .queue(&ctx.accounts.queue) .slothash_sysvar(&ctx.accounts.slothashes) .ix_sysvar(&ctx.accounts.instructions) .clock_slot(clock_slot) .max_age(150) .verify_instruction_at(0)?; // Access verified feed data for feed in quote.feeds() { msg!("Feed {}: {}", feed.hex_id(), feed.value()); } Ok(()) } ``` -------------------------------- ### Enable Pinocchio Optimization Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Configures dependencies in Cargo.toml to enable Pinocchio for reduced compute unit usage during account deserialization. ```toml [dependencies] switchboard-on-demand = { version = "0.10.0", features = ["cpi", "pinocchio"] } pinocchio = "0.9" ``` -------------------------------- ### version() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Returns the quote format version from the ED25519 instruction data. ```APIDOC ## version() ### Description Returns the quote format version from the ED25519 instruction data. ### Returns - **u8** - Quote format version ### Example ```rust let version = quote.version(); ``` ``` -------------------------------- ### verify() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Core verification method that performs all security checks on raw ED25519 instruction data. ```APIDOC ## verify(data: &[u8]) ### Description Core verification method that performs all security checks on raw ED25519 instruction data, including signature parsing, key validation, slot hash verification, and quote age validation. ### Parameters - **data** (&'data [u8]) - Required - Raw ED25519 instruction data ### Returns - **Result, AnyError>** - The verified oracle quote or an error if verification fails. ``` -------------------------------- ### Construct SwitchboardDecimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Create a new instance by providing the mantissa and scale directly. ```rust pub fn new(mantissa: i128, scale: u32) -> SwitchboardDecimal ``` ```rust use switchboard_on_demand::SwitchboardDecimal; // Create 123.45 let dec = SwitchboardDecimal::new(12345, 2); ``` -------------------------------- ### SwitchboardDecimal methods Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/types.md Available methods for creating and manipulating SwitchboardDecimal instances. ```rust pub fn new(mantissa: i128, scale: u32) -> SwitchboardDecimal pub fn from_rust_decimal(d: Decimal) -> SwitchboardDecimal pub fn from_f64(v: f64) -> SwitchboardDecimal pub fn scale_to(&self, new_scale: u32) -> i128 pub fn new_with_scale(&self, new_scale: u32) -> Self ``` -------------------------------- ### verify_instruction_at() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Loads and verifies an ED25519 instruction from the instructions sysvar at the specified index, then verifies the oracle quote data. ```APIDOC ## verify_instruction_at(instruction_idx: i64) ### Description Loads and verifies an ED25519 instruction from the instructions sysvar at the specified index, then verifies the oracle quote data. ### Parameters - **instruction_idx** (i64) - Required - Index of instruction in sysvar (typically 0 for first/current) ### Returns - **Result** - The verified oracle quote or an error if verification fails. ``` -------------------------------- ### Parse and verify oracle feed data on-chain Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/README.md Use PullFeedAccountData to parse feed accounts and retrieve verified prices with staleness and sample count constraints. ```rust use switchboard_on_demand::PullFeedAccountData; use rust_decimal::Decimal; use solana_program::sysvar::clock::Clock; pub fn solana_ix<'a>(mut ctx: Context>, params: Params) -> Result<()> { // Parse the oracle feed account data let feed = PullFeedAccountData::parse(ctx.accounts.sb_feed)?; // Configure staleness and accuracy requirements let max_stale_slots = 100; // Maximum slots before data is considered stale let min_samples = 5; // Minimum oracle samples required for accuracy // Get the verified oracle price with enhanced error handling let price: Decimal = feed.get_value(&Clock::get()?, max_stale_slots, min_samples, true)?; msg!("Oracle Price: {}", price); Ok(()) } ``` -------------------------------- ### Process Oracle Quote in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Demonstrates how to verify an oracle quote using the QuoteVerifier and access its metadata, feed data, and oracle indices. ```rust use switchboard_on_demand::{QuoteVerifier, OracleQuote}; #[derive(Accounts)] pub struct ProcessQuoteCtx<'info> { pub queue: AccountLoader<'info, QueueAccountData>, pub slothashes: Sysvar<'info, SlotHashes>, pub instructions: Sysvar<'info, Instructions>, pub clock: Sysvar<'info, Clock>, } pub fn process_oracle_quote(ctx: Context) -> Result<()> { let clock_slot = switchboard_on_demand::clock::get_slot(&ctx.accounts.clock); // Verify and get the quote let quote = QuoteVerifier::new() .queue(&ctx.accounts.queue) .slothash_sysvar(&ctx.accounts.slothashes) .ix_sysvar(&ctx.accounts.instructions) .clock_slot(clock_slot) .max_age(150) .verify_instruction_at(0)?; // Access quote metadata msg!("Quote slot: {}", quote.slot()); msg!("Quote version: {}", quote.version()); msg!("Oracle count: {}", quote.oracle_count); msg!("Feed count: {}", quote.len()); // Iterate over feeds for (idx, feed) in quote.feeds().iter().enumerate() { msg!( "Feed {}: ID={}, Value={}", idx, hex::encode(feed.feed_id()), feed.value() ); } // Access oracle indices for i in 0..quote.oracle_count { let oracle_idx = quote.oracle_index(i as usize)?; msg!("Signature {} from oracle index {}", i, oracle_idx); } // Get header info let header = quote.header(); msg!("Signed slot hash verified"); // Store or transmit raw data let raw_data = quote.raw_data(); msg!("Raw quote data: {} bytes", raw_data.len()); Ok(()) } ``` -------------------------------- ### Implement Ordering and Comparison Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md SwitchboardDecimal supports standard comparison traits by converting to Decimal internally. ```rust impl Ord for SwitchboardDecimal { fn cmp(&self, other: &Self) -> Ordering { let s: Decimal = self.try_into().unwrap(); let other: Decimal = other.try_into().unwrap(); s.cmp(&other) } } ``` ```rust let dec1 = SwitchboardDecimal::new(100, 2); let dec2 = SwitchboardDecimal::new(200, 2); assert!(dec1 < dec2); ``` -------------------------------- ### Oracle Account Constants Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Constants defining seeds for PDAs and timing thresholds for oracle operations. ```rust /// Seed for deriving oracle feed statistics PDAs pub const ORACLE_FEED_STATS_SEED: &[u8; 15] = b"OracleFeedStats"; /// Number of slots to keep oracle key rotation alive pub const KEY_ROTATE_KEEPALIVE_SLOTS: u64 = 1500; /// Maximum number of seconds before oracle data is considered stale pub const MAX_STALE_SECONDS: i64 = 300; ``` -------------------------------- ### Extract Instruction Data Usage Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/sysvar-utilities.md Demonstrates extracting ED25519 instruction data at a specific index using the Instructions utility. ```rust use switchboard_on_demand::Instructions; // Extract the ED25519 instruction (typically at index 0) let ed25519_data = Instructions::extract_ix_data(&ix_sysvar, 0); ``` -------------------------------- ### Convert from f64 Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Create a SwitchboardDecimal from a 64-bit float. Note that this may introduce rounding errors. ```rust pub fn from_f64(v: f64) -> SwitchboardDecimal ``` ```rust let dec = SwitchboardDecimal::from_f64(123.45); ``` -------------------------------- ### Verify Oracle Authority and Queue Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Utility functions to validate that an oracle account matches the expected authority or queue public key. ```rust pub fn verify_oracle_authority( oracle_data: &OracleAccountData, expected_authority: &Pubkey, ) -> Result<()> { if oracle_data.authority != *expected_authority { return Err(OnDemandError::InvalidData.into()); } Ok(()) } pub fn verify_oracle_queue( oracle_data: &OracleAccountData, expected_queue: &Pubkey, ) -> Result<()> { if oracle_data.queue != *expected_queue { return Err(OnDemandError::InvalidData.into()); } Ok(()) } ``` -------------------------------- ### Accessing OracleQuote Version Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Retrieves the quote format version from the ED25519 instruction data. ```rust pub fn version(&self) -> u8 ``` ```rust let version = quote.version(); ``` -------------------------------- ### Checking Oracle Permission Flags Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Use bitwise AND operations to verify if an oracle possesses specific permissions like heartbeat or data submission. ```rust const PERMISSION_HEARTBEAT: u64 = 1 << 0; const PERMISSION_SUBMIT_DATA: u64 = 1 << 1; if oracle.permissions & PERMISSION_SUBMIT_DATA != 0 { // Oracle can submit data } ``` -------------------------------- ### SwitchboardDecimal::from_f64 Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Creates a SwitchboardDecimal from a 64-bit floating point number. ```APIDOC ## SwitchboardDecimal::from_f64 ### Description Creates a SwitchboardDecimal from a 64-bit float. Note that this may introduce rounding errors. ### Parameters - **v** (f64) - Required - The floating point value to convert. ### Returns - **SwitchboardDecimal** - The resulting decimal instance. ``` -------------------------------- ### SwitchboardDecimal::new Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Creates a new instance of SwitchboardDecimal with a specified mantissa and scale. ```APIDOC ## SwitchboardDecimal::new ### Description Creates a new SwitchboardDecimal instance with the provided mantissa and scale. ### Parameters - **mantissa** (i128) - Required - The significant digits of the decimal. - **scale** (u32) - Required - The number of decimal places. ### Returns - **SwitchboardDecimal** - A new instance representing the value. ### Example ```rust let dec = SwitchboardDecimal::new(12345, 2); // Represents 123.45 ``` ``` -------------------------------- ### QuoteVerifier::verify_instruction_at Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Verifies an oracle quote instruction and returns a validated OracleQuote instance. ```APIDOC ## QuoteVerifier::verify_instruction_at ### Description Verifies an oracle quote instruction at a specific index within the transaction instructions, ensuring the quote is valid against the provided queue and system variables. ### Method Rust Method ### Parameters - **queue** (AccountLoader) - Required - The queue account data. - **slothash_sysvar** (Sysvar) - Required - The slot hashes sysvar. - **ix_sysvar** (Sysvar) - Required - The instructions sysvar. - **clock_slot** (u64) - Required - The current clock slot. - **max_age** (u64) - Required - Maximum age of the quote in slots. ### Response - **OracleQuote** (Struct) - Returns a validated OracleQuote instance containing metadata and feed information. ``` -------------------------------- ### Verify oracle quotes using QuoteVerifier Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/README.md Configure the QuoteVerifier with necessary sysvars and accounts to cryptographically verify oracle data from instructions. ```rust use switchboard_on_demand::prelude::*; // Configure the verifier with required accounts let mut verifier = QuoteVerifier::new(); verifier .queue(&queue_account) .slothash_sysvar(&slothash_sysvar) .ix_sysvar(&instructions_sysvar) .clock_slot(clock_slot) .max_age(150); // Verify the oracle quote from instruction at index 0 let quote = verifier.verify_instruction_at(0)?; // Access verified feed data for feed in quote.feeds() { let feed_id = feed.feed_id(); let value = feed.value(); msg!("Feed {}: {}", feed.hex_id(), value); } ``` -------------------------------- ### verify_delimited() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Verifies length-delimited raw ED25519 instruction data. ```APIDOC ## verify_delimited(data: &[u8]) ### Description Verifies length-delimited raw ED25519 instruction data. The data must have a 2-byte length prefix followed by the actual quote data. ### Parameters - **data** (&'data [u8]) - Required - Length-delimited ED25519 instruction data ### Returns - **Result, AnyError>** - The verified oracle quote or an error if verification fails. ``` -------------------------------- ### Define Switchboard Program ID Constants Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/types.md Use these constants to reference the correct Switchboard program addresses across different Solana environments. ```rust pub const SWITCHBOARD_PROGRAM_ID: Pubkey = pubkey!("SW1TCH7qEPTdLsDHRgPuMQjbQxKdH2aBStViMFnt64f"); pub const ON_DEMAND_MAINNET_PID: Pubkey = pubkey!("SBondMDrcV3K4kxZR1HNVT7osZxAHVHgYXL5Ze1oMUv"); pub const ON_DEMAND_DEVNET_PID: Pubkey = pubkey!("Aio4gaXjXzJNVLtzwtNVmSqGKpANtXhybbkhtAC94ji2"); pub const QUOTE_PROGRAM_ID: Pubkey = pubkey!("orac1eFjzWL5R3RbbdMV68K9H6TaCVVcL6LjvQQWAbz"); ``` -------------------------------- ### Validate Account Existence Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/errors.md Verify that an account exists and is owned by the Switchboard On-Demand program. ```rust match account_info.owner { ref owner if owner == &get_switchboard_on_demand_program_id() => {}, _ => return Err(OnDemandError::AccountNotFound.into()), } ``` -------------------------------- ### verify_account() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Verifies an oracle account containing oracle quote data by extracting and validating the quote data. ```APIDOC ## verify_account(oracle_account: &T) ### Description Verifies an oracle account containing oracle quote data. Extracts quote data from the account (skipping the 8-byte discriminator) and verifies it. ### Parameters - **oracle_account** (&'data T) - Required - Oracle account with quote data ### Returns - **Result, AnyError>** - The verified oracle quote or an error if verification fails. ``` -------------------------------- ### Perform Scale Conversion for Token Amounts Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Adjust decimal precision to match specific token requirements like Solana standard decimals. ```rust // Oracle price in USDC (8 decimals) let oracle_price = SwitchboardDecimal::new(123456789, 8); // Convert to Solana standard (6 decimals for USDC) let solana_price: Decimal = oracle_price.try_into()?; let scaled = oracle_price.scale_to(6); // 12345679 // Use in calculations let amount_usdcs = 1000; // 1000 USDC (6 decimals) let price_in_lamports = (amount_usdcs * scaled) / 1_000_000; ``` -------------------------------- ### Create Rescaled SwitchboardDecimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Return a new SwitchboardDecimal instance with the specified scale. ```rust pub fn new_with_scale(&self, new_scale: u32) -> Self ``` ```rust let dec = SwitchboardDecimal::new(12345, 2); let rescaled = dec.new_with_scale(18); ``` -------------------------------- ### Validate Account Data Size Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/errors.md Perform size verification before attempting to parse account data buffers. ```rust const EXPECTED_SIZE: usize = 8 + std::mem::size_of::(); if account_data.len() < EXPECTED_SIZE { return Err(OnDemandError::CheckSizeError.into()); } ``` -------------------------------- ### Manage Decimal Precision Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Utility functions to convert between standard Decimal types and fixed-precision oracle mantissas. ```rust // Standard Oracle Precision pub const ORACLE_PRECISION: u32 = 18; pub fn to_oracle_precision(value: Decimal) -> i128 { // Ensure value is at correct precision let mut scaled = value; scaled.rescale(ORACLE_PRECISION); scaled.mantissa() } pub fn from_oracle_precision(mantissa: i128) -> Decimal { Decimal::from_i128_with_scale(mantissa, ORACLE_PRECISION) } ``` -------------------------------- ### Verify oracle account in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Verifies an oracle account containing quote data by skipping the 8-byte discriminator. ```rust let quote = verifier.verify_account(&ctx.accounts.oracle)?; for feed in quote.feeds() { println!("Feed {}: ${}", feed.hex_id(), feed.value()); } ``` -------------------------------- ### Calculate Oracle Account Size Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Retrieves the total byte size of an oracle account, including the 8-byte discriminator. ```rust let account_size = OracleAccountData::size(); ``` -------------------------------- ### Integrate SwitchboardDecimal with rust_decimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Convert SwitchboardDecimal types to rust_decimal::Decimal to leverage standard crate operations. ```rust use rust_decimal::prelude::*; use switchboard_on_demand::SwitchboardDecimal; let a = SwitchboardDecimal::new(100, 2); // 1.00 let b = SwitchboardDecimal::new(200, 2); // 2.00 let decimal_a: Decimal = a.try_into()?; let decimal_b: Decimal = b.try_into()?; let result = decimal_a + decimal_b; // 3.00 ``` -------------------------------- ### Checking OracleQuote Length Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Returns the number of valid feeds present in the quote. ```rust pub fn len(&self) -> usize ``` ```rust if quote.len() > 0 { msg!("Quote contains {} feeds", quote.len()); } ``` -------------------------------- ### Define Sysvar Account IDs in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/sysvar-utilities.md Provides the constant Pubkey definitions for standard Solana sysvars and the ED25519 program. ```rust pub const CLOCK_SYSVAR_ID: Pubkey = pubkey!("SysvarC1ock11111111111111111111111111111111"); pub const SLOT_HASHES_SYSVAR_ID: Pubkey = pubkey!("SysvarS1otHashes111111111111111111111111111"); pub const INSTRUCTIONS_SYSVAR_ID: Pubkey = pubkey!("Sysvar1nstructions1111111111111111111111111"); pub const ED25519_PROGRAM_ID: Pubkey = pubkey!("Ed25519SigVerify111111111111111111111111111"); ``` -------------------------------- ### raw_data() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Returns reference to the raw ED25519 instruction data used to create this quote. ```APIDOC ## raw_data() ### Description Returns reference to the raw ED25519 instruction data used to create this quote. Can be stored or transmitted for serialization. ### Returns - **&[u8]** - Raw verified instruction data ### Example ```rust if let Some(raw_data) = quote.raw_data() { store_oracle_quote(raw_data)?; } ``` ``` -------------------------------- ### OracleQuote Constructor Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Internal constructor for creating an OracleQuote instance, typically invoked by QuoteVerifier methods. ```rust pub(crate) fn new( quote_header_ref: &'a PackedQuoteHeader, oracle_count: u8, packed_feed_infos: &'a [PackedFeedInfo], feed_count: u8, oracle_idxs: &'a [u8], recent_slot: u64, version: u8, raw_buffer: &'a [u8], ) -> Self ``` -------------------------------- ### Define OracleSubmission Data Structure Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/types.md Represents an individual data submission from an oracle, including the oracle's address and timing metadata. ```rust #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct OracleSubmission { pub oracle: Pubkey, pub slot: u64, pub landed_at: u64, pub value: i128, } ``` -------------------------------- ### Verify raw instruction data in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Performs core security checks on raw ED25519 instruction data. ```rust let quote = verifier.verify(&instruction_data)?; ``` -------------------------------- ### Calculate Oracle Account Size Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Calculates the total size of the OracleAccountData account including the 8-byte discriminator. ```rust pub fn size() -> usize { 8 + std::mem::size_of::() } ``` -------------------------------- ### Convert SwitchboardDecimal to Decimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Use try_into to convert a SwitchboardDecimal instance into a Rust Decimal. ```rust impl From for Decimal { // Implemented via TryInto } ``` ```rust let sb_dec = SwitchboardDecimal::new(12345, 2); let rust_dec: Decimal = sb_dec.try_into()?; ``` -------------------------------- ### SwitchboardDecimal::from_rust_decimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Converts a rust_decimal::Decimal instance into a SwitchboardDecimal. ```APIDOC ## SwitchboardDecimal::from_rust_decimal ### Description Converts a standard rust_decimal::Decimal type to the SwitchboardDecimal format. ### Parameters - **d** (Decimal) - Required - The rust_decimal::Decimal instance to convert. ### Returns - **SwitchboardDecimal** - The converted decimal instance. ``` -------------------------------- ### Define Quote structure Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/types.md Represents a TEE quote containing attestation proof and oracle enclave information. ```rust #[repr(C)] #[derive(Debug, Copy, Clone, bytemuck::Zeroable, bytemuck::Pod)] pub struct Quote { pub enclave_signer: Pubkey, pub mr_enclave: [u8; 32], pub verification_status: u8, padding1: [u8; 7], pub verification_timestamp: i64, pub valid_until: i64, pub quote_registry: [u8; 32], pub registry_key: [u8; 64], pub secp256k1_signer: [u8; 64], pub last_ed25519_signer: Pubkey, pub last_secp256k1_signer: [u8; 64], pub last_rotate_slot: u64, pub guardian_approvers: [Pubkey; 64], pub guardian_approvers_len: u8, padding2: [u8; 7], pub _ebuf: [u8; 1024], } ``` -------------------------------- ### Configure QuoteVerificationAccounts in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/sysvar-utilities.md Defines the required sysvars for a QuoteVerificationAccounts struct in a Solana program. ```rust #[derive(Accounts)] pub struct QuoteVerificationAccounts<'info> { // Switchboard accounts pub queue: AccountLoader<'info, QueueAccountData>, // Required sysvars pub slot_hashes: Sysvar<'info, SlotHashes>, pub instructions: Sysvar<'info, Instructions>, pub clock: Sysvar<'info, Clock>, } ``` -------------------------------- ### Handle Account Borrow Errors Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/errors.md Catch this error when encountering concurrent borrow conflicts during account data access. ```rust match OracleAccountData::new(&account_info) { Err(OnDemandError::AccountBorrowError) => { msg!("Account data is already borrowed"); } _ => {} } ``` -------------------------------- ### Handle Integer Overflow Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/errors.md Catch arithmetic overflows during calculations involving oracle values. ```rust let result = value.checked_add(other) .ok_or(OnDemandError::IntegerOverflowError)?; ``` -------------------------------- ### Configure Test-Only Ignore Singers Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Disables signature verification for testing purposes. Never use in production. ```toml [dev-dependencies] switchboard-on-demand = { version = "0.10.0", features = ["cpi", "test_only_ignore_singers"] } ``` -------------------------------- ### len() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Returns the number of valid feeds in this quote. ```APIDOC ## len() ### Description Returns the number of valid feeds in this quote. ### Returns - **usize** - Number of feeds ### Example ```rust if quote.len() > 0 { msg!("Quote contains {} feeds", quote.len()); } ``` ``` -------------------------------- ### OracleAccountData::new() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Deserializes and validates an oracle account from AccountInfo. ```APIDOC ## OracleAccountData::new() ### Description Deserializes and validates an oracle account from AccountInfo. ### Signature `pub fn new<'info>(quote_account_info: &'info AccountInfo) -> Result, OnDemandError>` ### Parameters - **quote_account_info** (`&'info AccountInfo`) - Required - Account info to parse ### Returns `Result, OnDemandError>` ### Errors - `OnDemandError::AccountBorrowError` — Failed to borrow account data - `OnDemandError::InvalidDiscriminator` — Account discriminator mismatch - `OnDemandError::InvalidData` — Account data is too small or invalid - `OnDemandError::AccountDeserializeError` — Deserialization failed ### Example ```rust use switchboard_on_demand::OracleAccountData; match OracleAccountData::new(&oracle_account_info) { Ok(oracle_data) => { msg!("Oracle authority: {}", oracle_data.authority); } Err(e) => { msg!("Failed to load oracle: {:?}", e); } } ``` ``` -------------------------------- ### Accessing OracleQuote Raw Data Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Retrieves the raw ED25519 instruction data, useful for serialization or storage. ```rust pub fn raw_data(&self) -> &[u8] ``` ```rust if let Some(raw_data) = quote.raw_data() { store_oracle_quote(raw_data)?; } ``` -------------------------------- ### Handle Floating Point Precision in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Avoid precision loss by using string parsing instead of direct f64 conversion when initializing decimal values. ```rust // WARNING: f64 has only ~15-17 significant digits let price = SwitchboardDecimal::from_f64(123.456789012345678); // Result: 123.45678901234568 (precision loss) // BETTER: Use string parsing let price: Decimal = Decimal::from_str("123.456789012345678")?; let price = SwitchboardDecimal::from_rust_decimal(price); ``` -------------------------------- ### Accessing OracleQuote Feeds Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Retrieves a slice of all valid packed feeds contained within the quote. ```rust pub fn feeds(&self) -> &[PackedFeedInfo] ``` ```rust for feed in quote.feeds() { let value = feed.value(); let feed_id = feed.feed_id(); } ``` -------------------------------- ### feeds() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Returns a slice of all valid packed feeds in the quote. ```APIDOC ## feeds() ### Description Returns a slice of all valid packed feeds in the quote. ### Returns - **&[PackedFeedInfo]** - Slice of verified feed data ### Example ```rust for feed in quote.feeds() { let value = feed.value(); let feed_id = feed.feed_id(); } ``` ``` -------------------------------- ### Validate Account Discriminator Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/errors.md Check if the account data matches the expected oracle account discriminator before parsing. ```rust if data.len() < 8 { return Err(OnDemandError::InvalidDiscriminator.into()); } let disc_bytes = &data[..8]; if disc_bytes != OracleAccountData::DISCRIMINATOR { return Err(OnDemandError::InvalidDiscriminator.into()); } ``` -------------------------------- ### Access SlotHash in QuoteVerifier Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/sysvar-utilities.md Demonstrates how to pass the SlotHash sysvar account to the QuoteVerifier for instruction verification. ```rust use switchboard_on_demand::QuoteVerifier; let verifier = QuoteVerifier::new() .slothash_sysvar(&ctx.accounts.slot_hashes) // Required for verification .queue(&ctx.accounts.queue) .ix_sysvar(&ctx.accounts.instructions) .clock_slot(clock_slot) .verify_instruction_at(0)?; ``` -------------------------------- ### Convert BorshDecimal to SwitchboardDecimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Direct conversion from BorshDecimal to SwitchboardDecimal by mapping mantissa and scale fields. ```rust impl From for SwitchboardDecimal { fn from(val: BorshDecimal) -> Self { SwitchboardDecimal { mantissa: val.mantissa, scale: val.scale, } } } ``` ```rust let borsh_dec = BorshDecimal { mantissa: 12345, scale: 2 }; let sb_dec = SwitchboardDecimal::from(borsh_dec); ``` -------------------------------- ### Handle Generic Errors Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/errors.md Use as a fallback for unspecified error conditions. ```rust match result { Err(OnDemandError::Generic) => { msg!("An unspecified error occurred"); } _ => {} } ``` -------------------------------- ### Verify length-delimited data in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Verifies raw ED25519 instruction data that includes a 2-byte length prefix. ```rust let delimited_data = &account_data[40..]; // Skip 8-byte discriminator and account metadata let quote = verifier.verify_delimited(delimited_data)?; ``` -------------------------------- ### Define CompactResult Data Structure Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/types.md A space-efficient structure used for storing historical oracle results. ```rust #[repr(C)] #[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct CompactResult { pub std_dev: f32, pub mean: f32, pub slot: u64, } ``` -------------------------------- ### CurrentResult Methods Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md Methods for retrieving aggregated metrics from the CurrentResult object. ```APIDOC ## CurrentResult Methods ### `value()` Returns the median value as a `rust_decimal::Decimal`. Returns `None` if uninitialized. ### `std_dev()` Returns standard deviation as a `Decimal`. Returns `None` if uninitialized. ### `mean()` Returns the mean as a `Decimal`. Returns `None` if uninitialized. ### `range()` Returns the range as a `Decimal`. Returns `None` if uninitialized. ### `min_value()` Returns the minimum value as a `Decimal`. Returns `None` if uninitialized. ### `max_value()` Returns the maximum value as a `Decimal`. Returns `None` if uninitialized. ### `result_slot()` Returns the slot when this result was recorded. Returns `None` if uninitialized. ### `min_slot()` Returns the minimum slot of submissions used in this result. Returns `None` if uninitialized. ### `max_slot()` Returns the maximum slot of submissions used in this result. Returns `None` if uninitialized. ``` -------------------------------- ### Extract On-Chain Oracle Values Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Convert raw oracle feed data into a Rust Decimal for safe arithmetic operations. ```rust use switchboard_on_demand::{PullFeedAccountData, SwitchboardDecimal}; use rust_decimal::Decimal; pub fn get_oracle_price(feed: &PullFeedAccountData) -> Result { // Get current result value (i128 with scale 18) let value_i128 = feed.last_update.value; // Convert to Decimal for safe arithmetic let price = Decimal::from_i128_with_scale(value_i128, 18); Ok(price) } ``` -------------------------------- ### Parse Unverified Oracle Account Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Parses oracle quote data directly from an account without verification. ```rust pub fn parse_account_unverified<'data, T>(&self, oracle_account: &'data T) -> Result, AnyError> where T: AsAccountInfo<'data> ``` ```rust let unverified_quote = verifier.parse_account_unverified(&oracle_account)?; ``` -------------------------------- ### Convert BorshDecimal to Rust Decimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Implementation of TryInto trait for converting BorshDecimal back to rust_decimal::Decimal. ```rust impl TryInto for &BorshDecimal { type Error = OnDemandError; fn try_into(self) -> Result { Decimal::try_from_i128_with_scale(self.mantissa, self.scale) .map_err(|_| OnDemandError::DecimalConversionError) } } ``` ```rust let borsh_dec = BorshDecimal { mantissa: 12345, scale: 2 }; let rust_dec: Decimal = (&borsh_dec).try_into()?; ``` -------------------------------- ### slot() Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-quote.md Returns the recent slot from the ED25519 instruction data, used for freshness validation. ```APIDOC ## slot() ### Description Returns the recent slot from the ED25519 instruction data. Used for freshness validation. ### Returns - **u64** - Recent slot number ### Example ```rust let quote = verifier.verify_instruction_at(0)?; let slot = quote.slot(); ``` ``` -------------------------------- ### sb_pid Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md Returns the Switchboard On-Demand program ID based on the current network (mainnet or devnet). ```APIDOC ## sb_pid ### Description Returns the Switchboard On-Demand program ID based on the current network (mainnet or devnet). ### Returns - **Pubkey** - Program ID for current network ### Example ```rust let program_id = sb_pid(); ``` ``` -------------------------------- ### Convert from Rust Decimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Convert a rust_decimal::Decimal instance into a SwitchboardDecimal. ```rust pub fn from_rust_decimal(d: Decimal) -> SwitchboardDecimal ``` ```rust use rust_decimal::Decimal; use switchboard_on_demand::SwitchboardDecimal; let rust_dec = Decimal::from_str("123.45")?; let sb_dec = SwitchboardDecimal::from_rust_decimal(rust_dec); ``` -------------------------------- ### parse_instruction Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/sysvar-utilities.md Parses raw ED25519 instruction data to extract signatures and associated quote metadata. ```APIDOC ## parse_instruction ### Description Parses ED25519 instruction data to extract signatures and quote metadata. ### Signature `pub fn parse_instruction(data: &[u8]) -> Result<(Vec, u8, Vec, u64, u8), AnyError>` ### Parameters - **data** (&[u8]) - Required - Raw ED25519 instruction data ### Returns - `(Vec, u8, Vec, u64, u8)` - A tuple containing parsed signatures, number of signatures, oracle indices, recent slot, and quote version. ### Errors - `AnyError` - Returned if the data format is invalid. ``` -------------------------------- ### Handle Decimal Conversion Errors Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/errors.md Use when converting numeric values to Decimal; ensure mantissa and scale are within valid ranges. ```rust let decimal: Decimal = switchboard_decimal.try_into() .map_err(|_| OnDemandError::DecimalConversionError)?; ``` -------------------------------- ### Verify instruction at index in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/quote-verifier.md Loads and verifies an ED25519 instruction from the instructions sysvar at a specific index. ```rust use switchboard_on_demand::QuoteVerifier; let quote = QuoteVerifier::new() .queue(&queue_account) .slothash_sysvar(&slothash_sysvar) .ix_sysvar(&instructions_sysvar) .clock_slot(clock_slot) .max_age(150) .verify_instruction_at(0)?; for feed in quote.feeds() { msg!("Feed {}: {}", feed.hex_id(), feed.value()); } ``` -------------------------------- ### Deserialize Oracle Account Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/oracle-account.md Deserializes and validates an oracle account from AccountInfo, ensuring correct discriminator and data alignment. ```rust use switchboard_on_demand::OracleAccountData; match OracleAccountData::new(&oracle_account_info) { Ok(oracle_data) => { msg!("Oracle authority: {}", oracle_data.authority); } Err(e) => { msg!("Failed to load oracle: {:?}", e); } } ``` -------------------------------- ### Convert SwitchboardDecimal to BorshDecimal Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/decimal.md Implementation of From trait for converting SwitchboardDecimal to BorshDecimal. ```rust impl From for BorshDecimal { fn from(s: SwitchboardDecimal) -> Self { Self { mantissa: s.mantissa, scale: s.scale, } } } ``` ```rust let sb_dec = SwitchboardDecimal::new(12345, 2); let borsh_dec = BorshDecimal::from(sb_dec); ``` -------------------------------- ### Retrieve Switchboard Program ID in Rust Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md Returns the appropriate program ID for the current network, either mainnet or devnet. ```rust let program_id = sb_pid(); ``` -------------------------------- ### Detect Network and Program ID Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/configuration.md Determines the target network based on compile-time features or environment variables and returns the corresponding program ID. ```rust pub fn is_devnet() -> bool { cfg!(feature = "devnet") || std::env::var("SB_ENV").unwrap_or_default() == "devnet" } pub fn get_switchboard_on_demand_program_id() -> Pubkey { if is_devnet() { ON_DEMAND_DEVNET_PID } else { ON_DEMAND_MAINNET_PID } } ``` -------------------------------- ### Retrieve Current Median Value Source: https://github.com/switchboard-xyz/solana-sdk/blob/main/_autodocs/api-reference/pull-feed.md Accesses the median value from the current result, returning None if the account is uninitialized. ```rust if let Some(price) = result.value() { msg!("Current price: {}", price); } ```