Guest User

Untitled

a guest
May 16th, 2026
1,752
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 10.71 KB | Cryptocurrency | 0 0
  1. // programs/hausdorff/src/lib.rs
  2. // hausdorff — token-2022 transfer hook, solana mainnet
  3. // the solana equivalent of a uniswap v4 beforeSwap hook, applied at the
  4. // token transfer layer rather than the pool layer
  5.  
  6. use anchor_lang::prelude::*;
  7. use anchor_spl::token_interface::{Mint, TokenAccount};
  8. use spl_tlv_account_resolution::{
  9. account::ExtraAccountMeta, seeds::Seed, state::ExtraAccountMetaList,
  10. };
  11. use spl_transfer_hook_interface::instruction::{ExecuteInstruction, TransferHookInstruction};
  12.  
  13. declare_id!("HausDorFFhookProGramAddRess1111111111111111");
  14.  
  15. // ─── constants ──────────────────────────────────────────────────────────────
  16.  
  17. const BUFFER_LEN: usize = 256;
  18. const FP_SCALE: i128 = 1_000_000_000_000; // 1e12 fixed-point
  19. const NATURAL_DIM_FP: i128 = 1_382_000_000_000; // 1.382 * 1e12 (natural fractal dimension)
  20. const SURCHARGE_K_FP: i128 = 50_000_000_000; // 0.05 * 1e12 — quadratic scale constant
  21. const VAULT_THRESHOLD: u64 = 10_000_000_000; // 10 token units before payout fires
  22. const LAGS: [usize; 6] = [8, 16, 32, 64, 128, 256];
  23.  
  24. // precomputed ln(lag) * 1e12, six values for the higuchi log-log fit
  25. const LN_LAGS_FP: [i128; 6] = [
  26. 2_079_441_541_679, // ln(8)
  27. 2_772_588_722_239, // ln(16)
  28. 3_465_735_902_799, // ln(32)
  29. 4_158_883_083_359, // ln(64)
  30. 4_852_030_263_919, // ln(128)
  31. 5_545_177_444_479, // ln(256)
  32. ];
  33.  
  34. // ─── on-chain accounts ──────────────────────────────────────────────────────
  35.  
  36. #[account]
  37. pub struct BinBuffer {
  38. pub head: u16, // circular write pointer, wraps at 256
  39. pub filled: u16, // count of valid entries (caps at 256)
  40. pub mint: Pubkey, // hausdorff mint
  41. pub dlmm_pool: Pubkey, // meteora dlmm pool for hausdorff/sol
  42. pub last_dim_fp: i128, // most recent dimension estimate, 1e12 fp
  43. pub cached_length_sums: [i128; 6], // higuchi length sums per lag, carried forward
  44. pub bin_ids: [i32; BUFFER_LEN], // dlmm active bin id history
  45. pub prices_fp: [i128; BUFFER_LEN], // bin prices, 1e12 fixed-point
  46. pub slots: [u64; BUFFER_LEN], // slot of each observation
  47. }
  48.  
  49. impl BinBuffer {
  50. pub const LEN: usize = 8 + 2 + 2 + 32 + 32 + 16 + (16 * 6)
  51. + (4 * BUFFER_LEN) + (16 * BUFFER_LEN) + (8 * BUFFER_LEN);
  52. }
  53.  
  54. #[account]
  55. pub struct VaultState {
  56. pub accumulated: u64,
  57. pub last_distribution_slot: u64,
  58. pub bump: u8,
  59. }
  60.  
  61. #[account]
  62. pub struct HolderTenure {
  63. pub wallet: Pubkey,
  64. pub first_acquisition_slot: u64,
  65. pub bump: u8,
  66. }
  67.  
  68. // ─── execute: the hook entrypoint (v4-style beforeSwap analogue) ────────────
  69. //
  70. // token-2022 invokes this on every transfer of the hausdorff mint, regardless
  71. // of the calling program. on a meteora dlmm swap, the call path is:
  72. //
  73. // user → dlmm_pool::swap → token_2022::transfer → hausdorff::execute
  74. //
  75. // the hook returns a surcharge that token-2022 withholds from the input amount
  76. // before the transfer settles. atomic. no router can route around it.
  77.  
  78. #[derive(Accounts)]
  79. pub struct Execute<'info> {
  80. pub source: InterfaceAccount<'info, TokenAccount>,
  81. pub mint: InterfaceAccount<'info, Mint>,
  82. pub destination: InterfaceAccount<'info, TokenAccount>,
  83. /// CHECK: meteora dlmm pool, read-only, validated against buffer.dlmm_pool
  84. pub dlmm_pool: AccountInfo<'info>,
  85. #[account(
  86. mut,
  87. seeds = [b"bins", mint.key().as_ref()],
  88. bump,
  89. constraint = buffer.dlmm_pool == dlmm_pool.key(),
  90. )]
  91. pub buffer: Account<'info, BinBuffer>,
  92. #[account(
  93. mut,
  94. seeds = [b"vault", mint.key().as_ref()],
  95. bump = vault.bump,
  96. )]
  97. pub vault: Account<'info, VaultState>,
  98. }
  99.  
  100. #[program]
  101. pub mod hausdorff {
  102. use super::*;
  103.  
  104. pub fn execute(ctx: Context<Execute>, amount: u64) -> Result<u64> {
  105. let clock = Clock::get()?;
  106. let buf = &mut ctx.accounts.buffer;
  107.  
  108. // 1. read the dlmm pool's active bin (the v4 equivalent of reading
  109. // pool.slot0() inside a beforeSwap hook on ethereum)
  110. let (bin_id, price_fp) = read_active_bin(&ctx.accounts.dlmm_pool)?;
  111.  
  112. // 2. append the (slot, bin_id, price) tuple to the circular buffer.
  113. // the eviction at the head position is the point we displace.
  114. let head = buf.head as usize;
  115. let evicted_price = buf.prices_fp[head];
  116. let evicted_valid = (buf.filled as usize) == BUFFER_LEN;
  117.  
  118. buf.bin_ids[head] = bin_id;
  119. buf.prices_fp[head] = price_fp;
  120. buf.slots[head] = clock.slot;
  121. buf.head = ((head + 1) % BUFFER_LEN) as u16;
  122. if (buf.filled as usize) < BUFFER_LEN {
  123. buf.filled += 1;
  124. }
  125.  
  126. // we need at least BUFFER_LEN points before the dimension is meaningful
  127. if (buf.filled as usize) < BUFFER_LEN {
  128. return Ok(0);
  129. }
  130.  
  131. // 3. update cached higuchi length sums incrementally.
  132. // L(k) = Σ |price[i] - price[i - k]| over the buffer.
  133. // when a new point arrives and an old point is evicted, only the
  134. // differences involving those two points change. O(LAGS.len()) per
  135. // swap instead of O(BUFFER_LEN · LAGS.len()) per swap.
  136. for (k_idx, &k) in LAGS.iter().enumerate() {
  137. let new_pt = price_fp;
  138. let lagged_idx = (head + BUFFER_LEN - k) % BUFFER_LEN;
  139. let lagged_pt = buf.prices_fp[lagged_idx];
  140. let add = (new_pt - lagged_pt).abs();
  141.  
  142. let sub = if evicted_valid {
  143. let prev_lagged_idx = (head + BUFFER_LEN - k + 1) % BUFFER_LEN;
  144. (evicted_price - buf.prices_fp[prev_lagged_idx]).abs()
  145. } else {
  146. 0
  147. };
  148.  
  149. buf.cached_length_sums[k_idx] = buf.cached_length_sums[k_idx]
  150. .saturating_add(add)
  151. .saturating_sub(sub);
  152. }
  153.  
  154. // 4. fit a line through (ln(k), ln(L(k))). slope = -dimension.
  155. let dim_fp = higuchi_fit(&buf.cached_length_sums);
  156. buf.last_dim_fp = dim_fp;
  157.  
  158. // 5. surcharge = k · (D − 1.382)² in fixed-point arithmetic.
  159. // a swap during a smooth manipulated trend pays heavily.
  160. // a swap during wash-traded chop pays heavily.
  161. // a swap during natural-dimension conditions pays nothing extra.
  162. let dev = dim_fp - NATURAL_DIM_FP;
  163. let dev_sq_fp = (dev * dev) / FP_SCALE;
  164. let surcharge_rate_fp = (SURCHARGE_K_FP * dev_sq_fp) / FP_SCALE;
  165.  
  166. let surcharge = ((amount as i128 * surcharge_rate_fp) / FP_SCALE)
  167. .max(0)
  168. .min(amount as i128) as u64;
  169.  
  170. // 6. accumulate in vault. the actual token movement is handled
  171. // atomically by the token-2022 program when it reads this return
  172. // value and withholds `surcharge` lamports from the transfer.
  173. ctx.accounts.vault.accumulated = ctx
  174. .accounts
  175. .vault
  176. .accumulated
  177. .saturating_add(surcharge);
  178.  
  179. // emit a structured log line for off-chain indexers
  180. msg!(
  181. "hook: dim={} dev={} surcharge={} amount={} bin={}",
  182. dim_fp,
  183. dev,
  184. surcharge,
  185. amount,
  186. bin_id
  187. );
  188.  
  189. Ok(surcharge)
  190. }
  191. }
  192.  
  193. // ─── higuchi line fit in i128 fixed-point ───────────────────────────────────
  194.  
  195. fn higuchi_fit(lengths_fp: &[i128; 6]) -> i128 {
  196. // ordinary least squares on (ln(k), ln(L(k))) with the precomputed LN_LAGS_FP.
  197. // slope = (n·Σxy − Σx·Σy) / (n·Σx² − (Σx)²)
  198. // dimension D = -slope
  199. let n = LAGS.len() as i128;
  200.  
  201. let mut sum_x: i128 = 0;
  202. let mut sum_y: i128 = 0;
  203. let mut sum_xy: i128 = 0;
  204. let mut sum_xx: i128 = 0;
  205.  
  206. for i in 0..LAGS.len() {
  207. let x = LN_LAGS_FP[i];
  208. let y = ln_fp(lengths_fp[i]);
  209. sum_x += x;
  210. sum_y += y;
  211. sum_xy += (x * y) / FP_SCALE;
  212. sum_xx += (x * x) / FP_SCALE;
  213. }
  214.  
  215. let num = n * sum_xy - (sum_x * sum_y) / FP_SCALE;
  216. let den = n * sum_xx - (sum_x * sum_x) / FP_SCALE;
  217.  
  218. if den == 0 { return NATURAL_DIM_FP; }
  219.  
  220. let slope_fp = (num * FP_SCALE) / den;
  221. -slope_fp
  222. }
  223.  
  224. // integer natural log, accurate to ~1e-4 over the relevant input range.
  225. // production deployments swap this for a 256-entry LUT keyed on bit length.
  226. fn ln_fp(x_fp: i128) -> i128 {
  227. if x_fp <= 0 { return 0; }
  228. let approx_bits = 128 - x_fp.leading_zeros() as i128;
  229. let base = approx_bits * 693_147_180_559; // ln(2) * 1e12
  230. let frac = (x_fp << 12) / (1i128 << approx_bits);
  231. base + (frac - FP_SCALE)
  232. }
  233.  
  234. // ─── meteora dlmm pool reader ───────────────────────────────────────────────
  235. //
  236. // dlmm packs the active bin id at offset 88 (i32) and the bin step (basis
  237. // points) at offset 92 (u16). price = (1 + bin_step / 10_000)^active_id,
  238. // computed in i128 fixed-point via exponentiation by squaring.
  239.  
  240. fn read_active_bin(pool: &AccountInfo) -> Result<(i32, i128)> {
  241. let data = pool.try_borrow_data()?;
  242. require!(data.len() >= 96, ErrorCode::PoolAccountMalformed);
  243.  
  244. let active_id = i32::from_le_bytes(data[88..92].try_into().unwrap());
  245. let bin_step = u16::from_le_bytes(data[92..94].try_into().unwrap()) as i128;
  246.  
  247. let base = FP_SCALE + (bin_step * FP_SCALE) / 10_000;
  248. let price_fp = pow_fp(base, active_id);
  249. Ok((active_id, price_fp))
  250. }
  251.  
  252. fn pow_fp(base_fp: i128, exp: i32) -> i128 {
  253. let mut result = FP_SCALE;
  254. let mut b = base_fp;
  255. let mut e = exp.abs();
  256. while e > 0 {
  257. if e & 1 == 1 { result = (result * b) / FP_SCALE; }
  258. b = (b * b) / FP_SCALE;
  259. e >>= 1;
  260. }
  261. if exp < 0 { (FP_SCALE * FP_SCALE) / result } else { result }
  262. }
  263.  
  264. // ─── errors ─────────────────────────────────────────────────────────────────
  265.  
  266. #[error_code]
  267. pub enum ErrorCode {
  268. #[msg("dlmm pool account data is malformed or too short")]
  269. PoolAccountMalformed,
  270. #[msg("buffer not yet filled to 256 entries")]
  271. InsufficientHistory,
  272. #[msg("vault threshold not reached for distribution")]
  273. BelowDistributionThreshold,
  274. }
Add Comment
Please, Sign In to add comment