Created
April 12, 2026 12:14
-
-
Save nathfavour/5a57c010f3ccd988bbdd1904bf61335d to your computer and use it in GitHub Desktop.
High-performance Solana SOL PnL engine leveraging getTransactionsForAddress for adaptive parallel partitioning. Optimized with SIMD-JSON parsing, speculative "leapfrog" networking, and hardware-aware concurrency to minimize average latency across busy and sparse wallets.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| DEPENDENCIES (Cargo.toml): | |
| [dependencies] | |
| tokio = { version = "1", features = ["full"] } | |
| reqwest = { version = "0.11", features = ["json", "http2"] } | |
| serde = { version = "1.0", features = ["derive"] } | |
| serde_json = "1.0" | |
| simd-json = "0.13" | |
| INSTRUCTIONS: | |
| 1. Replace 'YOUR_KEY' with your Helius API Key. | |
| 2. Compile: RUSTFLAGS="-C target-cpu=native" cargo build --release | |
| 3. Run: ./target/release/sol_pnl_hacker | |
| LATENCY PROFILE: | |
| - Dual-Boundary Overlap Probe (1-RTT resolution for sparse wallets) | |
| - Parallel Slot-Chunking (Bypasses sequential pagination) | |
| - SIMD-JSON Zero-Copy Parsing & Hardware-Scaled Concurrency | |
| - "Any" status filter to catch fee deductions in failed txs | |
| */ | |
| use reqwest::Client; | |
| use serde::Deserialize; | |
| use std::sync::Arc; | |
| use tokio::sync::mpsc; | |
| use std::hint::black_box; | |
| use std::fmt::Write; | |
| const RPC_URL: &str = "https://mainnet.helius-rpc.com/?api-key=YOUR_KEY"; | |
| const LIMIT: u64 = 100; | |
| #[derive(Debug, Clone)] | |
| struct PnLDelta { | |
| slot: u64, | |
| index: u32, | |
| delta: i64, | |
| } | |
| #[derive(Debug, Deserialize)] | |
| struct EncodedTx { | |
| slot: u64, | |
| #[serde(rename = "transactionIndex")] | |
| index: u32, | |
| meta: Option<serde_json::Value>, | |
| } | |
| #[derive(Debug, Deserialize, Default)] | |
| struct GtfaResponse { | |
| result: Vec<EncodedTx>, | |
| #[serde(rename = "paginationToken")] | |
| token: Option<String>, | |
| } | |
| #[tokio::main] | |
| async fn main() -> Result<(), Box<dyn std::error::Error>> { | |
| let wallet = "ENTER_WALLET_ADDRESS"; | |
| let core_count = std::thread::available_parallelism()?.get() as u64; | |
| let concurrency = (core_count * 2).min(32); | |
| for _ in 0..500_000 { black_box(9999_u64.wrapping_mul(9999)); } | |
| let client = Arc::new(Client::builder() | |
| .http2_prior_knowledge() | |
| .tcp_nodelay(true) | |
| .pool_max_idle_per_host(concurrency as usize) | |
| .build()?); | |
| // TRICK 1: DUAL-BOUNDARY PROBE | |
| // Fire Ascending and Descending probes in parallel. | |
| // If they overlap or cover all txs, we finish in 1 RTT. | |
| let c1 = Arc::clone(&client); | |
| let c2 = Arc::clone(&client); | |
| let w1 = wallet.to_string(); | |
| let w2 = wallet.to_string(); | |
| let probe_asc = tokio::spawn(async move { fetch_gtfa_raw(&c1, &w1, "asc", None, None, None).await }); | |
| let probe_desc = tokio::spawn(async move { fetch_gtfa_raw(&c2, &w2, "desc", None, None, None).await }); | |
| let mut body_asc = probe_asc.await??; | |
| let mut body_desc = probe_desc.await??; | |
| let res_asc: GtfaResponse = unsafe { simd_json::from_slice(&mut body_asc).unwrap_or_default() }; | |
| let res_desc: GtfaResponse = unsafe { simd_json::from_slice(&mut body_desc).unwrap_or_default() }; | |
| if res_asc.result.is_empty() { return Ok(()); } | |
| let (tx_chan, mut rx_chan) = mpsc::channel(25000); | |
| // Check for "Sparse Wallet" 1-RTT Resolution | |
| let start_slot = res_asc.result.first().unwrap().slot; | |
| let end_slot = res_desc.result.first().unwrap().slot; | |
| let mut seen_sigs = std::collections::HashSet::new(); | |
| // Helper to send to channel | |
| let push_res = |res: GtfaResponse, ch: &mpsc::Sender<PnLDelta>| { | |
| for tx in res.result { | |
| if let Some(meta) = tx.meta { | |
| let pre = meta["preBalances"].get(0).and_then(|v| v.as_u64()).unwrap_or(0); | |
| let post = meta["postBalances"].get(0).and_then(|v| v.as_u64()).unwrap_or(0); | |
| let _ = ch.try_send(PnLDelta { slot: tx.slot, index: tx.index, delta: post as i64 - pre as i64 }); | |
| } | |
| } | |
| }; | |
| push_res(res_asc, &tx_chan); | |
| push_res(res_desc, &tx_chan); | |
| // TRICK 2: PARALLEL STRIDE (For Busy Wallets) | |
| // If the probes didn't overlap, gap-fill with parallel slot-chunks | |
| if end_slot > start_slot && res_asc.token.is_some() { | |
| let gap_step = (end_slot - start_slot) / concurrency; | |
| for i in 0..concurrency { | |
| let c = Arc::clone(&client); | |
| let w = wallet.to_string(); | |
| let chan = tx_chan.clone(); | |
| let s_gte = start_slot + (i * gap_step); | |
| let s_lte = if i == concurrency - 1 { end_slot } else { s_gte + gap_step - 1 }; | |
| tokio::spawn(async move { | |
| let mut token: Option<String> = None; | |
| loop { | |
| let mut body = match fetch_gtfa_raw(&c, &w, "asc", Some(s_gte), Some(s_lte), token).await { | |
| Ok(b) => b, | |
| Err(_) => break, | |
| }; | |
| let parsed: GtfaResponse = unsafe { simd_json::from_slice(&mut body).unwrap_or_default() }; | |
| let has_more = parsed.token.is_some(); | |
| let next_token = parsed.token.clone(); | |
| for tx in parsed.result { | |
| if let Some(meta) = tx.meta { | |
| let pre = meta["preBalances"].get(0).and_then(|v| v.as_u64()).unwrap_or(0); | |
| let post = meta["postBalances"].get(0).and_then(|v| v.as_u64()).unwrap_or(0); | |
| let _ = chan.send(PnLDelta { slot: tx.slot, index: tx.index, delta: post as i64 - pre as i64 }).await; | |
| } | |
| } | |
| if !has_more { break; } | |
| token = next_token; | |
| } | |
| }); | |
| } | |
| } | |
| drop(tx_chan); | |
| // TRICK 3: CHRONOLOGICAL ACCURACY (Slot + Index sorting) | |
| let mut history = Vec::with_capacity(25000); | |
| while let Some(point) = rx_chan.recv().await { | |
| history.push(point); | |
| } | |
| // Sort by slot then transactionIndex for perfect ledger sequence | |
| history.sort_unstable_by(|a, b| a.slot.cmp(&b.slot).then(a.index.cmp(&b.index))); | |
| let mut balance: i64 = 0; | |
| let mut output = String::with_capacity(history.len() * 64); | |
| for point in history { | |
| balance += point.delta; | |
| if point.delta != 0 { | |
| let _ = writeln!(output, "Slot: {} | Bal: {:.6} SOL", point.slot, balance as f64 / 1e9); | |
| } | |
| } | |
| print!("{}", output); | |
| Ok(()) | |
| } | |
| async fn fetch_gtfa_raw( | |
| c: &Client, | |
| addr: &str, | |
| sort: &str, | |
| gte: Option<u64>, | |
| lte: Option<u64>, | |
| token: Option<String> | |
| ) -> Result<Vec<u8>, Box<dyn std::error::Error + Send + Sync>> { | |
| let mut filters = serde_json::json!({ "status": "any", "tokenAccounts": "none" }); | |
| if gte.is_some() || lte.is_some() { | |
| let mut sf = serde_json::json!({}); | |
| if let Some(v) = gte { sf["gte"] = serde_json::json!(v); } | |
| if let Some(v) = lte { sf["lte"] = serde_json::json!(v); } | |
| filters["slot"] = sf; | |
| } | |
| let mut params = serde_json::json!({ | |
| "encoding": "base64", | |
| "transactionDetails": "full", | |
| "limit": LIMIT, | |
| "sortOrder": sort, | |
| "filters": filters | |
| }); | |
| if let Some(t) = token { params["paginationToken"] = serde_json::json!(t); } | |
| let res = c.post(RPC_URL).json(&serde_json::json!({"jsonrpc":"2.0","id":1,"method":"getTransactionsForAddress","params":[addr, params]})) | |
| .send().await?.bytes().await?; | |
| Ok(res.to_vec()) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment