import assert from 'node:assert/strict'; import {createRequire} from 'node:module'; import {resolve} from 'node:path'; import {readFile} from 'node:fs/promises'; import test from 'node:test'; import {Pool} from 'pg'; import {Keypair,PublicKey,SystemProgram} from '@solana/web3.js'; import {base58} from '@metaplex-foundation/umi/serializers'; import {analyticsRetryAt,decodeAnalyticsReceipt,discoverAnalyticsPage,handleAdminAnalytics,readAdminAnalytics,syncAdminAnalytics} from '../lib/admin-analytics.mjs'; import {V1_REGISTRY,V2_REGISTRY,V3_REGISTRY,createGrantIx} from '../lib/registry.mjs'; const key = n => Keypair.fromSeed(Buffer.alloc(32,n)).publicKey.toBase58(); const signature = n => base58.deserialize(Buffer.alloc(64,n))[0]; const system = SystemProgram.programId.toBase58(); const owner = key(1), delegate = key(2), treasury = key(3), parent = key(4); const transfer = (destination,lamports,stackHeight=2,source=owner) => ({ programId:system, stackHeight, parsed:{type:'transfer',info:{source,destination,lamports}}, }); function fixture({vault=owner, signed=true, nested=false, fee=231, cap=250, profile=V2_REGISTRY}={}) { const ix = createGrantIx(new PublicKey(profile.programId),{owner:vault,delegate,scope:'wallet',expiresAt:'2030-01-01T00:00:00Z'}, Buffer.alloc(32,13),{serviceTreasury:treasury,serviceMaxLamports:cap,serviceFeeLamports:cap,feeMode:'fixedSOL',quoteExpiresAt:'2030-01-01T00:00:00Z',configVersion:'1'}); const accounts = ix.keys.map(k=>k.pubkey.toBase58()); const grant = {programId:profile.programId,accounts,data:base58.deserialize(ix.data)[0],stackHeight:nested?2:1}; const children = [transfer(accounts[1],10000,nested?3:2,vault)]; if (fee) children.unshift(transfer(treasury,fee,nested?3:2,vault)); const instructions = nested ? [{programId:parent}] : [grant]; const inner = nested ? [transfer(treasury,9999),grant,...children,transfer(treasury,7777)] : children; return {slot:100,blockTime:1780000000,transaction:{signatures:[signature(1)],message:{accountKeys:[{pubkey:vault,signer:signed}],instructions}}, meta:{err:null,fee:5000,innerInstructions:[{index:0,instructions:inner}]}}; } const row = tx => ({signature:tx.transaction.signatures[0],slot:tx.slot,failed_hint:tx.meta.err!==null}); const decode = tx => decodeAnalyticsReceipt(tx,row(tx),V2_REGISTRY,50); const decodeV3 = tx => decodeAnalyticsReceipt(tx,row(tx),V3_REGISTRY,50); test('v3 credits exactly the fixed SOL service transfer, with no oracle account or USD conversion',()=>{ for(const fee of [0,1,32_000_000,1_000_000_000]) { const tx=fixture({profile:V3_REGISTRY,fee,cap:fee}); const ix=tx.transaction.message.instructions[0]; assert.equal(ix.accounts.length,6); assert.equal(base58.serialize(ix.data).length,122); assert.equal(decodeV3(tx).actions[0].feeLamports,String(fee)); } for(const fee of [0,31_999_999,32_000_001]) { assert.throws(()=>decodeV3(fixture({profile:V3_REGISTRY,fee,cap:32_000_000}))); } const tx=fixture({profile:V3_REGISTRY,fee:32_000_000,cap:32_000_000,nested:true}); assert.equal(decodeV3(tx).actions[0].feeLamports,'32000000'); for(const alter of [ t=>{t.transaction.message.instructions[0].accounts[5]=parent;}, t=>{t.transaction.message.instructions[0].accounts.push(treasury);}, t=>{const ix=t.transaction.message.instructions[0],data=Buffer.from(base58.serialize(ix.data));data[0]=3;ix.data=base58.deserialize(data)[0];}, t=>{const ix=t.transaction.message.instructions[0],data=Buffer.from(base58.serialize(ix.data));data.writeBigUInt64LE(1_000_000_001n,106);ix.data=base58.deserialize(data)[0];}, ]) { const altered=fixture({profile:V3_REGISTRY,fee:32_000_000,cap:32_000_000});alter(altered); assert.throws(()=>decodeV3(altered)); } }); test('provider backoff accepts Retry-After seconds and HTTP dates and defaults to one minute',()=>{ const now=Date.UTC(2026,10,10); assert.equal(analyticsRetryAt('90',now),now+90000); assert.equal(analyticsRetryAt(new Date(now+300000).toUTCString(),now),now+300000); for(const invalid of [null,'not a time','-1','9999999999999999999999'])assert.equal(analyticsRetryAt(invalid,now),now+60000); }); test('counts only the completed service transfer, excludes rent, donations, failed grants and free promotions',()=>{ const tx=fixture(); tx.transaction.message.instructions.push(transfer(treasury,7500,1)); const [action]=decode(tx).actions; assert.deepEqual(action,{ordinal:0,kind:'grant',vault:owner,delegate,recipient:treasury,feeLamports:'231'}); const free=decode(fixture({fee:0,cap:0})).actions[0]; assert.equal(free.recipient,null);assert.equal(free.feeLamports,'0'); tx.meta.err={InstructionError:[0,'Custom']}; assert.deepEqual(decode(tx),{actions:[],failed:true,blockTime:1780000000}); }); test('nested payments exclude caller transfers and honor a PDA authorized by invoke_signed',()=>{ const vault=PublicKey.findProgramAddressSync([Buffer.from('vault')],new PublicKey(parent))[0].toBase58(); const tx=fixture({vault,signed:false,nested:true}); assert.equal(decode(tx).actions[0].feeLamports,'231'); const second=fixture(); tx.transaction.message.instructions.push(second.transaction.message.instructions[0]); tx.transaction.message.accountKeys.push(...second.transaction.message.accountKeys); tx.meta.innerInstructions.push({...second.meta.innerInstructions[0],index:1}); const results=decode(tx).actions; assert.equal(results.length,2); assert.ok(results[0].ordinalx.vault),[vault,owner]); assert.throws(()=>decode(fixture({signed:false,nested:true}))); assert.throws(()=>decode(fixture({signed:false,vault}))); }); test('rejects malformed or ambiguous fee receipts instead of crediting a guessed payment',()=>{ for (const change of [ t=>{t.meta.innerInstructions=null;}, t=>{t.meta.innerInstructions[0].instructions.push(transfer(treasury,1));}, t=>{t.meta.innerInstructions[0].instructions.reverse();}, t=>{t.meta.innerInstructions[0].instructions[0].parsed.info.lamports=251;}, t=>{t.meta.innerInstructions[0].instructions[0].parsed.info.lamports=0.5;}, t=>{t.meta.innerInstructions[0].instructions[0].parsed.info.source=delegate;}, t=>{t.meta.innerInstructions[0].instructions[0].parsed.info.destination=parent;}, t=>{t.transaction.message.instructions[0].accounts[5]=delegate;}, t=>{t.transaction.message.instructions[0].accounts[4]=t.transaction.message.instructions[0].accounts[1];}, t=>{t.transaction.message.instructions[0].accounts[2]=parent;}, t=>{t.transaction.message.accountKeys[0].signer=false;}, t=>{t.slot=49;}, ]) {const tx=fixture();change(tx);assert.throws(()=>decode(tx));} const tx=fixture({nested:true}); tx.meta.innerInstructions[0].instructions[1].stackHeight=null; assert.throws(()=>decode(tx)); assert.throws(()=>decodeAnalyticsReceipt(fixture(),{...row(fixture()),signature:signature(2)},V2_REGISTRY,50)); }); test('bounded overlapping pages reconnect a busy head and retain missing historical coverage',async()=>{ const ledger=new Map(); let rows=[5,4,3,2,1].map(n=>({signature:signature(n),slot:n,err:null,confirmationStatus:'finalized'})); const store=async entries=>{for(const r of entries)ledger.set(r.signature,r);}; const list=async before=>{ const start=before?rows.findIndex(r=>r.signature===before)+1:0; return rows.slice(start,start+2); }; const discover=s=>discoverAnalyticsPage(s,list,store,signature(1)); let s=await discover({}); assert.equal(ledger.size,2); rows.unshift(...[9,8,7,6].map(n=>({signature:signature(n),slot:n,err:null}))); s=await discover(s);assert.equal(s.head,signature(5));assert.equal(s.forwardBefore,signature(8)); s=await discover(s);s=await discover(s); assert.equal(s.head,signature(9));assert.ok(s.seenDeployment);assert.equal(ledger.size,9); s=await discover(s);assert.equal(ledger.size,9); const truncated=await discoverAnalyticsPage({},async()=>[],store,signature(1)); assert.equal(truncated.seenDeployment,undefined); await assert.rejects(()=>discoverAnalyticsPage({},async()=>[rows[0],rows[0]],store,signature(1))); }); // Opt-in test infrastructure stays out of the shipped dependency tree. Pass the // directory containing an isolated PGlite + pglite-socket installation. const pgFixture=process.env.SOLBOUND_TEST_PGLITE_DIR; test('actual PostgreSQL aggregation, idempotence, unavailable retry and outage retention',{skip:!pgFixture},async t=>{ const load=createRequire(resolve(pgFixture,'package.json')); const {PGlite}=load('@electric-sql/pglite'); const {PGLiteSocketServer}=load('@electric-sql/pglite-socket'); const engine=await PGlite.create(); const server=new PGLiteSocketServer({db:engine,port:0,host:'127.0.0.1'}); await server.start(); const port=Number(server.getServerConn().split(':').at(-1)); const pool=new Pool({host:'127.0.0.1',port,database:'postgres',user:'postgres',max:1,connectionTimeoutMillis:4000}); t.after(async()=>{await pool.end();await server.stop();await engine.close();}); const start=await readAdminAnalytics(pool); assert.equal(start.coverage.status,'not_started');assert.equal(start.totals,null); const allowNextPass=()=>pool.query("UPDATE solbound_analytics_sync SET next_sync_at=CURRENT_TIMESTAMP-interval '1 second' WHERE singleton"); const post=sourceFactory=>handleAdminAnalytics(new Request('https://solbound.test/api/admin/analytics/sync',{method:'POST'}),{ path:'/api/admin/analytics/sync',body:{},database:pool,sourceFactory}); let tried=0; const blocked=(profile,signal,onLimit)=>{tried++;return {verify:async()=>{ onLimit(Date.now()+105000);throw Error('simulated 429');}};}; const firstFail=await post(blocked); assert.equal(firstFail.status,503);assert.ok(Number(firstFail.headers.get('Retry-After'))>=100); assert.equal(tried,1,'no second program request after the provider rate limit'); assert.equal((await post(blocked)).status,503);assert.equal(tried,1); await allowNextPass(); let degraded=false, missing=true, calls=0; const paid=fixture(), unknown=fixture();unknown.transaction.signatures[0]=signature(2); const fake=profile=>({ verify:async()=>{calls++;if(degraded)throw Error('temporary provider failure');return 0;}, list:async before=>before||profile.version!==2?[]:[paid,unknown].map(tx=>({signature:tx.transaction.signatures[0],slot:tx.slot,err:null})), receipt:async sig=>sig===signature(1)?paid:missing?null:unknown, }); const simultaneous=await Promise.all([syncAdminAnalytics(pool,fake),syncAdminAnalytics(pool,fake)]); assert.deepEqual(simultaneous.sort(),['cooldown','updated']);assert.equal(calls,3); let snapshot=await readAdminAnalytics(pool); assert.equal(snapshot.totals.feeLamports,'231');assert.equal(snapshot.coverage.unavailableTransactions,1); assert.equal(snapshot.coverage.status,'partial'); assert.equal(await syncAdminAnalytics(pool,fake),'cooldown'); assert.equal(calls,3);assert.deepEqual((await readAdminAnalytics(pool)).totals,snapshot.totals); assert.ok(Date.parse(snapshot.coverage.nextSyncAt)>Date.now()); missing=false; await allowNextPass(); await pool.query("UPDATE solbound_analytics_receipt SET retry_at=CURRENT_TIMESTAMP WHERE status='unavailable'"); await syncAdminAnalytics(pool,fake); snapshot=await readAdminAnalytics(pool); assert.equal(snapshot.totals.feeLamports,'462');assert.equal(snapshot.totals.uniqueVaults,1); assert.deepEqual(snapshot.recipients,[{address:treasury,feeLamports:'462',paidActions:2}]); assert.equal(snapshot.recent.length,2); const day=await readAdminAnalytics(pool,new Date(paid.blockTime*1000)); assert.equal(day.daily.length,30); assert.equal(day.daily.at(-1).feeLamports,'462'); degraded=true;await allowNextPass(); const partial=await post(fake);assert.equal(partial.status,200); const retained=await partial.json();assert.deepEqual(retained.totals,snapshot.totals); assert.equal(retained.coverage.status,'partial');assert.ok(retained.coverage.syncWarning); await allowNextPass(); assert.equal((await post(blocked)).status,200);assert.equal(tried,2); assert.ok(Date.parse((await readAdminAnalytics(pool)).coverage.nextSyncAt)-Date.now()>100000); degraded=false; const fixed=fixture({profile:V3_REGISTRY,fee:32_000_000,cap:32_000_000}); fixed.transaction.signatures[0]=signature(3); const mixed=profile=>profile.version===3?{ verify:async()=>0, list:async before=>before?[]:[{signature:signature(3),slot:fixed.slot,err:null}], receipt:async()=>fixed, }:fake(profile); await allowNextPass();await syncAdminAnalytics(pool,mixed); const combined=await readAdminAnalytics(pool); assert.equal(combined.totals.feeLamports,'32000462'); assert.equal(combined.totals.paidActions,3);assert.equal(combined.recent.length,3); assert.deepEqual(combined.recipients,[{address:treasury,feeLamports:'32000462',paidActions:3}]); assert.deepEqual((await pool.query('SELECT version,count(*)::int AS actions FROM solbound_analytics_action GROUP BY version ORDER BY version')).rows, [{version:2,actions:2},{version:3,actions:1}],'Adding v3 must preserve indexed v2 records.'); await allowNextPass();await syncAdminAnalytics(pool,mixed); assert.equal((await readAdminAnalytics(pool)).totals.feeLamports,'32000462','Repeated v3 scans must be idempotent.'); // Optionally run the same production SQL and parser on privately retained, // public finalized Devnet RPC fixtures without contacting a live endpoint. if (process.env.SOLBOUND_TEST_PUBLIC_RECEIPTS) { const f=JSON.parse(await readFile(process.env.SOLBOUND_TEST_PUBLIC_RECEIPTS,'utf8')); await pool.query('TRUNCATE solbound_analytics_action,solbound_analytics_receipt'); await pool.query("UPDATE solbound_analytics_scan SET cursor='{}', synced_at=NULL, issue=false"); const actual=profile=>{ const txs=Object.values(profile===V1_REGISTRY?f.legacyTxs:profile===V2_REGISTRY?f.txs:{}); const history=profile===V1_REGISTRY?f.legacyHistory:profile===V2_REGISTRY?f.history:[]; return {verify:async()=>0,list:async before=>before?[]:history, receipt:async sig=>txs.find(tx=>tx.transaction.signatures[0]===sig)}; }; for(let i=0;i<3;i++) { await allowNextPass();await syncAdminAnalytics(pool,actual); } const publicData=await readAdminAnalytics(pool); assert.deepEqual(publicData.totals,{feeLamports:'60130508',grantWrites:8,paidActions:2,revocations:8, uniqueVaults:5,uniqueDelegates:5,failedTransactions:0}); assert.equal(publicData.coverage.status,'partial','Historical v1/v2 fixtures do not establish v3 deployment coverage.'); assert.equal(publicData.coverage.discoveredTransactions,19); } });