Skip to main content

nyx_txodds_oracle/
lib.rs

1//! # nyx-txodds-oracle (unofficial)
2//!
3//! Rust building blocks for the **Nyx** trust-minimized settlement stack on
4//! **Solana**: program IDs, Anchor discriminators, PDA derivation, borsh account
5//! decoders, instruction-data builders, and an on-chain CPI helper to push a
6//! dispute-finalized outcome into settlement. No Anchor dependency — just
7//! `solana-program` + `borsh`.
8//!
9//! > **Unofficial / community project.** Not affiliated with or endorsed by
10//! > TxODDS or Tether. "TxODDS", "TxLINE" and "USD₮" are trademarks of their
11//! > respective owners; used here only to describe compatibility.
12//!
13//! ## Why this exists
14//! TxLINE proves a feed is internally consistent (a Merkle root), not that an
15//! outcome is *true*, and gives no on-chain way to challenge a bad signer. Built
16//! naively, every market keeps an admin key that can call `resolve()`. This crate
17//! is the Rust side of removing that key: a market's oracle is a program PDA, and
18//! an outcome reaches settlement only after `propose -> dispute -> arbitrate` via
19//! `push_resolution`, which forwards exactly the finalized result.
20
21use borsh::{BorshDeserialize, BorshSerialize};
22use solana_program::{
23    account_info::AccountInfo,
24    instruction::{AccountMeta, Instruction},
25    program::invoke,
26    program_error::ProgramError,
27    pubkey::Pubkey,
28};
29
30// ------------------------------- program ids -------------------------------
31
32/// `nyx_settlement` program id (devnet).
33pub const SETTLEMENT_PROGRAM_ID: Pubkey =
34    solana_program::pubkey!("AmMSLCCtJPCU3EJHEyxwAUTXQuzcAHVEVkCFJv6JrrW3");
35/// `nyx_dispute` program id (devnet).
36pub const DISPUTE_PROGRAM_ID: Pubkey =
37    solana_program::pubkey!("7bSmAPPAypVtWsRMvMhmT6bUrJyvmc76VKXinAgwc8vN");
38/// `nyx_oracle_bridge` program id (devnet).
39pub const ORACLE_BRIDGE_PROGRAM_ID: Pubkey =
40    solana_program::pubkey!("BiJaXJ7kEXy8cohxf7NxfyqS2sLbxZSa3Fx4JjEZS9bk");
41/// SPL Token program id.
42pub const TOKEN_PROGRAM_ID: Pubkey =
43    solana_program::pubkey!("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA");
44
45/// Assertion lifecycle states (mirrors `nyx_dispute`).
46pub const STATE_PROPOSED: u8 = 0;
47pub const STATE_DISPUTED: u8 = 1;
48pub const STATE_RESOLVED: u8 = 2;
49
50// ------------------------------ discriminators -----------------------------
51
52fn sighash(namespace: &str, name: &str) -> [u8; 8] {
53    let pre = format!("{namespace}:{name}");
54    let full = solana_program::hash::hash(pre.as_bytes()).to_bytes();
55    let mut out = [0u8; 8];
56    out.copy_from_slice(&full[..8]);
57    out
58}
59
60/// Anchor instruction discriminator = sha256("global:<name>")[..8].
61pub fn ix_disc(name: &str) -> [u8; 8] {
62    sighash("global", name)
63}
64
65/// Anchor account discriminator = sha256("account:<Name>")[..8].
66pub fn account_disc(name: &str) -> [u8; 8] {
67    sighash("account", name)
68}
69
70// ------------------------------ account decoders ---------------------------
71
72/// `nyx_settlement` Market account (fields after the 8-byte discriminator).
73#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
74pub struct Market {
75    pub authority: [u8; 32],
76    pub oracle: [u8; 32],
77    pub vault: [u8; 32],
78    pub mint: [u8; 32],
79    pub fixture_id: u64,
80    pub market_key: [u8; 8],
81    pub close_ts: i64,
82    pub pool_yes: u64,
83    pub pool_no: u64,
84    pub resolved: bool,
85    pub outcome_yes: bool,
86    pub bump: u8,
87}
88
89/// `nyx_dispute` Assertion account (fields after the 8-byte discriminator).
90#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
91pub struct Assertion {
92    pub arbiter: [u8; 32],
93    pub mint: [u8; 32],
94    pub vault: [u8; 32],
95    pub proposer: [u8; 32],
96    pub disputer: [u8; 32],
97    pub fixture_id: u64,
98    pub market_key: [u8; 8],
99    pub proposed_outcome_yes: bool,
100    pub final_outcome_yes: bool,
101    pub bond: u64,
102    pub challenge_end_ts: i64,
103    pub state: u8,
104    pub bump: u8,
105}
106
107/// Decode a Market account, skipping its 8-byte discriminator.
108pub fn decode_market(account_data: &[u8]) -> Result<Market, ProgramError> {
109    let body = account_data.get(8..).ok_or(ProgramError::InvalidAccountData)?;
110    Market::try_from_slice(body).map_err(|_| ProgramError::InvalidAccountData)
111}
112
113/// Decode an Assertion account, skipping its 8-byte discriminator.
114pub fn decode_assertion(account_data: &[u8]) -> Result<Assertion, ProgramError> {
115    let body = account_data.get(8..).ok_or(ProgramError::InvalidAccountData)?;
116    Assertion::try_from_slice(body).map_err(|_| ProgramError::InvalidAccountData)
117}
118
119// --------------------------- instruction data ------------------------------
120
121fn with_disc(name: &str) -> Vec<u8> {
122    ix_disc(name).to_vec()
123}
124
125/// `nyx_settlement::create_market(fixture_id, market_key, close_ts)`.
126pub fn create_market_data(fixture_id: u64, market_key: &[u8; 8], close_ts: i64) -> Vec<u8> {
127    let mut d = with_disc("create_market");
128    d.extend_from_slice(&fixture_id.to_le_bytes());
129    d.extend_from_slice(market_key);
130    d.extend_from_slice(&close_ts.to_le_bytes());
131    d
132}
133
134/// `nyx_settlement::place_bet(side_yes, amount)`.
135pub fn place_bet_data(side_yes: bool, amount: u64) -> Vec<u8> {
136    let mut d = with_disc("place_bet");
137    d.push(side_yes as u8);
138    d.extend_from_slice(&amount.to_le_bytes());
139    d
140}
141
142/// `nyx_settlement::claim()`.
143pub fn claim_data() -> Vec<u8> {
144    with_disc("claim")
145}
146
147/// `nyx_settlement::resolve(outcome_yes)`.
148pub fn resolve_data(outcome_yes: bool) -> Vec<u8> {
149    let mut d = with_disc("resolve");
150    d.push(outcome_yes as u8);
151    d
152}
153
154/// `nyx_dispute::propose(fixture_id, market_key, outcome_yes, bond, liveness)`.
155pub fn propose_data(
156    fixture_id: u64,
157    market_key: &[u8; 8],
158    outcome_yes: bool,
159    bond: u64,
160    liveness: i64,
161) -> Vec<u8> {
162    let mut d = with_disc("propose");
163    d.extend_from_slice(&fixture_id.to_le_bytes());
164    d.extend_from_slice(market_key);
165    d.push(outcome_yes as u8);
166    d.extend_from_slice(&bond.to_le_bytes());
167    d.extend_from_slice(&liveness.to_le_bytes());
168    d
169}
170
171/// `nyx_dispute::dispute()`.
172pub fn dispute_data() -> Vec<u8> {
173    with_disc("dispute")
174}
175
176/// `nyx_dispute::settle_undisputed()`.
177pub fn settle_undisputed_data() -> Vec<u8> {
178    with_disc("settle_undisputed")
179}
180
181/// `nyx_dispute::arbitrate(final_outcome_yes)`.
182pub fn arbitrate_data(final_outcome_yes: bool) -> Vec<u8> {
183    let mut d = with_disc("arbitrate");
184    d.push(final_outcome_yes as u8);
185    d
186}
187
188/// `nyx_oracle_bridge::create_bound_market(fixture_id, market_key, close_ts)`.
189pub fn create_bound_market_data(fixture_id: u64, market_key: &[u8; 8], close_ts: i64) -> Vec<u8> {
190    let mut d = with_disc("create_bound_market");
191    d.extend_from_slice(&fixture_id.to_le_bytes());
192    d.extend_from_slice(market_key);
193    d.extend_from_slice(&close_ts.to_le_bytes());
194    d
195}
196
197/// `nyx_oracle_bridge::push_resolution()`.
198pub fn push_resolution_data() -> Vec<u8> {
199    with_disc("push_resolution")
200}
201
202// -------------------------------- PDAs -------------------------------------
203
204/// Market PDA: `["market", fixture_id_le, market_key]` under settlement.
205pub fn market_pda(fixture_id: u64, market_key: &[u8; 8]) -> (Pubkey, u8) {
206    Pubkey::find_program_address(
207        &[&b"market"[..], &fixture_id.to_le_bytes()[..], &market_key[..]],
208        &SETTLEMENT_PROGRAM_ID,
209    )
210}
211
212/// Vault PDA: `["vault", market]` under settlement.
213pub fn vault_pda(market: &Pubkey) -> (Pubkey, u8) {
214    Pubkey::find_program_address(&[&b"vault"[..], market.as_ref()], &SETTLEMENT_PROGRAM_ID)
215}
216
217/// Position PDA: `["pos", market, owner]` under settlement.
218pub fn position_pda(market: &Pubkey, owner: &Pubkey) -> (Pubkey, u8) {
219    Pubkey::find_program_address(
220        &[&b"pos"[..], market.as_ref(), owner.as_ref()],
221        &SETTLEMENT_PROGRAM_ID,
222    )
223}
224
225/// Assertion PDA: `["assertion", fixture_id_le, market_key]` under dispute.
226pub fn assertion_pda(fixture_id: u64, market_key: &[u8; 8]) -> (Pubkey, u8) {
227    Pubkey::find_program_address(
228        &[&b"assertion"[..], &fixture_id.to_le_bytes()[..], &market_key[..]],
229        &DISPUTE_PROGRAM_ID,
230    )
231}
232
233/// Dispute vault PDA: `["dispute_vault", assertion]` under dispute.
234pub fn dispute_vault_pda(assertion: &Pubkey) -> (Pubkey, u8) {
235    Pubkey::find_program_address(
236        &[&b"dispute_vault"[..], assertion.as_ref()],
237        &DISPUTE_PROGRAM_ID,
238    )
239}
240
241/// Oracle PDA: `["oracle"]` under the bridge (the market's non-human oracle).
242pub fn oracle_pda() -> (Pubkey, u8) {
243    Pubkey::find_program_address(&[&b"oracle"[..]], &ORACLE_BRIDGE_PROGRAM_ID)
244}
245
246// --------------------------- bridge CPI helper -----------------------------
247
248/// Build the `nyx_oracle_bridge::push_resolution` instruction.
249///
250/// Accounts: assertion (ro), market (w), oracle (w), dispute_program (ro),
251/// settlement_program (ro). It forwards *only* the outcome the dispute layer
252/// already finalized; anything else reverts on-chain.
253pub fn push_resolution_instruction(assertion: &Pubkey, market: &Pubkey, oracle: &Pubkey) -> Instruction {
254    Instruction {
255        program_id: ORACLE_BRIDGE_PROGRAM_ID,
256        accounts: vec![
257            AccountMeta::new_readonly(*assertion, false),
258            AccountMeta::new(*market, false),
259            AccountMeta::new(*oracle, false),
260            AccountMeta::new_readonly(DISPUTE_PROGRAM_ID, false),
261            AccountMeta::new_readonly(SETTLEMENT_PROGRAM_ID, false),
262        ],
263        data: push_resolution_data(),
264    }
265}
266
267/// CPI into `nyx_oracle_bridge::push_resolution` from your own program.
268pub fn push_resolution_cpi<'a>(
269    bridge_program: &AccountInfo<'a>,
270    assertion: &AccountInfo<'a>,
271    market: &AccountInfo<'a>,
272    oracle: &AccountInfo<'a>,
273    dispute_program: &AccountInfo<'a>,
274    settlement_program: &AccountInfo<'a>,
275) -> Result<(), ProgramError> {
276    let ix = push_resolution_instruction(assertion.key, market.key, oracle.key);
277    invoke(
278        &ix,
279        &[
280            assertion.clone(),
281            market.clone(),
282            oracle.clone(),
283            dispute_program.clone(),
284            settlement_program.clone(),
285            bridge_program.clone(),
286        ],
287    )
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293
294    const FIX: u64 = 2001;
295    const MK: [u8; 8] = [3, 0, 0, 0, 0, 0, 0, 0];
296
297    #[test]
298    fn discriminators_are_distinct_and_stable() {
299        assert_eq!(ix_disc("place_bet").len(), 8);
300        assert_ne!(ix_disc("create_market"), ix_disc("place_bet"));
301        assert_ne!(ix_disc("resolve"), account_disc("Market"));
302        assert_eq!(ix_disc("push_resolution"), ix_disc("push_resolution"));
303    }
304
305    #[test]
306    fn instruction_data_layout_matches_programs() {
307        let bet = place_bet_data(true, 10_000_000);
308        assert_eq!(bet.len(), 17); // 8 disc + 1 side + 8 amount
309        assert_eq!(bet[8], 1);
310        assert_eq!(&bet[..8], &ix_disc("place_bet")[..]);
311
312        let prop = propose_data(FIX, &MK, false, 10_000_000, 3600);
313        assert_eq!(prop.len(), 41); // 8 + 8 + 8 + 1 + 8 + 8
314        assert_eq!(prop[24], 0); // outcome_yes = false
315
316        assert_eq!(claim_data().len(), 8);
317        assert_eq!(push_resolution_data().len(), 8);
318    }
319
320    #[test]
321    fn pdas_are_deterministic() {
322        let (m, _) = market_pda(FIX, &MK);
323        assert_eq!(market_pda(FIX, &MK).0, m);
324        assert_eq!(vault_pda(&m).0, vault_pda(&m).0);
325        assert_eq!(oracle_pda().0, oracle_pda().0);
326    }
327
328    #[test]
329    fn market_layout_roundtrips_and_sizes() {
330        let mkt = Market {
331            authority: [1u8; 32],
332            oracle: oracle_pda().0.to_bytes(),
333            vault: [2u8; 32],
334            mint: [3u8; 32],
335            fixture_id: FIX,
336            market_key: MK,
337            close_ts: 1_800_000_000,
338            pool_yes: 10_000_000,
339            pool_no: 5_000_000,
340            resolved: true,
341            outcome_yes: true,
342            bump: 254,
343        };
344        let bytes = borsh::to_vec(&mkt).unwrap();
345        assert_eq!(bytes.len(), 171); // account size on-chain = 8 + 171 = 179
346        let mut acct = account_disc("Market").to_vec();
347        acct.extend_from_slice(&bytes);
348        assert_eq!(acct.len(), 179);
349        assert_eq!(decode_market(&acct).unwrap(), mkt);
350    }
351
352    #[test]
353    fn assertion_layout_roundtrips_and_sizes() {
354        let a = Assertion {
355            arbiter: [9u8; 32],
356            mint: [3u8; 32],
357            vault: [2u8; 32],
358            proposer: [4u8; 32],
359            disputer: [5u8; 32],
360            fixture_id: FIX,
361            market_key: MK,
362            proposed_outcome_yes: false,
363            final_outcome_yes: true,
364            bond: 10_000_000,
365            challenge_end_ts: 1_800_003_600,
366            state: STATE_RESOLVED,
367            bump: 253,
368        };
369        let bytes = borsh::to_vec(&a).unwrap();
370        assert_eq!(bytes.len(), 196); // account size on-chain = 8 + 196 = 204
371        let mut acct = account_disc("Assertion").to_vec();
372        acct.extend_from_slice(&bytes);
373        let back = decode_assertion(&acct).unwrap();
374        assert_eq!(back, a);
375        assert_eq!(back.state, STATE_RESOLVED);
376    }
377}