Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
* text=auto eol=lf
2 changes: 1 addition & 1 deletion app/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Next 16 app router, React 19, Tailwind 4, wagmi 3 + viem 2, Postgres (postgres.j
- `/` list (new · active · volume · market cap) + live tape · `/launch` form · `/t/<token>` trade + fees
- `/rules` how it works · `/agents` contract call + JSON · `/llms.txt`
- `GET /api/launch/list?sort=&limit=` · `GET /api/launch/feed` · `GET /api/launch/meta/<token>`
- `POST /api/launch/meta` (metadata before launching → `{uri, token}`) · `POST /api/launch/sync?tx=` · `GET /api/health`
- `POST /api/launch/meta` (metadata before launching → `{uri, token}`) · `POST /api/launch/sync?tx=` (transaction hash required; full polling runs in the server loop) · `GET /api/health`

## How it hangs together
- `src/lib/launchpad/` — `abi.ts` (factory / locker / PoolManager Swap / StateView / Quoter /
Expand Down
46 changes: 46 additions & 0 deletions app/db/schema.sql
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
-- basebid.lol · free token launchpad on Base.
--
-- Applied by scripts/migrate.mjs (Fly release_command) against the DEDICATED
Expand Down Expand Up @@ -657,3 +657,49 @@
-- the scoring rules a season runs on (score.rulesFor): a season keeps the version it was started with, so a rule
-- added later never changes a season already running. Every season before this column scores on version 1
ALTER TABLE bb_seasons ADD COLUMN IF NOT EXISTS rules_version integer NOT NULL DEFAULT 1;
-- Canonical index recovery. Version 0 is legacy hashless history: the indexer
-- rebuilds chain facts from the deployment block, preserving authored records.
ALTER TABLE bb_launch_sync_cursor ADD COLUMN IF NOT EXISTS reorg_version integer NOT NULL DEFAULT 0;
ALTER TABLE bb_launch_sync_cursor ADD COLUMN IF NOT EXISTS reorg_generation bigint NOT NULL DEFAULT 0;
ALTER TABLE bb_launch_sync_cursor ADD COLUMN IF NOT EXISTS rebuilding_until bigint;
CREATE TABLE IF NOT EXISTS bb_launch_blocks (
chain_id integer NOT NULL,
block_number bigint NOT NULL,
block_hash text NOT NULL,
PRIMARY KEY (chain_id, block_number)
);
CREATE TABLE IF NOT EXISTS bb_launch_recovery (
chain_id integer NOT NULL,
token text NOT NULL,
tx_hash text NOT NULL,
reason text NOT NULL CHECK (reason IN ('reorg', 'rebuilding')),
created_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (chain_id, token)
);
-- Valuations belong to an exact event and placement, not to whichever live
-- quote happens to exist during recovery. Retain them separately from facts.
CREATE TABLE IF NOT EXISTS bb_launch_replay_values (
chain_id integer NOT NULL,
kind text NOT NULL CHECK (kind IN ('swap', 'fee', 'pair')),
tx_hash text NOT NULL,
log_index integer NOT NULL,
block_number bigint NOT NULL,
block_time timestamptz NOT NULL,
block_hash text,
payload jsonb NOT NULL,
usd double precision,
priced_by text,
PRIMARY KEY (chain_id, kind, tx_hash, log_index, block_number)
);
CREATE TABLE IF NOT EXISTS bb_launch_reorgs (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
chain_id integer NOT NULL,
from_block bigint NOT NULL,
old_cursor bigint NOT NULL,
observed_head bigint NOT NULL,
reason text NOT NULL,
created_at timestamptz NOT NULL DEFAULT now()
);
ALTER TABLE bb_seasons ADD COLUMN IF NOT EXISTS reorg_invalidated_at timestamptz;
ALTER TABLE bb_pair_applications ADD COLUMN IF NOT EXISTS payment_reorg boolean NOT NULL DEFAULT false;
ALTER TABLE bb_pair_burns ADD COLUMN IF NOT EXISTS valuation_pending boolean NOT NULL DEFAULT false;
146 changes: 146 additions & 0 deletions app/scripts/indexer-audit-db-checks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import * as indexer from "../src/lib/launchpad/indexer";
import { launchpad } from "../src/lib/launchpad/config";
import { systemAddressesOf, holderRebuildSql } from "../src/lib/launchpad/holder-system-addresses";
import { A, ALICE, F, L, PM, ZERO, DEAD, hash, launched, standardModel, transfer, type ChainModel } from "./reorg-db-test-model";
import type { Db } from "./reorg-db-test-db";

type Context = {
check: (label: string, run: () => Promise<unknown>) => Promise<void>;
database: (label: string) => Promise<Db>;
activate: (db: Db, model: ChainModel) => void;
indexedOld: (label: string) => Promise<{ db: Db; model: ChainModel }>;
compareOracle: (label: string, db: Db, model: ChainModel) => Promise<unknown>;
};

export async function indexerAuditDbChecks({ check, database, activate, indexedOld, compareOracle }: Context) {
await check("a collection receipt before its launch is deferred and later counted exactly once", async () => {
const db = await database("earlycollect"), model = standardModel();
activate(db, model);
const early = await indexer.applyLaunchTx("base", hash("old-fees"));
assert.equal(early.fees, 0);
assert.equal((await db`SELECT * FROM bb_launch_fee_events WHERE kind = 'collected'`).length, 0);
assert.equal((await db`SELECT * FROM bb_launches`).length, 0);
await indexer.applyLaunchTx("base", hash("common-launch"));
await indexer.pollLaunches("base");
await indexer.applyLaunchTx("base", hash("old-fees"));
const [row] = await db`SELECT fees_quote_collected::text, fees_token_collected::text FROM bb_launches WHERE token=${A}`;
assert.equal(row.fees_quote_collected, "7");
assert.equal(row.fees_token_collected, "3");
assert.equal((await db`SELECT * FROM bb_launch_fee_events WHERE kind='collected'`).length, 1);
return compareOracle("earlycollect", db, model);
});

await check("holder backfill lowers first_block after newer transfers were indexed live", async () => {
const db = await database("holderfirst"), model = standardModel();
model.events.old = [launched(), transfer(101, A, ZERO, ALICE, 50n, "early-holder", 0),
transfer(1002, A, ZERO, ALICE, 10n, "later-holder", 0)];
model.head = 1004;
activate(db, model);
await indexer.applyLaunchTx("base", hash("common-launch"));
// A known launch can still need historical holder backfill while live polling is near the tip.
await db`UPDATE bb_launch_sync_cursor SET cursor_block=1000, head_block=1004 WHERE chain_id=8453`;
await indexer.pollLaunches("base");
assert.equal(BigInt((await db`SELECT first_block FROM bb_token_holders WHERE token=${A} AND holder=${ALICE}`)[0].first_block), 1002n);
await indexer.backfillHolders("base");
const [row] = await db`SELECT first_block, balance::text FROM bb_token_holders WHERE token=${A} AND holder=${ALICE}`;
assert.equal(BigInt(row.first_block), 101n);
assert.equal(row.balance, "60");
await indexer.backfillHolders("base");
assert.deepEqual((await db`SELECT first_block, balance::text FROM bb_token_holders WHERE token=${A} AND holder=${ALICE}`)[0], row);
});

await check("individual transaction receipts recover a capped token block without skipping balances", async () => {
const db = await database("individualreceipts"), model = standardModel();
model.events.old = [launched(), transfer(100, A, ZERO, PM, 1000000n, "common-launch", 1),
transfer(101, A, PM, ALICE, 50n, "capped-transfer", 0)];
const originalBlock = model.block.bind(model), originalRequest = model.request.bind(model);
model.block = (height, branch = model.branch) => ({ ...originalBlock(height, branch),
transactions: [...new Set((model.events[branch] ?? []).filter((event) => event.height === height).map((event) => hash(event.tx)))] });
let recovered = 0;
model.request = async (method, params) => {
if (method === "eth_getLogs") {
const filter = params[0] as { address: string | string[]; fromBlock: string; toBlock: string };
const addresses = Array.isArray(filter.address) ? filter.address : [filter.address];
if (addresses.includes(A) && BigInt(filter.fromBlock) <= 101n && BigInt(filter.toBlock) >= 101n) throw Error("query returned more than 10000 results");
}
if (method === "eth_getTransactionReceipt" && params[0] === hash("capped-transfer")) recovered++;
return originalRequest(method, params);
};
activate(db, model);
await indexer.pollLaunches("base");
assert.ok(recovered > 0);
assert.equal((await db`SELECT balance::text FROM bb_token_holders WHERE token=${A} AND holder=${ALICE}`)[0].balance, "50");
model.request = originalRequest;
return compareOracle("individualreceipts", db, model);
});

await check("configured holder rebuild excludes Arc and Elysium protocol addresses and rejects missing chains", async () => {
const { db } = await indexedOld("holderrebuild");
const exclusions: Record<string, string[]> = { "8453": [...indexer.systemAddresses("base"), ZERO, DEAD] };
for (const [chain, cid] of [["arc", 5042], ["elysium", 99901]] as const) {
const cfg = { ...launchpad(chain), factory: F as `0x${string}`, locker: L as `0x${string}` };
const addresses = [cfg.v4.positionManager, cfg.v4.universalRouter, cfg.v4.poolManager].map((a) => a.toLowerCase());
exclusions[cid] = [...systemAddressesOf(cfg), ZERO, DEAD];
await db`INSERT INTO bb_launches SELECT (jsonb_populate_record(NULL::bb_launches,
to_jsonb(l) || jsonb_build_object('chain_id', ${cid}::int, 'supply', 400, 'holders', 99))).*
FROM bb_launches l WHERE chain_id=8453 AND token=${A}`;
for (const [i, holder] of [...addresses, ALICE].entries()) {
await db`INSERT INTO bb_token_transfers (chain_id,token,tx_hash,log_index,from_addr,to_addr,value,block_number,block_time)
VALUES (${cid},${A},${hash(`rebuild-${cid}-${i}`)},0,${ZERO},${holder},100,100,now())`;
}
}
// A Base-only protocol address is an ordinary address on Arc: exclusions must be keyed by chain.
await db`INSERT INTO bb_token_transfers (chain_id,token,tx_hash,log_index,from_addr,to_addr,value,block_number,block_time)
VALUES (5042,${A},${hash("cross-chain-holder")},0,${ZERO},${PM},1,100,now())`;
const template = readFileSync(new URL("./rebuild-holders.sql", import.meta.url), "utf8");
const connection = await db.reserve();
try {
await assert.rejects(connection.unsafe(holderRebuildSql(template, { "8453": exclusions[8453] })), /does not cover every stored launch chain/);
await connection`ROLLBACK`;
assert.deepEqual((await db`SELECT holders FROM bb_launches WHERE chain_id IN (5042,99901) ORDER BY chain_id`).map((r) => r.holders), [99, 99]);
const generated = holderRebuildSql(template, exclusions);
await connection.unsafe(generated);
assert.deepEqual((await db`SELECT holders FROM bb_launches WHERE chain_id IN (5042,99901) ORDER BY chain_id`).map((r) => r.holders), [2, 1]);
await connection.unsafe(generated);
assert.deepEqual((await db`SELECT holders FROM bb_launches WHERE chain_id IN (5042,99901) ORDER BY chain_id`).map((r) => r.holders), [2, 1]);
} finally {
await connection`ROLLBACK`.catch(() => {});
connection.release();
}
});

await check("holder rebuild waits before transfer locks so an active index writer can complete", async () => {
const { db } = await indexedOld("holderlocks");
const generated = holderRebuildSql(readFileSync(new URL("./rebuild-holders.sql", import.meta.url), "utf8"),
{ "8453": [...indexer.systemAddresses("base"), ZERO, DEAD] });
const writer = await db.reserve(), rebuilder = await db.reserve();
let rebuilding: Promise<unknown> | undefined;
try {
await writer`BEGIN`;
await writer`LOCK TABLE bb_launch_swaps, bb_launch_fee_events, bb_launches IN ROW EXCLUSIVE MODE`;
const [{ pid }] = await rebuilder`SELECT pg_backend_pid() AS pid`;
rebuilding = Promise.resolve(rebuilder.unsafe(generated));
// Observe the real PostgreSQL lock wait rather than guessing from a fixed delay.
const until = Date.now() + 3_000;
while (true) {
const waiting = await db`SELECT 1 FROM pg_locks WHERE pid=${pid} AND relation='bb_launches'::regclass AND NOT granted`;
if (waiting.length) break;
assert.ok(Date.now() < until, "rebuild must wait on launches");
await new Promise((resolve) => setTimeout(resolve, 10));
}
assert.equal((await db`SELECT 1 FROM pg_locks WHERE pid=${pid} AND relation='bb_token_transfers'::regclass AND granted`).length, 0);
await writer`INSERT INTO bb_token_transfers (chain_id,token,tx_hash,log_index,from_addr,to_addr,value,block_number,block_time)
VALUES (8453,${A},${hash("lock-order-transfer")},0,${ZERO},${ALICE},1,102,now())`;
await writer`COMMIT`;
await rebuilding;
assert.equal((await db`SELECT balance::text FROM bb_token_holders WHERE token=${A} AND holder=${ALICE}`)[0].balance, "51");
} finally {
await writer`ROLLBACK`.catch(() => {});
await rebuilding?.catch(() => {});
await rebuilder`ROLLBACK`.catch(() => {});
writer.release(); rebuilder.release();
}
});
}
15 changes: 15 additions & 0 deletions app/scripts/pair-db-test-chain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// Opt-in integration-test adapter: real EOA signature checks, synthetic prices, no network transport.
import { verifyMessage } from "viem";

export function publicClient() {
return {
verifyMessage,
readContract: async ({ functionName }: { functionName: string }) => {
if (functionName === "latestRoundData") return [1n, 2000_00000000n, 0n, BigInt(Math.floor(Date.now() / 1000)), 1n];
if (functionName === "getSlot0") return [10_000n * 2n ** 96n, 0n, 0n, 0n];
if (functionName === "observe") return [[0n, 184216n * 1800n], []];
throw new Error(`unexpected synthetic contract read: ${functionName}`);
},
};
}
export function b20Client(): never { throw new Error("external RPC disabled in pair tests"); }
13 changes: 13 additions & 0 deletions app/scripts/posts-db-test-chain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// The integration tests use real signatures, replacing only the external RPC.
import type { Address, Hex } from "viem";

type Client = {
readContract: () => Promise<bigint>;
verifyMessage: (args: { address: Address; message: string; signature: Hex }) => Promise<boolean>;
};
let client: Client | null = null;
export function setPostsTestClient(value: Client) { client = value; }
export function publicClient() {
if (!client) throw new Error("posts integration-test client not configured");
return client;
}
8 changes: 8 additions & 0 deletions app/scripts/posts-db-test-db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Explicit integration-test adapter. Never imported by the application build.
import type { Db } from "../src/lib/db.ts";

let connection: Db | null = null;

export function setPostsTestDb(value: Db | null) { connection = value; }
export function maybeDb(): Db | null { return connection; }
export type { Db };
33 changes: 17 additions & 16 deletions app/scripts/rebuild-holders.sql
Original file line number Diff line number Diff line change
@@ -1,11 +1,22 @@
-- Rebuild bb_token_holders from bb_token_transfers (the deduped source of truth) and refresh the
-- per-launch holders counters. Idempotent; safe to run any time (a few thousand rows).
-- Usage: fly ssh console -a basebid-db -C "sh -c 'PGPASSWORD=$OPERATOR_PASSWORD psql -h localhost -p 5433 -U postgres -d basebid -f /tmp/rebuild-holders.sql'"
-- per-launch holders counters. Generate the public per-chain config with scripts/rebuild-holders.ts first.
-- Review the generated file and run with psql -v ON_ERROR_STOP=1; running this template alone fails closed.
BEGIN;
-- serialize against the indexer: transfers cannot be ingested while balances are recomputed
SET LOCAL lock_timeout = '5s';
-- Match canonical writer ordering: acquire launches before requesting any transfer/holder locks.
LOCK TABLE bb_launches IN EXCLUSIVE MODE;
CREATE TEMP TABLE holder_rebuild_exclusions ON COMMIT DROP AS
SELECT entry.key::integer AS chain_id, lower(address.value) AS address
FROM jsonb_each(current_setting('openlaunch.holder_exclusions')::jsonb) entry
CROSS JOIN LATERAL jsonb_array_elements_text(entry.value) address(value);
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM bb_launches l WHERE NOT EXISTS
(SELECT 1 FROM holder_rebuild_exclusions e WHERE e.chain_id = l.chain_id)) THEN
RAISE EXCEPTION 'holder rebuild configuration does not cover every stored launch chain';
END IF;
END $$;
LOCK TABLE bb_token_transfers IN SHARE MODE;
LOCK TABLE bb_token_holders IN EXCLUSIVE MODE;
LOCK TABLE bb_launches IN EXCLUSIVE MODE;
WITH legs AS (
SELECT chain_id, token, from_addr AS holder, -value AS d, block_number FROM bb_token_transfers WHERE from_addr <> '0x0000000000000000000000000000000000000000'
UNION ALL
Expand All @@ -20,21 +31,11 @@
-- rows with no transfer legs left (should not exist) → zero them rather than delete, keeps history
UPDATE bb_token_holders h SET balance = 0
WHERE NOT EXISTS (SELECT 1 FROM bb_token_transfers t WHERE t.chain_id = h.chain_id AND t.token = h.token AND (t.from_addr = h.holder OR t.to_addr = h.holder));
-- holders counter: wallets with balance > 0, excluding protocol + burn addresses on either chain
-- One chain-aware exclusion set, shared with the live indexer (public config generated above).
UPDATE bb_launches l SET holders = COALESCE(c.n, 0)
FROM (SELECT l2.chain_id, l2.token,
(SELECT count(*) FROM bb_token_holders h WHERE h.chain_id = l2.chain_id AND h.token = l2.token AND h.balance > 0
AND h.holder NOT IN ('0x0000000000000000000000000000000000000000',
'0x000000000000000000000000000000000000dead',
'0x000000000022d473030f116ddee9f6b43ac78ba3',
'0x498581ff718922c3f8e6a244956af099b2652b2b',
'0x58daec3116aae6d93017baaea7749052e8a04fa7',
'0x6ff5693b99212da76ad316178a184ab56d299b43',
'0x7c5f5a4bbd8fd63184577525326123b519429bdc',
'0x815542e8b392389a1389e22e588e4b62a67ade72',
'0x8366a39cc670b4001a1121b8f6a443a643e40951',
'0x8876789976decbfcbbbe364623c63652db8c0904',
'0xcd1680d26922fcd9cabfbb8a56ba40c333fd842a')) AS n
AND NOT EXISTS (SELECT 1 FROM holder_rebuild_exclusions e WHERE e.chain_id = h.chain_id AND e.address = h.holder)) AS n
FROM bb_launches l2) c
WHERE l.chain_id = c.chain_id AND l.token = c.token;
COMMIT;
Expand Down
16 changes: 16 additions & 0 deletions app/scripts/rebuild-holders.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/**
* From app/, with the same NEXT_PUBLIC_LAUNCH_FACTORY* and NEXT_PUBLIC_LAUNCH_LOCKER* configuration as the site:
* npx tsx scripts/rebuild-holders.ts > rebuild-holders.generated.sql
* Review the generated SQL, then run it with psql -v ON_ERROR_STOP=1 on the intended database.
* This command writes SQL to stdout only. It never connects to a database or reads private credentials.
*/
import { readFileSync } from "node:fs";
import { holderExclusionsByChain, holderRebuildSql } from "../src/lib/launchpad/holder-system-addresses";

try {
const sql = readFileSync(new URL("./rebuild-holders.sql", import.meta.url), "utf8");
process.stdout.write(holderRebuildSql(sql, holderExclusionsByChain()));
} catch (error) {
console.error(error instanceof Error ? error.message : "could not generate holder rebuild SQL");
process.exitCode = 1;
}
11 changes: 11 additions & 0 deletions app/scripts/reorg-db-test-chain.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Test-only RPC adapter: all reads use the synthetic viem transport.
export * from "../src/lib/chainPublic";
import type { ChainModel } from "./reorg-db-test-model";
let active: ReturnType<ChainModel["client"]> | null = null;
export function setClient(value: ReturnType<ChainModel["client"]>) { active = value; }
export function publicClient() {
if (!active)
throw new Error("reorg test chain not configured");
return active;
}
export function b20Client() { throw new Error("External B20 RPC disabled in reorg tests"); }
13 changes: 13 additions & 0 deletions app/scripts/reorg-db-test-db.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// Test-only DB adapter. The opted-in suite owns random schemas on a loopback DB.
export { errMessage, uniqueViolation } from "../src/lib/pg";
import type { Db } from "../src/lib/db";
let active: Db | null = null;
export function setDb(value: Db | null) { active = value; }
export function maybeDb() { return active; }
export function db() {
if (!active)
throw new Error("reorg test database not configured");
return active;
}
export function dbConfigured() { return active !== null; }
export type { Db };
Loading
Loading