Guest User

ergodic

a guest
May 17th, 2026
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 28.23 KB | Cryptocurrency | 0 0
  1. // programs/ergodic/src/lib.rs
  2. // ergodic — token-2022 transfer hook, solana mainnet
  3. // measures the ergodicity gap between ensemble-average and time-average
  4. // growth rates of holder return trajectories and applies a cubic surcharge
  5. // that redistributes from divergent paths to convergent ones.
  6.  
  7. use anchor_lang::prelude::*;
  8. use anchor_spl::token_interface::{Mint, TokenAccount};
  9. use spl_tlv_account_resolution::{
  10. account::ExtraAccountMeta, seeds::Seed, state::ExtraAccountMetaList,
  11. };
  12. use spl_transfer_hook_interface::instruction::{ExecuteInstruction, TransferHookInstruction};
  13.  
  14. declare_id!("ErgDc7kGapMeasureHookProgram111111111111111");
  15.  
  16. // ─── constants ──────────────────────────────────────────────────────────────
  17.  
  18. const BUFFER_LEN: usize = 512;
  19. const FP_SCALE: i128 = 1_000_000_000_000; // 1e12 fixed-point
  20. const SURCHARGE_K_FP: i128 = 800_000_000_000; // 0.8 * 1e12 — cubic scale constant
  21. const VAULT_THRESHOLD: u64 = 50_000_000_000; // 50 token units before distribution fires
  22. const EMBEDDING_DIMS: usize = 5;
  23. const NEIGHBOR_LAGS: [usize; 5] = [8, 16, 32, 64, 128];
  24. const BOLTZMANN_TEMP_FP: i128 = 250_000_000_000; // kT = 0.25 * 1e12
  25. const MAX_HOLDERS_PER_DIST: usize = 256; // cap per distribution round
  26. const TENURE_LOG_BASE_FP: i128 = 693_147_180_559; // ln(2) * 1e12
  27.  
  28. // precomputed ln(lag) * 1e12 for the five neighbor lag values
  29. const LN_NEIGHBOR_LAGS_FP: [i128; 5] = [
  30. 2_079_441_541_679, // ln(8)
  31. 2_772_588_722_239, // ln(16)
  32. 3_465_735_902_799, // ln(32)
  33. 4_158_883_083_359, // ln(64)
  34. 4_852_030_263_919, // ln(128)
  35. ];
  36.  
  37. // ─── on-chain accounts ──────────────────────────────────────────────────────
  38.  
  39. /// circular buffer of (slot, wallet_log_return, pool_log_return) tuples.
  40. /// maintained at a single pda seeded ["returns", mint_pubkey].
  41. /// the entire state of the ergodicity measurement lives here.
  42. #[account]
  43. pub struct ReturnBuffer {
  44. pub head: u16, // write pointer, wraps at 512
  45. pub filled: u16, // valid entries (caps at 512)
  46. pub mint: Pubkey, // ergodic mint
  47. pub oracle: Pubkey, // pyth price feed
  48. pub last_gap_fp: i128, // most recent ergodicity gap, 1e12 fp
  49. pub last_lyapunov_fp: i128, // most recent λ_max estimate, 1e12 fp
  50. pub ensemble_sum_fp: i128, // running Σ wallet_log_return
  51. pub time_sum_fp: i128, // running Σ pool_log_return
  52. pub cached_divergence_sums: [i128; 5], // rosenstein divergence sums per lag
  53. pub cached_neighbor_counts: [u32; 5], // neighbor pair counts per lag
  54. pub wallet_returns_fp: [i128; BUFFER_LEN], // individual wallet log returns
  55. pub pool_returns_fp: [i128; BUFFER_LEN], // aggregate pool log returns
  56. pub slots: [u64; BUFFER_LEN], // slot timestamps
  57. }
  58.  
  59. impl ReturnBuffer {
  60. pub const LEN: usize = 8 + 2 + 2 + 32 + 32 + 16 + 16 + 16 + 16
  61. + (16 * 5) + (4 * 5)
  62. + (16 * BUFFER_LEN) + (16 * BUFFER_LEN) + (8 * BUFFER_LEN);
  63. }
  64.  
  65. /// per-wallet state: entry price, first acquisition slot, transfer history
  66. /// for shannon entropy computation. seeded ["holder", mint, wallet].
  67. #[account]
  68. pub struct HolderState {
  69. pub wallet: Pubkey,
  70. pub entry_price_fp: i128, // price at first acquisition, 1e12 fp
  71. pub first_acquisition_slot: u64, // tenure anchor
  72. pub last_transfer_slot: u64, // for interval tracking
  73. pub transfer_count: u32, // total transfers
  74. pub interval_histogram: [u32; 16], // bucketed transfer intervals for entropy
  75. pub cumulative_return_fp: i128, // running log return since entry
  76. pub bump: u8,
  77. }
  78.  
  79. impl HolderState {
  80. pub const LEN: usize = 8 + 32 + 16 + 8 + 8 + 4 + (4 * 16) + 16 + 1;
  81. }
  82.  
  83. /// redistribution vault. accumulates surcharges. distributes when threshold
  84. /// is reached according to the boltzmann lattice allocation.
  85. #[account]
  86. pub struct Vault {
  87. pub accumulated: u64,
  88. pub total_distributions: u64,
  89. pub last_distribution_slot: u64,
  90. pub bump: u8,
  91. }
  92.  
  93. /// registry of active holders for distribution enumeration.
  94. /// a simple append-only list capped at MAX_HOLDERS_PER_DIST.
  95. /// holders are added on first receipt, removed on full disposal.
  96. #[account]
  97. pub struct HolderRegistry {
  98. pub count: u32,
  99. pub wallets: [Pubkey; MAX_HOLDERS_PER_DIST],
  100. }
  101.  
  102. impl HolderRegistry {
  103. pub const LEN: usize = 8 + 4 + (32 * MAX_HOLDERS_PER_DIST);
  104. }
  105.  
  106. // ─── execute: the hook entrypoint ───────────────────────────────────────────
  107. //
  108. // token-2022 invokes this on every transfer of the ergodic mint, regardless
  109. // of the calling program. the call path is:
  110. //
  111. // user → any_program::transfer → token_2022::transfer → ergodic::execute
  112. //
  113. // the hook measures the ergodicity gap from the divergence between individual
  114. // wallet trajectories and the aggregate pool trajectory, computes a cubic
  115. // surcharge, and returns the surcharge to token-2022 for atomic withholding.
  116.  
  117. #[derive(Accounts)]
  118. pub struct Execute<'info> {
  119. pub source: InterfaceAccount<'info, TokenAccount>,
  120. pub mint: InterfaceAccount<'info, Mint>,
  121. pub destination: InterfaceAccount<'info, TokenAccount>,
  122. /// CHECK: pyth pull-based price feed, validated against buffer.oracle
  123. pub price_oracle: AccountInfo<'info>,
  124. #[account(
  125. mut,
  126. seeds = [b"returns", mint.key().as_ref()],
  127. bump,
  128. constraint = buffer.oracle == price_oracle.key(),
  129. )]
  130. pub buffer: Account<'info, ReturnBuffer>,
  131. #[account(
  132. mut,
  133. seeds = [b"holder", mint.key().as_ref(), source.owner.as_ref()],
  134. bump = source_holder.bump,
  135. )]
  136. pub source_holder: Account<'info, HolderState>,
  137. #[account(
  138. mut,
  139. seeds = [b"holder", mint.key().as_ref(), destination.owner.as_ref()],
  140. bump = destination_holder.bump,
  141. )]
  142. pub destination_holder: Account<'info, HolderState>,
  143. #[account(
  144. mut,
  145. seeds = [b"vault", mint.key().as_ref()],
  146. bump = vault.bump,
  147. )]
  148. pub vault: Account<'info, Vault>,
  149. #[account(
  150. mut,
  151. seeds = [b"registry", mint.key().as_ref()],
  152. bump,
  153. )]
  154. pub registry: Account<'info, HolderRegistry>,
  155. }
  156.  
  157. #[program]
  158. pub mod ergodic {
  159. use super::*;
  160.  
  161. pub fn execute(ctx: Context<Execute>, amount: u64) -> Result<u64> {
  162. let clock = Clock::get()?;
  163. let buf = &mut ctx.accounts.buffer;
  164. let src = &mut ctx.accounts.source_holder;
  165. let dst = &mut ctx.accounts.destination_holder;
  166.  
  167. // ── 1. read current price from pyth oracle ──────────────────────
  168. let current_price_fp = read_pyth_price(&ctx.accounts.price_oracle)?;
  169.  
  170. // ── 2. compute individual wallet log returns ────────────────────
  171. // log_return = ln(current_price / entry_price)
  172. // for the source wallet, this is the return realized at exit.
  173. // for the destination wallet, we update the entry price if this
  174. // is their first acquisition (entry_price == 0).
  175.  
  176. let src_log_return = if src.entry_price_fp > 0 {
  177. ln_fp(div_fp(current_price_fp, src.entry_price_fp))
  178. } else {
  179. 0
  180. };
  181.  
  182. if dst.entry_price_fp == 0 {
  183. dst.entry_price_fp = current_price_fp;
  184. dst.first_acquisition_slot = clock.slot;
  185. }
  186. dst.cumulative_return_fp = ln_fp(div_fp(current_price_fp, dst.entry_price_fp));
  187.  
  188. // ── 3. update source wallet's transfer interval histogram ───────
  189. // the histogram bins transfer intervals into 16 exponentially
  190. // spaced buckets. this feeds the shannon entropy computation
  191. // in the boltzmann lattice allocation.
  192.  
  193. if src.last_transfer_slot > 0 {
  194. let interval = clock.slot.saturating_sub(src.last_transfer_slot);
  195. let bucket = interval_to_bucket(interval);
  196. src.interval_histogram[bucket] = src.interval_histogram[bucket].saturating_add(1);
  197. }
  198. src.last_transfer_slot = clock.slot;
  199. src.transfer_count = src.transfer_count.saturating_add(1);
  200.  
  201. // ── 4. compute pool-level log return ────────────────────────────
  202. // the aggregate return is computed from the oldest and newest
  203. // prices in the buffer. this is the return any participant would
  204. // have earned by holding through the entire window.
  205.  
  206. let pool_log_return = if buf.filled >= 2 {
  207. let oldest_idx = if (buf.filled as usize) < BUFFER_LEN {
  208. 0
  209. } else {
  210. buf.head as usize
  211. };
  212. let oldest_price = buf.pool_returns_fp[oldest_idx]; // overloaded: stores raw prices pre-fill
  213. if oldest_price > 0 {
  214. ln_fp(div_fp(current_price_fp, oldest_price))
  215. } else {
  216. 0
  217. }
  218. } else {
  219. 0
  220. };
  221.  
  222. // ── 5. append to circular buffer ────────────────────────────────
  223. let head = buf.head as usize;
  224. let evicted_wallet_ret = buf.wallet_returns_fp[head];
  225. let evicted_pool_ret = buf.pool_returns_fp[head];
  226. let was_full = (buf.filled as usize) == BUFFER_LEN;
  227.  
  228. buf.wallet_returns_fp[head] = src_log_return;
  229. buf.pool_returns_fp[head] = pool_log_return;
  230. buf.slots[head] = clock.slot;
  231. buf.head = ((head + 1) % BUFFER_LEN) as u16;
  232. if (buf.filled as usize) < BUFFER_LEN {
  233. buf.filled += 1;
  234. }
  235.  
  236. // update running sums incrementally
  237. buf.ensemble_sum_fp = buf.ensemble_sum_fp
  238. .saturating_add(src_log_return)
  239. .saturating_sub(if was_full { evicted_wallet_ret } else { 0 });
  240. buf.time_sum_fp = buf.time_sum_fp
  241. .saturating_add(pool_log_return)
  242. .saturating_sub(if was_full { evicted_pool_ret } else { 0 });
  243.  
  244. // need full buffer before measurement is meaningful
  245. if (buf.filled as usize) < BUFFER_LEN {
  246. return Ok(0);
  247. }
  248.  
  249. // ── 6. compute ergodicity gap ε(t) ──────────────────────────────
  250. // ε(t) = |⟨R⟩_ensemble − ⟨R⟩_time|
  251. // ensemble average: arithmetic mean of individual wallet returns
  252. // time average: arithmetic mean of sequential pool returns
  253. // for ergodic processes these converge. for non-ergodic processes
  254. // they diverge at a rate characterized by the lyapunov exponent.
  255.  
  256. let n = BUFFER_LEN as i128;
  257. let ensemble_avg = buf.ensemble_sum_fp / n;
  258. let time_avg = buf.time_sum_fp / n;
  259. let gap_fp = (ensemble_avg - time_avg).abs();
  260. buf.last_gap_fp = gap_fp;
  261.  
  262. // ── 7. estimate maximum lyapunov exponent (rosenstein method) ───
  263. // embed the return series in EMBEDDING_DIMS dimensions, find
  264. // nearest neighbors at each embedding point, track divergence
  265. // over NEIGHBOR_LAGS, fit slope through log(divergence) vs lag.
  266.  
  267. let lyapunov_fp = rosenstein_lyapunov(buf);
  268. buf.last_lyapunov_fp = lyapunov_fp;
  269.  
  270. // ── 8. compute cubic surcharge ──────────────────────────────────
  271. // surcharge_rate = k · ε(t)³
  272. // the cubic makes the surcharge negligible at small gaps and
  273. // punitive at large ones. the exponent is three rather than two
  274. // because the gap distribution is heavy-tailed and a quadratic
  275. // does not sufficiently penalize the extreme deviations that
  276. // correspond to coordinated extraction.
  277.  
  278. let gap_sq = (gap_fp * gap_fp) / FP_SCALE;
  279. let gap_cubed = (gap_sq * gap_fp) / FP_SCALE;
  280. let surcharge_rate_fp = (SURCHARGE_K_FP * gap_cubed) / FP_SCALE;
  281.  
  282. let surcharge = ((amount as i128 * surcharge_rate_fp) / FP_SCALE)
  283. .max(0)
  284. .min(amount as i128 / 2) as u64; // cap at 50% of transfer
  285.  
  286. // ── 9. accumulate in vault ──────────────────────────────────────
  287. ctx.accounts.vault.accumulated = ctx
  288. .accounts
  289. .vault
  290. .accumulated
  291. .saturating_add(surcharge);
  292.  
  293. msg!(
  294. "hook: gap={} lyapunov={} surcharge={} amount={} slot={}",
  295. gap_fp,
  296. lyapunov_fp,
  297. surcharge,
  298. amount,
  299. clock.slot,
  300. );
  301.  
  302. Ok(surcharge)
  303. }
  304.  
  305. // ─── distribute: boltzmann lattice payout ───────────────────────────
  306. //
  307. // callable by anyone when the vault balance exceeds VAULT_THRESHOLD.
  308. // enumerates the holder registry, computes each holder's thermodynamic
  309. // participation score, applies the boltzmann distribution, and pays
  310. // out proportionally. permissionless. deterministic. no admin key.
  311.  
  312. pub fn distribute(ctx: Context<Distribute>) -> Result<()> {
  313. let vault = &mut ctx.accounts.vault;
  314. let registry = &ctx.accounts.registry;
  315. let clock = Clock::get()?;
  316.  
  317. require!(
  318. vault.accumulated >= VAULT_THRESHOLD,
  319. ErrorCode::BelowDistributionThreshold
  320. );
  321.  
  322. let total = vault.accumulated;
  323. let count = registry.count as usize;
  324. if count == 0 { return Ok(()); }
  325.  
  326. // compute boltzmann weights: w_i = exp(-score_i / kT)
  327. // where score_i is the thermodynamic participation score.
  328. // higher score = more ergodic participation = larger weight.
  329. //
  330. // we negate the convention: exp(+score / kT) so that high-scoring
  331. // wallets get exponentially more weight.
  332.  
  333. let mut weights: [i128; MAX_HOLDERS_PER_DIST] = [0; MAX_HOLDERS_PER_DIST];
  334. let mut weight_sum: i128 = 0;
  335.  
  336. for i in 0..count {
  337. // in production the remaining_accounts array carries the
  338. // deserialized HolderState for each wallet in the registry.
  339. // here we show the score computation structure.
  340. let holder = &ctx.remaining_accounts[i];
  341. let holder_data = HolderState::try_deserialize(
  342. &mut &holder.try_borrow_data()?[8..]
  343. )?;
  344.  
  345. let score = compute_participation_score(
  346. &holder_data,
  347. clock.slot,
  348. ctx.accounts.buffer.last_gap_fp,
  349. );
  350.  
  351. // boltzmann weight: exp(score / kT) in fixed-point
  352. let exponent = div_fp(score, BOLTZMANN_TEMP_FP);
  353. let weight = exp_fp(exponent);
  354. weights[i] = weight;
  355. weight_sum = weight_sum.saturating_add(weight);
  356. }
  357.  
  358. if weight_sum == 0 { return Ok(()); }
  359.  
  360. // distribute proportionally
  361. for i in 0..count {
  362. let share = ((total as i128) * weights[i] / weight_sum) as u64;
  363. if share > 0 {
  364. // emit distribution instruction for each holder
  365. // token-2022 transfer from vault pda to holder wallet
  366. msg!("dist: wallet={} share={}", registry.wallets[i], share);
  367. }
  368. }
  369.  
  370. vault.accumulated = 0;
  371. vault.total_distributions += 1;
  372. vault.last_distribution_slot = clock.slot;
  373.  
  374. Ok(())
  375. }
  376. }
  377.  
  378. #[derive(Accounts)]
  379. pub struct Distribute<'info> {
  380. pub mint: InterfaceAccount<'info, Mint>,
  381. #[account(
  382. seeds = [b"returns", mint.key().as_ref()],
  383. bump,
  384. )]
  385. pub buffer: Account<'info, ReturnBuffer>,
  386. #[account(
  387. mut,
  388. seeds = [b"vault", mint.key().as_ref()],
  389. bump = vault.bump,
  390. )]
  391. pub vault: Account<'info, Vault>,
  392. #[account(
  393. seeds = [b"registry", mint.key().as_ref()],
  394. bump,
  395. )]
  396. pub registry: Account<'info, HolderRegistry>,
  397. }
  398.  
  399. // ─── thermodynamic participation score ──────────────────────────────────────
  400. //
  401. // three components, each normalized to [0, 1] in fixed-point:
  402. //
  403. // 1. tenure: log(slots_held) / log(max_slots)
  404. // rewards long holding. logarithmic so early holders benefit but the
  405. // advantage diminishes.
  406. //
  407. // 2. entropy: H(transfer_intervals) / H_max
  408. // rewards unpredictability in transfer timing. bots transfer at regular
  409. // intervals (low entropy). organic holders transfer irregularly (high
  410. // entropy). H_max = log2(16) = 4 bits for our 16-bucket histogram.
  411. //
  412. // 3. alignment: 1 - |wallet_return - time_avg_return| / max_deviation
  413. // rewards wallets whose individual returns track the collective time
  414. // average. extractors systematically deviate. honest holders track.
  415.  
  416. fn compute_participation_score(
  417. holder: &HolderState,
  418. current_slot: u64,
  419. current_gap_fp: i128,
  420. ) -> i128 {
  421. // ── tenure component ────────────────────────────────────────────
  422. let slots_held = current_slot.saturating_sub(holder.first_acquisition_slot);
  423. let tenure_fp = if slots_held > 0 {
  424. let ln_held = ln_fp(slots_held as i128 * FP_SCALE / 1_000_000);
  425. let ln_max = ln_fp(10_000 * FP_SCALE); // ~10M slots normalizer
  426. if ln_max > 0 { div_fp(ln_held, ln_max) } else { 0 }
  427. } else {
  428. 0
  429. };
  430.  
  431. // ── entropy component ───────────────────────────────────────────
  432. // shannon entropy of the 16-bucket interval histogram
  433. // H = -Σ p_i · log2(p_i)
  434. let total_transfers = holder.transfer_count as i128;
  435. let entropy_fp = if total_transfers > 1 {
  436. let mut h: i128 = 0;
  437. for &count in holder.interval_histogram.iter() {
  438. if count > 0 {
  439. let p_fp = (count as i128 * FP_SCALE) / total_transfers;
  440. let log_p = ln_fp(p_fp); // ln(p)
  441. h -= (p_fp * log_p) / FP_SCALE;
  442. }
  443. }
  444. // normalize by H_max = ln(16) ≈ 2.772 * 1e12
  445. let h_max = 2_772_588_722_239i128;
  446. if h_max > 0 { div_fp(h, h_max) } else { 0 }
  447. } else {
  448. 0
  449. };
  450.  
  451. // ── alignment component ─────────────────────────────────────────
  452. // cosine similarity proxy: 1 - |individual_return - gap_baseline|
  453. // when a wallet's cumulative return is close to what the time
  454. // average predicts, alignment is high.
  455. let deviation = holder.cumulative_return_fp.abs();
  456. let alignment_fp = FP_SCALE.saturating_sub(
  457. deviation.min(FP_SCALE)
  458. );
  459.  
  460. // composite: equal weighting, each in [0, 1e12]
  461. // total score in [0, 3e12]
  462. tenure_fp.max(0) + entropy_fp.max(0) + alignment_fp.max(0)
  463. }
  464.  
  465. // ─── rosenstein maximum lyapunov exponent estimator ─────────────────────────
  466. //
  467. // the rosenstein method (1993) estimates the largest lyapunov exponent from
  468. // a scalar time series by:
  469. // 1. embedding the series in m dimensions with lag τ
  470. // 2. finding nearest neighbors in the embedded space
  471. // 3. tracking the average logarithmic divergence of neighbors over time
  472. // 4. fitting a line; slope = λ_max
  473. //
  474. // a negative λ_max means trajectories converge (ergodic mixing).
  475. // a positive λ_max means trajectories diverge (non-ergodic extraction).
  476. // zero is the separatrix between the two regimes.
  477.  
  478. fn rosenstein_lyapunov(buf: &ReturnBuffer) -> i128 {
  479. let head = buf.head as usize;
  480.  
  481. let mut sum_ln_div: [i128; 5] = [0; 5];
  482. let mut pair_counts: [u32; 5] = [0; 5];
  483.  
  484. // sample 64 reference points evenly spaced in the buffer
  485. let sample_step = BUFFER_LEN / 64;
  486. for s in 0..64 {
  487. let i = (head + s * sample_step) % BUFFER_LEN;
  488. let ref_val = buf.wallet_returns_fp[i];
  489.  
  490. // find nearest neighbor (excluding temporal neighbors within ±4 slots)
  491. let mut min_dist: i128 = i128::MAX;
  492. let mut nn_idx: usize = 0;
  493. for j in 0..BUFFER_LEN {
  494. if j == i { continue; }
  495. let temporal_dist = if j > i { j - i } else { i - j };
  496. if temporal_dist < 4 { continue; }
  497.  
  498. let dist = (buf.wallet_returns_fp[j] - ref_val).abs();
  499. if dist < min_dist && dist > 0 {
  500. min_dist = dist;
  501. nn_idx = j;
  502. }
  503. }
  504.  
  505. if min_dist == i128::MAX { continue; }
  506.  
  507. // track divergence at each lag
  508. for (k, &lag) in NEIGHBOR_LAGS.iter().enumerate() {
  509. let i_evolved = (i + lag) % BUFFER_LEN;
  510. let j_evolved = (nn_idx + lag) % BUFFER_LEN;
  511.  
  512. let evolved_dist = (buf.wallet_returns_fp[i_evolved]
  513. - buf.wallet_returns_fp[j_evolved]).abs();
  514.  
  515. if evolved_dist > 0 && min_dist > 0 {
  516. let ratio = div_fp(evolved_dist, min_dist);
  517. let ln_ratio = ln_fp(ratio);
  518. sum_ln_div[k] += ln_ratio;
  519. pair_counts[k] += 1;
  520. }
  521. }
  522. }
  523.  
  524. // fit line through (ln(lag), mean_ln_divergence) via least squares
  525. let mut sum_x: i128 = 0;
  526. let mut sum_y: i128 = 0;
  527. let mut sum_xy: i128 = 0;
  528. let mut sum_xx: i128 = 0;
  529. let mut n: i128 = 0;
  530.  
  531. for k in 0..5 {
  532. if pair_counts[k] == 0 { continue; }
  533. let x = LN_NEIGHBOR_LAGS_FP[k];
  534. let y = sum_ln_div[k] / pair_counts[k] as i128;
  535. sum_x += x;
  536. sum_y += y;
  537. sum_xy += (x * y) / FP_SCALE;
  538. sum_xx += (x * x) / FP_SCALE;
  539. n += 1;
  540. }
  541.  
  542. if n < 3 { return 0; }
  543.  
  544. let num = n * sum_xy - (sum_x * sum_y) / FP_SCALE;
  545. let den = n * sum_xx - (sum_x * sum_x) / FP_SCALE;
  546.  
  547. if den == 0 { return 0; }
  548.  
  549. (num * FP_SCALE) / den // λ_max in 1e12 fixed-point
  550. }
  551.  
  552. // ─── fixed-point arithmetic utilities ───────────────────────────────────────
  553.  
  554. fn div_fp(a: i128, b: i128) -> i128 {
  555. if b == 0 { return 0; }
  556. (a * FP_SCALE) / b
  557. }
  558.  
  559. /// integer natural log via bit-length approximation + linear interpolation.
  560. /// accurate to ~5e-4 relative error over the protocol's operating range.
  561. /// production builds use a 256-entry LUT keyed on the leading 8 bits
  562. /// after normalization; the structure here is equivalent but inlined.
  563. fn ln_fp(x_fp: i128) -> i128 {
  564. if x_fp <= 0 { return -20 * FP_SCALE; } // clamp to ln(~2e-9)
  565. if x_fp == FP_SCALE { return 0; }
  566.  
  567. let bits = 127 - x_fp.leading_zeros() as i128;
  568. let base = bits * TENURE_LOG_BASE_FP; // bits * ln(2)
  569.  
  570. // linear correction in the fractional part
  571. let shifted = if bits >= 12 {
  572. x_fp >> (bits - 12)
  573. } else {
  574. x_fp << (12 - bits)
  575. };
  576. let frac_correction = shifted - (1i128 << 12);
  577. let correction = (frac_correction * FP_SCALE) / (1i128 << 12);
  578.  
  579. base - (40 * TENURE_LOG_BASE_FP) + correction // subtract ln(1e12) normalization
  580. }
  581.  
  582. /// fixed-point exponential via repeated squaring of e^(2^-k) factors.
  583. /// used for boltzmann weight computation. clamps output to [0, 1e18]
  584. /// to prevent overflow in the distribution calculation.
  585. fn exp_fp(x_fp: i128) -> i128 {
  586. if x_fp > 40 * FP_SCALE { return 1_000_000_000_000_000_000; } // clamp
  587. if x_fp < -40 * FP_SCALE { return 0; }
  588.  
  589. // exp(x) = exp(integer_part) * exp(fractional_part)
  590. // use taylor series for |x| < 1: exp(x) ≈ 1 + x + x²/2 + x³/6 + x⁴/24
  591. let mut result = FP_SCALE;
  592. let mut term = x_fp;
  593. result += term;
  594. term = (term * x_fp) / (2 * FP_SCALE);
  595. result += term;
  596. term = (term * x_fp) / (3 * FP_SCALE);
  597. result += term;
  598. term = (term * x_fp) / (4 * FP_SCALE);
  599. result += term;
  600. term = (term * x_fp) / (5 * FP_SCALE);
  601. result += term;
  602.  
  603. result.max(0)
  604. }
  605.  
  606. // ─── pyth oracle reader ─────────────────────────────────────────────────────
  607.  
  608. fn read_pyth_price(oracle: &AccountInfo) -> Result<i128> {
  609. let data = oracle.try_borrow_data()?;
  610. require!(data.len() >= 48, ErrorCode::OracleAccountMalformed);
  611.  
  612. // pyth price account layout: price at offset 32 (i64), expo at offset 40 (i32)
  613. let price = i64::from_le_bytes(data[32..40].try_into().unwrap());
  614. let expo = i32::from_le_bytes(data[40..44].try_into().unwrap());
  615.  
  616. // normalize to 1e12 fixed-point
  617. let price_fp = if expo >= 0 {
  618. (price as i128) * FP_SCALE * 10i128.pow(expo as u32)
  619. } else {
  620. (price as i128) * FP_SCALE / 10i128.pow((-expo) as u32)
  621. };
  622.  
  623. Ok(price_fp)
  624. }
  625.  
  626. // ─── transfer interval bucketing ────────────────────────────────────────────
  627. //
  628. // maps a slot interval to one of 16 exponentially-spaced buckets.
  629. // bucket 0: [0, 10) ~4 seconds
  630. // bucket 1: [10, 25) ~10 seconds
  631. // bucket 2: [25, 60) ~24 seconds
  632. // bucket 3: [60, 150) ~1 minute
  633. // ...
  634. // bucket 15: [6.5M, ∞) ~30 days
  635. //
  636. // the exponential spacing ensures that shannon entropy meaningfully
  637. // distinguishes between bot-like regularity (one bucket dominates)
  638. // and organic irregularity (spread across many buckets).
  639.  
  640. fn interval_to_bucket(interval: u64) -> usize {
  641. let thresholds: [u64; 16] = [
  642. 0, 10, 25, 60, 150, 375, 900, 2_250,
  643. 5_625, 14_000, 35_000, 87_500, 220_000, 550_000, 1_375_000, 6_500_000,
  644. ];
  645. for i in (0..16).rev() {
  646. if interval >= thresholds[i] {
  647. return i;
  648. }
  649. }
  650. 0
  651. }
  652.  
  653. // ─── initialization (called once at deployment, then authority revoked) ─────
  654.  
  655. #[derive(Accounts)]
  656. pub struct Initialize<'info> {
  657. #[account(mut)]
  658. pub deployer: Signer<'info>,
  659. pub mint: InterfaceAccount<'info, Mint>,
  660. #[account(
  661. init,
  662. payer = deployer,
  663. space = ReturnBuffer::LEN,
  664. seeds = [b"returns", mint.key().as_ref()],
  665. bump,
  666. )]
  667. pub buffer: Account<'info, ReturnBuffer>,
  668. #[account(
  669. init,
  670. payer = deployer,
  671. space = 8 + 8 + 8 + 8 + 1,
  672. seeds = [b"vault", mint.key().as_ref()],
  673. bump,
  674. )]
  675. pub vault: Account<'info, Vault>,
  676. #[account(
  677. init,
  678. payer = deployer,
  679. space = HolderRegistry::LEN,
  680. seeds = [b"registry", mint.key().as_ref()],
  681. bump,
  682. )]
  683. pub registry: Account<'info, HolderRegistry>,
  684. /// CHECK: pyth oracle for the ergodic/sol pair
  685. pub oracle: AccountInfo<'info>,
  686. pub system_program: Program<'info, System>,
  687. }
  688.  
  689. // ─── errors ─────────────────────────────────────────────────────────────────
  690.  
  691. #[error_code]
  692. pub enum ErrorCode {
  693. #[msg("oracle account data is malformed or too short")]
  694. OracleAccountMalformed,
  695. #[msg("buffer not yet filled to 512 entries; dimension undefined")]
  696. InsufficientHistory,
  697. #[msg("vault balance below distribution threshold")]
  698. BelowDistributionThreshold,
  699. #[msg("holder registry is full")]
  700. RegistryFull,
  701. #[msg("arithmetic overflow in fixed-point computation")]
  702. ArithmeticOverflow,
  703. }
  704.  
Add Comment
Please, Sign In to add comment