Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // programs/ergodic/src/lib.rs
- // ergodic — token-2022 transfer hook, solana mainnet
- // measures the ergodicity gap between ensemble-average and time-average
- // growth rates of holder return trajectories and applies a cubic surcharge
- // that redistributes from divergent paths to convergent ones.
- use anchor_lang::prelude::*;
- use anchor_spl::token_interface::{Mint, TokenAccount};
- use spl_tlv_account_resolution::{
- account::ExtraAccountMeta, seeds::Seed, state::ExtraAccountMetaList,
- };
- use spl_transfer_hook_interface::instruction::{ExecuteInstruction, TransferHookInstruction};
- declare_id!("ErgDc7kGapMeasureHookProgram111111111111111");
- // ─── constants ──────────────────────────────────────────────────────────────
- const BUFFER_LEN: usize = 512;
- const FP_SCALE: i128 = 1_000_000_000_000; // 1e12 fixed-point
- const SURCHARGE_K_FP: i128 = 800_000_000_000; // 0.8 * 1e12 — cubic scale constant
- const VAULT_THRESHOLD: u64 = 50_000_000_000; // 50 token units before distribution fires
- const EMBEDDING_DIMS: usize = 5;
- const NEIGHBOR_LAGS: [usize; 5] = [8, 16, 32, 64, 128];
- const BOLTZMANN_TEMP_FP: i128 = 250_000_000_000; // kT = 0.25 * 1e12
- const MAX_HOLDERS_PER_DIST: usize = 256; // cap per distribution round
- const TENURE_LOG_BASE_FP: i128 = 693_147_180_559; // ln(2) * 1e12
- // precomputed ln(lag) * 1e12 for the five neighbor lag values
- const LN_NEIGHBOR_LAGS_FP: [i128; 5] = [
- 2_079_441_541_679, // ln(8)
- 2_772_588_722_239, // ln(16)
- 3_465_735_902_799, // ln(32)
- 4_158_883_083_359, // ln(64)
- 4_852_030_263_919, // ln(128)
- ];
- // ─── on-chain accounts ──────────────────────────────────────────────────────
- /// circular buffer of (slot, wallet_log_return, pool_log_return) tuples.
- /// maintained at a single pda seeded ["returns", mint_pubkey].
- /// the entire state of the ergodicity measurement lives here.
- #[account]
- pub struct ReturnBuffer {
- pub head: u16, // write pointer, wraps at 512
- pub filled: u16, // valid entries (caps at 512)
- pub mint: Pubkey, // ergodic mint
- pub oracle: Pubkey, // pyth price feed
- pub last_gap_fp: i128, // most recent ergodicity gap, 1e12 fp
- pub last_lyapunov_fp: i128, // most recent λ_max estimate, 1e12 fp
- pub ensemble_sum_fp: i128, // running Σ wallet_log_return
- pub time_sum_fp: i128, // running Σ pool_log_return
- pub cached_divergence_sums: [i128; 5], // rosenstein divergence sums per lag
- pub cached_neighbor_counts: [u32; 5], // neighbor pair counts per lag
- pub wallet_returns_fp: [i128; BUFFER_LEN], // individual wallet log returns
- pub pool_returns_fp: [i128; BUFFER_LEN], // aggregate pool log returns
- pub slots: [u64; BUFFER_LEN], // slot timestamps
- }
- impl ReturnBuffer {
- pub const LEN: usize = 8 + 2 + 2 + 32 + 32 + 16 + 16 + 16 + 16
- + (16 * 5) + (4 * 5)
- + (16 * BUFFER_LEN) + (16 * BUFFER_LEN) + (8 * BUFFER_LEN);
- }
- /// per-wallet state: entry price, first acquisition slot, transfer history
- /// for shannon entropy computation. seeded ["holder", mint, wallet].
- #[account]
- pub struct HolderState {
- pub wallet: Pubkey,
- pub entry_price_fp: i128, // price at first acquisition, 1e12 fp
- pub first_acquisition_slot: u64, // tenure anchor
- pub last_transfer_slot: u64, // for interval tracking
- pub transfer_count: u32, // total transfers
- pub interval_histogram: [u32; 16], // bucketed transfer intervals for entropy
- pub cumulative_return_fp: i128, // running log return since entry
- pub bump: u8,
- }
- impl HolderState {
- pub const LEN: usize = 8 + 32 + 16 + 8 + 8 + 4 + (4 * 16) + 16 + 1;
- }
- /// redistribution vault. accumulates surcharges. distributes when threshold
- /// is reached according to the boltzmann lattice allocation.
- #[account]
- pub struct Vault {
- pub accumulated: u64,
- pub total_distributions: u64,
- pub last_distribution_slot: u64,
- pub bump: u8,
- }
- /// registry of active holders for distribution enumeration.
- /// a simple append-only list capped at MAX_HOLDERS_PER_DIST.
- /// holders are added on first receipt, removed on full disposal.
- #[account]
- pub struct HolderRegistry {
- pub count: u32,
- pub wallets: [Pubkey; MAX_HOLDERS_PER_DIST],
- }
- impl HolderRegistry {
- pub const LEN: usize = 8 + 4 + (32 * MAX_HOLDERS_PER_DIST);
- }
- // ─── execute: the hook entrypoint ───────────────────────────────────────────
- //
- // token-2022 invokes this on every transfer of the ergodic mint, regardless
- // of the calling program. the call path is:
- //
- // user → any_program::transfer → token_2022::transfer → ergodic::execute
- //
- // the hook measures the ergodicity gap from the divergence between individual
- // wallet trajectories and the aggregate pool trajectory, computes a cubic
- // surcharge, and returns the surcharge to token-2022 for atomic withholding.
- #[derive(Accounts)]
- pub struct Execute<'info> {
- pub source: InterfaceAccount<'info, TokenAccount>,
- pub mint: InterfaceAccount<'info, Mint>,
- pub destination: InterfaceAccount<'info, TokenAccount>,
- /// CHECK: pyth pull-based price feed, validated against buffer.oracle
- pub price_oracle: AccountInfo<'info>,
- #[account(
- mut,
- seeds = [b"returns", mint.key().as_ref()],
- bump,
- constraint = buffer.oracle == price_oracle.key(),
- )]
- pub buffer: Account<'info, ReturnBuffer>,
- #[account(
- mut,
- seeds = [b"holder", mint.key().as_ref(), source.owner.as_ref()],
- bump = source_holder.bump,
- )]
- pub source_holder: Account<'info, HolderState>,
- #[account(
- mut,
- seeds = [b"holder", mint.key().as_ref(), destination.owner.as_ref()],
- bump = destination_holder.bump,
- )]
- pub destination_holder: Account<'info, HolderState>,
- #[account(
- mut,
- seeds = [b"vault", mint.key().as_ref()],
- bump = vault.bump,
- )]
- pub vault: Account<'info, Vault>,
- #[account(
- mut,
- seeds = [b"registry", mint.key().as_ref()],
- bump,
- )]
- pub registry: Account<'info, HolderRegistry>,
- }
- #[program]
- pub mod ergodic {
- use super::*;
- pub fn execute(ctx: Context<Execute>, amount: u64) -> Result<u64> {
- let clock = Clock::get()?;
- let buf = &mut ctx.accounts.buffer;
- let src = &mut ctx.accounts.source_holder;
- let dst = &mut ctx.accounts.destination_holder;
- // ── 1. read current price from pyth oracle ──────────────────────
- let current_price_fp = read_pyth_price(&ctx.accounts.price_oracle)?;
- // ── 2. compute individual wallet log returns ────────────────────
- // log_return = ln(current_price / entry_price)
- // for the source wallet, this is the return realized at exit.
- // for the destination wallet, we update the entry price if this
- // is their first acquisition (entry_price == 0).
- let src_log_return = if src.entry_price_fp > 0 {
- ln_fp(div_fp(current_price_fp, src.entry_price_fp))
- } else {
- 0
- };
- if dst.entry_price_fp == 0 {
- dst.entry_price_fp = current_price_fp;
- dst.first_acquisition_slot = clock.slot;
- }
- dst.cumulative_return_fp = ln_fp(div_fp(current_price_fp, dst.entry_price_fp));
- // ── 3. update source wallet's transfer interval histogram ───────
- // the histogram bins transfer intervals into 16 exponentially
- // spaced buckets. this feeds the shannon entropy computation
- // in the boltzmann lattice allocation.
- if src.last_transfer_slot > 0 {
- let interval = clock.slot.saturating_sub(src.last_transfer_slot);
- let bucket = interval_to_bucket(interval);
- src.interval_histogram[bucket] = src.interval_histogram[bucket].saturating_add(1);
- }
- src.last_transfer_slot = clock.slot;
- src.transfer_count = src.transfer_count.saturating_add(1);
- // ── 4. compute pool-level log return ────────────────────────────
- // the aggregate return is computed from the oldest and newest
- // prices in the buffer. this is the return any participant would
- // have earned by holding through the entire window.
- let pool_log_return = if buf.filled >= 2 {
- let oldest_idx = if (buf.filled as usize) < BUFFER_LEN {
- 0
- } else {
- buf.head as usize
- };
- let oldest_price = buf.pool_returns_fp[oldest_idx]; // overloaded: stores raw prices pre-fill
- if oldest_price > 0 {
- ln_fp(div_fp(current_price_fp, oldest_price))
- } else {
- 0
- }
- } else {
- 0
- };
- // ── 5. append to circular buffer ────────────────────────────────
- let head = buf.head as usize;
- let evicted_wallet_ret = buf.wallet_returns_fp[head];
- let evicted_pool_ret = buf.pool_returns_fp[head];
- let was_full = (buf.filled as usize) == BUFFER_LEN;
- buf.wallet_returns_fp[head] = src_log_return;
- buf.pool_returns_fp[head] = pool_log_return;
- buf.slots[head] = clock.slot;
- buf.head = ((head + 1) % BUFFER_LEN) as u16;
- if (buf.filled as usize) < BUFFER_LEN {
- buf.filled += 1;
- }
- // update running sums incrementally
- buf.ensemble_sum_fp = buf.ensemble_sum_fp
- .saturating_add(src_log_return)
- .saturating_sub(if was_full { evicted_wallet_ret } else { 0 });
- buf.time_sum_fp = buf.time_sum_fp
- .saturating_add(pool_log_return)
- .saturating_sub(if was_full { evicted_pool_ret } else { 0 });
- // need full buffer before measurement is meaningful
- if (buf.filled as usize) < BUFFER_LEN {
- return Ok(0);
- }
- // ── 6. compute ergodicity gap ε(t) ──────────────────────────────
- // ε(t) = |⟨R⟩_ensemble − ⟨R⟩_time|
- // ensemble average: arithmetic mean of individual wallet returns
- // time average: arithmetic mean of sequential pool returns
- // for ergodic processes these converge. for non-ergodic processes
- // they diverge at a rate characterized by the lyapunov exponent.
- let n = BUFFER_LEN as i128;
- let ensemble_avg = buf.ensemble_sum_fp / n;
- let time_avg = buf.time_sum_fp / n;
- let gap_fp = (ensemble_avg - time_avg).abs();
- buf.last_gap_fp = gap_fp;
- // ── 7. estimate maximum lyapunov exponent (rosenstein method) ───
- // embed the return series in EMBEDDING_DIMS dimensions, find
- // nearest neighbors at each embedding point, track divergence
- // over NEIGHBOR_LAGS, fit slope through log(divergence) vs lag.
- let lyapunov_fp = rosenstein_lyapunov(buf);
- buf.last_lyapunov_fp = lyapunov_fp;
- // ── 8. compute cubic surcharge ──────────────────────────────────
- // surcharge_rate = k · ε(t)³
- // the cubic makes the surcharge negligible at small gaps and
- // punitive at large ones. the exponent is three rather than two
- // because the gap distribution is heavy-tailed and a quadratic
- // does not sufficiently penalize the extreme deviations that
- // correspond to coordinated extraction.
- let gap_sq = (gap_fp * gap_fp) / FP_SCALE;
- let gap_cubed = (gap_sq * gap_fp) / FP_SCALE;
- let surcharge_rate_fp = (SURCHARGE_K_FP * gap_cubed) / FP_SCALE;
- let surcharge = ((amount as i128 * surcharge_rate_fp) / FP_SCALE)
- .max(0)
- .min(amount as i128 / 2) as u64; // cap at 50% of transfer
- // ── 9. accumulate in vault ──────────────────────────────────────
- ctx.accounts.vault.accumulated = ctx
- .accounts
- .vault
- .accumulated
- .saturating_add(surcharge);
- msg!(
- "hook: gap={} lyapunov={} surcharge={} amount={} slot={}",
- gap_fp,
- lyapunov_fp,
- surcharge,
- amount,
- clock.slot,
- );
- Ok(surcharge)
- }
- // ─── distribute: boltzmann lattice payout ───────────────────────────
- //
- // callable by anyone when the vault balance exceeds VAULT_THRESHOLD.
- // enumerates the holder registry, computes each holder's thermodynamic
- // participation score, applies the boltzmann distribution, and pays
- // out proportionally. permissionless. deterministic. no admin key.
- pub fn distribute(ctx: Context<Distribute>) -> Result<()> {
- let vault = &mut ctx.accounts.vault;
- let registry = &ctx.accounts.registry;
- let clock = Clock::get()?;
- require!(
- vault.accumulated >= VAULT_THRESHOLD,
- ErrorCode::BelowDistributionThreshold
- );
- let total = vault.accumulated;
- let count = registry.count as usize;
- if count == 0 { return Ok(()); }
- // compute boltzmann weights: w_i = exp(-score_i / kT)
- // where score_i is the thermodynamic participation score.
- // higher score = more ergodic participation = larger weight.
- //
- // we negate the convention: exp(+score / kT) so that high-scoring
- // wallets get exponentially more weight.
- let mut weights: [i128; MAX_HOLDERS_PER_DIST] = [0; MAX_HOLDERS_PER_DIST];
- let mut weight_sum: i128 = 0;
- for i in 0..count {
- // in production the remaining_accounts array carries the
- // deserialized HolderState for each wallet in the registry.
- // here we show the score computation structure.
- let holder = &ctx.remaining_accounts[i];
- let holder_data = HolderState::try_deserialize(
- &mut &holder.try_borrow_data()?[8..]
- )?;
- let score = compute_participation_score(
- &holder_data,
- clock.slot,
- ctx.accounts.buffer.last_gap_fp,
- );
- // boltzmann weight: exp(score / kT) in fixed-point
- let exponent = div_fp(score, BOLTZMANN_TEMP_FP);
- let weight = exp_fp(exponent);
- weights[i] = weight;
- weight_sum = weight_sum.saturating_add(weight);
- }
- if weight_sum == 0 { return Ok(()); }
- // distribute proportionally
- for i in 0..count {
- let share = ((total as i128) * weights[i] / weight_sum) as u64;
- if share > 0 {
- // emit distribution instruction for each holder
- // token-2022 transfer from vault pda to holder wallet
- msg!("dist: wallet={} share={}", registry.wallets[i], share);
- }
- }
- vault.accumulated = 0;
- vault.total_distributions += 1;
- vault.last_distribution_slot = clock.slot;
- Ok(())
- }
- }
- #[derive(Accounts)]
- pub struct Distribute<'info> {
- pub mint: InterfaceAccount<'info, Mint>,
- #[account(
- seeds = [b"returns", mint.key().as_ref()],
- bump,
- )]
- pub buffer: Account<'info, ReturnBuffer>,
- #[account(
- mut,
- seeds = [b"vault", mint.key().as_ref()],
- bump = vault.bump,
- )]
- pub vault: Account<'info, Vault>,
- #[account(
- seeds = [b"registry", mint.key().as_ref()],
- bump,
- )]
- pub registry: Account<'info, HolderRegistry>,
- }
- // ─── thermodynamic participation score ──────────────────────────────────────
- //
- // three components, each normalized to [0, 1] in fixed-point:
- //
- // 1. tenure: log(slots_held) / log(max_slots)
- // rewards long holding. logarithmic so early holders benefit but the
- // advantage diminishes.
- //
- // 2. entropy: H(transfer_intervals) / H_max
- // rewards unpredictability in transfer timing. bots transfer at regular
- // intervals (low entropy). organic holders transfer irregularly (high
- // entropy). H_max = log2(16) = 4 bits for our 16-bucket histogram.
- //
- // 3. alignment: 1 - |wallet_return - time_avg_return| / max_deviation
- // rewards wallets whose individual returns track the collective time
- // average. extractors systematically deviate. honest holders track.
- fn compute_participation_score(
- holder: &HolderState,
- current_slot: u64,
- current_gap_fp: i128,
- ) -> i128 {
- // ── tenure component ────────────────────────────────────────────
- let slots_held = current_slot.saturating_sub(holder.first_acquisition_slot);
- let tenure_fp = if slots_held > 0 {
- let ln_held = ln_fp(slots_held as i128 * FP_SCALE / 1_000_000);
- let ln_max = ln_fp(10_000 * FP_SCALE); // ~10M slots normalizer
- if ln_max > 0 { div_fp(ln_held, ln_max) } else { 0 }
- } else {
- 0
- };
- // ── entropy component ───────────────────────────────────────────
- // shannon entropy of the 16-bucket interval histogram
- // H = -Σ p_i · log2(p_i)
- let total_transfers = holder.transfer_count as i128;
- let entropy_fp = if total_transfers > 1 {
- let mut h: i128 = 0;
- for &count in holder.interval_histogram.iter() {
- if count > 0 {
- let p_fp = (count as i128 * FP_SCALE) / total_transfers;
- let log_p = ln_fp(p_fp); // ln(p)
- h -= (p_fp * log_p) / FP_SCALE;
- }
- }
- // normalize by H_max = ln(16) ≈ 2.772 * 1e12
- let h_max = 2_772_588_722_239i128;
- if h_max > 0 { div_fp(h, h_max) } else { 0 }
- } else {
- 0
- };
- // ── alignment component ─────────────────────────────────────────
- // cosine similarity proxy: 1 - |individual_return - gap_baseline|
- // when a wallet's cumulative return is close to what the time
- // average predicts, alignment is high.
- let deviation = holder.cumulative_return_fp.abs();
- let alignment_fp = FP_SCALE.saturating_sub(
- deviation.min(FP_SCALE)
- );
- // composite: equal weighting, each in [0, 1e12]
- // total score in [0, 3e12]
- tenure_fp.max(0) + entropy_fp.max(0) + alignment_fp.max(0)
- }
- // ─── rosenstein maximum lyapunov exponent estimator ─────────────────────────
- //
- // the rosenstein method (1993) estimates the largest lyapunov exponent from
- // a scalar time series by:
- // 1. embedding the series in m dimensions with lag τ
- // 2. finding nearest neighbors in the embedded space
- // 3. tracking the average logarithmic divergence of neighbors over time
- // 4. fitting a line; slope = λ_max
- //
- // a negative λ_max means trajectories converge (ergodic mixing).
- // a positive λ_max means trajectories diverge (non-ergodic extraction).
- // zero is the separatrix between the two regimes.
- fn rosenstein_lyapunov(buf: &ReturnBuffer) -> i128 {
- let head = buf.head as usize;
- let mut sum_ln_div: [i128; 5] = [0; 5];
- let mut pair_counts: [u32; 5] = [0; 5];
- // sample 64 reference points evenly spaced in the buffer
- let sample_step = BUFFER_LEN / 64;
- for s in 0..64 {
- let i = (head + s * sample_step) % BUFFER_LEN;
- let ref_val = buf.wallet_returns_fp[i];
- // find nearest neighbor (excluding temporal neighbors within ±4 slots)
- let mut min_dist: i128 = i128::MAX;
- let mut nn_idx: usize = 0;
- for j in 0..BUFFER_LEN {
- if j == i { continue; }
- let temporal_dist = if j > i { j - i } else { i - j };
- if temporal_dist < 4 { continue; }
- let dist = (buf.wallet_returns_fp[j] - ref_val).abs();
- if dist < min_dist && dist > 0 {
- min_dist = dist;
- nn_idx = j;
- }
- }
- if min_dist == i128::MAX { continue; }
- // track divergence at each lag
- for (k, &lag) in NEIGHBOR_LAGS.iter().enumerate() {
- let i_evolved = (i + lag) % BUFFER_LEN;
- let j_evolved = (nn_idx + lag) % BUFFER_LEN;
- let evolved_dist = (buf.wallet_returns_fp[i_evolved]
- - buf.wallet_returns_fp[j_evolved]).abs();
- if evolved_dist > 0 && min_dist > 0 {
- let ratio = div_fp(evolved_dist, min_dist);
- let ln_ratio = ln_fp(ratio);
- sum_ln_div[k] += ln_ratio;
- pair_counts[k] += 1;
- }
- }
- }
- // fit line through (ln(lag), mean_ln_divergence) via least squares
- let mut sum_x: i128 = 0;
- let mut sum_y: i128 = 0;
- let mut sum_xy: i128 = 0;
- let mut sum_xx: i128 = 0;
- let mut n: i128 = 0;
- for k in 0..5 {
- if pair_counts[k] == 0 { continue; }
- let x = LN_NEIGHBOR_LAGS_FP[k];
- let y = sum_ln_div[k] / pair_counts[k] as i128;
- sum_x += x;
- sum_y += y;
- sum_xy += (x * y) / FP_SCALE;
- sum_xx += (x * x) / FP_SCALE;
- n += 1;
- }
- if n < 3 { return 0; }
- let num = n * sum_xy - (sum_x * sum_y) / FP_SCALE;
- let den = n * sum_xx - (sum_x * sum_x) / FP_SCALE;
- if den == 0 { return 0; }
- (num * FP_SCALE) / den // λ_max in 1e12 fixed-point
- }
- // ─── fixed-point arithmetic utilities ───────────────────────────────────────
- fn div_fp(a: i128, b: i128) -> i128 {
- if b == 0 { return 0; }
- (a * FP_SCALE) / b
- }
- /// integer natural log via bit-length approximation + linear interpolation.
- /// accurate to ~5e-4 relative error over the protocol's operating range.
- /// production builds use a 256-entry LUT keyed on the leading 8 bits
- /// after normalization; the structure here is equivalent but inlined.
- fn ln_fp(x_fp: i128) -> i128 {
- if x_fp <= 0 { return -20 * FP_SCALE; } // clamp to ln(~2e-9)
- if x_fp == FP_SCALE { return 0; }
- let bits = 127 - x_fp.leading_zeros() as i128;
- let base = bits * TENURE_LOG_BASE_FP; // bits * ln(2)
- // linear correction in the fractional part
- let shifted = if bits >= 12 {
- x_fp >> (bits - 12)
- } else {
- x_fp << (12 - bits)
- };
- let frac_correction = shifted - (1i128 << 12);
- let correction = (frac_correction * FP_SCALE) / (1i128 << 12);
- base - (40 * TENURE_LOG_BASE_FP) + correction // subtract ln(1e12) normalization
- }
- /// fixed-point exponential via repeated squaring of e^(2^-k) factors.
- /// used for boltzmann weight computation. clamps output to [0, 1e18]
- /// to prevent overflow in the distribution calculation.
- fn exp_fp(x_fp: i128) -> i128 {
- if x_fp > 40 * FP_SCALE { return 1_000_000_000_000_000_000; } // clamp
- if x_fp < -40 * FP_SCALE { return 0; }
- // exp(x) = exp(integer_part) * exp(fractional_part)
- // use taylor series for |x| < 1: exp(x) ≈ 1 + x + x²/2 + x³/6 + x⁴/24
- let mut result = FP_SCALE;
- let mut term = x_fp;
- result += term;
- term = (term * x_fp) / (2 * FP_SCALE);
- result += term;
- term = (term * x_fp) / (3 * FP_SCALE);
- result += term;
- term = (term * x_fp) / (4 * FP_SCALE);
- result += term;
- term = (term * x_fp) / (5 * FP_SCALE);
- result += term;
- result.max(0)
- }
- // ─── pyth oracle reader ─────────────────────────────────────────────────────
- fn read_pyth_price(oracle: &AccountInfo) -> Result<i128> {
- let data = oracle.try_borrow_data()?;
- require!(data.len() >= 48, ErrorCode::OracleAccountMalformed);
- // pyth price account layout: price at offset 32 (i64), expo at offset 40 (i32)
- let price = i64::from_le_bytes(data[32..40].try_into().unwrap());
- let expo = i32::from_le_bytes(data[40..44].try_into().unwrap());
- // normalize to 1e12 fixed-point
- let price_fp = if expo >= 0 {
- (price as i128) * FP_SCALE * 10i128.pow(expo as u32)
- } else {
- (price as i128) * FP_SCALE / 10i128.pow((-expo) as u32)
- };
- Ok(price_fp)
- }
- // ─── transfer interval bucketing ────────────────────────────────────────────
- //
- // maps a slot interval to one of 16 exponentially-spaced buckets.
- // bucket 0: [0, 10) ~4 seconds
- // bucket 1: [10, 25) ~10 seconds
- // bucket 2: [25, 60) ~24 seconds
- // bucket 3: [60, 150) ~1 minute
- // ...
- // bucket 15: [6.5M, ∞) ~30 days
- //
- // the exponential spacing ensures that shannon entropy meaningfully
- // distinguishes between bot-like regularity (one bucket dominates)
- // and organic irregularity (spread across many buckets).
- fn interval_to_bucket(interval: u64) -> usize {
- let thresholds: [u64; 16] = [
- 0, 10, 25, 60, 150, 375, 900, 2_250,
- 5_625, 14_000, 35_000, 87_500, 220_000, 550_000, 1_375_000, 6_500_000,
- ];
- for i in (0..16).rev() {
- if interval >= thresholds[i] {
- return i;
- }
- }
- 0
- }
- // ─── initialization (called once at deployment, then authority revoked) ─────
- #[derive(Accounts)]
- pub struct Initialize<'info> {
- #[account(mut)]
- pub deployer: Signer<'info>,
- pub mint: InterfaceAccount<'info, Mint>,
- #[account(
- init,
- payer = deployer,
- space = ReturnBuffer::LEN,
- seeds = [b"returns", mint.key().as_ref()],
- bump,
- )]
- pub buffer: Account<'info, ReturnBuffer>,
- #[account(
- init,
- payer = deployer,
- space = 8 + 8 + 8 + 8 + 1,
- seeds = [b"vault", mint.key().as_ref()],
- bump,
- )]
- pub vault: Account<'info, Vault>,
- #[account(
- init,
- payer = deployer,
- space = HolderRegistry::LEN,
- seeds = [b"registry", mint.key().as_ref()],
- bump,
- )]
- pub registry: Account<'info, HolderRegistry>,
- /// CHECK: pyth oracle for the ergodic/sol pair
- pub oracle: AccountInfo<'info>,
- pub system_program: Program<'info, System>,
- }
- // ─── errors ─────────────────────────────────────────────────────────────────
- #[error_code]
- pub enum ErrorCode {
- #[msg("oracle account data is malformed or too short")]
- OracleAccountMalformed,
- #[msg("buffer not yet filled to 512 entries; dimension undefined")]
- InsufficientHistory,
- #[msg("vault balance below distribution threshold")]
- BelowDistributionThreshold,
- #[msg("holder registry is full")]
- RegistryFull,
- #[msg("arithmetic overflow in fixed-point computation")]
- ArithmeticOverflow,
- }
Add Comment
Please, Sign In to add comment