Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions contracts/Anchor.toml
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ dummy_receiver = "5z38tFCAmcPJb1DXUHSoKQhR8qQ8o9aNZ8rZFWe6gH4L"
keystone_forwarder = "whV7Q5pi17hPPyaPksToDw1nMx6Lh8qmNWKFaLRQ4wz"
data_feeds_cache = "3kX63udXtYcsdj2737Wi2KGd2PhqiKPgAFAxstrjtRUa"
data_feeds_store = "9qCsUGTdKCanybkroJuPzAhuRU8P2SZN4NCexevSZAwu"
data_feeds_proxy = "CeRGs3KJ4HXk4S6eyj8Zs2yp4mZdT4zSLz3qrQVRnfuT"
log-read-test = "J1zQwrBNBngz26jRPNWsUSZMHJwBwpkoDitXRV95LdK4"
mock-ccip-events = "CGn5MQX5GK9qKqERhjnADhd6i2LiSF6XUC2ewUHND1Mw"
mock_forwarder = "7kuEAA3mSC1Tz8gQjnvH7bKFda9xSPRRin9SZbH49cNK"
Expand Down
19 changes: 19 additions & 0 deletions contracts/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions contracts/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ members = [
"crates/arrayvec",
"crates/chainlink-solana-data-feeds-cache",
"crates/chainlink-solana-data-feeds-store",
"crates/chainlink-solana-data-feeds-proxy",
# Exclude crates/chainlink-solana-data-streams: it uses solana-sdk 1.17 which
# pulls zeroize <1.4, conflicting with anchor-spl 0.31 (zeroize ^1.7).
# Not used by any program; only for off-chain/tests (cfg(not(target_os = "solana"))).
Expand Down
20 changes: 20 additions & 0 deletions contracts/crates/chainlink-solana-data-feeds-proxy/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[package]
name = "chainlink_solana_data_feeds_proxy"
description = "CPI accessors for the Chainlink Data Feeds proxy on Solana"
version = "0.0.1"
edition = "2021"
license = "MIT"

[lib]
crate-type = ["cdylib", "lib"]
name = "chainlink_solana_data_feeds_proxy"

[features]
default = []

[dependencies]
anchor-lang = "0.31.0"
data-feeds-proxy = { path = "../../programs/data-feeds-proxy", features = ["cpi"] }

[lints]
workspace = true
177 changes: 177 additions & 0 deletions contracts/crates/chainlink-solana-data-feeds-proxy/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
//! CPI accessors for the Chainlink Data Feeds proxy. One proxy serves every feed: pass the data ID
//! and, for `read_scaled`, the decimals you want.
//!
//! The proxy address (its program id and state account) is what stays stable. A read also passes
//! the accounts of the store behind the proxy: its program, its state and the data ID's feed, which
//! clients resolve from the proxy state (`store_program`, `store_state`).
//!
//! Reads go only to the proxy program this crate is built for ([`DATA_FEEDS_PROXY_ID`]); anyone can
//! create a proxy state under it, so pin the proxy state you trust. The proxy checks the store
//! accounts against that state. Each read takes the answer only from the proxy and fails, rather
//! than panics, on a missing or malformed answer.
//!
//! Round IDs are those of the store behind the proxy: they restart if the proxy owner points it to
//! another store (the proxy emits `StoreSet`), so don't carry round IDs across that change.

use anchor_lang::prelude::*;
use anchor_lang::solana_program::program::get_return_data;
use data_feeds_proxy::cpi::accounts::{Read, ReadScaled};

pub use data_feeds_proxy::state::Round;
pub use data_feeds_proxy::ID as DATA_FEEDS_PROXY_ID;

/// The latest round of a data ID, or the round with `round_id`, with the store's 18 decimals.
pub fn read<'info>(
proxy_program: AccountInfo<'info>,
proxy_state: AccountInfo<'info>,
store_program: AccountInfo<'info>,
store_state: AccountInfo<'info>,
feed: AccountInfo<'info>,
data_id: [u8; 16],
round_id: Option<u64>,
) -> Result<Round> {
require_keys_eq!(
proxy_program.key(),
DATA_FEEDS_PROXY_ID,
ErrorCode::InvalidProgramId
);
let ctx = CpiContext::new(
proxy_program,
Read {
state: proxy_state,
store_program,
store_state,
feed,
},
);
data_feeds_proxy::cpi::read(ctx, data_id, round_id)?;
returned()
}

/// Like [`read`], with the answer at `decimals`: at least the data ID's minimum (18 unless an admin
/// lowered it, pass its `feed_config` account to use a lower one) and at most 18. Fails if a
/// non-zero answer would round to zero.
#[allow(clippy::too_many_arguments)]
pub fn read_scaled<'info>(
proxy_program: AccountInfo<'info>,
proxy_state: AccountInfo<'info>,
store_program: AccountInfo<'info>,
store_state: AccountInfo<'info>,
feed: AccountInfo<'info>,
feed_config: Option<AccountInfo<'info>>,
data_id: [u8; 16],
decimals: u8,
round_id: Option<u64>,
) -> Result<Round> {
require_keys_eq!(
proxy_program.key(),
DATA_FEEDS_PROXY_ID,
ErrorCode::InvalidProgramId
);
let ctx = CpiContext::new(
proxy_program,
ReadScaled {
state: proxy_state,
store_program,
store_state,
feed,
feed_config,
},
);
data_feeds_proxy::cpi::read_scaled(ctx, data_id, decimals, round_id)?;
returned()
}

/// The return data of the last call, which must come from the proxy.
fn returned() -> Result<Round> {
match get_return_data() {
Some((from, data)) if from == DATA_FEEDS_PROXY_ID => {
Round::try_from_slice(&data).map_err(|_| {
msg!("Malformed answer from the proxy");
ProgramError::InvalidAccountData.into()
})
}
_ => {
msg!("No answer from the proxy");
Err(ProgramError::IncorrectProgramId.into())
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use anchor_lang::solana_program::program_stubs::{set_syscall_stubs, SyscallStubs};
use std::sync::Mutex;

static RETURN_DATA: Mutex<Option<(Pubkey, Vec<u8>)>> = Mutex::new(None);

struct Stubs;
impl SyscallStubs for Stubs {
fn sol_get_return_data(&self) -> Option<(Pubkey, Vec<u8>)> {
RETURN_DATA.lock().unwrap().clone()
}
}

#[test]
fn takes_the_answer_only_from_the_proxy() {
set_syscall_stubs(Box::new(Stubs));
let answer = |data: Option<(Pubkey, Vec<u8>)>| {
*RETURN_DATA.lock().unwrap() = data;
returned()
};
let round = Round {
round_id: 7,
answer: -42,
observations_timestamp: 1_700_000_000,
recorded_timestamp: 1_700_000_001,
};
let encoded = round.try_to_vec().unwrap();
assert_eq!(
answer(Some((DATA_FEEDS_PROXY_ID, encoded.clone()))).unwrap(),
round
);
assert_eq!(
answer(None).unwrap_err(),
ProgramError::IncorrectProgramId.into()
);
assert_eq!(
answer(Some((Pubkey::new_unique(), encoded.clone()))).unwrap_err(),
ProgramError::IncorrectProgramId.into()
);
assert_eq!(
answer(Some((DATA_FEEDS_PROXY_ID, encoded[..10].to_vec()))).unwrap_err(),
ProgramError::InvalidAccountData.into()
);
}

#[test]
fn only_calls_the_proxy_it_is_built_for() {
let key = Pubkey::new_unique();
let mut lamports = 0;
let mut data = vec![];
let owner = Pubkey::default();
let info = AccountInfo::new(
&key,
false,
false,
&mut lamports,
&mut data,
&owner,
true,
0,
);
// the program check comes before any account is used, so one account stands in for all
let err = read(
info.clone(),
info.clone(),
info.clone(),
info.clone(),
info,
[0; 16],
None,
)
.unwrap_err();
assert!(format!("{err:?}").contains("InvalidProgramId"), "{err:?}");
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ name = "chainlink_solana_data_feeds_store"

[features]
default = []
idl-build = ["data-feeds-store/idl-build"]

[dependencies]
anchor-lang = "0.31.0"
Expand Down
79 changes: 74 additions & 5 deletions contracts/crates/chainlink-solana-data-feeds-store/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,14 @@
//!
//! Proxies read through this interface, so a store version that keeps it can replace the store
//! behind a proxy. Reads that need other decimals go through the data feeds proxy, not here.
//!
//! The store program, its state and the feed accounts come from the caller. Pin the store program
//! and state you trust (and check `feed` is the data ID's feed of that state, or let the store do
//! it): any program can answer a read through this interface. Each read takes the answer only from
//! the program it called and fails, rather than panics, on a missing or malformed answer.

use anchor_lang::prelude::*;
use anchor_lang::solana_program::program::get_return_data;
use data_feeds_store::cpi::accounts::{DescriptionRead, FeedRead, FeedsRead};

pub use data_feeds_store::state::ReaderRound;
Expand All @@ -18,8 +24,10 @@ pub fn get_latest_round<'info>(
feed: AccountInfo<'info>,
data_id: [u8; 16],
) -> Result<ReaderRound> {
let program = store_program.key();
let ctx = CpiContext::new(store_program, FeedRead { state, feed });
Ok(data_feeds_store::cpi::get_latest_round(ctx, data_id)?.get())
data_feeds_store::cpi::get_latest_round(ctx, data_id)?;
returned(&program)
}

/// Latest rounds of up to 31 data IDs, `feeds` in the same order. A feed without a report yields
Expand All @@ -30,8 +38,10 @@ pub fn get_latest_rounds<'info>(
feeds: Vec<AccountInfo<'info>>,
data_ids: Vec<[u8; 16]>,
) -> Result<Vec<ReaderRound>> {
let program = store_program.key();
let ctx = CpiContext::new(store_program, FeedsRead { state }).with_remaining_accounts(feeds);
Ok(data_feeds_store::cpi::get_latest_rounds(ctx, data_ids)?.get())
data_feeds_store::cpi::get_latest_rounds(ctx, data_ids)?;
returned(&program)
}

/// A stored round of a data ID. Fails with the store's `NoDataPresent` for a round that was never
Expand All @@ -43,8 +53,10 @@ pub fn get_round<'info>(
data_id: [u8; 16],
round_id: u64,
) -> Result<ReaderRound> {
let program = store_program.key();
let ctx = CpiContext::new(store_program, FeedRead { state, feed });
Ok(data_feeds_store::cpi::get_round(ctx, data_id, round_id)?.get())
data_feeds_store::cpi::get_round(ctx, data_id, round_id)?;
returned(&program)
}

/// Decimals the store keeps answers with.
Expand All @@ -53,14 +65,16 @@ pub fn get_decimals<'info>(
state: AccountInfo<'info>,
data_id: [u8; 16],
) -> Result<u8> {
let program = store_program.key();
let ctx = CpiContext::new(
store_program,
DescriptionRead {
state,
feed_description: None,
},
);
Ok(data_feeds_store::cpi::get_decimals(ctx, data_id)?.get())
data_feeds_store::cpi::get_decimals(ctx, data_id)?;
returned(&program)
}

/// Description of the feed of a data ID, empty when none is set. Pass the feed description
Expand All @@ -71,12 +85,67 @@ pub fn get_description<'info>(
feed_description: Option<AccountInfo<'info>>,
data_id: [u8; 16],
) -> Result<String> {
let program = store_program.key();
let ctx = CpiContext::new(
store_program,
DescriptionRead {
state,
feed_description,
},
);
Ok(data_feeds_store::cpi::get_description(ctx, data_id)?.get())
data_feeds_store::cpi::get_description(ctx, data_id)?;
returned(&program)
}

/// The return data of the last call, which must come from `program`.
fn returned<T: AnchorDeserialize>(program: &Pubkey) -> Result<T> {
match get_return_data() {
Some((from, data)) if from == *program => T::try_from_slice(&data).map_err(|_| {
msg!("Malformed answer from {}", program);
ProgramError::InvalidAccountData.into()
}),
_ => {
msg!("No answer from {}", program);
Err(ProgramError::IncorrectProgramId.into())
}
}
}

#[cfg(test)]
mod tests {
use super::*;
use anchor_lang::solana_program::program_stubs::{set_syscall_stubs, SyscallStubs};
use std::sync::Mutex;

static RETURN_DATA: Mutex<Option<(Pubkey, Vec<u8>)>> = Mutex::new(None);

struct Stubs;
impl SyscallStubs for Stubs {
fn sol_get_return_data(&self) -> Option<(Pubkey, Vec<u8>)> {
RETURN_DATA.lock().unwrap().clone()
}
}

#[test]
fn takes_the_answer_only_from_the_called_program() {
set_syscall_stubs(Box::new(Stubs));
let store = Pubkey::new_unique();
let answer = |data: Option<(Pubkey, Vec<u8>)>| {
*RETURN_DATA.lock().unwrap() = data;
returned::<u8>(&store)
};
assert_eq!(answer(Some((store, vec![18]))).unwrap(), 18);
assert_eq!(
answer(None).unwrap_err(),
ProgramError::IncorrectProgramId.into()
);
assert_eq!(
answer(Some((Pubkey::new_unique(), vec![18]))).unwrap_err(),
ProgramError::IncorrectProgramId.into()
);
assert_eq!(
answer(Some((store, vec![]))).unwrap_err(),
ProgramError::InvalidAccountData.into()
);
}
}
Loading
Loading