Skip to main content

nyx_txodds_verifier/
lib.rs

1//! # txodds-verifier (unofficial)
2//!
3//! Verify **TxODDS TxLINE** sports data on **Solana** through an on-chain
4//! Cross-Program Invocation (CPI) into the `txoracle` program's
5//! `validate_stat_v2` instruction.
6//!
7//! > **Unofficial / community project.** Not affiliated with or endorsed by
8//! > TxODDS. The `txoracle` program, its IDL, and all data belong to TxODDS.
9//!
10//! What you get:
11//! - Borsh types matching the txoracle IDL byte-for-byte
12//!   ([`StatValidationInput`], [`NDimensionalStrategy`], [`StatPredicate`], ...).
13//! - [`build_validate_stat_v2_data`] — exact instruction data (discriminator + args).
14//! - [`validate_stat_v2_instruction`] — a ready-to-send [`Instruction`].
15//! - [`verify_stat_cpi`] / [`verify_stat_cpi_raw`] — CPI from your program, read the `bool`.
16//! - [`derive_daily_scores_roots_pda`] — the daily scores root PDA.
17
18use borsh::{BorshDeserialize, BorshSerialize};
19use solana_program::{
20    account_info::AccountInfo,
21    instruction::{AccountMeta, Instruction},
22    program::{get_return_data, invoke},
23    program_error::ProgramError,
24    pubkey::Pubkey,
25};
26
27/// Anchor discriminator for `validate_stat_v2` = sha256("global:validate_stat_v2")[..8].
28pub const VALIDATE_STAT_V2_DISCRIMINATOR: [u8; 8] = [208, 215, 194, 214, 241, 71, 246, 178];
29
30/// `txoracle` program id on devnet.
31pub const TXORACLE_DEVNET: Pubkey =
32    solana_program::pubkey!("6pW64gN1s2uqjHkn1unFeEjAwJkPGHoppGvS715wyP2J");
33
34/// `txoracle` program id on mainnet-beta.
35pub const TXORACLE_MAINNET: Pubkey =
36    solana_program::pubkey!("9ExbZjAapQww1vfcisDmrngPinHTEfpjYRWMunJgcKaA");
37
38/// PDA seed prefix for the daily scores merkle roots account.
39pub const DAILY_SCORES_ROOTS_SEED: &[u8] = b"daily_scores_roots";
40
41/// Milliseconds per day, used for the `epoch_day` PDA seed.
42pub const MS_PER_DAY: i64 = 86_400_000;
43
44// --------------------------- IDL-matching types ---------------------------
45
46/// A single Merkle proof node. Mirrors `ProofNode`.
47#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
48pub struct ProofNode {
49    pub hash: [u8; 32],
50    pub is_right_sibling: bool,
51}
52
53/// A provable key/value statistic. Mirrors `ScoreStat`.
54#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
55pub struct ScoreStat {
56    pub key: u32,
57    pub value: i32,
58    pub period: i32,
59}
60
61/// Update statistics for a fixture batch. Mirrors `ScoresUpdateStats`.
62#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
63pub struct ScoresUpdateStats {
64    pub update_count: i32,
65    pub min_timestamp: i64,
66    pub max_timestamp: i64,
67}
68
69/// Per-fixture scores summary within a 5-minute batch. Mirrors `ScoresBatchSummary`.
70#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
71pub struct ScoresBatchSummary {
72    pub fixture_id: i64,
73    pub update_stats: ScoresUpdateStats,
74    pub events_sub_tree_root: [u8; 32],
75}
76
77/// A stat plus its Merkle proof. Mirrors `StatLeaf`.
78#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
79pub struct StatLeaf {
80    pub stat: ScoreStat,
81    pub stat_proof: Vec<ProofNode>,
82}
83
84/// Full input for `validate_stat_v2`. Mirrors `StatValidationInput`.
85#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
86pub struct StatValidationInput {
87    pub ts: i64,
88    pub fixture_summary: ScoresBatchSummary,
89    pub fixture_proof: Vec<ProofNode>,
90    pub main_tree_proof: Vec<ProofNode>,
91    pub event_stat_root: [u8; 32],
92    pub stats: Vec<StatLeaf>,
93}
94
95/// Comparison operator. Variant order matches the IDL.
96#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
97pub enum Comparison {
98    GreaterThan,
99    LessThan,
100    EqualTo,
101}
102
103/// A threshold comparison. Mirrors `TraderPredicate`.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
105pub struct TraderPredicate {
106    pub threshold: i32,
107    pub comparison: Comparison,
108}
109
110impl TraderPredicate {
111    pub fn greater_than(threshold: i32) -> Self { Self { threshold, comparison: Comparison::GreaterThan } }
112    pub fn less_than(threshold: i32) -> Self { Self { threshold, comparison: Comparison::LessThan } }
113    pub fn equal_to(threshold: i32) -> Self { Self { threshold, comparison: Comparison::EqualTo } }
114}
115
116/// Binary arithmetic op between two stats. Variant order matches the IDL.
117#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
118pub enum BinaryExpression {
119    Add,
120    Subtract,
121}
122
123/// A discrete predicate over one or two stats. Mirrors `StatPredicate`.
124#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
125pub enum StatPredicate {
126    Single { index: u8, predicate: TraderPredicate },
127    Binary { index_a: u8, index_b: u8, op: BinaryExpression, predicate: TraderPredicate },
128}
129
130impl StatPredicate {
131    pub fn single(index: u8, predicate: TraderPredicate) -> Self { Self::Single { index, predicate } }
132    pub fn binary(index_a: u8, index_b: u8, op: BinaryExpression, predicate: TraderPredicate) -> Self {
133        Self::Binary { index_a, index_b, op, predicate }
134    }
135}
136
137/// A geometric target for distance-based strategies. Mirrors `GeometricTarget`.
138#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
139pub struct GeometricTarget {
140    pub stat_index: u8,
141    pub prediction: i32,
142}
143
144/// The strategy applied to the proven stats. Mirrors `NDimensionalStrategy`.
145#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
146pub struct NDimensionalStrategy {
147    pub geometric_targets: Vec<GeometricTarget>,
148    pub distance_predicate: Option<TraderPredicate>,
149    pub discrete_predicates: Vec<StatPredicate>,
150}
151
152impl NDimensionalStrategy {
153    /// Purely discrete strategy (no geometric targets / distance predicate).
154    pub fn discrete(discrete_predicates: Vec<StatPredicate>) -> Self {
155        Self { geometric_targets: Vec::new(), distance_predicate: None, discrete_predicates }
156    }
157    /// Geometric strategy with a distance predicate.
158    pub fn geometric(geometric_targets: Vec<GeometricTarget>, distance_predicate: TraderPredicate) -> Self {
159        Self { geometric_targets, distance_predicate: Some(distance_predicate), discrete_predicates: Vec::new() }
160    }
161}
162
163// --------------------- encoding + instruction building ---------------------
164
165/// Serialize the full `validate_stat_v2` instruction data:
166/// 8-byte discriminator + borsh(payload) + borsh(strategy).
167pub fn build_validate_stat_v2_data(
168    payload: &StatValidationInput,
169    strategy: &NDimensionalStrategy,
170) -> Result<Vec<u8>, ProgramError> {
171    let mut data = Vec::with_capacity(512);
172    data.extend_from_slice(&VALIDATE_STAT_V2_DISCRIMINATOR);
173    data.extend_from_slice(&borsh::to_vec(payload).map_err(|_| ProgramError::InvalidInstructionData)?);
174    data.extend_from_slice(&borsh::to_vec(strategy).map_err(|_| ProgramError::InvalidInstructionData)?);
175    Ok(data)
176}
177
178/// Build a ready-to-send `validate_stat_v2` [`Instruction`].
179pub fn validate_stat_v2_instruction(
180    txoracle_program_id: &Pubkey,
181    daily_scores_merkle_roots: &Pubkey,
182    payload: &StatValidationInput,
183    strategy: &NDimensionalStrategy,
184) -> Result<Instruction, ProgramError> {
185    Ok(Instruction {
186        program_id: *txoracle_program_id,
187        accounts: vec![AccountMeta::new_readonly(*daily_scores_merkle_roots, false)],
188        data: build_validate_stat_v2_data(payload, strategy)?,
189    })
190}
191
192/// Derive the `daily_scores_roots` PDA for the given `epoch_day`.
193pub fn derive_daily_scores_roots_pda(txoracle_program_id: &Pubkey, epoch_day: u16) -> (Pubkey, u8) {
194    Pubkey::find_program_address(
195        &[DAILY_SCORES_ROOTS_SEED, &epoch_day.to_le_bytes()],
196        txoracle_program_id,
197    )
198}
199
200/// Compute `epoch_day` (u16) from a millisecond timestamp.
201pub fn epoch_day_from_millis(ts_millis: i64) -> u16 {
202    (ts_millis / MS_PER_DAY) as u16
203}
204
205// --------------------------- on-chain CPI helpers ---------------------------
206
207fn read_verified_bool(txoracle_program_id: &Pubkey) -> Result<bool, ProgramError> {
208    let (returning_program, data) = get_return_data().ok_or(ProgramError::InvalidAccountData)?;
209    if &returning_program != txoracle_program_id {
210        return Err(ProgramError::IncorrectProgramId);
211    }
212    Ok(matches!(data.first(), Some(&b) if b != 0))
213}
214
215/// CPI into `txoracle::validate_stat_v2` and return the verified boolean.
216pub fn verify_stat_cpi<'a>(
217    txoracle_program: &AccountInfo<'a>,
218    daily_scores_merkle_roots: &AccountInfo<'a>,
219    payload: &StatValidationInput,
220    strategy: &NDimensionalStrategy,
221) -> Result<bool, ProgramError> {
222    let ix = validate_stat_v2_instruction(
223        txoracle_program.key,
224        daily_scores_merkle_roots.key,
225        payload,
226        strategy,
227    )?;
228    invoke(&ix, &[daily_scores_merkle_roots.clone(), txoracle_program.clone()])?;
229    read_verified_bool(txoracle_program.key)
230}
231
232/// Same as [`verify_stat_cpi`], but takes pre-serialized instruction data
233/// (discriminator + borsh args), e.g. produced by the companion JS client.
234pub fn verify_stat_cpi_raw<'a>(
235    txoracle_program: &AccountInfo<'a>,
236    daily_scores_merkle_roots: &AccountInfo<'a>,
237    cpi_data: Vec<u8>,
238) -> Result<bool, ProgramError> {
239    let ix = Instruction {
240        program_id: *txoracle_program.key,
241        accounts: vec![AccountMeta::new_readonly(*daily_scores_merkle_roots.key, false)],
242        data: cpi_data,
243    };
244    invoke(&ix, &[daily_scores_merkle_roots.clone(), txoracle_program.clone()])?;
245    read_verified_bool(txoracle_program.key)
246}
247
248#[cfg(test)]
249mod tests {
250    use super::*;
251
252    fn sample_payload() -> StatValidationInput {
253        StatValidationInput {
254            ts: 1_752_000_000_000,
255            fixture_summary: ScoresBatchSummary {
256                fixture_id: 17_926_686,
257                update_stats: ScoresUpdateStats { update_count: 3, min_timestamp: 1, max_timestamp: 2 },
258                events_sub_tree_root: [7u8; 32],
259            },
260            fixture_proof: vec![ProofNode { hash: [1u8; 32], is_right_sibling: true }],
261            main_tree_proof: vec![ProofNode { hash: [2u8; 32], is_right_sibling: false }],
262            event_stat_root: [9u8; 32],
263            stats: vec![StatLeaf {
264                stat: ScoreStat { key: 1, value: 3, period: 0 },
265                stat_proof: vec![ProofNode { hash: [4u8; 32], is_right_sibling: true }],
266            }],
267        }
268    }
269
270    #[test]
271    fn discriminator_matches_anchor() {
272        assert_eq!(VALIDATE_STAT_V2_DISCRIMINATOR, [208, 215, 194, 214, 241, 71, 246, 178]);
273    }
274
275    #[test]
276    fn data_has_discriminator_prefix() {
277        let payload = sample_payload();
278        let strategy = NDimensionalStrategy::discrete(vec![
279            StatPredicate::single(0, TraderPredicate::greater_than(0)),
280        ]);
281        let data = build_validate_stat_v2_data(&payload, &strategy).unwrap();
282        assert_eq!(&data[..8], &VALIDATE_STAT_V2_DISCRIMINATOR);
283        assert!(data.len() > 8);
284    }
285
286    #[test]
287    fn types_roundtrip_via_borsh() {
288        let payload = sample_payload();
289        let bytes = borsh::to_vec(&payload).unwrap();
290        assert_eq!(payload, StatValidationInput::try_from_slice(&bytes).unwrap());
291
292        let strategy = NDimensionalStrategy::geometric(
293            vec![GeometricTarget { stat_index: 0, prediction: 1 }],
294            TraderPredicate::less_than(2),
295        );
296        let sbytes = borsh::to_vec(&strategy).unwrap();
297        assert_eq!(strategy, NDimensionalStrategy::try_from_slice(&sbytes).unwrap());
298    }
299
300    #[test]
301    fn enum_discriminants_match_idl_order() {
302        assert_eq!(borsh::to_vec(&Comparison::GreaterThan).unwrap(), vec![0]);
303        assert_eq!(borsh::to_vec(&Comparison::LessThan).unwrap(), vec![1]);
304        assert_eq!(borsh::to_vec(&Comparison::EqualTo).unwrap(), vec![2]);
305        assert_eq!(borsh::to_vec(&BinaryExpression::Add).unwrap(), vec![0]);
306        assert_eq!(borsh::to_vec(&BinaryExpression::Subtract).unwrap(), vec![1]);
307    }
308
309    #[test]
310    fn pda_is_deterministic() {
311        assert_eq!(
312            derive_daily_scores_roots_pda(&TXORACLE_DEVNET, 20_275),
313            derive_daily_scores_roots_pda(&TXORACLE_DEVNET, 20_275),
314        );
315    }
316}