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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(execution): approvals and notification prefs updates, landing race doc, devnet race script and funder graph test
nirholasb988762ac06c
diff --git a/api/_lib/approvals.js b/api/_lib/approvals.jsindex 082a6e9b2..d3c10ae8b 100644--- a/api/_lib/approvals.js+++ b/api/_lib/approvals.js@@ -86,6 +86,10 @@ export const VENUES = Object.freeze({// The owner capped what the agent signs alone, so an auto-approve policy never// pre-answers the spends that cap sends here.agent_trade: { label: 'Agent trades above its burner cap', auto: false },+ // A reinvest-rule transfer (api/_lib/revenue-reinvest.js) that the agent's+ // spend policy wants the owner to answer. The rule itself was confirmed, but+ // a policy step-up is a separate yes, so it never auto-approves.+ revenue_reinvest: { label: 'Reinvest rule transfers above your spend policy', auto: false },});// Ceiling on a single auto-approve policy. Anything bigger is a decision the@@ -365,6 +369,7 @@ const EXECUTORS = {team_chat: async () => (await import('./team-chat/approval-executor.js')).executeTeamChatApproval,// An agent_send the owner's allowlist did not cover (api/_lib/agent-commerce/send.js).agent_commerce: async () => (await import('./agent-commerce/send.js')).executeApprovedCommerceAction,+ revenue_reinvest: async () => (await import('./revenue-reinvest.js')).executeApprovedReinvestLeg,token_budget: async () => (await import('./token-budgets.js')).executeTokenBudgetExtension,external_wallet: async () => (await import('./account-link/external-wallets.js')).executeApprovedPayoutWallet,// A funded launch intent the owner confirmed (api/_lib/pump-funded-launch.js).diff --git a/api/_lib/notify-prefs.js b/api/_lib/notify-prefs.jsindex a8d9e2086..8ca7737c3 100644--- a/api/_lib/notify-prefs.js+++ b/api/_lib/notify-prefs.js@@ -128,6 +128,11 @@ const TYPE_CATEGORY = {invoice_paid: 'sales',invoice_underpaid: 'sales',invoice_expired: 'sales',+ // Revenue ledger (api/_lib/revenue-*.js).+ revenue_milestone: 'sales',+ reinvest_run: 'sales',+ reinvest_rule_failed: 'alerts',+ revenue_reconcile_drift: 'alerts',skill_purchase_confirmed: 'purchases',asset_purchase_confirmed: 'purchases',diff --git a/docs/transaction-landing-race.md b/docs/transaction-landing-race.mdnew file mode 100644index 000000000..1a26f325b--- /dev/null+++ b/docs/transaction-landing-race.md@@ -0,0 +1,45 @@+# Transaction landing race++Every signed Solana transaction that goes through `submitProtected` in [api/_lib/execution-engine.js](../api/_lib/execution-engine.js) is sent through several landing providers at once. The first provider to report a confirmed landing wins, the others are aborted, and the caller gets exactly one result. Solana dedupes by signature, so the lanes are one transaction with several doors: a duplicate send can never double-spend.++## Providers++The provider list is data: [api/_lib/landing-providers.js](../api/_lib/landing-providers.js).++| Provider | Kind | Enabled when | Tip |+|---|---|---|---|+| `rpc` | primary connection (protected send) | always | none |+| `jito` | Jito block-engine bundle | mainnet and tip mode `economy` or `turbo` | Jito tip account |+| `helius` | Helius staked RPC | `HELIUS_API_KEY` is set | none |+| `helius_sender` | Helius sender | `HELIUS_SENDER_TIP_ACCOUNT` is set (mainnet, tip mode not `off`, Jito lane not in use) | transfer to that account |+| `extra_rpc` | any additional JSON-RPC endpoint | `LANDING_EXTRA_RPC_URL` is set | none |++A provider whose credential is missing stays in the table with the env var that enables it. `LANDING_DISABLED_PROVIDERS` (comma separated names) switches providers off without a deploy. The primary `rpc` lane is never skipped: it is the guaranteed route.++## How a trade is raced++1. Build, sign and serialize the transaction once.+2. Start one lane per enabled, non-skipped provider, ordered by recent success.+3. RPC lanes `sendTransaction` to their endpoint and then poll that endpoint's own `getSignatureStatuses`, so a slow provider genuinely loses.+4. The first lane to confirm wins. Lanes still in flight are aborted and counted as outpaced. A hard on-chain revert from any lane ends the race for everyone.+5. The result carries `landedBy` (the winning provider) and `lanes` (per-provider outcome and latency).++## Stats and the failure streak++Per provider and network the table `landing_provider_stats` ([migration](../api/_lib/migrations/20261023190000_landing_provider_stats.sql)) keeps:++- `landed`: first to confirm+- `lost`: errored, or finished without landing+- `outpaced`: still racing when another lane landed (not a failure)+- `streak`: consecutive losses; `latency_ms`: moving average landing latency++Lanes are ordered by Laplace-smoothed success rate. After 3 consecutive losses a provider is skipped. While skipped it gets a health probe at most every 30 seconds (off the trade path); a passing probe clears the streak and the provider rejoins on the next trade. Stats persist when `DATABASE_URL` is set and fall back to per-instance memory otherwise.++## Tip budget++`opts.maxTipLamports` (or the `LANDING_MAX_TIP_LAMPORTS` default) is a per-trade tip ceiling. The tip is one instruction inside the one signed transaction, so the ceiling binds every tip-bearing provider at once. If the ceiling is below the smallest tip a provider accepts (1000 lamports), the trade skips the tipped lane and rides the untipped providers with `fallbackReason: 'tip_over_budget'`.++## Proof++- `npx vitest run tests/landing-race.test.js` runs real JSON-RPC over local HTTP servers: slow provider loses, failing provider is recorded lost, one confirmation is reported, the skip and probe cycle, SQL persistence, and the tip ceiling.+- `node scripts/landing-race-devnet.mjs` sends real self-transfers through the race on a non-mainnet cluster and prints the stats table. Pass `--primary` and `--extra` RPC URLs; pass `--db <postgres url>` to persist into a real database.diff --git a/scripts/landing-race-devnet.mjs b/scripts/landing-race-devnet.mjsnew file mode 100644index 000000000..54050c62f--- /dev/null+++ b/scripts/landing-race-devnet.mjs@@ -0,0 +1,65 @@+#!/usr/bin/env node+// Devnet proof for the transaction landing race. Sends real self-transfers through+// submitProtected with two devnet providers (the primary RPC plus an additional+// public devnet RPC), then prints the per-provider stats table.+//+// node scripts/landing-race-devnet.mjs [--runs 4] [--extra <rpc url>] [--db <postgres url>]+//+// Devnet only: the payer is an ephemeral keypair funded by a devnet airdrop. With+// --db the counters persist to landing_provider_stats in that database (apply+// api/_lib/migrations/20261023190000_landing_provider_stats.sql first); without+// it an in-process Postgres holds them for the run.++import { readFileSync } from 'node:fs';+import { Connection, Keypair, LAMPORTS_PER_SOL, SystemProgram } from '@solana/web3.js';+import { submitProtected } from '../api/_lib/execution-engine.js';+import { createSqlStatsStore, getLandingStats } from '../api/_lib/landing-race.js';++const args = process.argv.slice(2);+const flag = (n, d) => (args.includes(n) ? args[args.indexOf(n) + 1] : d);+const runs = Number(flag('--runs', 4));+const primaryUrl = flag('--primary', 'https://api.devnet.solana.com');+const extraUrl = flag('--extra', 'https://solana-devnet.api.onfinality.io/public');+const dbUrl = flag('--db', null);++process.env.LANDING_EXTRA_RPC_URL = extraUrl;++const migration = readFileSync(new URL('../api/_lib/migrations/20261023190000_landing_provider_stats.sql', import.meta.url), 'utf8');+let run;+let closeDb = async () => {};+if (dbUrl) {+ const { neon } = await import('@neondatabase/serverless');+ const client = neon(dbUrl);+ run = (t, p) => client.query(t, p);+} else {+ const { PGlite } = await import('@electric-sql/pglite');+ const db = new PGlite();+ await db.exec(migration);+ run = async (t, p) => (await db.query(t, p)).rows;+ closeDb = () => db.close();+}+const store = createSqlStatsStore(run);+const stats = getLandingStats('devnet', store);++const connection = new Connection(primaryUrl, 'confirmed');+const payer = Keypair.generate();+const airdropSig = await connection.requestAirdrop(payer.publicKey, 0.05 * LAMPORTS_PER_SOL);+const bh = await connection.getLatestBlockhash();+await connection.confirmTransaction({ signature: airdropSig, ...bh }, 'confirmed');+console.log(`funded ${payer.publicKey.toBase58()} on devnet`);++for (let i = 0; i < runs; i++) {+ const ix = SystemProgram.transfer({ fromPubkey: payer.publicKey, toPubkey: Keypair.generate().publicKey, lamports: 1000 + i });+ const r = await submitProtected({ network: 'devnet', connection, payer, instructions: [ix], opts: { confirmTimeoutMs: 40_000 } });+ console.log(`run ${i + 1}: ${r.signature.slice(0, 16)}... landedBy=${r.landedBy} slot=${r.slot} ${r.landedMs}ms lanes=${r.lanes.map((l) => `${l.name}:${l.outcome}@${l.ms}ms`).join(' ')}`);+}++await stats.flush();+const rows = await run(+ 'select provider, network, landed, lost, outpaced, streak, latency_ms, last_error from landing_provider_stats order by provider',+ [],+);+console.log('\nlanding_provider_stats');+console.table(rows);+await closeDb();+process.exit(0);diff --git a/tests/funder-graph.test.js b/tests/funder-graph.test.jsnew file mode 100644index 000000000..c46fcb7fd--- /dev/null+++ b/tests/funder-graph.test.js@@ -0,0 +1,38 @@+import { describe, it, expect } from 'vitest';+import { buildGraph, clusterColor } from '../src/funder-graph.js';++const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++describe('buildGraph', () => {+ const wallets = [+ { wallet: `${THREE_MINT}a`, net_sol: 10, cluster: 1, is_creator: true },+ { wallet: `${THREE_MINT}b`, net_sol: 2.5, cluster: 1 },+ { wallet: `${THREE_MINT}c`, net_sol: 1, cluster: null },+ { wallet: `${THREE_MINT}d`, net_sol: 0, cluster: 2 },+ { wallet: `${THREE_MINT}e`, net_sol: -4, cluster: 2 },+ ];+ const g = buildGraph(wallets, [{ cluster: 1, wallets: 2, net_sol: 12.5 }]);++ it('keeps only wallets with a positive net position, plus one funder node per cluster', () => {+ expect(g.nodes.filter((n) => n.kind === 'wallet')).toHaveLength(3);+ expect(g.nodes.filter((n) => n.kind === 'funder').map((n) => n.id)).toEqual(['funder:1']);+ });++ it('links clustered wallets to their funder and leaves independents unlinked', () => {+ expect(g.edges).toHaveLength(2);+ expect(g.edges.every((e) => e.source === 'funder:1')).toBe(true);+ });++ it('sizes nodes by holdings and colors the creator and independents distinctly', () => {+ const byId = Object.fromEntries(g.nodes.map((n) => [n.id, n]));+ expect(byId[`${THREE_MINT}a`].radius).toBeGreaterThan(byId[`${THREE_MINT}b`].radius);+ expect(byId[`${THREE_MINT}b`].radius).toBeGreaterThan(byId[`${THREE_MINT}c`].radius);+ expect(byId[`${THREE_MINT}a`].color).toBe('#fbbf24');+ expect(byId[`${THREE_MINT}c`].color).toBe('#5b6478');+ expect(byId[`${THREE_MINT}b`].color).toBe(clusterColor(1));+ });++ it('returns an empty graph for no holders', () => {+ expect(buildGraph([], []).nodes).toEqual([]);+ });+});