Open source

The code that moves money here is readable.

This page serves the exact source the live site uses. Hash it yourself and compare it with the fingerprint below — if the code changes, the fingerprint changes with it.

Fingerprint · SHA-256
computing…
4 files · 831 lines
/api/public/keeper173 lines · sha256 ……
import { createFileRoute } from "@tanstack/react-router";
import { authenticateCronRequest } from "@/integrations/supabase/cron-auth";

// Fee-lane keeper. Called on a schedule with the KEEPER_SECRET header.
// 1) claims pump.fun creator fees for the treasury and splits them into each coin's lanes,
// 2) buys back on drawdown, 3) pays holders, 4) unlocks the creator lane at its milestone, 5) fills sealed batches.
// Every run is recorded in rp_keeper_runs, every holder payment in rp_payouts, and one row per day in rp_daily_snapshots.
export const Route = createFileRoute("/api/public/keeper")({
  server: {
    handlers: {
      POST: async ({ request }) => {
        const secret = process.env["KEEPER_SECRET"];
        if (!secret || request.headers.get("x-keeper-secret") !== secret) {
          const authFailure = await authenticateCronRequest(request);
          if (authFailure) return authFailure;
        }
        const T = await import("@/lib/treasury.server");
        const { PublicKey, SystemProgram, Transaction } = await import("@solana/web3.js");
        const { supabaseAdmin: db } = await import("@/integrations/supabase/client.server");

        const startedAt = new Date();
        const log: string[] = [];
        let actions = 0;

        // Public run log: every run is recorded, including runs that found nothing to do.
        const finish = async (status: string, coins = 0, claimedSol = 0) => {
          try {
            await db.from("rp_keeper_runs").insert({
              started_at: startedAt.toISOString(), finished_at: new Date().toISOString(),
              status, coins, claimed_sol: claimedSol, actions, log: log.join("\n").slice(0, 4000),
            });
          } catch { /* the run log is best effort */ }
        };

        const t = await T.treasury();
        const c = T.rpc();
        const SOL = T.LAMPORTS_PER_SOL;

        const { data: coins } = await db.from("rp_pump_coins").select("*").eq("treasury_creator", true);
        if (!coins?.length) { await finish("no_coins"); return Response.json({ ok: true, log: ["no ring coins"] }); }

        // Market data
        const market: Record<string, { price: number; mc: number; vol: number }> = {};
        for (let i = 0; i < coins.length; i += 30) {
          const ids = coins.slice(i, i + 30).map((x) => x.mint).join(",");
          const r = await fetch(`https://api.dexscreener.com/tokens/v1/solana/${ids}`).then((r) => r.json()).catch(() => []);
          for (const p of (r as any[]) ?? []) {
            const m = p.baseToken?.address; if (!m) continue;
            if (!market[m] || (p.liquidity?.usd ?? 0) > 0) market[m] = { price: Number(p.priceUsd ?? 0), mc: Number(p.marketCap ?? p.fdv ?? 0), vol: Number(p.volume?.h24 ?? 0) };
          }
        }

        // 1) Claim creator fees
        let claimed = 0;
        let claimSig = "";
        try {
          const before = await c.getBalance(t.publicKey);
          claimSig = await T.pumpTx({ publicKey: t.publicKey.toBase58(), action: "collectCreatorFee", priorityFee: 0.000051, pool: "pump" }, [t]);
          const after = await c.getBalance(t.publicKey);
          claimed = Math.max(0, after - before);
          if (claimed > 0) actions++;
        } catch (e) { log.push(`claim: ${(e as Error).message.slice(0, 120)}`); }
        const totalVol = coins.reduce((s, x) => s + (market[x.mint]?.vol ?? 0), 0);

        for (const coin of coins) {
          const mk = market[coin.mint];
          const share = claimed ? (totalVol ? (mk?.vol ?? 0) / totalVol : 1 / coins.length) * claimed / SOL : 0;
          let reserve = Number(coin.reserve_sol) + share * coin.lane_reserve / 100;
          let holders = Number(coin.holders_sol) + share * coin.lane_holders / 100;
          let creator = Number(coin.creator_sol) + share * coin.lane_creator / 100;
          let unlocked = coin.creator_unlocked;
          const ath = Math.max(Number(coin.ath_price), mk?.price ?? 0);
          if (share > 0) await db.from("rp_lane_events").insert({ mint: coin.mint, kind: "fees", sol: share, signature: claimSig || null });

          // 2) Drawdown buyback
          if (mk?.price && ath > 0 && mk.price <= ath * (1 - coin.buyback_drawdown / 100) && reserve >= 0.01) {
            try {
              const sig = await T.pumpTx({ publicKey: t.publicKey.toBase58(), action: "buy", mint: coin.mint, amount: Number(reserve.toFixed(6)), denominatedInSol: "true", slippage: 15, priorityFee: 0.0001, pool: "auto" }, [t]);
              await db.from("rp_lane_events").insert({ mint: coin.mint, kind: "buyback", sol: reserve, signature: sig });
              reserve = 0; actions++;
            } catch (e) { log.push(`buyback ${coin.ticker}: ${(e as Error).message.slice(0, 120)}`); }
          }

          // 3) Holder payouts (top holders, wallets only, excluding the curve and the treasury).
          // Every recipient and amount is recorded in rp_payouts so holders can check their share.
          if (holders >= 0.05) {
            try {
              const largest = await c.getTokenLargestAccounts(new PublicKey(coin.mint));
              const accs = await c.getMultipleParsedAccounts(largest.value.map((a) => a.address));
              const rows = accs.value.map((a, i) => ({ owner: (a?.data as any)?.parsed?.info?.owner as string | undefined, amt: Number(largest.value[i]!.amount) }))
                .filter((r) => r.owner && r.owner !== t.publicKey.toBase58() && PublicKey.isOnCurve(new PublicKey(r.owner).toBytes()));
              const sum = rows.reduce((s, r) => s + r.amt, 0);
              if (sum > 0) {
                const tx = new Transaction();
                const paid: { wallet: string; lamports: number }[] = [];
                for (const r of rows.slice(0, 18)) {
                  const lamports = Math.floor(holders * SOL * r.amt / sum);
                  if (lamports > 5000) { tx.add(SystemProgram.transfer({ fromPubkey: t.publicKey, toPubkey: new PublicKey(r.owner!), lamports })); paid.push({ wallet: r.owner!, lamports }); }
                }
                if (tx.instructions.length) {
                  tx.feePayer = t.publicKey; tx.recentBlockhash = (await c.getLatestBlockhash()).blockhash; tx.sign(t);
                  const sig = await c.sendRawTransaction(tx.serialize()); await c.confirmTransaction(sig, "confirmed");
                  await db.from("rp_lane_events").insert({ mint: coin.mint, kind: "holder_payout", sol: holders, signature: sig });
                  if (paid.length) await db.from("rp_payouts").insert(paid.map((p) => ({ mint: coin.mint, wallet: p.wallet, lamports: p.lamports, signature: sig })));
                  holders = 0; actions++;
                }
              }
            } catch (e) { log.push(`holders ${coin.ticker}: ${(e as Error).message.slice(0, 120)}`); }
          }

          // 4) Creator milestone unlock
          if (!unlocked && mk?.mc && mk.mc >= Number(coin.milestone_mc_usd)) unlocked = true;
          if (unlocked && creator >= 0.01) {
            try {
              const sig = await T.sendSol(coin.creator, creator * SOL);
              await db.from("rp_lane_events").insert({ mint: coin.mint, kind: "creator_unlock", sol: creator, signature: sig });
              creator = 0; actions++;
            } catch (e) { log.push(`creator ${coin.ticker}: ${(e as Error).message.slice(0, 120)}`); }
          }

          await db.from("rp_pump_coins").update({ reserve_sol: reserve, holders_sol: holders, creator_sol: creator, creator_unlocked: unlocked, ath_price: ath, fees_total_sol: Number(coin.fees_total_sol) + share }).eq("mint", coin.mint);
          coin.reserve_sol = reserve; coin.holders_sol = holders; coin.creator_sol = creator; coin.fees_total_sol = Number(coin.fees_total_sol) + share;

          // 5) Sealed batch fill: one curve buy for every pending commit, tokens split pro-rata
          const { data: commits } = await db.from("rp_batch_commits").select("*").eq("mint", coin.mint).eq("status", "pending").lt("created_at", new Date(Date.now() - 60_000).toISOString());
          if (commits?.length) {
            try {
              const total = commits.reduce((s, x) => s + Number(x.lamports), 0);
              const before = await T.tokenBalance(t.publicKey, coin.mint);
              const sig = await T.pumpTx({ publicKey: t.publicKey.toBase58(), action: "buy", mint: coin.mint, amount: Number(((total * 0.99) / SOL).toFixed(6)), denominatedInSol: "true", slippage: 15, priorityFee: 0.0001, pool: "auto" }, [t]);
              const got = (await T.tokenBalance(t.publicKey, coin.mint)) - before;
              for (const cm of commits) {
                const amt = (got * BigInt(cm.lamports)) / BigInt(total);
                let tsig: string | null = null;
                if (amt > 0n) tsig = await T.sendTokens(coin.mint, cm.wallet, amt);
                await db.from("rp_batch_commits").update({ status: "filled", fill_signature: sig, transfer_signature: tsig }).eq("signature", cm.signature);
              }
              await db.from("rp_lane_events").insert({ mint: coin.mint, kind: "batch_fill", sol: total / SOL, signature: sig });
              actions++;
            } catch (e) { log.push(`batch ${coin.ticker}: ${(e as Error).message.slice(0, 120)}`); }
          }
        }

        // Daily snapshot: one immutably dated row per day, first run of the day writes it.
        try {
          const day = new Date().toISOString().slice(0, 10);
          const { data: seen } = await db.from("rp_daily_snapshots").select("day").eq("day", day).maybeSingle();
          if (!seen) {
            const kinds = ["register", "shield", "private_send", "unshield"] as const;
            const counts = await Promise.all(kinds.map(async (k) => {
              const { count } = await db.from("rp_ring_proofs").select("signature", { count: "exact", head: true }).eq("kind", k);
              return [k, count ?? 0] as const;
            }));
            await db.from("rp_daily_snapshots").insert({
              day,
              treasury_sol: (await c.getBalance(t.publicKey)) / SOL,
              reserve_sol: coins.reduce((s, x) => s + Number(x.reserve_sol), 0),
              holders_sol: coins.reduce((s, x) => s + Number(x.holders_sol), 0),
              creator_sol: coins.reduce((s, x) => s + Number(x.creator_sol), 0),
              fees_sol: coins.reduce((s, x) => s + Number(x.fees_total_sol), 0),
              coins: coins.length,
              ring_txs: Object.fromEntries(counts.map(([k, v]) => [k, v])),
            });
          }
        } catch (e) { log.push(`snapshot: ${(e as Error).message.slice(0, 120)}`); }

        await finish("ok", coins.length, claimed / SOL);
        return Response.json({ ok: true, claimed: claimed / SOL, actions, log });
      },
    },
  },
});
01

What this code does with money

  • The launch wallet is the pump.fun creator of every Ring coin, so creator fees land there.
  • The fee bot claims those fees, splits them into the reserve, holder and creator lanes, buys back on drawdowns, pays holders, unlocks the creator lane at its milestone and fills sealed batches.
  • Every payment it makes is written to the public records on the Proofs page, with its transaction signature.