import { Connection, PublicKey, SystemProgram } from '@solana/web3.js'; import { base58 } from '@metaplex-foundation/umi/serializers'; import { checkDeployment, configPda, DEVNET_RPC, grantPda, V1_REGISTRY, V2_REGISTRY, V3_REGISTRY, vaultPda } from './registry.mjs'; const profiles = [V1_REGISTRY, V2_REGISTRY, V3_REGISTRY]; const legacyPriceAccount = '7UVimffxr9ow1uXYxsr4LHAcV58mLzhmwaeKvJ1pjLiE'; // Finalized first deployments published in protocol/README.md and devnet-v2-release.json. const deploymentSignatures = { 1:'3eCHdec79tqTeM7ZAvcDW45c97cyKSJxUMCDdJKZ2Bog5uNSqnzo3CxeyW6Y5VQk4kfqTKnVe6eswtqVQPXP2dp9', 2:'4cDdqPTwRnmbJaLh5DnJg8frRjZUwbYg9ZSf1x8fUTRfgLg65CLYvRvmB6waDw5z259robiMLvHNDDnty2TvdyHW', 3:V3_REGISTRY.deploymentSignature, }; const system = SystemProgram.programId.toBase58(); const prefix = '/api/admin/analytics'; const dayMs = 86400000; const pageSize = 35; const receiptLimit = 8; const rateWarning = 'The Devnet provider limited this sync. Verified receipts have been saved.'; const rpcWarning = 'The Devnet provider could not complete this sync. Previously verified receipts are retained.'; const schemas = new WeakMap(); const address = value => value?.toBase58?.() ?? value; const iso = value => value == null ? null : new Date(value).toISOString(); const check = value => { if (!value) throw Error('Invalid or incomplete finalized receipt.'); }; function signatureOK(value) { return typeof value === 'string' && /^[1-9A-HJ-NP-Za-km-z]{64,88}$/.test(value) && base58.serialize(value).length === 64; } function grantPayment(children, keys, max, exact = false) { const [vault, state, grant, , treasury] = keys; check(treasury !== state && treasury !== grant && max <= 1000000000n); let payment = 0n; for (const [index,ix] of children.entries()) { // This release makes only direct System CPIs. Any other tree is ambiguous. check(address(ix.programId) === system); const type = ix.parsed?.type, info = ix.parsed?.info; if (type === 'allocate' || type === 'assign') { check(info?.account === state || info?.account === grant); continue; } check(type === 'transfer' && info?.source === vault && Number.isSafeInteger(info.lamports) && info.lamports > 0); if (info.destination === state || info.destination === grant) continue; check(info.destination === treasury && treasury !== vault && index === 0 && payment === 0n && BigInt(info.lamports) <= max); payment = BigInt(info.lamports); } if (exact) check(payment === max); return payment.toString(); } // Rebuild the CPI call tree. An inner transfer at the same height as a registry // invocation is a sibling and must never be attributed to that invocation. function registryCalls(message, inner, programId) { check(Array.isArray(inner)); const groups = new Map(); for (const group of inner) { check(Number.isInteger(group.index) && group.index >= 0 && group.index < message.instructions.length && !groups.has(group.index) && Array.isArray(group.instructions)); groups.set(group.index,group.instructions); } const calls = []; let ordinal = 0; message.instructions.forEach((ix,index) => { const children = groups.get(index) ?? []; const root = {ix,ordinal:ordinal++,children:[],height:1}; const direct = address(ix.programId) === programId; if (direct) calls.push(root); const nested = children.some(child => address(child.programId) === programId); if (!direct && !nested) { ordinal += children.length; return; } const stack = [root]; for (const child of children) { // A direct call to the pinned registry can only call the native System // Program, which itself makes no CPIs. Older receipts can omit heights. const height = child.stackHeight ?? (direct && !nested && address(child.programId) === system ? 2 : null); check(Number.isInteger(height) && height >= 2 && height <= stack.length+1); stack.length = height-1; stack.at(-1).children.push(child); const node = {ix:child,ordinal:ordinal++,children:[],height}; if (address(child.programId) === programId) calls.push(node); stack.push(node); } }); return calls; } /** Decode one pinned program's top-level and nested instructions in a finalized RPC receipt. */ export function decodeAnalyticsReceipt(tx, row, profile, verifiedSinceSlot) { check(profiles.includes(profile) && signatureOK(row.signature) && tx?.transaction?.signatures?.[0] === row.signature); check(Number.isSafeInteger(tx.slot) && tx.slot === Number(row.slot) && tx.meta && 'err' in tx.meta); check((tx.meta.err !== null) === row.failed_hint); const message = tx.transaction.message; check(Array.isArray(message?.accountKeys) && Array.isArray(message.instructions)); const calls = registryCalls(message,tx.meta.innerInstructions,profile.programId); const blockTime = tx.blockTime == null ? null : tx.blockTime; check(blockTime === null || (Number.isSafeInteger(blockTime) && blockTime > 0 && blockTime < 253402300800)); const actions = []; let failed = false; const program = new PublicKey(profile.programId); for (const {ix,ordinal,height,children} of calls) { check(tx.slot >= verifiedSinceSlot && typeof ix.data === 'string'); const data = Buffer.from(base58.serialize(ix.data)), op = data[0]; const grant = op === (profile.version === 1 ? 0 : profile.version === 2 ? 3 : 6); if (tx.meta.err !== null) { if (grant || op === 1 || op === 2) failed = true; continue; } if (profile.version >= 2 && (op === 4 || op === 5)) continue; check(grant || op === 1 || op === 2); const keys = ix.accounts.map(address), vault = keys[0]; const owner = message.accountKeys.find(key => address(key.pubkey) === vault); check(owner && (owner.signer === true || (height > 1 && !PublicKey.isOnCurve(new PublicKey(vault).toBytes())))); let delegate = null, recipient = null, feeLamports = '0'; if (grant) { const paidVersion = profile.version >= 2, fixedSol = profile.version === 3; check(data.length === (fixedSol ? 122 : paidVersion ? 130 : 106) && keys.length === (fixedSol ? 6 : paidVersion ? 7 : 4) && keys[3] === system); check(data[1] <= 1); delegate = new PublicKey(data.subarray(2,34)).toBase58(); const asset = new PublicKey(data.subarray(66,98)).toBase58(); check(delegate !== vault && delegate !== system && (asset === system) === (data[1] === 0)); check(keys[1] === vaultPda(program,vault).toBase58() && keys[2] === grantPda(program,vault,delegate, data.subarray(34,66),data[1] === 0 ? 'wallet' : 'asset',asset).toBase58()); if (paidVersion) { check(fixedSol ? keys[5] === configPda(program).toBase58() : keys[5] === legacyPriceAccount && keys[6] === configPda(program).toBase58()); feeLamports = grantPayment(children,keys,data.readBigUInt64LE(106),fixedSol); if (feeLamports !== '0') recipient = new PublicKey(keys[4]).toBase58(); } } else { check(data.length === 1 && keys.length === 2); if (op === 2) check(keys[1] === vaultPda(program,vault).toBase58()); } actions.push({ordinal,kind:grant ? 'grant' : op === 1 ? 'revoke' : 'revoke_all',vault,delegate,recipient,feeLamports}); } return {actions,failed,blockTime}; } async function transaction(pool, run, readOnly = false) { const db = await pool.connect(); let discard = false; try { await db.query(readOnly ? 'BEGIN ISOLATION LEVEL REPEATABLE READ READ ONLY' : 'BEGIN'); await db.query("SET LOCAL statement_timeout = '5s'"); const result = await run(db); await db.query('COMMIT'); return result; } catch (error) { try { await db.query('ROLLBACK'); } catch { discard = true; } throw error; } finally { db.release(discard); } } async function schema(pool) { if (!schemas.has(pool)) schemas.set(pool, transaction(pool, async db => { await db.query('SELECT pg_advisory_xact_lock(1936485476, 104929)'); await db.query(` CREATE TABLE IF NOT EXISTS solbound_analytics_scan ( version smallint PRIMARY KEY, cursor jsonb NOT NULL DEFAULT '{}', synced_at timestamptz, issue boolean NOT NULL DEFAULT false); CREATE TABLE IF NOT EXISTS solbound_analytics_sync ( singleton boolean PRIMARY KEY CHECK(singleton), next_sync_at timestamptz, warning text); INSERT INTO solbound_analytics_sync(singleton) VALUES(true) ON CONFLICT DO NOTHING; CREATE TABLE IF NOT EXISTS solbound_analytics_receipt ( version smallint NOT NULL, signature text NOT NULL, slot bigint NOT NULL, failed_hint boolean NOT NULL, status text NOT NULL DEFAULT 'pending', retry_at timestamptz, block_time timestamptz, PRIMARY KEY(version,signature)); CREATE INDEX IF NOT EXISTS solbound_analytics_queue ON solbound_analytics_receipt(status,retry_at,slot); CREATE TABLE IF NOT EXISTS solbound_analytics_action ( version smallint NOT NULL, signature text NOT NULL, ordinal int NOT NULL, kind text NOT NULL, vault text NOT NULL, delegate text, recipient text, lamports bigint NOT NULL CHECK(lamports >= 0), PRIMARY KEY(version,signature,ordinal), FOREIGN KEY(version,signature) REFERENCES solbound_analytics_receipt); INSERT INTO solbound_analytics_scan(version) VALUES(1),(2),(3) ON CONFLICT DO NOTHING`); }).catch(error => { schemas.delete(pool); throw error; })); return schemas.get(pool); } // Page towards the previous head and away from the oldest cursor independently. // This avoids losing new signatures during a long initial scan or a burst of writes. export async function discoverAnalyticsPage(previous, list, store, deployment) { const state = {...previous}; async function page(before) { const rows = await list(before); check(Array.isArray(rows) && rows.length <= pageSize); let lastSlot = Infinity; const seen = new Set(); for (const row of rows) { check(signatureOK(row.signature) && row.signature !== before && !seen.has(row.signature) && Number.isSafeInteger(row.slot) && row.slot >= 0 && row.slot <= lastSlot && 'err' in row && (row.confirmationStatus == null || row.confirmationStatus === 'finalized')); seen.add(row.signature); if (row.signature === deployment) state.seenDeployment = true; lastSlot = row.slot; } await store(rows); return rows; } if (!state.head) { const rows = await page(); state.head = rows[0]?.signature ?? null; state.oldest = rows.at(-1)?.signature ?? null; state.historyScanned = !rows.length || state.seenDeployment === true; return state; } const rows = await page(state.forwardBefore || undefined); state.newHead ||= rows[0]?.signature; if (rows.some(r => r.signature === state.head) || !rows.length) { if (!rows.length) state.gap = true; state.head = state.newHead || state.head; delete state.newHead; delete state.forwardBefore; } else { state.forwardBefore = rows.at(-1).signature; } if (!state.historyScanned) { const older = await page(state.oldest); if (!older.length || state.seenDeployment) state.historyScanned = true; else state.oldest = older.at(-1).signature; } return state; } export function analyticsRetryAt(header, now = Date.now()) { const value = header?.trim(); const deadline = /^\d+$/.test(value ?? '') ? now + Number(value)*1000 : Date.parse(value); return Number.isFinite(deadline) && deadline >= now && deadline < Date.UTC(9999,0,1) ? deadline : now + 60000; } function productionSource(profile, signal, rateLimited) { const program = new PublicKey(profile.programId); const connection = new Connection(DEVNET_RPC,{commitment:'finalized',disableRetryOnRateLimit:true, fetch:async (url,init) => { const response = await fetch(url,{...init,redirect:'error',signal:AbortSignal.any([signal,AbortSignal.timeout(4500)])}); if (response.status === 429) rateLimited(analyticsRetryAt(response.headers.get('retry-after'))); return response; }}); return { async verify() { // Read the loader's deployment slot from the exact account whose ELF checkDeployment hashes. let slot; await checkDeployment({program,connection:{ getGenesisHash:() => connection.getGenesisHash(), getAccountInfo:async (key,commitment) => { const info = await connection.getAccountInfo(key,commitment); if (!key.equals(program) && info?.data.length >= 12) slot = Number(info.data.readBigUInt64LE(4)); return info; }, }}); check(Number.isSafeInteger(slot) && slot >= 0); return slot; }, list:before => connection.getSignaturesForAddress(program,{before,limit:pageSize},'finalized'), receipt:signature => connection.getParsedTransaction(signature,{commitment:'finalized',maxSupportedTransactionVersion:0}), }; } async function storePage(db, version, rows) { if (!rows.length) return; await db.query(`INSERT INTO solbound_analytics_receipt(version,signature,slot,failed_hint) SELECT $1, * FROM unnest($2::text[], $3::bigint[], $4::boolean[]) ON CONFLICT DO NOTHING`, [version,rows.map(r=>r.signature),rows.map(r=>r.slot),rows.map(r=>r.err !== null)]); } /** Context/source dependencies can be injected by the local PostgreSQL integration test. */ export async function syncAdminAnalytics(pool, sourceFactory = productionSource) { await schema(pool); const signal = AbortSignal.timeout(15000); return transaction(pool, async db => { const lock = await db.query('SELECT pg_try_advisory_xact_lock(1936485476, 104930) AS acquired'); if (!lock.rows[0].acquired) return 'busy'; const gate = await db.query('SELECT next_sync_at > clock_timestamp() AS cooling FROM solbound_analytics_sync WHERE singleton'); if (gate.rows[0].cooling) return 'cooldown'; const available = new Map(), issues = new Set(); let retryAt = null; const rateLimited = deadline => { retryAt = Math.max(retryAt ?? 0, deadline); }; for (const profile of profiles) { if (retryAt !== null) { issues.add(profile.version); continue; } const source = sourceFactory(profile,signal,rateLimited); const state = (await db.query('SELECT cursor FROM solbound_analytics_scan WHERE version=$1',[profile.version])).rows[0].cursor; let cursor; try { const since = await source.verify(); cursor = await discoverAnalyticsPage(state,source.list,rows => storePage(db,profile.version,rows),deploymentSignatures[profile.version]); available.set(profile.version,{source,since,profile}); } catch { issues.add(profile.version); continue; } await db.query('UPDATE solbound_analytics_scan SET cursor=$2, synced_at=CURRENT_TIMESTAMP WHERE version=$1',[profile.version,cursor]); } const work = await db.query(`SELECT * FROM ( SELECT *, row_number() OVER(PARTITION BY version ORDER BY COALESCE(retry_at, '-infinity'),slot DESC,signature) AS n FROM solbound_analytics_receipt WHERE version = ANY($1::smallint[]) AND status IN ('pending','unavailable') AND (retry_at IS NULL OR retry_at <= CURRENT_TIMESTAMP)) q ORDER BY n,version DESC LIMIT $2`, [[...available.keys()],receiptLimit]); for (const row of work.rows) { if (signal.aborted || retryAt !== null) break; const version = row.version; if (issues.has(version)) continue; const {source,since,profile} = available.get(version); let tx; try { tx = await source.receipt(row.signature); } catch (error) { // New transaction formats remain an explicit coverage gap. A transient // transport error backs off this receipt so later records can progress. if (error?.code === -32015) tx = null; else { await db.query(`UPDATE solbound_analytics_receipt SET retry_at=CURRENT_TIMESTAMP+interval '30 seconds' WHERE version=$1 AND signature=$2`,[version,row.signature]); issues.add(version); continue; } } let decoded; try { decoded = decodeAnalyticsReceipt(tx,row,profile,since); } catch { await db.query(`UPDATE solbound_analytics_receipt SET status='unavailable',retry_at=CURRENT_TIMESTAMP+interval '1 hour' WHERE version=$1 AND signature=$2`,[version,row.signature]); continue; } if (decoded.actions.length) await db.query(`INSERT INTO solbound_analytics_action (version,signature,ordinal,kind,vault,delegate,recipient,lamports) SELECT $1,$2,ordinal,kind,vault,delegate,recipient,"feeLamports" FROM jsonb_to_recordset($3) AS a(ordinal int, kind text, vault text, delegate text, recipient text, "feeLamports" bigint) ON CONFLICT DO NOTHING`,[version,row.signature,JSON.stringify(decoded.actions)]); await db.query(`UPDATE solbound_analytics_receipt SET status=$3,block_time=to_timestamp($4),retry_at=NULL WHERE version=$1 AND signature=$2`,[version,row.signature,decoded.failed?'failed':'done',decoded.blockTime]); } await db.query('UPDATE solbound_analytics_scan SET issue=(version=ANY($1::smallint[]))',[[...issues]]); await db.query(`UPDATE solbound_analytics_sync SET next_sync_at=greatest(clock_timestamp()+interval '15 seconds', $1::timestamptz),warning=$2 WHERE singleton`, [iso(retryAt),retryAt !== null ? rateWarning : issues.size ? rpcWarning : null]); return issues.size ? 'unavailable' : 'updated'; }); } const counts = `COALESCE(sum(lamports),0)::text AS "feeLamports", count(*) FILTER (WHERE kind='grant')::int AS "grantWrites", count(*) FILTER (WHERE lamports>0)::int AS "paidActions", count(*) FILTER (WHERE kind IN ('revoke','revoke_all'))::int AS revocations`; export async function readAdminAnalytics(pool, now = new Date()) { await schema(pool); return transaction(pool, async db => { const scans = (await db.query('SELECT * FROM solbound_analytics_scan ORDER BY version')).rows; const gate = (await db.query('SELECT next_sync_at,warning FROM solbound_analytics_sync WHERE singleton')).rows[0]; const q = (await db.query(`SELECT count(DISTINCT signature)::int AS discovered, count(DISTINCT signature) FILTER(WHERE status='pending')::int AS pending, count(DISTINCT signature) FILTER(WHERE status='unavailable')::int AS unavailable, count(*) FILTER(WHERE status IN ('done','failed'))::int AS decoded, count(DISTINCT signature) FILTER(WHERE status='failed')::int AS failed FROM solbound_analytics_receipt`)).rows[0]; const registries = scans.map(s => ({version:s.version,historyScanned:s.cursor.seenDeployment === true, lastSyncedAt:iso(s.synced_at),headCaughtUp:Boolean(s.synced_at && !s.issue && !s.cursor.forwardBefore)})); const checked = scans.map(s=>iso(s.synced_at)).filter(Boolean).sort(); const status = !checked.length ? 'not_started' : q.unavailable || q.pending || scans.some(s=>s.issue || s.cursor.gap) || registries.some(r=>!r.headCaughtUp || !r.historyScanned) ? 'partial' : 'caught_up'; const totals = q.decoded || status === 'caught_up' ? {...(await db.query(`SELECT ${counts}, (count(DISTINCT vault) FILTER(WHERE kind='grant'))::int AS "uniqueVaults", count(DISTINCT delegate)::int AS "uniqueDelegates" FROM solbound_analytics_action`)).rows[0],failedTransactions:q.failed} : null; const recent = (await db.query(`SELECT a.signature,a.version,a.kind,a.vault,a.delegate,a.recipient,a.lamports::text AS "feeLamports", r.block_time AS "blockTime" FROM solbound_analytics_action a JOIN solbound_analytics_receipt r USING(version,signature) ORDER BY r.slot DESC,a.signature,a.ordinal DESC LIMIT 30`)).rows; const recipients = (await db.query(`SELECT recipient AS address,sum(lamports)::text AS "feeLamports",count(*)::int AS "paidActions" FROM solbound_analytics_action WHERE lamports>0 GROUP BY recipient ORDER BY sum(lamports) DESC,recipient LIMIT 20`)).rows; const today = now.toISOString().slice(0,10); const first = new Date(Date.parse(today)-29*dayMs).toISOString().slice(0,10); const bounds = [first+'T00:00:00Z',new Date(Date.parse(today)+dayMs).toISOString()]; const byDay = (await db.query(`SELECT to_char(block_time AT TIME ZONE 'UTC','YYYY-MM-DD') AS date,${counts} FROM solbound_analytics_action JOIN solbound_analytics_receipt USING(version,signature) WHERE block_time >= $1 AND block_time < $2 GROUP BY 1`,bounds)).rows; const failures = (await db.query(`SELECT to_char(block_time AT TIME ZONE 'UTC','YYYY-MM-DD') AS date, count(DISTINCT signature)::int AS failed FROM solbound_analytics_receipt WHERE status='failed' AND block_time >= $1 AND block_time < $2 GROUP BY 1`,bounds)).rows; const daily = Array.from({length:30},(_,i)=>{ const date = new Date(Date.parse(first)+i*dayMs).toISOString().slice(0,10); return {date,feeLamports:'0',grantWrites:0,paidActions:0,revocations:0,...byDay.find(d=>d.date===date), failedTransactions:failures.find(d=>d.date===date)?.failed ?? 0}; }); const note = 'Totals sum actual SOL service transfers in verified finalized Devnet receipts across v1, legacy USD-priced v2 and fixed-SOL v3. No historical USD conversion is estimated. ' + 'A complete scan reaches all recorded deployments. Missing receipts or call traces limit coverage. Actions without a block time appear only in totals.'; return {network:'devnet',asOf:now.toISOString(),coverage:{status,lastSyncedAt:checked.length === profiles.length ? checked[0] : null, nextSyncAt:iso(gate.next_sync_at),syncWarning:gate.warning, discoveredTransactions:q.discovered,pendingTransactions:q.pending,unavailableTransactions:q.unavailable,registries,note}, totals,daily,recipients,recent:recent.map(e=>({...e,blockTime:iso(e.blockTime)}))}; },true); } export async function handleAdminAnalytics(request,{path,body,database,sourceFactory}) { const json = (value,status=200,headers={})=>Response.json(value,{status,headers:{ 'Cache-Control':'private, no-store','X-Content-Type-Options':'nosniff',...headers}}); try { const sync = path === prefix + '/sync' && request.method === 'POST'; if (sync) { if (!body || typeof body!=='object' || Array.isArray(body) || Object.keys(body).length) return json({error:'Send an empty JSON object.'},400); const result = await syncAdminAnalytics(database,sourceFactory); if (result === 'busy') return json({error:'Another sync is already running.'},409); } else if (path !== prefix || request.method !== 'GET') return json({error:'Not found.'},404); const snapshot = await readAdminAnalytics(database); if (sync && snapshot.coverage.status === 'not_started' && snapshot.coverage.syncWarning) { const seconds = Math.max(1,Math.ceil((Date.parse(snapshot.coverage.nextSyncAt)-Date.now())/1000)); return json({error:'Devnet history is temporarily unavailable.'},503,{'Retry-After':String(seconds)}); } return json(snapshot); } catch { return json({error:'Analytics are temporarily unavailable.'},503); } }