1use 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
27pub const VALIDATE_STAT_V2_DISCRIMINATOR: [u8; 8] = [208, 215, 194, 214, 241, 71, 246, 178];
29
30pub const TXORACLE_DEVNET: Pubkey =
32 solana_program::pubkey!("6pW64gN1s2uqjHkn1unFeEjAwJkPGHoppGvS715wyP2J");
33
34pub const TXORACLE_MAINNET: Pubkey =
36 solana_program::pubkey!("9ExbZjAapQww1vfcisDmrngPinHTEfpjYRWMunJgcKaA");
37
38pub const DAILY_SCORES_ROOTS_SEED: &[u8] = b"daily_scores_roots";
40
41pub const MS_PER_DAY: i64 = 86_400_000;
43
44#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
48pub struct ProofNode {
49 pub hash: [u8; 32],
50 pub is_right_sibling: bool,
51}
52
53#[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#[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#[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#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
79pub struct StatLeaf {
80 pub stat: ScoreStat,
81 pub stat_proof: Vec<ProofNode>,
82}
83
84#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
97pub enum Comparison {
98 GreaterThan,
99 LessThan,
100 EqualTo,
101}
102
103#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
118pub enum BinaryExpression {
119 Add,
120 Subtract,
121}
122
123#[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#[derive(Clone, Copy, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
139pub struct GeometricTarget {
140 pub stat_index: u8,
141 pub prediction: i32,
142}
143
144#[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 pub fn discrete(discrete_predicates: Vec<StatPredicate>) -> Self {
155 Self { geometric_targets: Vec::new(), distance_predicate: None, discrete_predicates }
156 }
157 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
163pub 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
178pub 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
192pub 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
200pub fn epoch_day_from_millis(ts_millis: i64) -> u16 {
202 (ts_millis / MS_PER_DAY) as u16
203}
204
205fn 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
215pub 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
232pub 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}