Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: implement Proof-of-Reserves for agent wallets

nirholas6ad1c7c5e342
diff --git a/api/_lib/trust/proof-of-reserves.js b/api/_lib/trust/proof-of-reserves.js
new file mode 100644
index 000000000..23a8c6c21
--- /dev/null
+++ b/api/_lib/trust/proof-of-reserves.js
@@ -0,0 +1,323 @@
+// Proof-of-Reserves — verifiable, on-chain-derived solvency for an agent wallet.
+//
+// "Trustless, not trust-us." Every figure here is either a LIVE read of real
+// Solana chain state (the wallet's actual SOL + SPL holdings, independently
+// checkable on Solscan) or a real, already-settled row in the custody ledger
+// (each linking to its on-chain signature). Nothing is asserted; everything is
+// verifiable. This is the data layer behind the transparency panel and feeds the
+// `solvency` factor of the financial reputation score.
+//
+// Three real reads compose the picture:
+// • reserves — live SOL + SPL balances, USD-valued, with a one-tap
+// verify-on-chain link and an honest verified_at timestamp.
+// When RPC is throttled we return the LAST verified snapshot
+// marked `degraded` with its real timestamp — never a stale
+// "verified now".
+// • lifetime — total received (tips + streams) vs total out (withdraws +
+// spends/trades/snipes/x402) from agent_custody_events.
+// • obligations — what it still owes: pending spends + live money-streams.
+
+import { PublicKey } from '@solana/web3.js';
+import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token';
+import { sql } from '../db.js';
+import { solanaConnection } from '../agent-pumpfun.js';
+import { solanaMintUsdPrice } from '../balances.js';
+import { solUsdPrice, explorerTxUrl, explorerAccountUrl } from '../avatar-wallet.js';
+import { cacheGet, cacheSet } from '../cache.js';
+
+const USDC_MINT_BY_CLUSTER = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const FRESH_TTL_S = 60; // matches the wallet balance cache window
+const SNAPSHOT_TTL_S = 3600; // keep last-good snapshot for the degraded fallback
+const STREAM_LIVE_WINDOW_S = 150; // a stream that settled inside this window is "live"
+const MAX_PRICED_TOKENS = 24; // price at most this many distinct SPL holdings
+
+const round2 = (n) => Math.round((Number(n) || 0) * 100) / 100;
+
+/**
+ * Live, USD-valued reserves for an agent's Solana wallet, cached and RPC-resilient.
+ * Returns `degraded:true` with the previous verified snapshot when the RPC read
+ * fails — the timestamp is always the true moment the data was last verified.
+ *
+ * @param {string} address base58 wallet address
+ * @param {'mainnet'|'devnet'} network
+ * @returns {Promise<object>} reserves snapshot
+ */
+export async function getReservesSnapshot(address, network = 'mainnet') {
+ const cacheKey = `reserves:snap:v1:${address}:${network}`;
+ const cached = await cacheGet(cacheKey).catch(() => null);
+ if (cached?.verified_at && Date.now() - new Date(cached.verified_at).getTime() < FRESH_TTL_S * 1000) {
+ return { ...cached, degraded: false };
+ }
+
+ try {
+ const snap = await readReservesLive(address, network);
+ await cacheSet(cacheKey, snap, SNAPSHOT_TTL_S).catch(() => {});
+ return { ...snap, degraded: false };
+ } catch (err) {
+ // RPC throttled / unreachable — fall back to the last verified snapshot,
+ // honestly labelled. Never fabricate a "verified now".
+ if (cached) return { ...cached, degraded: true, last_verified_at: cached.verified_at };
+ const e = new Error('could not read reserves from the network — try again');
+ e.code = 'rpc_error';
+ e.status = 502;
+ throw e;
+ }
+}
+
+async function readReservesLive(address, network) {
+ const conn = solanaConnection(network);
+ const owner = new PublicKey(address);
+
+ const lamports = await conn.getBalance(owner, 'confirmed');
+ const sol = lamports / 1e9;
+
+ const usdcMint = USDC_MINT_BY_CLUSTER[network];
+ const raw = [];
+ for (const programId of [TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID]) {
+ let resp;
+ try {
+ resp = await conn.getParsedTokenAccountsByOwner(owner, { programId });
+ } catch {
+ continue; // one token program failing shouldn't blank the whole list
+ }
+ for (const { account } of resp.value) {
+ const info = account.data?.parsed?.info;
+ const amt = info?.tokenAmount;
+ if (!info || !amt || !(Number(amt.uiAmount) > 0)) continue;
+ raw.push({
+ mint: info.mint,
+ ui_amount: Number(amt.uiAmount),
+ amount_raw: amt.amount,
+ decimals: amt.decimals,
+ is_usdc: info.mint === usdcMint,
+ is_three: info.mint === THREE_MINT,
+ });
+ }
+ }
+ raw.sort((a, b) => b.ui_amount - a.ui_amount);
+
+ // Price SOL once; price the largest holdings (USDC is $1; others via Jupiter/
+ // pump.fun). Cap the number priced so a whale wallet never fans out hundreds of
+ // price calls — the cache amortises repeats.
+ const solUsd = (await solUsdPrice().catch(() => 0)) || 0;
+ const tokens = [];
+ for (const t of raw.slice(0, MAX_PRICED_TOKENS)) {
+ let price = 0;
+ if (t.is_usdc) price = 1;
+ else price = (await solanaMintUsdPrice(t.mint).catch(() => 0)) || 0;
+ tokens.push({
+ mint: t.mint,
+ ui_amount: t.ui_amount,
+ decimals: t.decimals,
+ is_usdc: t.is_usdc,
+ is_three: t.is_three,
+ usd: price > 0 ? round2(price * t.ui_amount) : null,
+ });
+ }
+ // Any holdings beyond the priced cap are still disclosed (count + as unpriced).
+ for (const t of raw.slice(MAX_PRICED_TOKENS)) {
+ tokens.push({ mint: t.mint, ui_amount: t.ui_amount, decimals: t.decimals, is_usdc: false, is_three: t.is_three, usd: null });
+ }
+
+ const solUsdValue = round2(sol * solUsd);
+ const tokenUsd = tokens.reduce((s, t) => s + (t.usd || 0), 0);
+ return {
+ address,
+ network,
+ sol,
+ sol_usd: solUsdValue,
+ tokens,
+ token_usd: round2(tokenUsd),
+ total_usd: round2(solUsdValue + tokenUsd),
+ verify_url: explorerAccountUrl(address, network),
+ verified_at: new Date().toISOString(),
+ };
+}
+
+/**
+ * Lifetime flows + outstanding obligations from the custody ledger. Cheap SQL,
+ * no RPC. `received` = inbound tips + money-streams; `out` = withdraws + spends
+ * (trades/snipes/x402). Obligations = pending spends still in flight + the count
+ * of live money-streams crediting/charging right now.
+ */
+export async function getLedgerSummary(agentId) {
+ const [tot] = await sql`
+ SELECT
+ coalesce(sum(usd) FILTER (WHERE event_type IN ('tip','stream') AND status IN ('ok','confirmed')), 0)::float8 AS received_usd,
+ count(*) FILTER (WHERE event_type IN ('tip','stream') AND status IN ('ok','confirmed'))::int AS received_count,
+ coalesce(sum(usd) FILTER (WHERE event_type = 'tip' AND status IN ('ok','confirmed')), 0)::float8 AS tip_usd,
+ coalesce(sum(usd) FILTER (WHERE event_type = 'stream' AND status IN ('ok','confirmed')), 0)::float8 AS stream_usd,
+ coalesce(sum(usd) FILTER (WHERE event_type IN ('withdraw','spend') AND status IN ('ok','confirmed')), 0)::float8 AS out_usd,
+ count(*) FILTER (WHERE event_type IN ('withdraw','spend') AND status IN ('ok','confirmed'))::int AS out_count,
+ coalesce(sum(usd) FILTER (WHERE event_type = 'withdraw' AND status IN ('ok','confirmed')), 0)::float8 AS withdraw_usd,
+ coalesce(sum(usd) FILTER (WHERE category = 'trade' AND status IN ('ok','confirmed')), 0)::float8 AS trade_usd,
+ coalesce(sum(usd) FILTER (WHERE category = 'snipe' AND status IN ('ok','confirmed')), 0)::float8 AS snipe_usd,
+ coalesce(sum(usd) FILTER (WHERE category = 'x402' AND status IN ('ok','confirmed')), 0)::float8 AS x402_usd,
+ coalesce(sum(usd) FILTER (WHERE event_type IN ('withdraw','spend') AND status = 'pending'), 0)::float8 AS pending_out_usd
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId}
+ `.catch(() => [null]);
+
+ const [liveStreams] = await sql`
+ SELECT count(DISTINCT meta->>'stream_id')::int AS n
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND category = 'stream'
+ AND status IN ('ok','confirmed','pending')
+ AND created_at > now() - (interval '1 second' * ${STREAM_LIVE_WINDOW_S})
+ `.catch(() => [{ n: 0 }]);
+
+ const r = tot || {};
+ const pendingOut = round2(r.pending_out_usd);
+ return {
+ received: {
+ usd: round2(r.received_usd),
+ count: r.received_count || 0,
+ by_kind: { tip: round2(r.tip_usd), stream: round2(r.stream_usd) },
+ },
+ out: {
+ usd: round2(r.out_usd),
+ count: r.out_count || 0,
+ by_kind: {
+ withdraw: round2(r.withdraw_usd),
+ trade: round2(r.trade_usd),
+ snipe: round2(r.snipe_usd),
+ x402: round2(r.x402_usd),
+ },
+ },
+ obligations: {
+ active_streams: liveStreams?.n || 0,
+ pending_spends_usd: pendingOut,
+ total_usd: pendingOut,
+ },
+ };
+}
+
+/**
+ * A paginated window of real custody flows, each row linking to its on-chain
+ * signature. Public-safe: amounts + counterparties are public on-chain facts.
+ */
+export async function getFlows(agentId, { limit = 25, beforeId = null } = {}) {
+ const lim = Math.min(100, Math.max(1, Number(limit) || 25));
+ const rows = beforeId
+ ? await sql`
+ SELECT id, event_type, category, network, asset, amount_lamports, amount_raw, usd, destination, signature, meta, created_at
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND status IN ('ok','confirmed') AND id < ${beforeId}
+ ORDER BY id DESC LIMIT ${lim}
+ `.catch(() => [])
+ : await sql`
+ SELECT id, event_type, category, network, asset, amount_lamports, amount_raw, usd, destination, signature, meta, created_at
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND status IN ('ok','confirmed')
+ ORDER BY id DESC LIMIT ${lim}
+ `.catch(() => []);
+
+ const items = rows.map((e) => {
+ const inbound = e.event_type === 'tip' || e.event_type === 'stream';
+ const counterparty = inbound ? e.meta?.from || null : e.destination || null;
+ return {
+ id: String(e.id),
+ kind: e.category || e.event_type,
+ direction: inbound ? 'in' : 'out',
+ network: e.network,
+ asset: e.asset,
+ amount_lamports: e.amount_lamports != null ? String(e.amount_lamports) : null,
+ amount_raw: e.amount_raw != null ? String(e.amount_raw) : null,
+ usd: e.usd != null ? Number(e.usd) : null,
+ counterparty,
+ signature: e.signature || null,
+ explorer: e.signature ? explorerTxUrl(e.signature, e.network) : null,
+ at: e.created_at ? new Date(e.created_at).toISOString() : null,
+ };
+ });
+ return { items, next_cursor: items.length === lim ? items[items.length - 1].id : null };
+}
+
+/**
+ * Compact reserves + obligations for the reputation `solvency` factor. Reads live
+ * reserves (cached) and the cheap ledger obligations. Returns reservesKnown:false
+ * (never a fabricated number) if the wallet has no address or the read degrades.
+ */
+export async function getSolvencyInputs(agentId, { address, network = 'mainnet' } = {}) {
+ if (!address) return { reserveUsd: 0, obligationsUsd: 0, reservesKnown: false };
+ try {
+ const [snap, ledger] = await Promise.all([getReservesSnapshot(address, network), getLedgerSummary(agentId)]);
+ if (snap.degraded) return { reserveUsd: 0, obligationsUsd: 0, reservesKnown: false };
+ return {
+ reserveUsd: Number(snap.total_usd) || 0,
+ obligationsUsd: Number(ledger.obligations.total_usd) || 0,
+ reservesKnown: true,
+ };
+ } catch {
+ return { reserveUsd: 0, obligationsUsd: 0, reservesKnown: false };
+ }
+}
+
+/**
+ * The full Proof-of-Reserves payload for the transparency panel / API.
+ */
+export async function getProofOfReserves(agentId, { network = 'mainnet', isOwner = false, flowsLimit = 25, beforeId = null } = {}) {
+ const [agent] = await sql`
+ SELECT id, name, user_id, meta->>'solana_address' AS solana_address
+ FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1
+ `;
+ if (!agent) {
+ const e = new Error('agent not found');
+ e.code = 'not_found';
+ e.status = 404;
+ throw e;
+ }
+
+ const address = agent.solana_address || null;
+ const [reservesRes, ledger, flows] = await Promise.all([
+ address ? getReservesSnapshot(address, network).catch((err) => ({ error: err.code || 'rpc_error' })) : Promise.resolve(null),
+ getLedgerSummary(agentId),
+ getFlows(agentId, { limit: flowsLimit, beforeId }),
+ ]);
+
+ const reserves = reservesRes && !reservesRes.error ? reservesRes : null;
+ const reserveUsd = reserves ? Number(reserves.total_usd) || 0 : 0;
+ const obligationsUsd = Number(ledger.obligations.total_usd) || 0;
+ const ratio = obligationsUsd > 0 ? round2(reserveUsd / obligationsUsd) : null;
+ const solvencyStatus = !reserves
+ ? 'unknown'
+ : obligationsUsd <= 0
+ ? 'no_obligations'
+ : reserveUsd >= obligationsUsd
+ ? 'solvent'
+ : 'under_reserved';
+
+ return {
+ agent_id: agent.id,
+ name: agent.name,
+ network,
+ address,
+ is_owner: isOwner,
+ reserves: reserves
+ ? {
+ sol: reserves.sol,
+ sol_usd: reserves.sol_usd,
+ tokens: reserves.tokens,
+ token_usd: reserves.token_usd,
+ total_usd: reserves.total_usd,
+ verify_url: reserves.verify_url,
+ verified_at: reserves.verified_at,
+ degraded: Boolean(reserves.degraded),
+ last_verified_at: reserves.last_verified_at || null,
+ }
+ : address
+ ? { error: reservesRes?.error || 'rpc_error', verify_url: explorerAccountUrl(address, network) }
+ : null,
+ lifetime: { received: ledger.received, out: ledger.out },
+ obligations: ledger.obligations,
+ solvency: { reserve_usd: reserveUsd, obligations_usd: obligationsUsd, ratio, status: solvencyStatus },
+ flows: flows.items,
+ next_cursor: flows.next_cursor,
+ computed_at: new Date().toISOString(),
+ };
+}
diff --git a/api/_lib/trust/wallet-reputation.js b/api/_lib/trust/wallet-reputation.js
index 63d4fadaf..30aefd9d1 100644
--- a/api/_lib/trust/wallet-reputation.js
+++ b/api/_lib/trust/wallet-reputation.js
@@ -1,346 +1,47 @@
-// Wallet Reputation — a real, non-gameable trust score for an agent's wallet.
+// Wallet Reputation — the server-authoritative I/O layer for the agent financial
+// reputation score.
//
-// In a world of infinite forkable avatars, trust is the scarce asset. A wallet's
-// real history — how much it has earned, how long it has been active, how
-// reliably it settles, how many distinct funded wallets tipped it, how often it
-// was forked, whether it carries a verified on-chain identity — is the most
-// honest reputation signal three.ws has. This module turns those real, already-
-// settled facts into ONE explainable 0–100 score.
+// The pure, explainable scoring formula lives in
+// src/shared/agent-financial-reputation.js (computeReputation) so it is identical
+// on server and client and fully unit-tested. THIS module does the real reads —
+// the custody ledger (agent_custody_events), the on-chain payment index
+// (pump_agent_*), realized trading P&L (agent_sniper_positions), live reserves
+// vs obligations (proof-of-reserves), fork lineage, signed Solana attestations,
+// and the EVM ERC-8004 reputation registry — and resolves the owner's full wallet
+// set so wash-tips and self-dealing between an owner's own agents are excluded
+// from the computation, not flagged after the fact.
//
-// Design principles (read before touching the weights):
-//
-// 1. Every input is a real, verifiable fact pulled from the ledger
-// (agent_custody_events), the on-chain payment index (pump_agent_*), signed
-// Solana attestations, the EVM ERC-8004 reputation registry, fork lineage
-// (avatars.parent_avatar_id), and the agent's own age. No invented numbers.
-//
-// 2. Costly, provable signals outweigh cheap ones. Real USD volume, wallet age,
-// on-chain verification, and tips from DISTINCT funded wallets are weighted
-// heavily; anything a single actor can manufacture for free (self-tips, a
-// pile of payments from one wallet) is discounted or ignored in the
-// computation — not flagged after the fact.
-//
-// 3. The formula is fully explainable. computeReputation() is a pure function
-// that returns, for every pillar, the raw inputs, the points awarded, the
-// max, and human-readable detail. The UI renders that breakdown verbatim:
-// transparency is the trust.
-//
-// 4. A brand-new agent reads honestly as "new" — near-zero score, `new` tier —
-// never a fake high or a fake low. Time and money are the two things you
-// cannot fast-forward.
-//
-// The pillars and their maxima sum to 100:
-//
-// tenure 15 wallet/agent age (log-scaled) + recent activity cadence
-// volume 25 real settled USD that flowed through the wallet (earnings + tips)
-// tips 15 count of DISTINCT external funded wallets that tipped it
-// reliability 15 on-chain settlement success rate (only once there's volume)
-// lineage 10 how many times the avatar was forked (others valued it)
-// identity 20 verified ERC-8004 identity + registry feedback + attestations
-//
-// computeReputation is pure and unit-tested (tests/wallet-reputation.test.js).
-// loadReputationInputs / getAgentReputation do the real I/O.
+// computeReputation never fabricates: a source that errors degrades to its
+// zero/neutral value and is reflected as `partial` by the caller.
import { sql } from '../db.js';
import { loadAgentReputation } from './solana-bouncer.js';
-
-export const REPUTATION_VERSION = 1;
-
-// Pillar definitions — label + max points. Order is the display order.
-export const PILLARS = [
- { key: 'tenure', label: 'Tenure & consistency', max: 15 },
- { key: 'volume', label: 'Earnings & volume', max: 25 },
- { key: 'tips', label: 'Tips from distinct wallets', max: 15 },
- { key: 'reliability', label: 'Payment reliability', max: 15 },
- { key: 'lineage', label: 'Fork lineage', max: 10 },
- { key: 'identity', label: 'On-chain identity', max: 20 },
-];
-
-export const MAX_SCORE = PILLARS.reduce((s, p) => s + p.max, 0); // 100
-
-// Tier ladder. Tiers reflect REAL thresholds, not just the raw score — `trusted`
-// and above additionally require genuine counterparty diversity so age + identity
-// alone can never manufacture trust.
-export const TIERS = {
- new: { label: 'New', rank: 0, accent: '#9ca3af' },
- emerging: { label: 'Emerging', rank: 1, accent: '#c4b5fd' },
- established: { label: 'Established', rank: 2, accent: '#a78bfa' },
- trusted: { label: 'Trusted', rank: 3, accent: '#4ade80' },
- elite: { label: 'Elite', rank: 4, accent: '#fbbf24' },
-};
-
-const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
-const round1 = (n) => Math.round(n * 10) / 10;
-const log2 = (n) => Math.log(n) / Math.LN2;
+import { getSolvencyInputs } from './proof-of-reserves.js';
+import {
+ computeReputation,
+ tierFor,
+ PILLARS,
+ TIERS,
+ MAX_SCORE,
+ REPUTATION_VERSION,
+} from '../../../src/shared/agent-financial-reputation.js';
+
+// Re-export the pure primitives so existing importers (and the unit tests) keep a
+// single import surface.
+export { computeReputation, tierFor, PILLARS, TIERS, MAX_SCORE, REPUTATION_VERSION };
+
+const round1 = (n) => Math.round((Number(n) || 0) * 10) / 10;
/**
- * Pure scoring function. Takes a fully-resolved, real `inputs` object (no I/O)
- * and returns an explainable reputation result. Kept pure so the formula is
- * unit-testable and identical on server and (if ever) client.
- *
- * @param {object} inputs
- * @param {number} inputs.ageDays agent/wallet age in days
- * @param {number} inputs.activeDays90 distinct days with ledger activity in last 90d
- * @param {number} inputs.externalTipUsd real USD tipped by NON-self wallets
- * @param {number} inputs.settledUsd real USD that settled through the wallet (earnings)
- * @param {number} inputs.tipCount total recorded tips
- * @param {number} inputs.distinctTippers distinct EXTERNAL funded tipper wallets
- * @param {number} inputs.selfTipCount tips whose sender == the wallet itself (ignored)
- * @param {number} inputs.confirmedPayments confirmed on-chain payments accepted
- * @param {number} inputs.failedPayments failed on-chain payments
- * @param {number} inputs.distinctPayers distinct confirmed payers
- * @param {number} inputs.distributionSuccess success rate of distribute/buyback runs (0..1)
- * @param {number} inputs.forkCount times this avatar was forked
- * @param {boolean} inputs.hasOnchainIdentity verified ERC-8004 identity present
- * @param {number} inputs.registryAverage ERC-8004 reputation registry average (0..5 or 0..100)
- * @param {number} inputs.registryCount ERC-8004 registry feedback count
- * @param {number} inputs.validationCount signed Solana validation attestations
- * @param {number} inputs.feedbackCount signed Solana feedback attestations
- * @param {boolean} inputs.hasSkillCollection on-chain skill-license collection minted
- * @returns {object} { version, score, tier, tierLabel, accent, isNew, pillars, discounted, totals }
- */
-export function computeReputation(inputs = {}) {
- const i = normalizeInputs(inputs);
- const pillars = [];
- const discounted = [];
-
- // Counterparty concentration — the core anti-gaming guard. Real trust comes
- // from MANY distinct funded wallets choosing to pay/tip. If volume is high but
- // it all came from a single counterparty (a classic wash / self-deal pattern),
- // the money-weighted pillars are heavily discounted: that volume is not
- // evidence the wider world trusts this agent.
- const tipDiversity = i.distinctTippers;
- const concentrated = i.tipCount > 1 && tipDiversity <= 1;
- const diversityMultiplier = concentrated ? 0.35 : 1;
-
- // ── Tenure & consistency (max 15) ──────────────────────────────────────────
- // Age is the single most non-gameable signal: you cannot fast-forward time.
- const agePts = clamp(3.4 * Math.log10(i.ageDays + 1), 0, 10);
- const consistencyPts = clamp((i.activeDays90 / 30) * 5, 0, 5);
- pushPillar(pillars, 'tenure', agePts + consistencyPts, {
- detail:
- i.ageDays < 1
- ? 'Brand-new wallet — no track record yet.'
- : `${fmtAge(i.ageDays)} old · active ${i.activeDays90} of the last 90 days.`,
- facts: { age_days: Math.round(i.ageDays), active_days_90: i.activeDays90 },
- });
-
- // ── Earnings & volume (max 25) ─────────────────────────────────────────────
- // Real USD that flowed through the wallet. Money moved is costly to fake.
- const rawVolume = i.settledUsd + i.externalTipUsd;
- const volumePtsRaw = clamp(6.5 * Math.log10(rawVolume + 1), 0, 25);
- const volumePts = volumePtsRaw * diversityMultiplier;
- pushPillar(pillars, 'volume', volumePts, {
- detail:
- rawVolume <= 0
- ? 'No settled volume yet.'
- : `$${fmtUsd(rawVolume)} in real settled volume${concentrated ? ' (discounted — single counterparty)' : ''}.`,
- facts: { settled_usd: round1(i.settledUsd), tip_usd: round1(i.externalTipUsd) },
- });
-
- // ── Tips from distinct wallets (max 15) ────────────────────────────────────
- // Each DISTINCT funded tipper is a real Sybil cost. Self-tips are excluded
- // entirely from the count below.
- const tipsPtsRaw = clamp(5 * log2(tipDiversity + 1), 0, 15);
- const tipsPts = tipsPtsRaw * diversityMultiplier;
- pushPillar(pillars, 'tips', tipsPts, {
- detail:
- tipDiversity === 0
- ? 'No tips from external wallets yet.'
- : `${tipDiversity} distinct funded wallet${tipDiversity === 1 ? '' : 's'} tipped this agent.`,
- facts: { distinct_tippers: tipDiversity, total_tips: i.tipCount },
- });
-
- // ── Payment reliability (max 15) ───────────────────────────────────────────
- // Only meaningful once there's real settlement volume. A new agent honestly
- // scores 0 here (no history) rather than an unearned full mark.
- const settled = i.confirmedPayments + i.failedPayments;
- let reliabilityPts = 0;
- let reliabilityDetail = 'No settled payments yet — reliability is unproven.';
- if (settled >= 5) {
- const successRate = i.confirmedPayments / settled;
- reliabilityPts = successRate * 12 + clamp(i.distributionSuccess * 3, 0, 3);
- reliabilityDetail = `${(successRate * 100).toFixed(0)}% of ${settled} settlements succeeded${
- i.distributionSuccess > 0 ? `, ${(i.distributionSuccess * 100).toFixed(0)}% distribution success` : ''
- }.`;
- }
- pushPillar(pillars, 'reliability', reliabilityPts, {
- detail: reliabilityDetail,
- facts: { confirmed_payments: i.confirmedPayments, failed_payments: i.failedPayments },
- });
-
- // ── Fork lineage (max 10) ──────────────────────────────────────────────────
- // Being forked a lot is a real, costly-to-fake signal that others valued this
- // agent enough to copy it.
- const lineagePts = clamp(3.3 * log2(i.forkCount + 1), 0, 10);
- pushPillar(pillars, 'lineage', lineagePts, {
- detail:
- i.forkCount === 0
- ? 'Not forked yet.'
- : `Forked ${i.forkCount} time${i.forkCount === 1 ? '' : 's'} by other creators.`,
- facts: { fork_count: i.forkCount },
- });
-
- // ── On-chain identity & verification (max 20) ──────────────────────────────
- let identityPts = 0;
- const idBits = [];
- if (i.hasOnchainIdentity) {
- identityPts += 8;
- idBits.push('verified ERC-8004 identity');
- }
- if (i.registryCount > 0) {
- // Registry average may arrive on a 0–5 star scale or a 0–100 scale.
- const norm = i.registryAverage > 5 ? i.registryAverage / 100 : i.registryAverage / 5;
- const regPts = clamp(norm * 4 + clamp(log2(i.registryCount + 1), 0, 2), 0, 6);
- identityPts += regPts;
- idBits.push(`${i.registryCount} on-chain review${i.registryCount === 1 ? '' : 's'}`);
- }
- const attPts = clamp(i.validationCount * 2 + i.feedbackCount * 0.5, 0, 4);
- if (attPts > 0) {
- identityPts += attPts;
- idBits.push(`${i.validationCount + i.feedbackCount} signed attestation${i.validationCount + i.feedbackCount === 1 ? '' : 's'}`);
- }
- if (i.hasSkillCollection) {
- identityPts += 2;
- idBits.push('on-chain skill licenses');
- }
- identityPts = clamp(identityPts, 0, 20);
- pushPillar(pillars, 'identity', identityPts, {
- detail: idBits.length ? `Carries ${idBits.join(', ')}.` : 'No on-chain identity or attestations yet.',
- facts: { verified: i.hasOnchainIdentity, registry_count: i.registryCount, attestations: i.validationCount + i.feedbackCount },
- });
-
- // ── Anti-gaming transparency ───────────────────────────────────────────────
- // Surface what did NOT count so the score reads as credible.
- if (i.selfTipCount > 0) {
- discounted.push({
- kind: 'self_tips',
- label: `${i.selfTipCount} self-tip${i.selfTipCount === 1 ? '' : 's'} ignored`,
- detail: 'Tips sent from the wallet to itself carry no trust and are excluded from the score.',
- });
- }
- if (concentrated) {
- discounted.push({
- kind: 'concentration',
- label: 'Single-counterparty volume discounted',
- detail:
- 'Most volume came from one wallet. Trust requires many distinct funded counterparties, so this volume is weighted down.',
- });
- }
-
- const score = round1(clamp(pillars.reduce((s, p) => s + p.points, 0), 0, MAX_SCORE));
-
- // Real activity floor for the "new" verdict — independent of the raw score,
- // which is never exactly 0 once an agent has any age.
- const realActivity =
- i.tipCount +
- i.confirmedPayments +
- i.forkCount +
- i.validationCount +
- i.feedbackCount +
- i.registryCount +
- (i.hasOnchainIdentity ? 1 : 0) +
- (rawVolume > 0 ? 1 : 0);
- const isNew = realActivity === 0;
-
- const tier = tierFor({ score, isNew, distinctTippers: tipDiversity, confirmedPayments: i.confirmedPayments });
-
- return {
- version: REPUTATION_VERSION,
- score,
- max: MAX_SCORE,
- tier,
- tierLabel: TIERS[tier].label,
- accent: TIERS[tier].accent,
- isNew,
- pillars,
- discounted,
- totals: {
- settled_usd: round1(rawVolume),
- distinct_tippers: tipDiversity,
- confirmed_payments: i.confirmedPayments,
- fork_count: i.forkCount,
- verified: i.hasOnchainIdentity,
- },
- };
-}
-
-/**
- * Tier from the real score + real counterparty thresholds. `trusted`/`elite`
- * require genuine counterparty diversity (≥3 distinct tippers OR ≥10 confirmed
- * payments) so that score earned purely from age + identity can never be sold as
- * peer trust.
- */
-export function tierFor({ score, isNew, distinctTippers = 0, confirmedPayments = 0 }) {
- if (isNew) return 'new';
- const hasPeerTrust = distinctTippers >= 3 || confirmedPayments >= 10;
- if (score >= 75 && hasPeerTrust) return 'elite';
- if (score >= 55 && hasPeerTrust) return 'trusted';
- if (score >= 30) return 'established';
- return 'emerging';
-}
-
-function pushPillar(arr, key, points, extra) {
- const def = PILLARS.find((p) => p.key === key);
- arr.push({
- key,
- label: def.label,
- points: round1(clamp(points, 0, def.max)),
- max: def.max,
- ...extra,
- });
-}
-
-function normalizeInputs(raw) {
- const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
- return {
- ageDays: Math.max(0, num(raw.ageDays)),
- activeDays90: Math.max(0, num(raw.activeDays90)),
- externalTipUsd: Math.max(0, num(raw.externalTipUsd)),
- settledUsd: Math.max(0, num(raw.settledUsd)),
- tipCount: Math.max(0, num(raw.tipCount)),
- distinctTippers: Math.max(0, num(raw.distinctTippers)),
- selfTipCount: Math.max(0, num(raw.selfTipCount)),
- confirmedPayments: Math.max(0, num(raw.confirmedPayments)),
- failedPayments: Math.max(0, num(raw.failedPayments)),
- distinctPayers: Math.max(0, num(raw.distinctPayers)),
- distributionSuccess: clamp(num(raw.distributionSuccess), 0, 1),
- forkCount: Math.max(0, num(raw.forkCount)),
- hasOnchainIdentity: Boolean(raw.hasOnchainIdentity),
- registryAverage: Math.max(0, num(raw.registryAverage)),
- registryCount: Math.max(0, num(raw.registryCount)),
- validationCount: Math.max(0, num(raw.validationCount)),
- feedbackCount: Math.max(0, num(raw.feedbackCount)),
- hasSkillCollection: Boolean(raw.hasSkillCollection),
- };
-}
-
-function fmtAge(days) {
- if (days >= 365) return `${(days / 365).toFixed(1)}y`;
- if (days >= 30) return `${Math.round(days / 30)}mo`;
- if (days >= 1) return `${Math.round(days)}d`;
- return '<1d';
-}
-function fmtUsd(n) {
- if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
- if (n >= 1_000) return `${(n / 1_000).toFixed(1)}k`;
- return n.toFixed(n < 10 ? 2 : 0);
-}
-
-// ── Real I/O ────────────────────────────────────────────────────────────────
-
-/**
- * Gather every REAL reputation input for an agent from the ledger, the on-chain
- * payment index, fork lineage, attestations, and (best-effort) the EVM ERC-8004
- * reputation registry. Never fabricates: a source that errors degrades to its
- * zero/neutral value and is reflected as `partial` by the caller.
+ * Gather every REAL reputation input for an agent. See computeReputation for the
+ * meaning of each field. Pass `lite:true` to skip the optional EVM ERC-8004 RPC
+ * read and the live-reserves RPC read (used for batch list rendering); those
+ * contribute ≤20 of 100 and the full per-agent endpoint always includes them, so
+ * a lite score stays honest.
*
* @param {string} agentId
* @param {object} [opts]
- * @param {boolean} [opts.lite=false] Skip the best-effort EVM ERC-8004 registry
- * RPC read — used for batch list rendering where dozens of agents are
- * scored at once. The registry contributes ≤6 of 100 and the full
- * per-agent endpoint always includes it, so a lite score stays honest.
+ * @param {boolean} [opts.lite=false]
* @returns {Promise<{ inputs: object, agent: object, evidence: object, partial: boolean }>}
*/
export async function loadReputationInputs(agentId, opts = {}) {
@@ -357,7 +58,7 @@ export async function loadReputationInputs(agentId, opts = {}) {
const [agent] = await sql`
select
- id, name, created_at, avatar_id, chain_id, erc8004_agent_id,
+ id, name, user_id, created_at, avatar_id, chain_id, erc8004_agent_id,
skill_collection_mint,
meta->>'solana_address' as solana_address,
wallet_address
@@ -375,7 +76,22 @@ export async function loadReputationInputs(agentId, opts = {}) {
const ownWallet = agent.solana_address || '__none__';
const ageDays = agent.created_at ? (Date.now() - new Date(agent.created_at).getTime()) / 86_400_000 : 0;
- // Ledger: tips, volume, cadence — all from agent_custody_events.
+ // The owner's full agent + wallet set — the basis for self-dealing detection.
+ // A "wash-tip" is a tip whose sender is ANOTHER agent the same owner controls;
+ // it carries no third-party trust and must be excluded, exactly like a self-tip.
+ const ownedRows = await soft(
+ sql`
+ select id, meta->>'solana_address' as addr
+ from agent_identities
+ where user_id = ${agent.user_id} and deleted_at is null
+ `,
+ [],
+ );
+ const ownedAgentIds = ownedRows.map((r) => r.id);
+ const ownedWallets = ownedRows.map((r) => r.addr).filter(Boolean);
+ const ownedWalletsParam = ownedWallets.length ? ownedWallets : ['__none__'];
+
+ // Ledger: tips received, volume, cadence, wash detection — all from the ledger.
const [ledger] = await soft(
sql`
select
@@ -383,18 +99,30 @@ export async function loadReputationInputs(agentId, opts = {}) {
as tip_count,
count(distinct case
when event_type = 'tip' and status in ('confirmed','ok')
- and meta->>'from' is not null and meta->>'from' <> ${ownWallet}
+ and meta->>'from' is not null and not (meta->>'from' = any(${ownedWalletsParam}))
then meta->>'from' end)::int
as distinct_tippers,
count(*) filter (
where event_type = 'tip' and meta->>'from' = ${ownWallet}
)::int as self_tip_count,
+ count(*) filter (
+ where event_type = 'tip' and status in ('confirmed','ok')
+ and meta->>'from' is not null and meta->>'from' <> ${ownWallet}
+ and meta->>'from' = any(${ownedWalletsParam})
+ )::int as wash_tip_count,
+ coalesce(sum(case
+ when event_type = 'tip' and status in ('confirmed','ok')
+ and meta->>'from' is not null and meta->>'from' <> ${ownWallet}
+ and meta->>'from' = any(${ownedWalletsParam})
+ then usd else 0 end), 0)::float8 as wash_tip_usd,
coalesce(sum(case
when event_type = 'tip' and status in ('confirmed','ok')
- and (meta->>'from') is distinct from ${ownWallet}
+ and not (meta->>'from' = any(${ownedWalletsParam}))
then usd else 0 end), 0)::float8 as external_tip_usd,
coalesce(sum(case
- when status in ('confirmed','ok') and usd is not null then usd else 0 end), 0)::float8
+ when status in ('confirmed','ok') and usd is not null
+ and not (coalesce(meta->>'from','') = any(${ownedWalletsParam}))
+ then usd else 0 end), 0)::float8
as settled_usd,
count(distinct date_trunc('day', created_at)) filter (
where created_at >= now() - interval '90 days'
@@ -405,7 +133,67 @@ export async function loadReputationInputs(agentId, opts = {}) {
[{}],
);
- // Fork lineage: how many avatars were forked from this agent's avatar.
+ // Generosity: tips this wallet GAVE to OTHER owners' agents (wash-excluded).
+ const [given] = await soft(
+ sql`
+ select
+ count(*)::int as cnt,
+ coalesce(sum(usd), 0)::float8 as usd
+ from agent_custody_events
+ where event_type = 'tip' and status in ('confirmed','ok')
+ and meta->>'from' = ${ownWallet}
+ and not (agent_id = any(${ownedAgentIds.length ? ownedAgentIds : ['00000000-0000-0000-0000-000000000000']}))
+ `,
+ [{ cnt: 0, usd: 0 }],
+ );
+
+ // Reciprocity: distinct external wallets that BOTH tipped this agent AND
+ // received an outbound transfer from it — a real two-way relationship.
+ const [recip] = await soft(
+ sql`
+ select count(*)::int as pairs from (
+ select distinct meta->>'from' as w
+ from agent_custody_events
+ where agent_id = ${agentId} and event_type = 'tip' and status in ('confirmed','ok')
+ and meta->>'from' is not null and not (meta->>'from' = any(${ownedWalletsParam}))
+ ) tin
+ join (
+ select distinct destination as w
+ from agent_custody_events
+ where agent_id = ${agentId} and event_type in ('withdraw','spend') and destination is not null
+ ) tout using (w)
+ `,
+ [{ pairs: 0 }],
+ );
+
+ // Trading conduct: realized P&L over CLOSED positions (a real settlement).
+ const [trades] = await soft(
+ sql`
+ select
+ count(*) filter (where status = 'closed')::int as closed,
+ count(*) filter (where status = 'closed' and realized_pnl_lamports > 0)::int as wins,
+ coalesce(sum(realized_pnl_lamports) filter (where status = 'closed'), 0)::float8 as pnl_lamports
+ from agent_sniper_positions
+ where agent_id = ${agentId} and realized_pnl_lamports is not null
+ `,
+ [{ closed: 0, wins: 0, pnl_lamports: 0 }],
+ );
+
+ // Dumps on supporters: large sells of its OWN launched coin within 24h of the
+ // launch — selling into the people who just bought in. Real, on-chain.
+ const [dumps] = await soft(
+ sql`
+ select count(*)::int as n
+ from pump_agent_trades t
+ join pump_agent_mints m on m.id = t.mint_id
+ where m.agent_id = ${agentId} and t.wallet = ${ownWallet} and t.direction = 'sell'
+ and t.created_at < m.created_at + interval '24 hours'
+ and t.sol_amount is not null and abs(t.sol_amount) > 1000000000
+ `,
+ [{ n: 0 }],
+ );
+
+ // Fork lineage.
const [forks] = agent.avatar_id
? await soft(
sql`
@@ -421,9 +209,16 @@ export async function loadReputationInputs(agentId, opts = {}) {
const solRep = await soft(loadAgentReputation(agentId), null);
// Best-effort EVM ERC-8004 reputation registry read (skipped in lite mode).
- const registry = lite
- ? { average: 0, count: 0 }
- : await soft(readErc8004Registry(agent), { average: 0, count: 0 });
+ const registry = lite ? { average: 0, count: 0 } : await soft(readErc8004Registry(agent), { average: 0, count: 0 });
+
+ // Live reserves vs obligations for solvency (skipped in lite mode — RPC heavy).
+ const solvency = lite
+ ? { reserveUsd: 0, obligationsUsd: 0, reservesKnown: false }
+ : await soft(getSolvencyInputs(agentId, { address: agent.solana_address, network: 'mainnet' }), {
+ reserveUsd: 0,
+ obligationsUsd: 0,
+ reservesKnown: false,
+ });
const inputs = {
ageDays,
@@ -433,10 +228,22 @@ export async function loadReputationInputs(agentId, opts = {}) {
tipCount: ledger?.tip_count || 0,
distinctTippers: ledger?.distinct_tippers || 0,
selfTipCount: ledger?.self_tip_count || 0,
+ washTipCount: ledger?.wash_tip_count || 0,
+ washTipUsd: ledger?.wash_tip_usd || 0,
confirmedPayments: solRep?.payments?.confirmed_count || 0,
failedPayments: solRep?.payments?.failed_count || 0,
distinctPayers: solRep?.payments?.distinct_payers || 0,
distributionSuccess: solRep?.distributions?.success_rate || 0,
+ tipsGivenUsd: given?.usd || 0,
+ tipsGivenCount: given?.cnt || 0,
+ reciprocalPairs: recip?.pairs || 0,
+ closedTrades: trades?.closed || 0,
+ winningTrades: trades?.wins || 0,
+ realizedPnlSol: (Number(trades?.pnl_lamports) || 0) / 1e9,
+ dumpEvents: dumps?.n || 0,
+ reserveUsd: solvency?.reserveUsd || 0,
+ obligationsUsd: solvency?.obligationsUsd || 0,
+ reservesKnown: Boolean(solvency?.reservesKnown),
forkCount: forks?.fork_count || 0,
hasOnchainIdentity: Boolean(agent.erc8004_agent_id),
registryAverage: registry?.average || 0,
@@ -469,10 +276,9 @@ export async function getAgentReputation(agentId, opts = {}) {
}
/**
- * Compact, best-effort reputation for a set of agents — used by discovery
- * ranking (trending, the trusted leaderboard) where many agents are scored at
- * once. Always lite (no per-agent EVM RPC), always resilient: an agent that
- * fails to score is simply omitted, never faked. Returns a Map id -> compact.
+ * Compact, best-effort reputation for a set of agents — used by discovery ranking
+ * (trending, the trusted leaderboard) where many agents are scored at once.
+ * Always lite, always resilient. Returns a Map id -> compact.
*/
export async function scoreAgentsLite(agentIds = [], { concurrency = 8 } = {}) {
const ids = [...new Set(agentIds.filter(Boolean))];
@@ -522,10 +328,7 @@ async function readErc8004Registry(agent) {
function buildEvidence(agent, { solRep, registry }) {
const ev = {};
if (agent.solana_address) {
- ev.wallet = {
- label: 'Wallet activity',
- href: `https://solscan.io/account/${agent.solana_address}`,
- };
+ ev.wallet = { label: 'Wallet activity', href: `https://solscan.io/account/${agent.solana_address}` };
ev.ledger = { label: 'Custody ledger', href: `/agent/${agent.id}/wallet` };
}
if (agent.avatar_id) {
@@ -548,11 +351,35 @@ function buildEvidence(agent, { solRep, registry }) {
// not see this — only the owner can act on it.
function buildGuidance(result, inputs, agent) {
const tips = [];
+ if (inputs.washTipCount > 0) {
+ tips.push({
+ action: 'stop_self_dealing',
+ label: 'Stop tipping yourself between your own agents',
+ detail: `${inputs.washTipCount} wash-tip${inputs.washTipCount === 1 ? '' : 's'} were ignored. Trust only grows from independent wallets.`,
+ href: `/agent/${agent.id}/wallet`,
+ });
+ }
+ if (inputs.reservesKnown && inputs.obligationsUsd > inputs.reserveUsd) {
+ tips.push({
+ action: 'top_up_reserves',
+ label: 'Top up reserves to cover obligations',
+ detail: `Your reserves ($${round1(inputs.reserveUsd)}) are below your outstanding obligations ($${round1(inputs.obligationsUsd)}).`,
+ href: `/agent/${agent.id}/wallet#reserves`,
+ });
+ }
+ if (inputs.dumpEvents > 0) {
+ tips.push({
+ action: 'protect_supporters',
+ label: 'Stop dumping on your supporters',
+ detail: 'Large sells right after your launch hurt early buyers and lower your trading conduct.',
+ href: `/agent/${agent.id}/wallet`,
+ });
+ }
if (!inputs.hasOnchainIdentity) {
tips.push({
action: 'verify_identity',
label: 'Verify your on-chain identity',
- detail: 'Register an ERC-8004 identity to add up to 8 points of provable trust.',
+ detail: 'Register an ERC-8004 identity to add provable trust.',
href: `/agent/${agent.id}/onchain`,
});
}
@@ -564,11 +391,11 @@ function buildGuidance(result, inputs, agent) {
href: `/agent/${agent.id}/wallet`,
});
}
- if (inputs.confirmedPayments < 10) {
+ if (inputs.tipsGivenUsd <= 0) {
tips.push({
- action: 'transact',
- label: 'Build a settlement history',
- detail: 'Reliable, confirmed on-chain payments raise your reliability score over time.',
+ action: 'give_back',
+ label: 'Tip the agents you work with',
+ detail: 'Reciprocity builds standing — supporting other agents raises your generosity factor.',
href: `/agent/${agent.id}/wallet`,
});
}
diff --git a/api/agents/_id/reserves.js b/api/agents/_id/reserves.js
new file mode 100644
index 000000000..1bbc443e6
--- /dev/null
+++ b/api/agents/_id/reserves.js
@@ -0,0 +1,68 @@
+// GET /api/agents/:id/solana/reserves (also reachable at /api/agents/:id/reserves)
+//
+// Proof-of-Reserves for an agent's wallet — verifiable, on-chain-derived
+// transparency. Public read: an agent's reserves and its flow history are public
+// on-chain facts, so owner, visitor, and logged-out all see the same numbers and
+// the same one-tap "verify on-chain" link. Only owner-only data (spend policy,
+// keys, private notes) is ever withheld — and none of that is in this payload.
+//
+// Everything here is either a LIVE read of real Solana chain state or a real,
+// already-settled custody-ledger row linking to its on-chain signature. When RPC
+// is throttled, reserves degrade to the last verified snapshot with an honest
+// timestamp — never a stale "verified now". All compute lives in
+// api/_lib/trust/proof-of-reserves.js.
+
+import { cors, json, error, method, wrap, rateLimited } from '../../_lib/http.js';
+import { limits, clientIp } from '../../_lib/rate-limit.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { sql } from '../../_lib/db.js';
+import { getProofOfReserves } from '../../_lib/trust/proof-of-reserves.js';
+
+async function resolveUserId(req) {
+ try {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ } catch {
+ /* anonymous */
+ }
+ return null;
+}
+
+export const handleReserves = wrap(async (req, res, agentId) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const flowsLimit = Math.min(100, Math.max(1, parseInt(url.searchParams.get('limit') || '25', 10) || 25));
+ const beforeRaw = url.searchParams.get('before');
+ const beforeId = beforeRaw && /^\d+$/.test(beforeRaw) ? beforeRaw : null;
+
+ // Ownership only unlocks the "improve your solvency" affordances client-side;
+ // the figures themselves are public, so we resolve it but never gate the data.
+ const userId = await resolveUserId(req);
+ let isOwner = false;
+ if (userId) {
+ const [own] = await sql`
+ select 1 from agent_identities where id = ${agentId} and user_id = ${userId} and deleted_at is null limit 1
+ `.catch(() => []);
+ isOwner = Boolean(own);
+ }
+
+ let payload;
+ try {
+ payload = await getProofOfReserves(agentId, { network, isOwner, flowsLimit, beforeId });
+ } catch (err) {
+ if (err.status === 404) return error(res, 404, 'not_found', 'agent not found');
+ throw err;
+ }
+
+ // Reserves are live; flows are a paginated ledger window. Short public cache so
+ // the "verify on-chain" claim stays close to real-time.
+ return json(res, 200, payload, { 'cache-control': 'public, max-age=30, stale-while-revalidate=120' });
+});
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index f892a3f9e..b466522db 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -2307,6 +2307,10 @@ export default async function handler(req, res, id, action) {
if (action === 'withdraw') return handleWithdraw(req, res, id);
if (action === 'vanity') return handleVanity(req, res, id);
if (action === 'holdings') return handleHoldings(req, res, id);
+ if (action === 'reserves') {
+ const mod = await import('./_id/reserves.js');
+ return mod.handleReserves(req, res, id);
+ }
if (action === 'networth') return handleNetWorth(req, res, id);
if (action === 'custody') return handleCustody(req, res, id);
if (action === 'limits') return handleLimits(req, res, id);
diff --git a/prompts/agent-wallets-ii/03-embodied-finance.md b/prompts/agent-wallets-ii/03-embodied-finance.md
deleted file mode 100644
index 8f7f7f961..000000000
--- a/prompts/agent-wallets-ii/03-embodied-finance.md
+++ /dev/null
@@ -1,89 +0,0 @@
-# Task 03 — Embodied Finance: the avatar *is* its wealth
-
-> Read [00-README-orchestration.md](./00-README-orchestration.md) first. This task
-> assumes all of it (ownership model, hard rules, design tokens, real APIs, concurrency
-> traps, definition of done, self-improve-then-delete).
-
-## The idea (why it's gamechanging)
-
-Every agent on three.ws is a **3D embodied avatar**. No other platform can do this: make
-the agent's wallet **visible in its body.** An agent that's earning, well-funded, and
-trading profitably *looks* alive — a subtle aura, a confident idle, a richer glow. An
-agent that's broke or bleeding looks dimmer. Wealth becomes embodied, ambient, and
-instantly legible across the whole world — the galaxy, the marketplace, IRL/AR, the
-profile — without a single chart.
-
-This is "show, don't tell" applied to money. It makes the platform feel alive and makes
-the wallet impossible to ignore, because it's *the character itself.* It's the kind of
-thing people screenshot and post.
-
-## How to build it for real (driven by real wallet data, never decorative noise)
-
-1. **A real "wealth state" derived from real data.** Build a shared, cached selector
- `src/shared/agent-wealth-state.js` that turns an agent's real wallet data into a small,
- honest state object: `{ tier, balanceSol, balanceUsd, momentum, streamingNow, lastTipAt }`.
- Inputs are all real:
- - balance/holdings from `GET /api/agents/:id/solana/holdings`,
- - realized momentum from the custody ledger (`listCustodyEvents` — tips/streams in,
- trades/withdraws out) and trade history
- ([api/agents/solana-trade.js](../../api/agents/solana-trade.js)),
- - "streaming now" from the Money Streams custody events (task 01),
- - $THREE context where relevant via the existing pricing helpers.
- `tier` is a small, well-defined ladder (e.g. dormant → active → thriving → whale)
- computed from real thresholds — **document the thresholds; never random.** Cache to
- respect RPC limits (mirror the 60s wallet-read cache already used in
- [api/agents/solana-wallet.js]).
-2. **Embodiment layer.** Map wealth state → tasteful, performant 3D/CSS treatment:
- - In 3D contexts (avatar page [src/avatar-page.js], galaxy [src/galaxy.js], IRL
- [src/irl.js], world): a subtle emissive aura / rim light / particle density / idle
- confidence keyed to `tier`, and a brief celebratory pulse on a real incoming
- tip/stream/profitable exit. Use the existing Three.js setup; keep it GPU-cheap
- (no per-frame allocations; respect the renderer already in place).
- - In 2D contexts (cards, chip, profile header): a matching aura ring / gradient token
- so the same agent reads at the same "wealth tier" everywhere. Route through
- `--wallet-accent` and new tokens; never scatter hex.
-3. **Honesty + restraint.** The effect must reflect **real** state — if balance is 0, the
- agent looks dormant, full stop (no fake shimmer). Keep it tasteful: it should enhance,
- never turn the app into a slot machine. Everything must degrade gracefully if holdings
- can't be read (RPC down → neutral state, never a misleading "rich" glow).
-
-## The UI / integration
-
-- A single source of truth (`agent-wealth-state.js`) consumed by every surface that
- renders an avatar, so the embodiment is consistent app-wide. Coordinate with Wave I's
- shared chip so the chip can show the tier label/aura too.
-- A small, optional **"why"** affordance on the owner's own agent: tap the aura to see the
- real numbers behind the state (balance, 24h momentum, streaming now) — links into the
- HUD. Visitors see the aura but not the owner-only breakdown.
-- Respect `prefers-reduced-motion`: replace animated auras with a static treatment.
-- Performance budget: the effect must not regress frame rate on the galaxy or IRL with
- many agents on screen — instanced/shared materials, LOD the effect by distance, throttle
- data refresh.
-
-## Ownership / viewer states
-
-- **Everyone** sees the embodiment (it's public, derived from public balance + public
- custody-flow signals — never exposes secret or owner-only data).
-- **Owner** additionally gets the "why" breakdown + a toggle to opt their agent's
- embodiment up/down (some owners may want it subtle). Never let embodiment leak
- owner-only figures to visitors — visitors see the *tier/aura*, not exact P&L unless the
- owner has made balance public (it already is, via the public holdings read) — keep
- visitor detail to balance-level only.
-
-## Definition of done (in addition to 00's list)
-
-- Wealth state is computed from **real** holdings + custody/trade data, cached sanely,
- documented thresholds, graceful neutral fallback on RPC failure.
-- Embodiment renders consistently in 3D (avatar/galaxy/IRL) and 2D (cards/chip/profile)
- with no frame-rate regression and full reduced-motion support.
-- Real incoming tip/stream/profit triggers a real-time celebratory pulse (subscribe to
- the same signals task 01/05 emit).
-- Edge cases: 0 balance, RPC throttled, 1000 agents in the galaxy at once, an agent with
- no avatar (fall back to the card aura), expired session.
-
-## Then improve, then delete
-
-After done, run the self-review protocol. Pick the biggest weakness and fix it — e.g.
-"level-up" moments when an agent crosses a tier (a tasteful, shareable card), or wiring
-the aura into the IRL/AR walk so a well-funded agent you pass in the real world glows.
-Then **delete this file**.
diff --git a/public/avatar-actions.js b/public/avatar-actions.js
index 02b8ec1a9..e48550bf4 100644
--- a/public/avatar-actions.js
+++ b/public/avatar-actions.js
@@ -232,7 +232,7 @@ class AvatarActions extends HTMLElement {
// Nothing to show for this viewer/mode combo — stay invisible rather than
// render an empty card.
- if (!body && !lineage && !forks) {
+ if (!body && !lineage && !forks && !royaltySignals) {
this.shadowRoot.innerHTML = '';
return;
}
@@ -240,12 +240,31 @@ class AvatarActions extends HTMLElement {
this.shadowRoot.innerHTML = `${css}
<div class="card">
${lineage || forks ? `<div class="row spread">${lineage}${forks}</div>` : ''}
+ ${royaltySignals ? `<div class="row">${royaltySignals}</div>` : ''}
<div class="body">${body}</div>
<div class="msg-slot"></div>
</div>`;
this._wire();
}
+ // Royalty trust chips: "earns from N forks" (ancestor) / "shares N% upstream"
+ // (descendant). Click opens the full transparent ledger. '' when nothing to say.
+ _royaltySignals() {
+ const d = this._royalty;
+ if (!d) return '';
+ const out = [];
+ const anc = d.ancestor;
+ const desc = d.descendant;
+ if (anc?.earns_royalties && anc.fork_count > 0) {
+ out.push(`<span class="rty-sig earn" data-royalty title="Earns a royalty when forks of this avatar earn">↑ earns from ${anc.fork_count} ${anc.fork_count === 1 ? 'fork' : 'forks'}</span>`);
+ }
+ if (desc?.shares_upstream && desc.total_bps > 0) {
+ const p = (desc.total_bps / 100).toLocaleString(undefined, { maximumFractionDigits: 2 });
+ out.push(`<span class="rty-sig" data-royalty title="Shares a slice of new income with the creators it descends from">⑂ shares ${p}% upstream</span>`);
+ }
+ return out.join('');
+ }
+
_walletBlock() {
const ag = this._agent;
if (!ag) {
@@ -305,6 +324,8 @@ class AvatarActions extends HTMLElement {
}),
);
root.querySelector('[data-act="fork"]')?.addEventListener('click', () => this._fork());
+ root.querySelectorAll('[data-royalty]').forEach((s) =>
+ s.addEventListener('click', () => this._openRoyalty()));
root
.querySelector('[data-act="create-wallet"]')
?.addEventListener('click', () => this._createWallet());
@@ -414,6 +435,17 @@ class AvatarActions extends HTMLElement {
}
}
+ // Open the transparent royalty ledger. Pages that load the app bundle expose
+ // the rich shared panel on window; everywhere else, route to the agent page
+ // where it is always available.
+ _openRoyalty() {
+ const agentId = this._agent?.id;
+ if (!agentId) return;
+ const panel = (typeof window !== 'undefined') && window.twsForkRoyalty?.openRoyaltyPanel;
+ if (panel) panel(agentId, { name: this._avatar?.name || 'this agent' });
+ else window.location.href = `/agent/${agentId}#royalties`;
+ }
+
// Inline royalty-consent dialog (self-contained — no cross-bundle import).
// Resolves true only on explicit accept. The fork is created by the caller.
_confirmRoyalty(royalty) {
diff --git a/src/agent-detail.js b/src/agent-detail.js
index c4ec403cb..cb69c1b2e 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -585,6 +585,17 @@ function render(agent) {
fork.style.display = 'block';
}
+ // Register the shared royalty panel so the avatar-actions royalty chips open
+ // the rich in-page ledger (rather than navigating away), and honor a
+ // /agent/:id#royalties deep link by opening it directly.
+ import('./shared/agent-fork-royalty.js')
+ .then((rty) => {
+ if (location.hash === '#royalties' && agent.id) {
+ rty.openRoyaltyPanel(agent.id, { name: agent.name || 'this agent' });
+ }
+ })
+ .catch(() => {});
+
// "See in 3D" drops this agent's avatar into the live $three world. Every
// agent has one — its own GLB if attached, the base mannequin otherwise — so
// the button is always live. Marketplace enrichment upgrades the href to a
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 9dbd3def5..74eb66128 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -18,6 +18,7 @@ import { PoseStage, loadPoseManifest } from './avatar-pose.js';
import { walletChipHTML, wireWalletChips } from './shared/agent-wallet-chip.js';
import { mountAgentSolanaWalletCard } from './agent-solana-wallet.js';
import { mountAgentVanityGrinderCard } from './agent-vanity-grinder.js';
+import { mountRoyaltySetting } from './shared/agent-fork-royalty.js';
import { hydrateAvatarWallet, walletTierBadge } from './shared/wallet-aura.js';
import { mountPresence } from './shared/networth-presence.js';
@@ -558,6 +559,15 @@ function mountWalletManager() {
} catch (err) {
log.error('[avatar] vanity card', err);
}
+
+ // Fork Royalty Streams: let the owner earn provenance income when others fork
+ // this avatar. Applies to future forks only; the forker always keeps the
+ // majority. Mounts under the wallet manager on the owner's own avatar.
+ try {
+ mountRoyaltySetting({ host, agentId: avatar.agent_id });
+ } catch (err) {
+ log.error('[avatar] royalty setting', err);
+ }
}
/**
diff --git a/src/forge.js b/src/forge.js
index 0efb528da..eec3f14eb 100644
--- a/src/forge.js
+++ b/src/forge.js
@@ -517,9 +517,12 @@ function updateEngineAvailability() {
// Live health beats the catalog's env-presence flag: a lane whose
// upstream auth/billing probe failed is disabled with the real reason.
const lane = health?.backends?.[btn.dataset.backend];
- const laneDown = lane && (lane.status === 'down' || lane.status === 'unconfigured');
+ const laneDown = Boolean(lane && (lane.status === 'down' || lane.status === 'unconfigured'));
const laneBusy = lane && lane.status === 'degraded';
- const blocked = (textOnly && hasPhotos) || laneDown;
+ // Boolean-coerce: before health loads, `lane` is undefined and a raw
+ // `(false) || undefined` would write aria-disabled="undefined" — an
+ // invalid ARIA token value (axe aria-valid-attr-value, WCAG 4.1.2).
+ const blocked = Boolean((textOnly && hasPhotos) || laneDown);
btn.disabled = blocked;
btn.setAttribute('aria-disabled', String(blocked));
btn.dataset.health = lane ? lane.status : '';
diff --git a/src/shared/agent-hire.js b/src/shared/agent-hire.js
index 1cb0b5b5c..c301840ba 100644
--- a/src/shared/agent-hire.js
+++ b/src/shared/agent-hire.js
@@ -119,7 +119,7 @@ export async function runHire({ hirerAgentId, serviceSlug, input = null, maxUsd,
body: JSON.stringify(body),
allowAnonymous: true,
});
- } catch (err) {
+ } catch {
return { ok: false, code: 'network', message: 'Network error — the hire did not start. No funds moved.' };
}
const j = await r.json().catch(() => null);
@@ -295,7 +295,7 @@ function ensureStyles() {
const escAttr = escHtml;
// Map a server error code to a designed, actionable message + optional CTA.
-function explainError(res, offer) {
+function explainError(res) {
const code = res.code || 'hire_failed';
const base = res.message || 'The hire could not complete.';
switch (code) {
@@ -472,7 +472,7 @@ export async function openHirePanel(offer, opts = {}) {
});
if (!res.ok) {
- const ex = explainError(res, offer);
+ const ex = explainError(res);
feedback.innerHTML = `<div class="tahx-alert tahx-alert-${ex.kind}">${ex.html}</div>`;
goBtn.disabled = false;
goBtn.textContent = original;
diff --git a/src/shared/irl-drops.js b/src/shared/irl-drops.js
new file mode 100644
index 000000000..4bee30197
--- /dev/null
+++ b/src/shared/irl-drops.js
@@ -0,0 +1,824 @@
+// IRL Money Drops & Bounties — client (Wave II task 06).
+//
+// Self-contained: src/irl.js calls initIrlDrops(ctx) once with accessors into the
+// live AR scene (scene, camera, the geo→world projection, the presence-token
+// headers). This module then owns everything else — world-anchored coin markers,
+// the accessible nearby/my-drops/my-claims panel, the "drop money here" create
+// flow (visitor-signed funding via src/shared/agent-tip.js), and the presence-
+// gated claim flow with a real Solscan receipt. No fakes: every number comes from
+// /api/irl/drops hitting the real escrow + on-chain release.
+
+import {
+ Group, Mesh, CylinderGeometry, TorusGeometry, MeshStandardMaterial,
+ MeshBasicMaterial, Vector3,
+} from 'three';
+import { tipAgent, TipError } from './agent-tip.js';
+import { detectSolanaWallet, solanaTxExplorerUrl } from '../erc8004/solana-deploy.js';
+
+const VIOLET = 0xc4b5fd;
+const VIOLET_DEEP = 0x8b5cf6;
+const ASSETS = ['SOL', 'USDC', 'THREE'];
+// Visitor-funded create signs through agent-tip.js, which moves SOL or USDC. A
+// $THREE drop is funded server-side from an agent's wallet (an agent bounty), so
+// the user-facing "drop money here" picker offers the two the visitor can sign.
+const CREATE_ASSETS = ['SOL', 'USDC'];
+const EXPIRY_PRESETS = [
+ { label: '1 hour', ms: 3600_000 },
+ { label: '24 hours', ms: 24 * 3600_000 },
+ { label: '7 days', ms: 7 * 24 * 3600_000 },
+];
+
+let ctx = null;
+let panelEl = null;
+let listEl = null;
+let tabsEl = null;
+let badgeEl = null;
+let activeTab = 'nearby';
+let nearby = []; // live nearby drops (from the presence-gated read)
+let mine = { drops: [], claims: [] };
+let pollTimer = null;
+let rafId = null;
+const markers = new Map(); // dropId → { group, label, drop }
+let _styled = false;
+let _lastFetchKey = '';
+
+// ── public entry ──────────────────────────────────────────────────────────────
+export function initIrlDrops(context) {
+ if (ctx) return; // once
+ ctx = context;
+ ensureStyles();
+ buildFab();
+ buildPanel();
+ startPolling();
+ startRaf();
+ window.addEventListener('pagehide', teardown, { once: true });
+}
+
+function teardown() {
+ if (pollTimer) clearInterval(pollTimer);
+ if (rafId) cancelAnimationFrame(rafId);
+ pollTimer = rafId = null;
+}
+
+// ── tiny DOM helpers ────────────────────────────────────────────────────────
+function el(tag, cls, html) {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ if (html != null) n.innerHTML = html;
+ return n;
+}
+function fmtAmount(d) {
+ const a = String(d.amount);
+ const sym = d.asset === 'THREE' ? '$THREE' : d.asset;
+ return `${a} ${sym}`;
+}
+function fmtDistance(m) {
+ if (m == null) return '';
+ return m < 1000 ? `${Math.round(m)} m` : `${(m / 1000).toFixed(1)} km`;
+}
+function timeLeft(iso) {
+ const ms = new Date(iso).getTime() - Date.now();
+ if (ms <= 0) return 'expired';
+ const h = ms / 3600_000;
+ if (h < 1) return `${Math.max(1, Math.round(ms / 60000))} min left`;
+ if (h < 48) return `${Math.round(h)} h left`;
+ return `${Math.round(h / 24)} d left`;
+}
+function gpsReady() {
+ const g = ctx.getGpsState();
+ return !!(g && g.ready && Number.isFinite(g.lat) && Number.isFinite(g.lng));
+}
+
+// ── data ─────────────────────────────────────────────────────────────────────
+async function presenceHeaders(extra) {
+ try { return await ctx.presenceHeaders(extra || {}); }
+ catch { return ctx.deviceHeaders ? ctx.deviceHeaders(extra || {}) : (extra || {}); }
+}
+
+async function fetchNearby() {
+ if (!gpsReady()) { nearby = []; return; }
+ const g = ctx.getGpsState();
+ const radius = ctx.NEARBY_READ_RADIUS || 60;
+ try {
+ const headers = await presenceHeaders();
+ const r = await fetch(`/api/irl/drops?lat=${g.lat}&lng=${g.lng}&radius=${radius}`, { headers, credentials: 'include' });
+ if (r.status === 401) { nearby = []; return; } // fix required — re-mint next cycle
+ if (!r.ok) return;
+ const data = await r.json();
+ nearby = Array.isArray(data.drops) ? data.drops : [];
+ reconcileMarkers();
+ if (activeTab === 'nearby' && panelOpen()) renderList();
+ updateBadge();
+ } catch { /* transient — keep last good set */ }
+}
+
+async function fetchMine() {
+ try {
+ const headers = ctx.deviceHeaders ? ctx.deviceHeaders() : {};
+ const r = await fetch('/api/irl/drops?mine=1', { headers, credentials: 'include' });
+ if (!r.ok) return;
+ mine = await r.json();
+ if ((activeTab === 'mine' || activeTab === 'claims') && panelOpen()) renderList();
+ } catch { /* ignore */ }
+}
+
+function startPolling() {
+ fetchNearby();
+ pollTimer = setInterval(() => {
+ const key = panelOpen() ? 'open' : 'bg';
+ // Poll nearby every cycle; refresh "mine" only when its tab is up.
+ fetchNearby();
+ if (panelOpen() && (activeTab === 'mine' || activeTab === 'claims')) fetchMine();
+ _lastFetchKey = key;
+ }, 12_000);
+}
+
+// ── 3D markers ────────────────────────────────────────────────────────────────
+function makeMarker(drop) {
+ const group = new Group();
+ // A glowing coin disc in the wallet-violet family.
+ const coin = new Mesh(
+ new CylinderGeometry(0.34, 0.34, 0.08, 28),
+ new MeshStandardMaterial({ color: VIOLET, emissive: VIOLET_DEEP, emissiveIntensity: 0.55, metalness: 0.7, roughness: 0.25 }),
+ );
+ coin.rotation.x = Math.PI / 2;
+ coin.position.y = 1.25;
+ group.add(coin);
+ // Claim-radius ring on the ground.
+ const ring = new Mesh(
+ new TorusGeometry(1, 0.03, 8, 48),
+ new MeshBasicMaterial({ color: VIOLET, transparent: true, opacity: 0.45 }),
+ );
+ ring.rotation.x = Math.PI / 2;
+ ring.position.y = 0.02;
+ ring.scale.set(Math.max(1, drop.radius_m * 0.25), Math.max(1, drop.radius_m * 0.25), 1);
+ group.add(ring);
+ group.userData = { drop, coin };
+
+ const label = el('button', 'irl-drop-label');
+ label.type = 'button';
+ label.setAttribute('aria-label', `${fmtAmount(drop)} drop — open to claim`);
+ label.addEventListener('click', () => openClaim(drop));
+ document.body.appendChild(label);
+
+ ctx.scene.add(group);
+ return { group, label, drop };
+}
+
+function reconcileMarkers() {
+ const seen = new Set();
+ for (const d of nearby) {
+ seen.add(d.id);
+ let m = markers.get(d.id);
+ if (!m) { m = makeMarker(d); markers.set(d.id, m); }
+ else m.drop = d;
+ }
+ for (const [id, m] of markers) {
+ if (seen.has(id)) continue;
+ ctx.scene.remove(m.group);
+ m.label?.remove();
+ markers.delete(id);
+ }
+}
+
+const _v = new Vector3();
+function startRaf() {
+ const tick = () => {
+ rafId = requestAnimationFrame(tick);
+ if (!markers.size || !gpsReady()) { hideAllLabels(); return; }
+ const camera = ctx.getCamera?.();
+ for (const m of markers.values()) {
+ const wp = ctx.gpsToWorld(m.drop.lat, m.drop.lng);
+ m.group.position.set(wp.x, 0, wp.z);
+ // Spin the coin for life; respect reduced-motion via CSS-free math gate.
+ if (!_reduceMotion()) m.group.userData.coin.rotation.z += 0.02;
+ positionLabel(m, camera);
+ }
+ };
+ rafId = requestAnimationFrame(tick);
+}
+
+function _reduceMotion() {
+ return window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
+}
+
+function positionLabel(m, camera) {
+ if (!camera) { m.label.style.display = 'none'; return; }
+ _v.copy(m.group.position); _v.y += 1.7;
+ _v.project(camera);
+ const behind = _v.z > 1;
+ if (behind || _v.x < -1.2 || _v.x > 1.2 || _v.y < -1.2 || _v.y > 1.2) {
+ m.label.style.display = 'none';
+ return;
+ }
+ const x = (_v.x * 0.5 + 0.5) * window.innerWidth;
+ const y = (-_v.y * 0.5 + 0.5) * window.innerHeight;
+ const dist = markerDistance(m.drop);
+ const inRange = dist != null && dist <= m.drop.radius_m;
+ m.label.style.display = '';
+ m.label.classList.toggle('is-claimable', inRange);
+ m.label.style.transform = `translate(-50%,-50%) translate(${Math.round(x)}px, ${Math.round(y)}px)`;
+ m.label.innerHTML = `<span class="irl-drop-label-amt">${fmtAmount(m.drop)}</span>`
+ + `<span class="irl-drop-label-sub">${inRange ? 'Tap to claim' : fmtDistance(dist) + ' away'}</span>`;
+}
+
+function hideAllLabels() {
+ for (const m of markers.values()) m.label.style.display = 'none';
+}
+
+function markerDistance(drop) {
+ if (!gpsReady()) return null;
+ const g = ctx.getGpsState();
+ return haversine(g.lat, g.lng, drop.lat, drop.lng);
+}
+function haversine(lat1, lng1, lat2, lng2) {
+ const R = 6371000, toRad = (d) => (d * Math.PI) / 180;
+ const dLat = toRad(lat2 - lat1), dLng = toRad(lng2 - lng1);
+ const a = Math.sin(dLat / 2) ** 2 + Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * Math.sin(dLng / 2) ** 2;
+ return 2 * R * Math.asin(Math.min(1, Math.sqrt(a)));
+}
+
+// ── FAB + panel ────────────────────────────────────────────────────────────
+function buildFab() {
+ const fab = el('button', 'irl-drops-fab');
+ fab.type = 'button';
+ fab.setAttribute('aria-label', 'Money drops near me');
+ fab.innerHTML = `
+ <svg width="20" height="20" viewBox="0 0 24 24" fill="none" aria-hidden="true">
+ <circle cx="12" cy="12" r="9" stroke="currentColor" stroke-width="1.6"/>
+ <path d="M12 7v10M9.2 9.4c0-1.2 1.2-1.9 2.8-1.9s2.8.7 2.8 1.7c0 2.5-5.6 1.3-5.6 3.9 0 1.1 1.2 1.8 2.8 1.8s2.8-.7 2.8-1.9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"/>
+ </svg>
+ <span class="irl-drops-fab-badge" hidden>0</span>`;
+ badgeEl = fab.querySelector('.irl-drops-fab-badge');
+ fab.addEventListener('click', togglePanel);
+ document.body.appendChild(fab);
+}
+
+function buildPanel() {
+ const backdrop = el('div', 'irl-drops-backdrop');
+ backdrop.addEventListener('click', closePanel);
+ panelEl = el('section', 'irl-drops-panel');
+ panelEl.setAttribute('role', 'dialog');
+ panelEl.setAttribute('aria-modal', 'false');
+ panelEl.setAttribute('aria-label', 'Money drops near you');
+ panelEl.innerHTML = `
+ <div class="irl-drops-handle" aria-hidden="true"></div>
+ <header class="irl-drops-head">
+ <h2>Money drops</h2>
+ <button class="irl-drops-close" type="button" aria-label="Close">✕</button>
+ </header>
+ <div class="irl-drops-tabs" role="tablist"></div>
+ <div class="irl-drops-list" role="region" aria-live="polite"></div>
+ <button class="irl-drops-create" type="button">+ Drop money here</button>`;
+ tabsEl = panelEl.querySelector('.irl-drops-tabs');
+ listEl = panelEl.querySelector('.irl-drops-list');
+ panelEl.querySelector('.irl-drops-close').addEventListener('click', closePanel);
+ panelEl.querySelector('.irl-drops-create').addEventListener('click', () => openCreate());
+ for (const [key, label] of [['nearby', 'Nearby'], ['mine', 'My drops'], ['claims', 'My claims']]) {
+ const t = el('button', 'irl-drops-tab', label);
+ t.type = 'button'; t.setAttribute('role', 'tab'); t.dataset.tab = key;
+ t.addEventListener('click', () => setTab(key));
+ tabsEl.appendChild(t);
+ }
+ panelEl._backdrop = backdrop;
+ document.body.appendChild(backdrop);
+ document.body.appendChild(panelEl);
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && panelOpen()) closePanel(); });
+ setTab('nearby');
+}
+
+function panelOpen() { return panelEl?.classList.contains('is-open'); }
+function togglePanel() { panelOpen() ? closePanel() : openPanel(); }
+function openPanel() {
+ panelEl.classList.add('is-open');
+ panelEl._backdrop.classList.add('is-open');
+ if (activeTab === 'nearby') fetchNearby(); else fetchMine();
+ renderList();
+ try { panelEl.querySelector('.irl-drops-close').focus({ preventScroll: true }); } catch { /* */ }
+}
+function closePanel() {
+ panelEl.classList.remove('is-open');
+ panelEl._backdrop.classList.remove('is-open');
+}
+
+function setTab(key) {
+ activeTab = key;
+ for (const t of tabsEl.children) t.setAttribute('aria-selected', String(t.dataset.tab === key));
+ if (key === 'nearby') fetchNearby(); else fetchMine();
+ renderList();
+}
+
+function updateBadge() {
+ if (!badgeEl) return;
+ const claimable = nearby.filter((d) => { const dist = markerDistance(d); return dist != null && dist <= d.radius_m; }).length;
+ const count = claimable || nearby.length;
+ badgeEl.hidden = count === 0;
+ badgeEl.textContent = String(count);
+ badgeEl.classList.toggle('is-hot', claimable > 0);
+}
+
+// ── list rendering (every state designed) ──────────────────────────────────
+function renderList() {
+ if (!listEl) return;
+ listEl.innerHTML = '';
+ if (activeTab === 'nearby') return renderNearby();
+ if (activeTab === 'mine') return renderMine();
+ return renderClaims();
+}
+
+function emptyState(title, body, action) {
+ const wrap = el('div', 'irl-drops-empty');
+ wrap.appendChild(el('div', 'irl-drops-empty-pulse'));
+ wrap.appendChild(el('p', 'irl-drops-empty-t', title));
+ wrap.appendChild(el('p', 'irl-drops-empty-b', body));
+ if (action) {
+ const b = el('button', 'irl-drops-empty-act', action.label);
+ b.type = 'button';
+ b.addEventListener('click', action.fn);
+ wrap.appendChild(b);
+ }
+ return wrap;
+}
+
+function renderNearby() {
+ if (!gpsReady()) {
+ listEl.appendChild(emptyState('Turn on location', 'We anchor drops to real places. Enable location to discover money around you.', null));
+ return;
+ }
+ if (!nearby.length) {
+ listEl.appendChild(emptyState('No drops nearby', 'Be the first — drop SOL, USDC or $THREE right here for whoever walks up.', { label: '+ Drop money here', fn: () => openCreate() }));
+ return;
+ }
+ for (const d of nearby) listEl.appendChild(nearbyRow(d));
+}
+
+function nearbyRow(d) {
+ const dist = markerDistance(d);
+ const inRange = dist != null && dist <= d.radius_m;
+ const row = el('div', 'irl-drop-row' + (inRange ? ' is-claimable' : ''));
+ row.appendChild(coinBadge(d));
+ const mid = el('div', 'irl-drop-mid');
+ mid.appendChild(el('div', 'irl-drop-amt', `${fmtAmount(d)}${d.kind === 'bounty' ? ' <span class="irl-drop-tag">bounty</span>' : ''}`));
+ mid.appendChild(el('div', 'irl-drop-meta', `${d.is_mine ? 'Your drop · ' : ''}${fmtDistance(dist)} · ${timeLeft(d.expires_at)}${d.claims_left < d.max_claims ? ` · ${d.claims_left}/${d.max_claims} left` : ''}`));
+ if (d.title) mid.appendChild(el('div', 'irl-drop-note', escapeHtml(d.title)));
+ row.appendChild(mid);
+ const btn = el('button', 'irl-drop-go', inRange ? 'Claim' : fmtDistance(dist));
+ btn.type = 'button';
+ btn.disabled = !inRange && !d.is_mine;
+ btn.addEventListener('click', () => (d.is_mine && !inRange) ? openClaim(d) : openClaim(d));
+ row.appendChild(btn);
+ return row;
+}
+
+function coinBadge(d) {
+ const b = el('div', 'irl-drop-coin');
+ b.textContent = d.asset === 'THREE' ? '3' : (d.asset === 'USDC' ? '$' : '◎');
+ return b;
+}
+
+function renderMine() {
+ const drops = mine.drops || [];
+ if (!drops.length) {
+ listEl.appendChild(emptyState('No drops yet', 'Leave money at a real place — a tip jar for a street-performing agent, or a treasure hunt.', { label: '+ Drop money here', fn: () => openCreate() }));
+ return;
+ }
+ for (const d of drops) listEl.appendChild(mineRow(d));
+}
+
+function mineRow(d) {
+ const row = el('div', 'irl-drop-row');
+ row.appendChild(coinBadge(d));
+ const mid = el('div', 'irl-drop-mid');
+ const statusLabel = {
+ pending_funding: 'Awaiting funding', active: 'Active', exhausted: 'Fully claimed',
+ expired: 'Expired', refunded: 'Refunded', cancelled: 'Cancelled',
+ }[d.status] || d.status;
+ mid.appendChild(el('div', 'irl-drop-amt', fmtAmount(d)));
+ mid.appendChild(el('div', 'irl-drop-meta', `<span class="irl-drop-status s-${d.status}">${statusLabel}</span> · ${d.claims_count}/${d.max_claims} claimed · ${timeLeft(d.expires_at)}`));
+ if (d.refund_tx && d.refund_tx !== 'empty') mid.appendChild(receiptLink('Refund', d.network, d.refund_tx));
+ if (d.funding_tx) mid.appendChild(receiptLink('Funding', d.network, d.funding_tx));
+ row.appendChild(mid);
+ if (['active', 'exhausted', 'pending_funding'].includes(d.status)) {
+ const cancel = el('button', 'irl-drop-cancel', d.status === 'pending_funding' ? 'Void' : 'Cancel & refund');
+ cancel.type = 'button';
+ cancel.addEventListener('click', () => cancelDrop(d, cancel));
+ row.appendChild(cancel);
+ }
+ return row;
+}
+
+function renderClaims() {
+ const claims = mine.claims || [];
+ if (!claims.length) {
+ listEl.appendChild(emptyState('No claims yet', 'Walk up to a glowing coin and claim it. Your receipts land here.', null));
+ return;
+ }
+ for (const c of claims) {
+ const row = el('div', 'irl-drop-row');
+ const badge = el('div', 'irl-drop-coin');
+ badge.textContent = c.asset === 'THREE' ? '3' : (c.asset === 'USDC' ? '$' : '◎');
+ row.appendChild(badge);
+ const mid = el('div', 'irl-drop-mid');
+ mid.appendChild(el('div', 'irl-drop-amt', `+${c.amount} ${c.asset === 'THREE' ? '$THREE' : c.asset}`));
+ mid.appendChild(el('div', 'irl-drop-meta', `<span class="irl-drop-status s-${c.status === 'confirmed' ? 'active' : c.status}">${c.status}</span> · ${new Date(c.created_at).toLocaleDateString()}`));
+ if (c.signature) mid.appendChild(receiptLink('Receipt', c.network, c.signature));
+ row.appendChild(mid);
+ listEl.appendChild(row);
+ }
+}
+
+function receiptLink(label, network, sig) {
+ const a = el('a', 'irl-drop-receipt', `${label} ↗`);
+ a.href = solanaTxExplorerUrl(network === 'devnet' ? 'devnet' : 'mainnet', sig);
+ a.target = '_blank'; a.rel = 'noopener noreferrer';
+ return a;
+}
+
+function escapeHtml(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+// ── create flow ───────────────────────────────────────────────────────────
+function openCreate() {
+ if (!gpsReady()) { toast('Enable location to drop money at this spot.'); return; }
+ closePanel();
+ const g = ctx.getGpsState();
+ const state = { asset: 'SOL', amount: '', radius: 30, expiry: EXPIRY_PRESETS[1].ms, kind: 'drop', maxClaims: 1, busy: false };
+ const { modal, body, close } = makeModal('Drop money here');
+
+ function render() {
+ body.innerHTML = '';
+ body.appendChild(fieldLabel('Asset'));
+ const assetRow = el('div', 'irl-dm-seg');
+ for (const a of CREATE_ASSETS) {
+ const b = el('button', 'irl-dm-seg-b' + (state.asset === a ? ' is-on' : ''), a === 'THREE' ? '$THREE' : a);
+ b.type = 'button';
+ b.addEventListener('click', () => { state.asset = a; render(); });
+ assetRow.appendChild(b);
+ }
+ body.appendChild(assetRow);
+
+ body.appendChild(fieldLabel('Amount per claim'));
+ const amt = el('input', 'irl-dm-input');
+ amt.type = 'text'; amt.inputMode = 'decimal'; amt.value = state.amount;
+ amt.placeholder = state.asset === 'SOL' ? '0.05' : '5';
+ amt.addEventListener('input', () => { state.amount = amt.value.trim(); });
+ body.appendChild(amt);
+
+ body.appendChild(fieldLabel('How many can claim'));
+ const claimsRow = el('div', 'irl-dm-seg');
+ for (const [n, lbl] of [[1, 'First only'], [5, '5 people'], [25, '25 people']]) {
+ const b = el('button', 'irl-dm-seg-b' + (state.maxClaims === n ? ' is-on' : ''), lbl);
+ b.type = 'button';
+ b.addEventListener('click', () => { state.maxClaims = n; render(); });
+ claimsRow.appendChild(b);
+ }
+ body.appendChild(claimsRow);
+
+ body.appendChild(fieldLabel(`Claim radius — ${state.radius} m`));
+ const slider = el('input', 'irl-dm-range');
+ slider.type = 'range'; slider.min = '10'; slider.max = '100'; slider.step = '5'; slider.value = String(state.radius);
+ slider.addEventListener('input', () => { state.radius = Number(slider.value); slider.previousSibling.textContent = `Claim radius — ${state.radius} m`; });
+ body.appendChild(slider);
+
+ body.appendChild(fieldLabel('Expires in'));
+ const expRow = el('div', 'irl-dm-seg');
+ for (const p of EXPIRY_PRESETS) {
+ const b = el('button', 'irl-dm-seg-b' + (state.expiry === p.ms ? ' is-on' : ''), p.label);
+ b.type = 'button';
+ b.addEventListener('click', () => { state.expiry = p.ms; render(); });
+ expRow.appendChild(b);
+ }
+ body.appendChild(expRow);
+
+ const totalAtoms = Number(state.amount || 0) * state.maxClaims;
+ const summary = el('p', 'irl-dm-summary', state.amount
+ ? `You'll fund <b>${totalAtoms} ${state.asset === 'THREE' ? '$THREE' : state.asset}</b> total (${state.amount} × ${state.maxClaims}). Whoever physically walks within ${state.radius} m and proves they're here claims their share to their own wallet. Unclaimed funds auto-refund to you on expiry.`
+ : 'Set an amount to fund a real, on-chain drop anchored to this exact spot.');
+ body.appendChild(summary);
+
+ const go = el('button', 'irl-dm-go', 'Fund & drop');
+ go.type = 'button';
+ go.addEventListener('click', () => submit());
+ body.appendChild(go);
+ state._go = go;
+ }
+
+ async function submit() {
+ const amt = Number(state.amount);
+ if (!Number.isFinite(amt) || amt <= 0) { toast('Enter an amount greater than zero.'); return; }
+ if (state.busy) return;
+ state.busy = true;
+ const go = state._go;
+ const setStage = (t) => { go.textContent = t; go.disabled = true; };
+ setStage('Creating drop…');
+ try {
+ // 1. Reserve the drop + escrow address.
+ const createRes = await fetch('/api/irl/drops', {
+ method: 'POST', credentials: 'include',
+ headers: ctx.deviceHeaders ? ctx.deviceHeaders({ 'Content-Type': 'application/json' }) : { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ asset: state.asset, amount: state.amount, maxClaims: state.maxClaims,
+ radiusM: state.radius, expiresInMs: state.expiry, lat: g.lat, lng: g.lng,
+ claimRule: state.maxClaims === 1 ? 'first' : 'each-once', kind: state.kind,
+ }),
+ });
+ const created = await createRes.json();
+ if (!createRes.ok) throw new Error(created.error_description || created.error || 'Could not create the drop.');
+ const dropId = created.drop.id;
+ const escrow = created.escrow_address;
+
+ // 2. Fund the escrow with the creator's own signed transfer.
+ setStage('Approve in your wallet…');
+ let funding;
+ try {
+ funding = await tipAgent({
+ toAddress: escrow, token: state.asset,
+ amount: Number(state.amount) * state.maxClaims,
+ onStage: (s) => setStage(stageLabel(s)),
+ });
+ } catch (e) {
+ // Roll the unfunded drop back so it isn't orphaned.
+ cancelSilently(dropId);
+ if (e instanceof TipError && e.code === 'cancelled') { setStage('Fund & drop'); go.disabled = false; state.busy = false; return; }
+ throw new Error(e?.message || 'Funding was not completed.');
+ }
+
+ // 3. Confirm funding on-chain server-side → drop goes active.
+ setStage('Confirming on-chain…');
+ let confirmed = null;
+ for (let i = 0; i < 8 && !confirmed; i++) {
+ const fr = await fetch(`/api/irl/drops/${dropId}/fund`, {
+ method: 'POST', credentials: 'include',
+ headers: ctx.deviceHeaders ? ctx.deviceHeaders({ 'Content-Type': 'application/json' }) : { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ signature: funding.signature, refundAddress: funding.from }),
+ });
+ const fd = await fr.json();
+ if (fr.ok && fd.drop) { confirmed = fd; break; }
+ if (fr.status === 202) { await sleep(2500); continue; } // awaiting confirmation
+ throw new Error(fd.error_description || fd.error || 'Funding confirmation failed.');
+ }
+ if (!confirmed) throw new Error('Funding is taking longer than expected — it will appear once confirmed.');
+
+ close();
+ toast(`Dropped ${state.amount} ${state.asset === 'THREE' ? '$THREE' : state.asset} here. Watch for who claims it.`);
+ fetchNearby();
+ fetchMine();
+ } catch (e) {
+ setStage('Fund & drop'); go.disabled = false;
+ toast(e?.message || 'Something went wrong creating the drop.', true);
+ } finally {
+ state.busy = false;
+ }
+ }
+
+ render();
+}
+
+function stageLabel(s) {
+ return ({ connecting: 'Connecting wallet…', building: 'Building transfer…', signing: 'Approve in your wallet…', sending: 'Sending…', confirming: 'Confirming…' })[s] || 'Working…';
+}
+
+async function cancelSilently(dropId) {
+ try {
+ await fetch(`/api/irl/drops/${dropId}/cancel`, {
+ method: 'POST', credentials: 'include',
+ headers: ctx.deviceHeaders ? ctx.deviceHeaders() : {},
+ });
+ } catch { /* best effort */ }
+}
+
+// ── claim flow ────────────────────────────────────────────────────────────
+async function openClaim(drop) {
+ const fresh = nearby.find((d) => d.id === drop.id) || drop;
+ const dist = markerDistance(fresh);
+ const inRange = dist != null && dist <= fresh.radius_m;
+ const { modal, body, close } = makeModal(fresh.kind === 'bounty' ? 'Bounty' : 'Money drop');
+
+ const head = el('div', 'irl-claim-head');
+ head.appendChild(coinBadge(fresh));
+ const ht = el('div', '');
+ ht.appendChild(el('div', 'irl-claim-amt', fmtAmount(fresh)));
+ ht.appendChild(el('div', 'irl-claim-sub', `${fmtDistance(dist)} away · ${timeLeft(fresh.expires_at)}`));
+ head.appendChild(ht);
+ body.appendChild(head);
+ if (fresh.note) body.appendChild(el('p', 'irl-claim-note', escapeHtml(fresh.note)));
+
+ let answerInput = null;
+ if (fresh.kind === 'bounty' && fresh.quiz_question) {
+ body.appendChild(el('p', 'irl-claim-q', escapeHtml(fresh.quiz_question)));
+ answerInput = el('input', 'irl-dm-input');
+ answerInput.type = 'text'; answerInput.placeholder = 'Your answer';
+ body.appendChild(answerInput);
+ }
+
+ if (!inRange) {
+ const oor = el('div', 'irl-claim-oor', `Get within ${Math.round(fresh.radius_m)} m to claim — you're ${fmtDistance(dist)} away. Walk closer with your camera up.`);
+ body.appendChild(oor);
+ const ok = el('button', 'irl-dm-go is-ghost', 'Got it');
+ ok.type = 'button'; ok.addEventListener('click', close);
+ body.appendChild(ok);
+ return;
+ }
+
+ const go = el('button', 'irl-dm-go', 'Claim to my wallet');
+ go.type = 'button';
+ body.appendChild(go);
+ go.addEventListener('click', async () => {
+ go.disabled = true; go.textContent = 'Connecting wallet…';
+ try {
+ const wallet = detectSolanaWallet();
+ if (!wallet) throw new Error('Install Phantom, Backpack, or Solflare to claim.');
+ const conn = await wallet.connect();
+ const pubkey = (conn?.publicKey || wallet.publicKey)?.toString();
+ if (!pubkey) throw new Error('Could not read your wallet address.');
+
+ go.textContent = 'Proving you are here…';
+ const g = ctx.getGpsState();
+ const headers = await presenceHeaders({ 'Content-Type': 'application/json' });
+ const r = await fetch(`/api/irl/drops/${fresh.id}/claim`, {
+ method: 'POST', credentials: 'include', headers,
+ body: JSON.stringify({ wallet: pubkey, lat: g.lat, lng: g.lng, answer: answerInput?.value }),
+ });
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error_description || data.error || 'Claim failed.');
+ renderReceipt(body, fresh, data);
+ } catch (e) {
+ go.disabled = false; go.textContent = 'Claim to my wallet';
+ toast(e?.message || 'Claim failed.', true);
+ }
+ });
+}
+
+function renderReceipt(body, drop, data) {
+ body.innerHTML = '';
+ const ok = el('div', 'irl-claim-ok');
+ ok.innerHTML = `<div class="irl-claim-ok-burst" aria-hidden="true"></div>
+ <div class="irl-claim-ok-amt">+${data.amount} ${data.asset === 'THREE' ? '$THREE' : data.asset}</div>
+ <div class="irl-claim-ok-sub">Sent to your wallet. Real, on-chain, yours.</div>`;
+ body.appendChild(ok);
+ const link = el('a', 'irl-dm-go', 'View receipt on Solscan ↗');
+ link.href = data.explorer_url; link.target = '_blank'; link.rel = 'noopener noreferrer';
+ body.appendChild(link);
+ fetchNearby(); fetchMine();
+}
+
+async function cancelDrop(drop, btn) {
+ btn.disabled = true; btn.textContent = 'Refunding…';
+ try {
+ const r = await fetch(`/api/irl/drops/${drop.id}/cancel`, {
+ method: 'POST', credentials: 'include',
+ headers: ctx.deviceHeaders ? ctx.deviceHeaders() : {},
+ });
+ const data = await r.json();
+ if (!r.ok) throw new Error(data.error_description || data.error || 'Refund failed.');
+ toast(data.refunded ? 'Refunded to your wallet.' : 'Drop cancelled.');
+ fetchMine(); fetchNearby();
+ } catch (e) {
+ btn.disabled = false; btn.textContent = 'Cancel & refund';
+ toast(e?.message || 'Could not cancel the drop.', true);
+ }
+}
+
+// ── modal + toast primitives ──────────────────────────────────────────────
+function makeModal(title) {
+ const backdrop = el('div', 'irl-dm-backdrop');
+ const modal = el('div', 'irl-dm-modal');
+ modal.setAttribute('role', 'dialog'); modal.setAttribute('aria-modal', 'true'); modal.setAttribute('aria-label', title);
+ const head = el('div', 'irl-dm-head');
+ head.appendChild(el('h3', '', title));
+ const x = el('button', 'irl-dm-x', '✕'); x.type = 'button'; x.setAttribute('aria-label', 'Close');
+ head.appendChild(x);
+ const body = el('div', 'irl-dm-body');
+ modal.appendChild(head); modal.appendChild(body);
+ backdrop.appendChild(modal);
+ document.body.appendChild(backdrop);
+ requestAnimationFrame(() => backdrop.classList.add('is-open'));
+ const close = () => { backdrop.classList.remove('is-open'); setTimeout(() => backdrop.remove(), 200); };
+ x.addEventListener('click', close);
+ backdrop.addEventListener('click', (e) => { if (e.target === backdrop) close(); });
+ document.addEventListener('keydown', function esc(e) { if (e.key === 'Escape') { close(); document.removeEventListener('keydown', esc); } });
+ try { x.focus({ preventScroll: true }); } catch { /* */ }
+ return { modal, body, close };
+}
+
+function fieldLabel(t) { return el('label', 'irl-dm-lbl', t); }
+
+let toastTimer = null;
+function toast(msg, isErr) {
+ let t = document.querySelector('.irl-drops-toast');
+ if (!t) { t = el('div', 'irl-drops-toast'); document.body.appendChild(t); }
+ t.textContent = msg;
+ t.classList.toggle('is-err', !!isErr);
+ t.classList.add('is-on');
+ clearTimeout(toastTimer);
+ toastTimer = setTimeout(() => t.classList.remove('is-on'), 4200);
+}
+
+function sleep(ms) { return new Promise((r) => setTimeout(r, ms)); }
+
+// ── styles (wallet-violet family, design tokens) ───────────────────────────
+function ensureStyles() {
+ if (_styled) return; _styled = true;
+ const css = `
+.irl-drops-fab{position:fixed;right:16px;bottom:calc(96px + env(safe-area-inset-bottom,0px));z-index:60;width:52px;height:52px;border-radius:999px;border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));background:linear-gradient(160deg,rgba(20,18,30,.95),rgba(12,10,18,.95));color:var(--wallet-accent,#c4b5fd);display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 6px 24px rgba(0,0,0,.5),0 0 0 0 var(--wallet-glow,rgba(139,92,246,.45));transition:transform .15s,box-shadow .2s,border-color .2s}
+.irl-drops-fab:hover{transform:translateY(-2px);border-color:var(--wallet-stroke-strong,rgba(139,92,246,.5));box-shadow:0 10px 30px rgba(0,0,0,.55),0 0 24px var(--wallet-glow,rgba(139,92,246,.45))}
+.irl-drops-fab:active{transform:translateY(0)}
+.irl-drops-fab:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:2px}
+.irl-drops-fab-badge{position:absolute;top:-4px;right:-4px;min-width:20px;height:20px;padding:0 5px;border-radius:999px;background:var(--wallet-accent-strong,#a78bfa);color:#0a0a0a;font:700 11px/20px var(--font-mono,ui-monospace,monospace);text-align:center;box-shadow:0 0 0 2px rgba(10,10,10,.9)}
+.irl-drops-fab-badge.is-hot{background:var(--success,#4ade80);animation:irl-drops-pulse 1.6s ease-in-out infinite}
+@keyframes irl-drops-pulse{0%,100%{box-shadow:0 0 0 2px rgba(10,10,10,.9),0 0 0 0 rgba(74,222,128,.6)}50%{box-shadow:0 0 0 2px rgba(10,10,10,.9),0 0 0 7px rgba(74,222,128,0)}}
+@media (prefers-reduced-motion:reduce){.irl-drops-fab-badge.is-hot{animation:none}}
+.irl-drops-backdrop{position:fixed;inset:0;z-index:64;background:rgba(0,0,0,.5);opacity:0;pointer-events:none;transition:opacity .2s}
+.irl-drops-backdrop.is-open{opacity:1;pointer-events:auto}
+.irl-drops-panel{position:fixed;left:0;right:0;bottom:0;z-index:65;max-height:80vh;display:flex;flex-direction:column;background:linear-gradient(180deg,rgba(16,14,22,.98),rgba(10,9,14,.99));border-top:1px solid var(--wallet-stroke,rgba(139,92,246,.3));border-radius:20px 20px 0 0;box-shadow:0 -12px 40px rgba(0,0,0,.6);transform:translateY(102%);transition:transform .28s cubic-bezier(.2,.8,.2,1);padding:10px 16px calc(16px + env(safe-area-inset-bottom,0px));color:var(--ink,#e5e7eb)}
+.irl-drops-panel.is-open{transform:translateY(0)}
+.irl-drops-handle{width:38px;height:4px;border-radius:99px;background:rgba(255,255,255,.18);margin:2px auto 10px}
+.irl-drops-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px}
+.irl-drops-head h2{margin:0;font:700 17px var(--font-display,Inter,sans-serif);color:var(--ink-bright,#fff)}
+.irl-drops-close{background:none;border:none;color:var(--ink-dim,#9ca3af);font-size:16px;cursor:pointer;padding:6px;border-radius:8px}
+.irl-drops-close:hover{color:#fff;background:rgba(255,255,255,.06)}
+.irl-drops-close:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:1px}
+.irl-drops-tabs{display:flex;gap:6px;margin-bottom:10px}
+.irl-drops-tab{flex:1;padding:8px 6px;border-radius:10px;border:1px solid transparent;background:rgba(255,255,255,.04);color:var(--ink-dim,#9ca3af);font:600 12.5px var(--font-body,Inter);cursor:pointer;transition:background .15s,color .15s,border-color .15s}
+.irl-drops-tab:hover{background:rgba(255,255,255,.07);color:#e5e7eb}
+.irl-drops-tab[aria-selected=true]{background:var(--wallet-accent-fill,rgba(139,92,246,.15));border-color:var(--wallet-stroke,rgba(139,92,246,.3));color:var(--wallet-accent,#c4b5fd)}
+.irl-drops-tab:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:1px}
+.irl-drops-list{overflow-y:auto;flex:1;min-height:120px;display:flex;flex-direction:column;gap:8px;padding:2px 0 8px}
+.irl-drop-row{display:flex;align-items:center;gap:11px;padding:11px;border-radius:13px;border:1px solid rgba(255,255,255,.07);background:rgba(255,255,255,.03);transition:border-color .15s,background .15s}
+.irl-drop-row.is-claimable{border-color:var(--wallet-stroke-strong,rgba(139,92,246,.5));background:var(--wallet-accent-soft,rgba(139,92,246,.1));box-shadow:0 0 18px rgba(139,92,246,.18)}
+.irl-drop-coin{width:38px;height:38px;flex-shrink:0;border-radius:50%;display:flex;align-items:center;justify-content:center;font:700 16px var(--font-mono,monospace);color:#0a0a0a;background:radial-gradient(circle at 35% 30%,#e9e1ff,var(--wallet-accent,#c4b5fd) 60%,var(--wallet-accent-strong,#a78bfa));box-shadow:0 2px 10px rgba(139,92,246,.4)}
+.irl-drop-mid{flex:1;min-width:0}
+.irl-drop-amt{font:700 15px var(--font-body,Inter);color:var(--ink-bright,#fff)}
+.irl-drop-tag{font:600 10px var(--font-mono,monospace);text-transform:uppercase;letter-spacing:.04em;color:var(--wallet-accent,#c4b5fd);border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));border-radius:5px;padding:1px 5px;margin-left:6px;vertical-align:middle}
+.irl-drop-meta{font:500 12px var(--font-body,Inter);color:var(--ink-dim,#9ca3af);margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
+.irl-drop-note{font:500 12px var(--font-body,Inter);color:#b9b3c7;margin-top:3px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.irl-drop-status{font-weight:700}.irl-drop-status.s-active{color:var(--success,#4ade80)}.irl-drop-status.s-refunded,.irl-drop-status.s-expired,.irl-drop-status.s-cancelled{color:var(--ink-dim,#9ca3af)}.irl-drop-status.s-pending_funding{color:var(--warn,#fbbf24)}.irl-drop-status.s-exhausted{color:var(--wallet-accent,#c4b5fd)}
+.irl-drop-receipt{display:inline-block;margin-top:3px;margin-right:10px;font:600 11.5px var(--font-mono,monospace);color:var(--wallet-accent,#c4b5fd);text-decoration:none}
+.irl-drop-receipt:hover{text-decoration:underline}
+.irl-drop-go,.irl-drop-cancel{flex-shrink:0;padding:9px 14px;border-radius:10px;font:700 13px var(--font-body,Inter);cursor:pointer;border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));background:var(--wallet-accent,#c4b5fd);color:#0a0a0a;transition:transform .12s,filter .15s,opacity .15s}
+.irl-drop-go:hover{filter:brightness(1.08)}.irl-drop-go:active{transform:scale(.97)}
+.irl-drop-go:disabled{opacity:.4;cursor:not-allowed;background:rgba(255,255,255,.08);color:var(--ink-dim,#9ca3af);border-color:rgba(255,255,255,.1)}
+.irl-drop-go:focus-visible,.irl-drop-cancel:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:2px}
+.irl-drop-cancel{background:rgba(248,113,113,.1);color:var(--danger,#f87171);border-color:rgba(248,113,113,.3)}
+.irl-drop-cancel:hover{background:rgba(248,113,113,.18)}
+.irl-drops-create{margin-top:8px;padding:13px;border-radius:13px;border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));background:var(--wallet-accent-fill,rgba(139,92,246,.15));color:var(--wallet-accent,#c4b5fd);font:700 14px var(--font-body,Inter);cursor:pointer;transition:background .15s}
+.irl-drops-create:hover{background:var(--wallet-accent-soft,rgba(139,92,246,.22))}
+.irl-drops-create:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:2px}
+.irl-drops-empty{text-align:center;padding:26px 16px;display:flex;flex-direction:column;align-items:center;gap:8px}
+.irl-drops-empty-pulse{width:46px;height:46px;border-radius:50%;background:radial-gradient(circle,var(--wallet-accent,#c4b5fd),transparent 70%);opacity:.5;animation:irl-drops-glow 2.4s ease-in-out infinite}
+@keyframes irl-drops-glow{0%,100%{transform:scale(.85);opacity:.35}50%{transform:scale(1.1);opacity:.6}}
+@media (prefers-reduced-motion:reduce){.irl-drops-empty-pulse{animation:none}}
+.irl-drops-empty-t{margin:4px 0 0;font:700 15px var(--font-body,Inter);color:#fff}
+.irl-drops-empty-b{margin:0;font:500 13px var(--font-body,Inter);color:var(--ink-dim,#9ca3af);max-width:260px;line-height:1.5}
+.irl-drops-empty-act{margin-top:6px;padding:10px 16px;border-radius:10px;border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));background:var(--wallet-accent-fill,rgba(139,92,246,.15));color:var(--wallet-accent,#c4b5fd);font:700 13px var(--font-body,Inter);cursor:pointer}
+.irl-drops-empty-act:hover{background:var(--wallet-accent-soft,rgba(139,92,246,.22))}
+.irl-drop-label{position:fixed;left:0;top:0;z-index:55;transform:translate(-50%,-50%);pointer-events:auto;display:flex;flex-direction:column;align-items:center;gap:1px;padding:5px 10px;border-radius:11px;border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));background:rgba(12,10,18,.86);backdrop-filter:blur(6px);cursor:pointer;white-space:nowrap;font-family:var(--font-body,Inter)}
+.irl-drop-label.is-claimable{border-color:var(--wallet-accent,#c4b5fd);box-shadow:0 0 22px var(--wallet-glow,rgba(139,92,246,.45))}
+.irl-drop-label-amt{font-weight:700;font-size:13px;color:#fff}
+.irl-drop-label-sub{font-size:10.5px;color:var(--wallet-accent,#c4b5fd)}
+.irl-dm-backdrop{position:fixed;inset:0;z-index:80;display:flex;align-items:flex-end;justify-content:center;background:rgba(0,0,0,.6);opacity:0;pointer-events:none;transition:opacity .2s}
+.irl-dm-backdrop.is-open{opacity:1;pointer-events:auto}
+.irl-dm-modal{width:100%;max-width:460px;max-height:88vh;overflow-y:auto;background:linear-gradient(180deg,rgba(18,16,24,.99),rgba(11,10,15,1));border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));border-radius:20px 20px 0 0;padding:16px 18px calc(20px + env(safe-area-inset-bottom,0px));transform:translateY(20px);transition:transform .24s cubic-bezier(.2,.8,.2,1);color:var(--ink,#e5e7eb)}
+.irl-dm-backdrop.is-open .irl-dm-modal{transform:translateY(0)}
+@media (min-width:560px){.irl-dm-backdrop{align-items:center}.irl-dm-modal{border-radius:20px}}
+.irl-dm-head{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px}
+.irl-dm-head h3{margin:0;font:700 17px var(--font-display,Inter)}
+.irl-dm-x{background:none;border:none;color:var(--ink-dim,#9ca3af);font-size:16px;cursor:pointer;padding:6px;border-radius:8px}
+.irl-dm-x:hover{color:#fff;background:rgba(255,255,255,.06)}
+.irl-dm-x:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:1px}
+.irl-dm-lbl{display:block;font:600 12px var(--font-body,Inter);color:var(--ink-dim,#9ca3af);margin:12px 0 6px}
+.irl-dm-seg{display:flex;gap:6px}
+.irl-dm-seg-b{flex:1;padding:9px 6px;border-radius:9px;border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.04);color:var(--ink-dim,#9ca3af);font:600 12.5px var(--font-body,Inter);cursor:pointer;transition:background .14s,border-color .14s,color .14s}
+.irl-dm-seg-b:hover{background:rgba(255,255,255,.07);color:#e5e7eb}
+.irl-dm-seg-b.is-on{background:var(--wallet-accent-fill,rgba(139,92,246,.15));border-color:var(--wallet-stroke,rgba(139,92,246,.3));color:var(--wallet-accent,#c4b5fd)}
+.irl-dm-seg-b:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:1px}
+.irl-dm-input{width:100%;padding:11px 13px;border-radius:10px;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.04);color:#fff;font:600 15px var(--font-mono,monospace)}
+.irl-dm-input:focus{outline:none;border-color:var(--wallet-stroke-strong,rgba(139,92,246,.5));box-shadow:0 0 0 3px var(--wallet-accent-soft,rgba(139,92,246,.1))}
+.irl-dm-range{width:100%;accent-color:var(--wallet-accent,#c4b5fd)}
+.irl-dm-summary{font:500 12.5px var(--font-body,Inter);color:var(--ink-dim,#9ca3af);line-height:1.55;margin:14px 0 4px;padding:10px 12px;border-radius:10px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.06)}
+.irl-dm-summary b{color:var(--wallet-accent,#c4b5fd)}
+.irl-dm-go{display:block;width:100%;margin-top:14px;padding:13px;border-radius:12px;border:none;background:var(--wallet-accent,#c4b5fd);color:#0a0a0a;font:700 14.5px var(--font-body,Inter);cursor:pointer;text-align:center;text-decoration:none;transition:filter .15s,transform .12s,opacity .15s}
+.irl-dm-go:hover{filter:brightness(1.08)}.irl-dm-go:active{transform:scale(.99)}
+.irl-dm-go:disabled{opacity:.6;cursor:default}
+.irl-dm-go.is-ghost{background:rgba(255,255,255,.06);color:#e5e7eb}
+.irl-dm-go:focus-visible{outline:2px solid var(--wallet-focus,rgba(139,92,246,.7));outline-offset:2px}
+.irl-claim-head{display:flex;align-items:center;gap:12px;margin-bottom:8px}
+.irl-claim-amt{font:700 22px var(--font-body,Inter);color:#fff}
+.irl-claim-sub{font:500 12.5px var(--font-body,Inter);color:var(--ink-dim,#9ca3af)}
+.irl-claim-note{font:500 13px var(--font-body,Inter);color:#c9c3d7;line-height:1.5;margin:6px 0}
+.irl-claim-q{font:600 14px var(--font-body,Inter);color:#fff;margin:12px 0 8px}
+.irl-claim-oor{margin-top:12px;padding:12px;border-radius:11px;background:rgba(251,191,36,.08);border:1px solid rgba(251,191,36,.25);color:#fcd34d;font:500 13px var(--font-body,Inter);line-height:1.5}
+.irl-claim-ok{text-align:center;padding:18px 8px 8px;position:relative}
+.irl-claim-ok-burst{position:absolute;left:50%;top:30%;width:120px;height:120px;transform:translate(-50%,-50%);background:radial-gradient(circle,var(--success,#4ade80),transparent 65%);opacity:.45;animation:irl-drops-glow 1.8s ease-in-out 2}
+.irl-claim-ok-amt{font:800 30px var(--font-body,Inter);color:var(--success,#4ade80);position:relative}
+.irl-claim-ok-sub{font:500 13px var(--font-body,Inter);color:var(--ink-dim,#9ca3af);margin-top:4px;position:relative}
+.irl-drops-toast{position:fixed;left:50%;bottom:calc(150px + env(safe-area-inset-bottom,0px));transform:translateX(-50%) translateY(12px);z-index:90;max-width:88vw;padding:11px 16px;border-radius:12px;background:rgba(16,14,22,.97);border:1px solid var(--wallet-stroke,rgba(139,92,246,.3));color:#fff;font:600 13px var(--font-body,Inter);box-shadow:0 8px 30px rgba(0,0,0,.6);opacity:0;pointer-events:none;transition:opacity .2s,transform .2s;text-align:center}
+.irl-drops-toast.is-on{opacity:1;transform:translateX(-50%) translateY(0)}
+.irl-drops-toast.is-err{border-color:rgba(248,113,113,.4)}
+`;
+ const style = document.createElement('style');
+ style.id = 'irl-drops-styles';
+ style.textContent = css;
+ document.head.appendChild(style);
+}
diff --git a/tests/market-maker.test.js b/tests/market-maker.test.js
new file mode 100644
index 000000000..43fe34890
--- /dev/null
+++ b/tests/market-maker.test.js
@@ -0,0 +1,146 @@
+/**
+ * Launch Copilot market-maker — policy model + anti-manipulation guard tests.
+ *
+ * Covers the pure rulebook in api/_lib/market-maker.js: preset normalization,
+ * lamports/SOL conversion, the HARD anti-manipulation caps (interval, volume
+ * share, recycle), the live-vs-budget safety gate, and the public view shaping.
+ * These are the rules that make the maker non-manipulative by construction, so
+ * the suite asserts every refusal path explicitly. No DB is touched (the pure
+ * functions never call sql).
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ GUARDS, PRESETS, PolicyError,
+ normalizePolicyPatch, assertPolicySafe, toPublicPolicy, toPublicAction, SOL,
+} from '../api/_lib/market-maker.js';
+
+describe('normalizePolicyPatch — presets + coercion', () => {
+ it('seeds the full behavioral shape from a preset', () => {
+ const p = normalizePolicyPatch({ preset: 'balanced', floor_price_sol: 0.0001 }, { isCreate: true });
+ expect(p.preset).toBe('balanced');
+ expect(p.floor_band_pct).toBe(PRESETS.balanced.floor_band_pct);
+ expect(p.recycle_pct).toBe(PRESETS.balanced.recycle_pct);
+ expect(p.graduation_action).toBe(PRESETS.balanced.graduation_action);
+ expect(p.floor_price_sol).toBe(0.0001);
+ });
+
+ it('lets explicit fields override the preset', () => {
+ const p = normalizePolicyPatch({ preset: 'gentle', floor_price_sol: 1, recycle_pct: 7 });
+ expect(p.recycle_pct).toBe(7);
+ });
+
+ it('converts SOL budgets to lamports strings', () => {
+ const p = normalizePolicyPatch({ floor_price_sol: 1, dip_buy_budget_sol: 0.5, daily_budget_sol: 2, seed_sol: 0.1 });
+ expect(p.dip_buy_budget_lamports).toBe(String(0.5 * SOL));
+ expect(p.daily_budget_lamports).toBe(String(2 * SOL));
+ expect(p.seed_lamports).toBe(String(0.1 * SOL));
+ });
+
+ it('requires a floor price on create', () => {
+ expect(() => normalizePolicyPatch({ preset: 'balanced' }, { isCreate: true })).toThrow(PolicyError);
+ });
+
+ it('rejects an invalid preset / mode / graduation action', () => {
+ expect(() => normalizePolicyPatch({ preset: 'wild', floor_price_sol: 1 })).toThrow(/preset/);
+ expect(() => normalizePolicyPatch({ mode: 'turbo', floor_price_sol: 1 })).toThrow(/mode/);
+ expect(() => normalizePolicyPatch({ graduation_action: 'rug', floor_price_sol: 1 })).toThrow(/graduation_action/);
+ });
+});
+
+describe('normalizePolicyPatch — anti-manipulation caps (refused at create)', () => {
+ it('refuses a sub-floor action interval (wash-trade prevention)', () => {
+ try {
+ normalizePolicyPatch({ floor_price_sol: 1, min_action_interval_seconds: GUARDS.MIN_ACTION_INTERVAL_SECONDS - 1 });
+ throw new Error('should have thrown');
+ } catch (e) {
+ expect(e).toBeInstanceOf(PolicyError);
+ expect(e.code).toBe('manipulation_guard');
+ expect(e.status).toBe(422);
+ expect(e.message).toMatch(/wash-trad/i);
+ }
+ });
+
+ it('refuses a volume share above the ceiling (tape-painting prevention)', () => {
+ try {
+ normalizePolicyPatch({ floor_price_sol: 1, max_volume_pct: GUARDS.MAX_VOLUME_PCT_CEILING + 5 });
+ throw new Error('should have thrown');
+ } catch (e) {
+ expect(e.code).toBe('manipulation_guard');
+ expect(e.message).toMatch(/painting the tape/i);
+ }
+ });
+
+ it('refuses a recycle share above the dump ceiling', () => {
+ expect(() => normalizePolicyPatch({ floor_price_sol: 1, recycle_pct: GUARDS.MAX_RECYCLE_PCT + 1 })).toThrow(/recycle/i);
+ });
+
+ it('accepts values exactly at the caps', () => {
+ const p = normalizePolicyPatch({
+ floor_price_sol: 1,
+ min_action_interval_seconds: GUARDS.MIN_ACTION_INTERVAL_SECONDS,
+ max_volume_pct: GUARDS.MAX_VOLUME_PCT_CEILING,
+ recycle_pct: GUARDS.MAX_RECYCLE_PCT,
+ });
+ expect(p.min_action_interval_seconds).toBe(GUARDS.MIN_ACTION_INTERVAL_SECONDS);
+ expect(p.max_volume_pct).toBe(GUARDS.MAX_VOLUME_PCT_CEILING);
+ });
+});
+
+describe('assertPolicySafe — final gate before enabling', () => {
+ const base = {
+ floor_price_sol: 0.0001,
+ min_action_interval_seconds: 60,
+ max_volume_pct: 15,
+ recycle_pct: 20,
+ enabled: true,
+ mode: 'simulate',
+ dip_buy_budget_lamports: '0',
+ daily_budget_lamports: '0',
+ seed_lamports: '0',
+ };
+
+ it('passes a sane simulate policy with no budget', () => {
+ expect(assertPolicySafe({ ...base })).toBe(true);
+ });
+
+ it('refuses enabling LIVE with no budget (misleading no-op)', () => {
+ expect(() => assertPolicySafe({ ...base, mode: 'live' })).toThrow(/budget/i);
+ });
+
+ it('allows LIVE once any budget is set', () => {
+ expect(assertPolicySafe({ ...base, mode: 'live', daily_budget_lamports: String(SOL) })).toBe(true);
+ });
+
+ it('refuses a sub-floor interval / over-ceiling volume even post-merge', () => {
+ expect(() => assertPolicySafe({ ...base, min_action_interval_seconds: 5 })).toThrow(/wash/i);
+ expect(() => assertPolicySafe({ ...base, max_volume_pct: 80 })).toThrow(/tape/i);
+ });
+});
+
+describe('toPublicPolicy / toPublicAction', () => {
+ it('shapes a row into SOL-denominated budgets + a disclosure', () => {
+ const pub = toPublicPolicy({
+ id: 'p1', mint: 'M', network: 'mainnet', agent_id: 'a1', enabled: true, mode: 'live',
+ preset: 'balanced', status: 'active', kill_switch: false,
+ floor_price_sol: '0.0001', floor_band_pct: '5', take_profit_band_pct: '25', recycle_pct: '20',
+ max_inventory_tokens: '0', graduation_action: 'provide_lp', slippage_bps: '500', max_price_impact_pct: '8',
+ min_action_interval_seconds: 60, max_volume_pct: '15',
+ dip_buy_budget_lamports: String(SOL / 2), daily_budget_lamports: String(2 * SOL), seed_lamports: '0',
+ realized_pnl_lamports: String(SOL), sol_deployed_lamports: String(3 * SOL), sol_recovered_lamports: String(4 * SOL),
+ inventory_tokens: '100', inventory_value_lamports: String(SOL), last_price_sol: '0.0002',
+ });
+ expect(pub.budgets.dip_buy_sol).toBeCloseTo(0.5, 6);
+ expect(pub.budgets.daily_sol).toBeCloseTo(2, 6);
+ expect(pub.realized.pnl_sol).toBeCloseTo(1, 6);
+ expect(pub.disclosure).toMatch(/non-manipulative|wash-trade/i);
+ expect(pub.disclosure).toContain('60s');
+ });
+
+ it('shapes an action row with lamports → SOL', () => {
+ const a = toPublicAction({ id: '7', kind: 'defend_buy', side: 'buy', sol_lamports: String(SOL / 10), price_sol: '0.0001', status: 'executed', created_at: '2026-06-23T00:00:00Z' });
+ expect(a.id).toBe(7);
+ expect(a.sol).toBeCloseTo(0.1, 6);
+ expect(a.kind).toBe('defend_buy');
+ });
+});
diff --git a/workers/agent-mm/engine.js b/workers/agent-mm/engine.js
index d417e8348..6a36a78b4 100644
--- a/workers/agent-mm/engine.js
+++ b/workers/agent-mm/engine.js
@@ -340,11 +340,19 @@ async function runGraduation({ cfg, policy, agent, price, inventoryWhole, invent
return 'graduation_distribute';
}
-// Record a non-firing decision (gated / dust / etc.) to the transparent ledger.
+// Record a non-firing decision. Routine pacing/budget/dust gates fire on EVERY
+// sweep, so persisting each one would flood the ledger — those update the
+// heartbeat (last_eval_at + last_error) instead, which the UI shows as a "what
+// it's doing right now" note. Only NOTABLE events — an anti-wash block or a
+// failure — earn a permanent ledger row.
async function skip({ policy, intent, price, status, detail, reason }) {
- await recordActionAndAdvance({
- policy,
- action: { kind: intent.kind, side: intent.side, triggerReason: intent.reason, priceSol: price, status, detail, meta: { reason } },
- });
+ if (status === 'blocked' || status === 'failed') {
+ await recordActionAndAdvance({
+ policy,
+ action: { kind: intent.kind, side: intent.side, triggerReason: intent.reason, priceSol: price, status, detail, meta: { reason } },
+ });
+ } else {
+ await markEvaluated(policy.id, { error: `holding: ${detail}`.slice(0, 200) });
+ }
return reason;
}