Using Data Feeds Onchain (Solana)

Chainlink Data Feeds are the quickest way to connect your smart contracts to the real-world market prices of assets. This guide demonstrates how to deploy a program to the Solana Devnet cluster and access Data Feeds onchain using the Chainlink Solana Starter Kit. To learn how to read price feed data using offchain applications, see the Using Data Feeds Offchain guide.

To get the full list of available Chainlink Data Feeds on Solana, see the Solana Feeds page. View the program that owns the Chainlink Data Feeds in the Solana Devnet Explorer, or the Solana Mainnet Explorer.

The program that owns the data feeds on both Devnet and Mainnet is HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny. This is the program ID that you use to retrieve Chainlink Price Data onchain in your program. The source code for this program is available in the smartcontractkit/chainlink-solana repository on GitHub.

You can add data feeds to an existing project or use the Solana Starter Kit.

Adding Data Feeds onchain in an existing project

You can read Chainlink Data Feed data onchain in your existing project using the Chainlink Solana Crate. SDK v2 uses direct account reads for improved performance and lower compute unit usage compared to the deprecated v1 SDK which used Cross-Program Invocation (CPI).

Import the Chainlink Solana Crate into your project and use the code sample to make function calls.

  1. Add the Chainlink Solana Crate as an entry in your Cargo.toml file dependencies section, as shown in the starter kit Cargo.toml example.

    [dependencies]
    chainlink_solana = "2.0.8"
    

    If you're using Anchor, also add:

    [dependencies]
    anchor-lang = "0.31.1"
    chainlink_solana = "2.0.8"
    
  2. Choose the code sample that matches your project setup:

    • Rust (Anchor)
    • Rust (Vanilla)

    Both samples demonstrate SDK v2, which reads data directly from the feed account. The code samples have the following components:

    • read_feed_v2: Reads feed data directly from the account data with the feed owner verification
    • latest_round_data: Returns the latest round information for the specified price pair including the latest price
    • description: Returns a price pair description such as SOL/USD
    • decimals: Returns the precision of the price, as in how many numbers the price is padded out to
    • Display: A helper function that formats the padded out price data into a human-readable price
/**
 * THIS IS EXAMPLE CODE THAT USES HARDCODED VALUES FOR CLARITY.
 * THIS IS EXAMPLE CODE THAT USES UN-AUDITED CODE.
 * DO NOT USE THIS CODE IN PRODUCTION.
 */

use anchor_lang::prelude::*;
use chainlink_solana::v2::read_feed_v2;

//Program ID required by Anchor. Replace with your unique program ID once you build your project
declare_id!("HPuUpM1bKbaqx7yY2EJ4hGBaA3QsfP5cofHHK99daz85");

#[account]
pub struct Decimal {
    pub value: i128,
    pub decimals: u32,
}

impl Decimal {
    pub fn new(value: i128, decimals: u32) -> Self {
        Decimal { value, decimals }
    }
}

impl std::fmt::Display for Decimal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut scaled_val = self.value.to_string();
        if scaled_val.len() <= self.decimals as usize {
            scaled_val.insert_str(
                0,
                &vec!["0"; self.decimals as usize - scaled_val.len()].join(""),
            );
            scaled_val.insert_str(0, "0.");
        } else {
            scaled_val.insert(scaled_val.len() - self.decimals as usize, '.');
        }
        f.write_str(&scaled_val)
    }
}

#[program]
pub mod chainlink_solana_demo {
    use super::*;
    pub fn execute(ctx: Context<Execute>) -> Result<()> {
        let feed = &ctx.accounts.chainlink_feed;
        
        // Read the feed data directly from the account (v2 SDK)
        let result = read_feed_v2(
            feed.try_borrow_data()?,
            feed.owner.to_bytes(),
        )
        .map_err(|_| DemoError::ReadError)?;

        // Get the latest round data
        let round = result
            .latest_round_data()
            .ok_or(DemoError::RoundDataMissing)?;

        let description = result.description();
        let decimals = result.decimals();

        // Convert description bytes to string
        let description_str = std::str::from_utf8(&description)
            .unwrap_or("Unknown")
            .trim_end_matches('\0');

        // write the latest price to the program output
        let decimal_print = Decimal::new(round.answer, u32::from(decimals));
        msg!("{} price is {}", description_str, decimal_print);
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Execute<'info> {
    /// CHECK: We're reading data from this chainlink feed account
    pub chainlink_feed: AccountInfo<'info>,
}

#[error_code]
pub enum DemoError {
    #[msg("read error")]
    ReadError,
    #[msg("no round data")]
    RoundDataMissing,
}

Program Transaction logs:

Fetching transaction logs... [ 'Program HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny
consumed 1826 of 1306895 compute units', 'Program return: HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny CA==',
'Program HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny success', 'Program log: SOL / USD price is 93.76988029', ]

To learn more about Solana and Anchor, see the Solana Documentation and the Anchor Documentation.

Using the Solana starter kit

This guide demonstrates the following tasks:

This example shows a full end to end example of using Chainlink Price Feeds on Solana. It includes an onchain program written in rust, as well as an offchain client written in JavaScript. The client passes in an account to the program, the program then looks up the latest price of the specified price feed account, and then stores the result in the passed in account. The offchain client then reads the value stored in the account.

Install the required tools

Before you begin, set up your environment for development on Solana:

  1. Install Git if it is not already configured on your system.

  2. Install Node.js 14 or higher. Run node --version to verify which version you have installed:

    node --version
    
  3. Install Yarn to simplify package management and run code samples.

  4. Install a C compiler such as the one included in GCC. Some of the dependencies require a C compiler.

  5. Install Rust:

    curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh &&
    source $HOME/.cargo/env
    
  6. Install the latest Mainnet version of the Solana CLI and export the path to the CLI:

    sh -c "$(curl -sSfL https://release.solana.com/v1.13.6/install)" &&
    export PATH="~/.local/share/solana/install/active_release/bin:$PATH"
    

    Run solana --version to make sure the Solana CLI is installed correctly.

    solana --version
    
  7. Install Anchor. On some operating systems, you might need to build and install Anchor locally. See the Anchor documentation for instructions.

After you install the required tools, build and deploy the example program from the solana-starter-kit repository.

Deploy the example program

This example includes a contract written in Rust. Deploy the contract to the Solana Devnet cluster.

  1. In a terminal, clone the solana-starter-kit repository and change to the solana-starter-kit directory:

    git clone https://github.com/smartcontractkit/solana-starter-kit &&
    cd ./solana-starter-kit
    

    You can see the complete code for the example on GitHub.

  2. In the ./solana-starter-kit directory, install Node.js dependencies defined in the package.json file:

    yarn install
    
  3. Create a temporary Solana wallet to use for this example. Use a temporary wallet to isolate development from your other wallets and prevent you from unintentionally using lamports on the Solana Mainnet. Alternatively, if you have an existing wallet that you want to use, locate the path to your keypair file and use it as the keypair for the rest of this guide.

    solana-keygen new --outfile ./id.json
    

    When you build your production applications and deploy Solana programs to the Mainnet cluster, always follow the security best practices in the Solana Wallet Guide for managing your wallets and keypairs.

  4. Fund your Solana wallet. On Devnet, use solana airdrop to add tokens to your account. The contract requires at least 4 SOL to deploy and the faucet limits each request to 2 SOL, so you must make two requests to get a total of 4 SOL on your wallet:

    solana airdrop 2 --keypair ./id.json --url devnet &&
    solana airdrop 2 --keypair ./id.json --url devnet
    
    • If the command line faucet does not work, run solana address on the temporary wallet to print the public key value for the wallet and request tokens from SolFaucet:

      solana address -k ./id.json
      
  5. Run anchor build to build the example program. If you receive the no such subcommand: 'build-bpf' error, restart your terminal session and run anchor build again:

    anchor build
    
  6. The build process generates keypairs for your program accounts. Before you deploy your programs, you must add these public keys to the respective lib.rs files. The starter kit contains two programs that both need their IDs updated:

    1. For the chainlink_solana_demo program:

      Get the keypair from the ./target/deploy/chainlink_solana_demo-keypair.json file that Anchor generated:

      solana address -k ./target/deploy/chainlink_solana_demo-keypair.json
      

      Edit the ./programs/chainlink_solana_demo/src/lib.rs file and replace the keypair in the declare_id!() definition with the output from the previous command:

      vi ./programs/chainlink_solana_demo/src/lib.rs
      

      Example (replace with your actual program ID):

      declare_id!("JC16qi56dgcLoaTVe4BvnCoDL6FhH5NtahA7jmWZFdqm");
      
    2. For the ccip_basic_receiver program:

      Get the keypair from the ./target/deploy/ccip_basic_receiver-keypair.json file:

      solana address -k ./target/deploy/ccip_basic_receiver-keypair.json
      

      Edit the ./programs/ccip-basic-receiver/src/lib.rs file and replace the keypair in the declare_id!() definition with the output from the previous command:

      vi ./programs/ccip-basic-receiver/src/lib.rs
      

      Example (replace with your actual program ID):

      declare_id!("ANvQpnDMhuuKmSWYV2ET7A78UZeU2bWbGjRpn4z27nv2");
      
  7. With the new program IDs added to both files, run anchor build again. This recreates the necessary program files with the correct program IDs:

    anchor build
    
  8. Run anchor deploy to deploy the program to the Solana Devnet. Remember to specify the keypair file for your wallet and override the default. This wallet is the account owner (authority) for the program:

    anchor deploy --provider.wallet ./id.json --provider.cluster devnet
    
  9. To confirm that the program deployed correctly, run solana program show --programs to get a list of deployed programs that your wallet owns. For this example, check the list of deployed programs for the id.json wallet on the Solana Devnet:

    solana program show --programs --keypair ./id.json --url devnet
    

    The command prints information for both deployed programs, including the program ID, slot number, the wallet address that owns each program, and the program balance:

    Program Id                                   | Slot      | Authority                                    | Balance
    ANvQpnDMhuuKmSWYV2ET7A78UZeU2bWbGjRpn4z27nv2 | 110801571 | FsQPnANKDhqpoayxCL3oDHFCBmrhP34NrfbDR34qbQUt | 2.23 SOL
    JC16qi56dgcLoaTVe4BvnCoDL6FhH5NtahA7jmWZFdqm | 110801572 | FsQPnANKDhqpoayxCL3oDHFCBmrhP34NrfbDR34qbQUt | 1.47 SOL
    

    To see additional details of your deployed programs, copy a program ID and look it up in the Solana Devnet Explorer.

Now that the program is onchain, you can call it.

Call the deployed program

Use your deployed program to retrieve price data from a Chainlink data feed on Solana Devnet. For this example, call your deployed program using the client.js example code.

  1. Set the Anchor environment variables. Anchor uses these to determine which wallet to use and Solana cluster to use.

    export ANCHOR_PROVIDER_URL=https://api.devnet.solana.com &&
    export ANCHOR_WALLET=./id.json
    
  2. Run the client.js example and pass the program address in using the --program flag:

    node client.js --program $(solana address -k ./target/deploy/chainlink_solana_demo-keypair.json)
    

    If the script executes correctly, you will see output with the current price of SOL / USD.

    ā‹®
    Price Is: 96.79778375
    Success
    ā‹®
    
  3. Each request costs an amount of SOL that is subtracted from the id.json wallet. Run solana balance to check the remaining balance for your temporary wallet on Devnet.

    solana balance --keypair ./id.json --url devnet
    
  4. To get prices for a different asset pair, run client.js again and add the --feed flag with one of the available Chainlink data feeds. For example, to get the price of BTC / USD on Devnet, use the following command:

    node client.js \
    --program $(solana address -k ./target/deploy/chainlink_solana_demo-keypair.json) \
    --feed 6PxBx93S8x3tno1TsFZwT5VqP8drrRCbCXygEXYNkFJe
    
    Price Is: 111198.0536333
    Success
    

The program that owns the data feeds is HEvSKofvBgfaexv23kMabbYqxasxU3mQ4ibBMEmJWHny, which you can see defined for const CHAINLINK_PROGRAM_ID in the client.js file.

Clean up

After you are done with your deployed contract and no longer need it, it is nice to close the program and withdraw the Devnet SOL tokens for future use. In a production environment, you will want to withdraw unused SOL tokens from any Solana program that you no longer plan to use, so it is good to practice the process when you are done with programs on Devnet.

  1. Run solana program show to see the list of deployed programs that your wallet owns and the balances for each of those programs:

    solana program show --programs --keypair ./id.json --url devnet
    
    Program Id                                   | Slot      | Authority                                    | Balance
    GRt21UnJFHZvcaWLbcUrXaTCFMREewDrm1DweDYBak3Z | 110801571 | FsQPnANKDhqpoayxCL3oDHFCBmrhP34NrfbDR34qbQUt | 3.07874904 SOL
    
  2. Run solana program close and specify the program that you want to close:

    solana program close [YOUR_PROGRAM_ID] --keypair ./id.json --url devnet
    

    The program closes and the remaining SOL is transferred to your temporary wallet.

  3. If you have deployments that failed, they might still be in the buffer holding SOL tokens. Run solana program show again with the --buffers flag:

    solana program show --buffers --keypair ./id.json --url devnet
    

    If you have open buffers, they will appear in the list.

    Buffer Address                               | Authority                                    | Balance
    CSc9hnBqYJoYtBgsryJAmrjAE6vZ918qaFhL6N6BdEmB | FsQPnANKDhqpoayxCL3oDHFCBmrhP34NrfbDR34qbQUt | 1.28936088 SOL
    
  4. If you have any buffers that you do not plan to finish deploying, run the same solana program close command to close them and retrieve the unused SOL tokens:

    solana program close [YOUR_PROGRAM_ID] --keypair ./id.json --url devnet
    
  5. Check the balance on your temporary wallet.

    solana balance --keypair ./id.json --url devnet
    
  6. If you are done using this wallet for examples and testing, you can use solana transfer to send the remaining SOL tokens to your default wallet or another Solana wallet that you use. For example, if your default wallet keypair is at ~/.config/solana/id.json, you can send ALL of the temporary wallet's balance with the following command:

    solana transfer ~/.config/solana/id.json ALL --keypair ./id.json --url devnet
    

    Alternatively, you can send the remaining balance to a web wallet. Specify the public key for your wallet instead of the path the default wallet keypair. Now you can use those Devnet funds for other examples and development.

To learn more about Solana and Anchor, see the Solana Documentation and the Anchor Documentation.

Migrating from v1 to v2

SDK v2 uses direct account reads instead of Cross-Program Invocation (CPI), resulting in better performance, lower compute units, and simpler code.

Key changes

  1. Update dependency in Cargo.toml:

    chainlink_solana = "2.0.8"  # was "1.0.0"
    
  2. Update imports:

    use chainlink_solana::v2::read_feed_v2;  // was: use chainlink_solana as chainlink;
    
  3. Remove chainlink_program from account context - only chainlink_feed is needed

  4. Replace multiple CPI calls with a single read:

    // Multiple CPI calls
    let round = chainlink::latest_round_data(
       ctx.accounts.chainlink_program.to_account_info(),
       ctx.accounts.chainlink_feed.to_account_info(),
    )?;
    let description = chainlink::description(/* ... */)?;
    let decimals = chainlink::decimals(/* ... */)?;
    
  5. Add error types (v2 requires explicit error handling):

    #[error_code]
    pub enum MyError {
        #[msg("read error")]
        ReadError,
        #[msg("no round data")]
        RoundDataMissing,
    }
    
  6. Update client code - remove chainlinkProgram from transaction accounts:

    await program.methods
      .execute()
      .accounts({ chainlinkFeed: CHAINLINK_FEED }) // Remove chainlinkProgram
      .rpc()
    

Complete example

use anchor_lang::prelude::*;
use chainlink_solana as chainlink;

#[program]
pub mod my_program {
    use super::*;
    pub fn execute(ctx: Context<Execute>) -> Result<()> {
        let round = chainlink::latest_round_data(
            ctx.accounts.chainlink_program.to_account_info(),
            ctx.accounts.chainlink_feed.to_account_info(),
        )?;
        msg!("Price: {}", round.answer);
        Ok(())
    }
}

#[derive(Accounts)]
pub struct Execute<'info> {
    pub chainlink_feed: AccountInfo<'info>,
    pub chainlink_program: AccountInfo<'info>,
}

What's next

Get the latest Chainlink content straight to your inbox.