Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // programs/hausdorff/src/lib.rs
- // hausdorff — token-2022 transfer hook, solana mainnet
- // the solana equivalent of a uniswap v4 beforeSwap hook, applied at the
- // token transfer layer rather than the pool layer
- 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!("HausDorFFhookProGramAddRess1111111111111111");
- // ─── constants ──────────────────────────────────────────────────────────────
- const BUFFER_LEN: usize = 256;
- const FP_SCALE: i128 = 1_000_000_000_000; // 1e12 fixed-point
- const NATURAL_DIM_FP: i128 = 1_382_000_000_000; // 1.382 * 1e12 (natural fractal dimension)
- const SURCHARGE_K_FP: i128 = 50_000_000_000; // 0.05 * 1e12 — quadratic scale constant
- const VAULT_THRESHOLD: u64 = 10_000_000_000; // 10 token units before payout fires
- const LAGS: [usize; 6] = [8, 16, 32, 64, 128, 256];
- // precomputed ln(lag) * 1e12, six values for the higuchi log-log fit
- const LN_LAGS_FP: [i128; 6] = [
- 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)
- 5_545_177_444_479, // ln(256)
- ];
- // ─── on-chain accounts ──────────────────────────────────────────────────────
- #[account]
- pub struct BinBuffer {
- pub head: u16, // circular write pointer, wraps at 256
- pub filled: u16, // count of valid entries (caps at 256)
- pub mint: Pubkey, // hausdorff mint
- pub dlmm_pool: Pubkey, // meteora dlmm pool for hausdorff/sol
- pub last_dim_fp: i128, // most recent dimension estimate, 1e12 fp
- pub cached_length_sums: [i128; 6], // higuchi length sums per lag, carried forward
- pub bin_ids: [i32; BUFFER_LEN], // dlmm active bin id history
- pub prices_fp: [i128; BUFFER_LEN], // bin prices, 1e12 fixed-point
- pub slots: [u64; BUFFER_LEN], // slot of each observation
- }
- impl BinBuffer {
- pub const LEN: usize = 8 + 2 + 2 + 32 + 32 + 16 + (16 * 6)
- + (4 * BUFFER_LEN) + (16 * BUFFER_LEN) + (8 * BUFFER_LEN);
- }
- #[account]
- pub struct VaultState {
- pub accumulated: u64,
- pub last_distribution_slot: u64,
- pub bump: u8,
- }
- #[account]
- pub struct HolderTenure {
- pub wallet: Pubkey,
- pub first_acquisition_slot: u64,
- pub bump: u8,
- }
- // ─── execute: the hook entrypoint (v4-style beforeSwap analogue) ────────────
- //
- // token-2022 invokes this on every transfer of the hausdorff mint, regardless
- // of the calling program. on a meteora dlmm swap, the call path is:
- //
- // user → dlmm_pool::swap → token_2022::transfer → hausdorff::execute
- //
- // the hook returns a surcharge that token-2022 withholds from the input amount
- // before the transfer settles. atomic. no router can route around it.
- #[derive(Accounts)]
- pub struct Execute<'info> {
- pub source: InterfaceAccount<'info, TokenAccount>,
- pub mint: InterfaceAccount<'info, Mint>,
- pub destination: InterfaceAccount<'info, TokenAccount>,
- /// CHECK: meteora dlmm pool, read-only, validated against buffer.dlmm_pool
- pub dlmm_pool: AccountInfo<'info>,
- #[account(
- mut,
- seeds = [b"bins", mint.key().as_ref()],
- bump,
- constraint = buffer.dlmm_pool == dlmm_pool.key(),
- )]
- pub buffer: Account<'info, BinBuffer>,
- #[account(
- mut,
- seeds = [b"vault", mint.key().as_ref()],
- bump = vault.bump,
- )]
- pub vault: Account<'info, VaultState>,
- }
- #[program]
- pub mod hausdorff {
- use super::*;
- pub fn execute(ctx: Context<Execute>, amount: u64) -> Result<u64> {
- let clock = Clock::get()?;
- let buf = &mut ctx.accounts.buffer;
- // 1. read the dlmm pool's active bin (the v4 equivalent of reading
- // pool.slot0() inside a beforeSwap hook on ethereum)
- let (bin_id, price_fp) = read_active_bin(&ctx.accounts.dlmm_pool)?;
- // 2. append the (slot, bin_id, price) tuple to the circular buffer.
- // the eviction at the head position is the point we displace.
- let head = buf.head as usize;
- let evicted_price = buf.prices_fp[head];
- let evicted_valid = (buf.filled as usize) == BUFFER_LEN;
- buf.bin_ids[head] = bin_id;
- buf.prices_fp[head] = price_fp;
- buf.slots[head] = clock.slot;
- buf.head = ((head + 1) % BUFFER_LEN) as u16;
- if (buf.filled as usize) < BUFFER_LEN {
- buf.filled += 1;
- }
- // we need at least BUFFER_LEN points before the dimension is meaningful
- if (buf.filled as usize) < BUFFER_LEN {
- return Ok(0);
- }
- // 3. update cached higuchi length sums incrementally.
- // L(k) = Σ |price[i] - price[i - k]| over the buffer.
- // when a new point arrives and an old point is evicted, only the
- // differences involving those two points change. O(LAGS.len()) per
- // swap instead of O(BUFFER_LEN · LAGS.len()) per swap.
- for (k_idx, &k) in LAGS.iter().enumerate() {
- let new_pt = price_fp;
- let lagged_idx = (head + BUFFER_LEN - k) % BUFFER_LEN;
- let lagged_pt = buf.prices_fp[lagged_idx];
- let add = (new_pt - lagged_pt).abs();
- let sub = if evicted_valid {
- let prev_lagged_idx = (head + BUFFER_LEN - k + 1) % BUFFER_LEN;
- (evicted_price - buf.prices_fp[prev_lagged_idx]).abs()
- } else {
- 0
- };
- buf.cached_length_sums[k_idx] = buf.cached_length_sums[k_idx]
- .saturating_add(add)
- .saturating_sub(sub);
- }
- // 4. fit a line through (ln(k), ln(L(k))). slope = -dimension.
- let dim_fp = higuchi_fit(&buf.cached_length_sums);
- buf.last_dim_fp = dim_fp;
- // 5. surcharge = k · (D − 1.382)² in fixed-point arithmetic.
- // a swap during a smooth manipulated trend pays heavily.
- // a swap during wash-traded chop pays heavily.
- // a swap during natural-dimension conditions pays nothing extra.
- let dev = dim_fp - NATURAL_DIM_FP;
- let dev_sq_fp = (dev * dev) / FP_SCALE;
- let surcharge_rate_fp = (SURCHARGE_K_FP * dev_sq_fp) / FP_SCALE;
- let surcharge = ((amount as i128 * surcharge_rate_fp) / FP_SCALE)
- .max(0)
- .min(amount as i128) as u64;
- // 6. accumulate in vault. the actual token movement is handled
- // atomically by the token-2022 program when it reads this return
- // value and withholds `surcharge` lamports from the transfer.
- ctx.accounts.vault.accumulated = ctx
- .accounts
- .vault
- .accumulated
- .saturating_add(surcharge);
- // emit a structured log line for off-chain indexers
- msg!(
- "hook: dim={} dev={} surcharge={} amount={} bin={}",
- dim_fp,
- dev,
- surcharge,
- amount,
- bin_id
- );
- Ok(surcharge)
- }
- }
- // ─── higuchi line fit in i128 fixed-point ───────────────────────────────────
- fn higuchi_fit(lengths_fp: &[i128; 6]) -> i128 {
- // ordinary least squares on (ln(k), ln(L(k))) with the precomputed LN_LAGS_FP.
- // slope = (n·Σxy − Σx·Σy) / (n·Σx² − (Σx)²)
- // dimension D = -slope
- let n = LAGS.len() as i128;
- let mut sum_x: i128 = 0;
- let mut sum_y: i128 = 0;
- let mut sum_xy: i128 = 0;
- let mut sum_xx: i128 = 0;
- for i in 0..LAGS.len() {
- let x = LN_LAGS_FP[i];
- let y = ln_fp(lengths_fp[i]);
- sum_x += x;
- sum_y += y;
- sum_xy += (x * y) / FP_SCALE;
- sum_xx += (x * x) / FP_SCALE;
- }
- 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 NATURAL_DIM_FP; }
- let slope_fp = (num * FP_SCALE) / den;
- -slope_fp
- }
- // integer natural log, accurate to ~1e-4 over the relevant input range.
- // production deployments swap this for a 256-entry LUT keyed on bit length.
- fn ln_fp(x_fp: i128) -> i128 {
- if x_fp <= 0 { return 0; }
- let approx_bits = 128 - x_fp.leading_zeros() as i128;
- let base = approx_bits * 693_147_180_559; // ln(2) * 1e12
- let frac = (x_fp << 12) / (1i128 << approx_bits);
- base + (frac - FP_SCALE)
- }
- // ─── meteora dlmm pool reader ───────────────────────────────────────────────
- //
- // dlmm packs the active bin id at offset 88 (i32) and the bin step (basis
- // points) at offset 92 (u16). price = (1 + bin_step / 10_000)^active_id,
- // computed in i128 fixed-point via exponentiation by squaring.
- fn read_active_bin(pool: &AccountInfo) -> Result<(i32, i128)> {
- let data = pool.try_borrow_data()?;
- require!(data.len() >= 96, ErrorCode::PoolAccountMalformed);
- let active_id = i32::from_le_bytes(data[88..92].try_into().unwrap());
- let bin_step = u16::from_le_bytes(data[92..94].try_into().unwrap()) as i128;
- let base = FP_SCALE + (bin_step * FP_SCALE) / 10_000;
- let price_fp = pow_fp(base, active_id);
- Ok((active_id, price_fp))
- }
- fn pow_fp(base_fp: i128, exp: i32) -> i128 {
- let mut result = FP_SCALE;
- let mut b = base_fp;
- let mut e = exp.abs();
- while e > 0 {
- if e & 1 == 1 { result = (result * b) / FP_SCALE; }
- b = (b * b) / FP_SCALE;
- e >>= 1;
- }
- if exp < 0 { (FP_SCALE * FP_SCALE) / result } else { result }
- }
- // ─── errors ─────────────────────────────────────────────────────────────────
- #[error_code]
- pub enum ErrorCode {
- #[msg("dlmm pool account data is malformed or too short")]
- PoolAccountMalformed,
- #[msg("buffer not yet filled to 256 entries")]
- InsufficientHistory,
- #[msg("vault threshold not reached for distribution")]
- BelowDistributionThreshold,
- }
Add Comment
Please, Sign In to add comment