const REPO = "jUXTAPOSITION1/V.A.P.E";
const RAW = `https://raw.githubusercontent.com/${REPO}/main`;
// The vape-x402 worker's base URL — backs the free Alchemy-powered
// /portfolio, /nfts, /network-status routes (more reliable + full token/NFT
// auto-discovery vs. the public mainnet.base.org RPC + curated token list)
// and the priced /scan/* x402 offerings. Every caller below still falls back
// to its direct-API path if this ever returns an error, so the site keeps
// working even if the worker is down.
//
// Cloudflare Workers is the primary deploy target (.github/workflows/
// deploy-worker.yml, which also runs a post-deploy smoke test against this
// exact URL on every deploy). worker/deno/ mirrors the identical src/index.ts
// on Deno Deploy as a documented fallback — switch this back to
// "https://vape.juxtaposition1.deno.net" with zero code changes if this
// Cloudflare account ever re-hits the workers.dev subdomain-registration bug
// described in worker/README.md's "Cloudflare + Deno Deploy" section.
//
// IMPORTANT: whichever URL this points to, it must be that platform's
// stable *production* URL, not an individual build's preview URL (e.g.
// Deno's "vape-8kje756vhqqy.deno.net") — preview URLs are frozen forever at
// whatever code was live for that one build and never receive later pushes,
// which is exactly what caused the x402 hire flow to keep failing with a
// stale CORS config after the fix had already shipped.
const WORKER_BASE = "https://vape-x402.vapex402.workers.dev";
const fmtUsd = n => n==null ? "—" : (n>=1e9 ? "$"+(n/1e9).toFixed(2)+"B" : n>=1e6 ? "$"+(n/1e6).toFixed(1)+"M" : "$"+Number(n).toLocaleString());
const pct = n => (typeof n==="number") ? `${n>=0?'+':''}${n.toFixed(2)}%` : "";
// Every successful x402 hire gets saved here (browser localStorage, keyed by
// the paying wallet) so "Portfolio Intelligence" can show a persistent
// engagement history with no backend — same zero-cost, keyless philosophy as
// the rest of the site. Scope: this device/browser only, not synced across
// devices; that's an honest limitation of a no-backend design, not a bug.
const CaseHistory = {
KEY: 'vape_case_history_v1',
MAX_ENTRIES: 200,
_all() {
try { return JSON.parse(localStorage.getItem(this.KEY) || '[]'); } catch (e) { return []; }
},
save(record) {
const all = this._all();
all.unshift({ id: `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`, timestamp: Date.now(), ...record });
try { localStorage.setItem(this.KEY, JSON.stringify(all.slice(0, this.MAX_ENTRIES))); } catch (e) { /* storage full/unavailable — non-fatal */ }
},
forWallet(address) {
if (!address) return [];
const a = address.toLowerCase();
return this._all().filter(c => (c.walletAddress || '').toLowerCase() === a);
},
};
window.CaseHistory = CaseHistory;
// app.js is a classic script; wallet.js/profile.js are ES modules with their own
// top-level scope, so top-level const bindings here aren't visible to them
// unless explicitly published on window.
window.fmtUsd = fmtUsd;
window.pct = pct;
window.WORKER_BASE = WORKER_BASE;
const App = {
async refresh() {
document.getElementById('live-label').textContent = 'SYNCING';
this._intelPromise = null; // force a fresh intel-index fetch this cycle, shared by reports() + intel()
await Promise.allSettled([this.metrics(), this.sentiment(), this.protocols(), this.baseMovers(), this.bounties(), this.bountyCommand(), this.reports(), this.chart(this._days||30), this.reputation(), this.intel()]);
document.getElementById('live-label').textContent = 'LIVE';
document.getElementById('last-sync').textContent = 'synced ' + new Date().toLocaleTimeString();
},
// Shared, memoized-per-cycle intel-index fetch — reports() and intel()
// both want it and run concurrently in refresh()'s allSettled, so this
// avoids a duplicate fetch and the race of reports() reading `this._intel`
// before intel() has populated it.
_intelPromise: null,
async _loadIntel() {
if (!this._intelPromise) {
this._intelPromise = fetch(`${RAW}/data/intel-index.json?t=` + Date.now()).then(r => r.json()).catch(() => null);
}
return this._intelPromise;
},
// Bounty Command Center telemetry strip + VAPE's own audit track record.
// opportunities.json is the same real feed bounties() renders cards from;
// this just adds the aggregate counts and the separate poc-reports ledger.
async bountyCommand() {
try {
const data = await (await fetch(`${RAW}/intel/bounty-radar/opportunities.json?t=`+Date.now())).json();
const list = Array.isArray(data) ? data : [];
const liveStatuses = new Set(['live','active']);
const live = list.filter(o => liveStatuses.has((o.status||'').toLowerCase())).length;
const platforms = new Set(list.map(o=>o.platform).filter(Boolean));
this._set('bcc-total', list.length.toLocaleString());
this._set('bcc-live', live.toLocaleString());
this._set('bcc-platforms', platforms.size);
document.getElementById('bcc-updated').textContent = 'radar synced ' + new Date().toLocaleTimeString();
} catch(e) {
document.getElementById('bcc-updated').textContent = 'radar telemetry unavailable';
}
const auditEl = document.getElementById('bcc-audit-list');
try {
const items = await (await fetch(`https://api.github.com/repos/${REPO}/contents/intel/audits/poc-reports`)).json();
const files = (Array.isArray(items)?items:[]).filter(f=>f.name.endsWith('.md'))
.map(f=>{
const stopped = /-STOPPED/.test(f.name);
const m = f.name.match(/(\d{4}-\d{2}-\d{2})/);
const base = f.name.replace(/\.md$/,'').replace(/-STOPPED/,'').replace(/^(audit|lead)-/,'').replace(/-\d{4}-\d{2}-\d{2}$/,'');
return { name: base.replace(/-/g,' '), stopped, date: m?m[1]:'', url: f.html_url, isAudit: f.name.startsWith('audit-') };
})
.sort((a,b)=>b.date.localeCompare(a.date));
this._set('bcc-audits', files.filter(f=>f.isAudit).length);
if (!files.length) throw 0;
auditEl.innerHTML = files.map(f => `
`).join('');
}
const acpGrid = document.getElementById('acp-offerings-grid');
if (acpGrid) {
acpGrid.innerHTML = manual.map(o=>`
`).join('');
}
const disc = document.getElementById('rep-disclaimer');
if (disc) disc.textContent = (r.disclaimer||'') + (a.first_report?` · Active since ${a.first_report.replace(/(\d{4})(\d{2})(\d{2})/,'$1-$2-$3')}.`:'');
} catch(e){
const grid = document.getElementById('rep-offerings-grid');
if (grid) grid.innerHTML = '
Reputation feed unavailable (regenerating).
';
}
},
// "The Workshop" — real PRs opened by VAPE's own build pipelines
// (agents/build_request.py, agents/skillforge_build.py), pre-fetched and
// filtered server-side in agents/publish_reputation.py::tool_builds() so
// the browser never needs its own GitHub Search API call/rate limit.
_renderWorkshop(builds, generatedAt) {
const el = document.getElementById('workshop-body');
if (!el) return;
const upd = document.getElementById('workshop-updated');
if (upd) upd.textContent = 'ledger ' + this._ago(generatedAt);
if (!builds.length) {
el.innerHTML = `
No open build proposals right now — the last cycle found no gap worth building against
(tool registry clean, no fresh findings to ground a proposal in). Checks run 2x/day automatically.
${flags.length?flags.map(f=>`${f}`).join(''):'No risk flags from real on-chain scan.'}
${note?`
${this._esc(note)}
`:''}
Real data: GoPlus token_security + DexScreener liquidity. Not investment advice.
`;
return verdict[0];
},
async hunt() {
const el = document.getElementById('hunt-result');
const addr = (document.getElementById('hunt-target').value||'').trim();
const chain = document.getElementById('hunt-chain').value;
if (!/^0x[a-fA-F0-9]{40}$/.test(addr)) { el.innerHTML = 'Enter a valid 0x… 40-hex contract address.'; return; }
el.innerHTML = ' Assessing real data (GoPlus + DexScreener)…';
try {
const [gpRaw, dsRaw] = await Promise.all([
this._safeFetchJson(`https://api.gopluslabs.io/api/v1/token_security/${chain}?contract_addresses=${addr}`),
this._safeFetchJson(`https://api.dexscreener.com/latest/dex/tokens/${addr}`)
]);
if (gpRaw?._error) { el.innerHTML = `GoPlus security data unavailable (${this._esc(gpRaw._error)}). Try again shortly.`; return; }
const gp = Object.values(gpRaw.result||{})[0] || {};
let pairs = dsRaw?.pairs || [];
let liq = pairs.reduce((s,p)=>s+(p.liquidity?.usd||0),0);
let note = null;
// DexScreener failed outright (not just "no pairs found") — reporting
// $0 liquidity for a token that may have plenty is misleading, not
// just incomplete. Fall back to GeckoTerminal, same as the paid
// offerings and agents/token_scan.py.
if (dsRaw?._error && !pairs.length) {
const fallback = await this._fetchLiquidityFallback(addr, chain);
if (fallback) {
liq = fallback.liquidity_usd;
note = `Liquidity from GeckoTerminal (DexScreener temporarily unavailable: ${dsRaw._error}).`;
} else {
note = `DexScreener unavailable (${dsRaw._error}) — liquidity may be understated.`;
}
}
this.renderScanResult(el, addr, chain, gp, liq, pairs, note);
} catch(e){ el.innerHTML = 'Scan failed unexpectedly. Try again.'; }
},
async metrics() {
// DefiLlama TVL
try {
const chains = await (await fetch('https://api.llama.fi/v2/chains')).json();
const base = chains.find(c => (c.name||'').toLowerCase()==='base');
document.getElementById('m-tvl').classList.remove('skeleton');
document.getElementById('m-tvl').textContent = base ? fmtUsd(base.tvl) : '—';
this._tvl = base?.tvl;
} catch(e){ this._set('m-tvl','—'); }
// Base block + gas — prefer the Alchemy-backed worker endpoint (more
// reliable, keyless from the browser's perspective) and fall back to
// the public RPC directly if the worker isn't deployed/configured.
try {
let block, gasGwei;
if (WORKER_BASE) {
try {
const s = await (await fetch(`${WORKER_BASE}/network-status`)).json();
if (typeof s.blockNumber === 'number') { block = s.blockNumber; gasGwei = s.gasPriceGwei; }
} catch (e) { /* fall through to public RPC */ }
}
if (block == null) {
const rpc = (m,p=[]) => fetch('https://mainnet.base.org',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({jsonrpc:'2.0',method:m,params:p,id:1})}).then(r=>r.json());
const [bn, gp] = await Promise.all([rpc('eth_blockNumber'), rpc('eth_gasPrice')]);
block = parseInt(bn.result,16);
gasGwei = parseInt(gp.result,16)/1e9;
}
this._set('m-block', block.toLocaleString());
this._set('m-gas', gasGwei.toFixed(3));
} catch(e){ this._set('m-block','—'); this._set('m-gas','—'); }
// Prices
try {
const p = await (await fetch('https://api.coingecko.com/api/v3/simple/price?ids=ethereum,bitcoin&vs_currencies=usd&include_24hr_change=true')).json();
this._ethPrice = p.ethereum.usd;
this._set('m-price', `$${Math.round(p.ethereum.usd).toLocaleString()} / $${Math.round(p.bitcoin.usd).toLocaleString()}`);
} catch(e){ this._set('m-price','—'); }
},
// Broader-market context alongside the Base-specific tiles above — both
// sources are free, unauthenticated, and already stable public APIs used
// industry-wide for exactly this (alternative.me's Fear & Greed Index,
// CoinGecko's /global). One call each per five-minute refresh cycle, well
// inside either service's rate limit.
async sentiment() {
try {
const fng = await (await fetch('https://api.alternative.me/fng/?limit=1')).json();
const d = (fng?.data || [])[0];
const v = d ? parseInt(d.value, 10) : null;
const el = document.getElementById('m-feargreed');
el.classList.remove('skeleton');
el.innerHTML = (v != null && !isNaN(v)) ? `${v} ${this._esc(d.value_classification || '')}` : '—';
const fill = document.getElementById('m-feargreed-fill');
if (fill && v != null && !isNaN(v)) {
fill.style.width = `${v}%`;
fill.style.background = v <= 24 ? '#fb7185' : v <= 44 ? '#fbbf24' : v <= 55 ? '#a1a1aa' : v <= 75 ? '#84cc16' : '#10b981';
}
} catch (e) { this._set('m-feargreed', '—'); }
try {
const g = await (await fetch('https://api.coingecko.com/api/v3/global')).json();
const mc = g?.data?.total_market_cap?.usd;
const chg = g?.data?.market_cap_change_percentage_24h_usd;
const el = document.getElementById('m-mcap');
el.classList.remove('skeleton');
el.innerHTML = mc != null ? `${fmtUsd(mc)}${typeof chg === 'number' ? ` ${pct(chg)}` : ''}` : '—';
} catch (e) { this._set('m-mcap', '—'); }
},
// "Base Movers" — real data source, tried in order:
// 1. CoinGecko's "Base Ecosystem" category (curated, real Base tokens
// with reliable logo/symbol/name/price data in one keyless,
// CORS-friendly call).
// 2. DexScreener's boosted-token feed as a fallback — kept because it
// was the only source before, but demoted: it's a paid-promotion
// signal (projects actively boosting a listing), not organic
// movers, and was observed going empty/unavailable often enough in
// practice that this section stopped populating entirely.
// Gainers/Losers/Volume just re-sort whichever set loaded, client-side —
// no extra requests per tab switch.
_movers: null,
_moversTab: 'trending',
async baseMovers() {
const el = document.getElementById('base-movers');
if (!el) return;
try {
await this._moversFromCoinGecko();
} catch (e) {
console.error('[baseMovers] CoinGecko unavailable, falling back to DexScreener boosts:', e.message || e);
try {
await this._moversFromDexScreenerBoosts();
} catch (e2) {
console.error('[baseMovers] Base Movers unavailable:', e2.message || e2);
el.innerHTML = `
Live trending data unavailable — retries next cycle.
`;
}
}
},
async _moversFromCoinGecko() {
// Real bug fixed here (caught by review): CoinGecko's /coins/markets
// `order` param only accepts market_cap_desc/asc, volume_desc/asc, or
// id_desc/asc — price_change_percentage_24h_desc isn't a real value
// and was silently falling back to the default (market_cap_desc), so
// the "trending" tab was actually just market-cap-ranked, not movers
// at all. Fetch by market cap (a legitimate, broad pool of real Base
// ecosystem tokens), then sort by absolute 24h change client-side —
// same "biggest movers" definition already used server-side in
// agents/data_fetchers.py::get_evm_movers().
const res = await fetch('https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&category=base-ecosystem&order=market_cap_desc&per_page=30&page=1&sparkline=false&price_change_percentage=24h');
if (!res.ok) throw new Error(`coingecko coins/markets -> HTTP ${res.status}`);
const coins = await res.json();
if (!Array.isArray(coins) || !coins.length) throw new Error('coingecko returned no base-ecosystem coins');
coins.sort((a, b) => Math.abs(b.price_change_percentage_24h ?? 0) - Math.abs(a.price_change_percentage_24h ?? 0));
// Normalized into the exact shape _renderMovers() already expects
// (priceUsd / priceChange.h24 / volume.h24 / baseToken.symbol+name /
// info.imageUrl / url) so that function needs zero changes regardless
// of which source actually supplied the data this cycle.
this._movers = coins.map(c => ({
url: `https://www.coingecko.com/en/coins/${c.id}`,
baseToken: { symbol: (c.symbol || '').toUpperCase(), name: c.name, address: null },
priceUsd: c.current_price,
priceChange: { h24: c.price_change_percentage_24h },
volume: { h24: c.total_volume },
info: { imageUrl: c.image },
}));
this._renderMovers();
},
async _moversFromDexScreenerBoosts() {
// DexScreener occasionally 403s or rate-limits this endpoint —
// fetch() only rejects on a network-level failure, not on a non-2xx
// response, so an unchecked `.json()` on a 403's (often non-JSON)
// body was throwing an opaque parse error that told a browser
// console nothing about the real cause. Check status explicitly so
// the actual reason is visible for debugging instead of a silent
// "Live data unavailable."
const boostsRes = await fetch('https://api.dexscreener.com/token-boosts/top/v1');
if (!boostsRes.ok) throw new Error(`token-boosts/top/v1 -> HTTP ${boostsRes.status}`);
const boosts = await boostsRes.json();
const addrs = [...new Set((Array.isArray(boosts) ? boosts : [])
.filter(b => b.chainId === 'base' && b.tokenAddress)
.map(b => b.tokenAddress.toLowerCase()))].slice(0, 30);
if (!addrs.length) throw new Error('no boosted Base tokens right now');
const pairsRes = await fetch(`https://api.dexscreener.com/latest/dex/tokens/${addrs.join(',')}`);
if (!pairsRes.ok) throw new Error(`latest/dex/tokens -> HTTP ${pairsRes.status}`);
const data = await pairsRes.json();
const byToken = new Map();
(data.pairs || []).forEach(p => {
if (p.chainId !== 'base') return;
const addr = (p.baseToken?.address || '').toLowerCase();
if (!addr) return;
const existing = byToken.get(addr);
if (!existing || (p.liquidity?.usd || 0) > (existing.liquidity?.usd || 0)) byToken.set(addr, p);
});
// Preserve the boost feed's own ranking for the "trending" tab —
// the tokens/{addrs} lookup above returns pairs in its own order,
// not the boost ranking, so rebuild from `addrs`.
this._movers = addrs.map(a => byToken.get(a)).filter(Boolean);
if (!this._movers.length) throw new Error('boosted addresses returned no matching Base pairs');
this._renderMovers();
},
_renderMovers() {
const el = document.getElementById('base-movers');
if (!el || !this._movers) return;
let items = this._movers.slice();
if (this._moversTab === 'gainers') items.sort((a,b) => (b.priceChange?.h24 ?? -Infinity) - (a.priceChange?.h24 ?? -Infinity));
else if (this._moversTab === 'losers') items.sort((a,b) => (a.priceChange?.h24 ?? Infinity) - (b.priceChange?.h24 ?? Infinity));
else if (this._moversTab === 'volume') items.sort((a,b) => (b.volume?.h24 || 0) - (a.volume?.h24 || 0));
items = items.slice(0, 12);
el.innerHTML = items.length ? items.map((p,i) => {
const chg = p.priceChange?.h24;
const icon = p.info?.imageUrl || this._tokenIcon(p.baseToken?.address, 'base');
const priceUsd = p.priceUsd != null ? Number(p.priceUsd) : null;
return `
${i+1}
${icon?``:''}
`;
}
},
// Prefers the generated intel index (real title/type/verdict/summary per
// report, same source the Archive's Reports tab uses) over a bare GitHub
// directory listing — falls back to filenames-only if the index isn't
// reachable for any reason, since that's still real, live data.
async reports() {
const el = document.getElementById('reports');
try {
const d = await this._loadIntel();
if (!d) throw new Error('intel index unavailable');
const items = (d.reports||[]).slice().sort((a,b)=>(b.date||'').localeCompare(a.date||'')).slice(0,6);
if (!items.length) throw new Error('no reports in index');
el.innerHTML = items.map(r=>`
`).join('');
} catch(e) {
try {
const items = await (await fetch(`https://api.github.com/repos/${REPO}/contents/reports`)).json();
const md = (Array.isArray(items)?items:[]).filter(f=>f.name.endsWith('.md'))
.map(f=>{ const m=f.name.match(/(\d{8})_(\d{6})/); f._ts=m?m[1]+m[2]:'0'; return f; })
.sort((a,b)=>b._ts.localeCompare(a._ts)).slice(0,6);
if (!md.length) throw 0;
el.innerHTML = md.map(f=>`
${f.name}`).join('');
} catch (e2) {
el.innerHTML = `View all reports on GitHub →`;
}
}
},
// ── Intel index: investigation summary + explorer (from data/intel-index.json)
_intel: null, _tab: 'investigations', _typeFilter: null,
_verdictColor(v){
v=(v||'').toUpperCase();
if(/REJECT|CRITICAL|HIGH|BEARISH|RISK-OFF|FEAR/.test(v)) return '#fb7185';
if(/CAUTION|MEDIUM|NEUTRAL/.test(v)) return '#fbbf24';
if(/PROCEED|LOW|ALL CLEAR|BULLISH|RISK-ON|GREED/.test(v)) return '#10b981';
return '#a1a1aa';
},
_pill(v){ if(!v) return ''; const c=this._verdictColor(v);
return `${v}`; },
_ago(iso){ if(!iso) return ''; const d=new Date(iso); if(isNaN(d)) return iso;
const s=(Date.now()-d)/1e3; if(s<3600) return Math.floor(s/60)+'m ago';
if(s<86400) return Math.floor(s/3600)+'h ago'; return Math.floor(s/86400)+'d ago'; },
// Escapes quotes too, not just tag-relevant chars — several call sites
// interpolate this into an HTML *attribute* value (e.g. title="${...}"),
// and a target/name containing a bare `"` could otherwise break out of
// the attribute and inject a new one (CodeQL: incomplete HTML attribute
// sanitization). Real risk: on-chain token/contract names are attacker-
// controlled data rendered here.
_esc(t){ return (t||'').replace(/[<>&"']/g,c=>({'<':'<','>':'>','&':'&','"':'"',"'":'''}[c])); },
_shortAddr(a){ return (a && a.length>12) ? a.slice(0,6)+'…'+a.slice(-4) : (a||''); },
_symFromTitle(t){ const m=(t||'').match(/Investigation\s*[—-]\s*(.+)$/); return m ? m[1].trim() : null; },
// Real bug fixed here: investigations are now genuinely multi-chain
// (agents/investigate.py rotates auto-target across 7 EVM chains), but
// this used to only distinguish arbitrum/ethereum/base — anything else
// (Optimism/Polygon/BNB Chain/Avalanche) silently fell through to 'base',
// giving a wrong-chain token-icon CDN path and a wrong explorer link.
// Extracts the leading chain-id number from whatever format the
// "Chain:" field is in (e.g. "42161 (Arbitrum)") and maps it directly —
// robust to the exact display text wrapping around it.
_CHAIN_ID_MAP: {'1':'ethereum','8453':'base','42161':'arbitrum','10':'optimism','137':'polygon','56':'bsc','43114':'avalanche'},
_chainSlug(c){
const m = String(c||'').match(/\d+/);
return (m && this._CHAIN_ID_MAP[m[0]]) || 'base';
},
_tokenIcon(address, chain){
if(!address || !/^0x[a-fA-F0-9]{40}$/.test(address)) return null;
return `https://dd.dexscreener.com/ds-data/tokens/${this._chainSlug(chain)}/${address.toLowerCase()}.png?size=lg`;
},
_explorerUrl(address, chain){
if(!address || !/^0x[a-fA-F0-9]{40}$/.test(address)) return null;
const slug = this._chainSlug(chain);
const hosts = {arbitrum:'arbiscan.io', ethereum:'etherscan.io', optimism:'optimistic.etherscan.io',
polygon:'polygonscan.com', bsc:'bscscan.com', avalanche:'snowtrace.io', base:'basescan.org'};
return `https://${hosts[slug]||'basescan.org'}/address/${address}`;
},
// Archive/report-card meta line: small wrapping chips instead of a single
// "·"-joined text string — a long joined line (long address, long offering
// name) has nowhere to shrink and can push a narrow card wider than its
// container; chips wrap onto a new line instead, so a card's width is
// always bounded by its own layout, never by its content.
_metaChips(parts){
const items = parts.filter(Boolean);
if(!items.length) return '';
return `