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
refactor: replace WebSocket confirmations with HTTP polling for transaction confirmations
fudjia97cba9ee2cda
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 958e8f49e..0796269b0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -13,6 +13,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **A redesigned Portfolio tab — see your whole wallet at a glance** — The agent wallet's Portfolio tab got a full visual pass. Net worth now leads with a bold headline figure beside a gradient trend chart that fills in live. A new Allocation bar shows exactly how the wallet is split across SOL, stablecoins, $THREE and any memecoins — one glance tells you the composition, with a colour-coded legend. The Risk tiles gained heat-coloured meters (green when calm, amber-to-red as concentration or tape exposure climbs) plus hover detail, P&L figures now sit in clean chips, and the whole panel animates in with a subtle staggered entrance. Every agent's Portfolio view gets it. `[improvement]`- **Agent creation now tells you what to do when your avatar library is full** — If you hit your plan's avatar limit while creating an agent, the wizard used to fail with a bare error and leave you stuck. It now explains what happened and gives you three ways forward, right in the form: connect an avatar you already own (one click jumps you to your library), free up a slot by deleting an old avatar, or upgrade your plan. Oversized model files get a clearer message too. (`/create-agent`) `[fix, improvement]`- **Agent profile page no longer collapses into a broken narrow column** — On some window sizes an agent's profile page could strand every card into a single skinny column down the left edge, leaving a huge empty gutter and a page that ran on forever. The card layout was rebuilt on a resilient grid that always tiles cards evenly across the full width and stretches to fill — so the page reads cleanly at every screen size, from ultrawide down to phone. `[fix]`+- **Agent wallet card now loads for signed-in visitors, not just the owner** — When you were signed in and viewed an agent that wasn't yours, its wallet card failed to load — the balance panel returned a permission error instead of the public wallet view an unauthenticated visitor already got. Signed-in visitors now see the same read-only wallet card (address and balance) as everyone else; provisioning, importing, or clearing a wallet stays owner-only. `[fix]`- **Agent wallet: a top-to-bottom polish and accessibility pass across every tab** — We went through all 23 sections of your agent's wallet — Balance, Go Live, Portfolio, Deposit, Trade, Snipe, Orders, Autopilot, Intents, Earn, Pay, Withdraw, Give, Trust, Signals, Vanity, Copilot, Proof of Custody, Access, Recovery, and more — and brought every one up to the same bar. Screen readers now announce live figures, quotes, order status, and errors as they happen; every button, form field, and progress bar has a proper label and a visible keyboard focus ring; charts and meters carry text descriptions; and failures show a clear, retryable message instead of a dead end. Along the way we fixed real bugs: the Balance tab was shipping unstyled, the Pay tab's live progress steps never appeared, the Withdraw tab was distorting the wallet header, and a few sections could blank out on a network error. Money amounts that can't be computed now show "—" instead of "NaN", and everything respects reduced-motion settings. `[improvement, fix]`- **Animation Gallery rebuilt — see every clip before you use it** — The animation gallery at three.ws/animations got a ground-up upgrade. All 2,100+ clips now show a real poster image of the avatar mid-motion instead of a blank tile, and hovering any card plays the full animation live in 3D. Clips are organized into 16 browsable categories (dance, combat, weapons, sports, and more) with search, sorting, and loop filters, and every clip has its own shareable link with playback controls — scrub the timeline, change the speed, then send it straight to the Animation Studio or copy an embed snippet for your own site. (`/animations`) `[feature, improvement]`- **Animation Studio — avatars no longer crumple when you preview a motion** — Loading your own avatar and playing a preset like Facepalm sometimes folded the whole character into a heap on the floor — even though the studio reported a clean "100% retargeted." The baked motion clips carry a per-bone scale and length channel from the character they were authored on, and those were being stamped onto your avatar, overwriting its own proportions. The Animation Studio now drives only what's actually motion — the joint rotations and the root's travel — and leaves every rig's bone lengths and scale untouched, so any avatar (tall, short, generated, Mixamo) plays every clip standing up in its own body. The "retargeted" percentage now counts only those real motion channels, so it reflects what you see. (`/pose`) `[fix]`@@ -22,6 +23,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Faster, steadier pages under load — cache now compresses what it stores** — Behind the scenes, three.ws caches heavy data (live money flows, trending snapshots, leaderboards) in a shared store so pages stay fast without re-crunching everything on every visit. When that store sits far from our servers, the largest of those writes were timing out and quietly falling back to a per-server memory copy that vanishes on restart — so under traffic, pages kept hitting the origin and slowed down. Those payloads are now gzip-compressed before they're stored, shrinking them 5–10×, which lets them land in the shared cache instead of timing out. The result is fewer cache misses, less origin load, and steadier response times on data-heavy pages during busy periods. No action needed — it just works. `[fix, infra]`- **Go Live: a real path to activate your agent even when the welcome grant is paused** — When the one-tap welcome grant is temporarily paused, the Go Live tab used to show a bare dead-end card. It's now a proper self-fund path: it explains that depositing your own SOL does the exact same thing — funds your agent and lands it on the live Money Pulse — shows how much is enough to go live, and reassures you the deposit stays yours and is withdrawable anytime. The grant reopens on its own when the treasury is back online. `[improvement]`- **Go Pro with SOL or $THREE — 20% off in the platform coin** — The Pro plan is now a real self-serve upgrade you can buy on-chain. The pricing page checkout accepts USDC, SOL, or $THREE on Solana: pick your asset, scan a Solana Pay QR (or open it straight in your wallet), and your account upgrades the moment the payment finalizes. SOL and $THREE amounts are quoted at the live market price and pinned for the session, and paying in $THREE takes 20% off the sticker price — holding the coin already earns discounts, and now spending it does too. (`/pricing`) `[feature]`+- **Live money feed hardened — on-chain confirmations no longer stall or flood the logs** — The engine that confirms the platform's real on-chain transactions (funding, transfers, trades, launches, tips, and every attestation) was waiting on a WebSocket to each Solana RPC. When a provider rate-limited that socket, it reconnected in a tight loop — burying the logs in thousands of errors a minute and hanging the autonomous activity engine until it timed out, which showed up as gaps in the live feed. Confirmations now poll the chain over plain HTTP, which rides the same multi-provider failover as every other RPC call: a throttled provider is skipped instead of hammered, and a reverted transaction is always caught instead of being recorded as success. The feed stays live and the noise is gone. `[fix, infra]`- **Open in Studio now previews the animation instantly** — Opening an animation from the gallery in the Animation Studio used to drop you onto an empty stage. Now it auto-loads a rigged avatar and plays the clip live the moment the page opens — no setup. Each animation previews on a character picked to fit it, and the new playback bar lets you scrub the clip’s timeline, pause on any frame, change speed, and export it as an animated GLB. (`/animations`) `[improvement]`- **Payments a wallet silently rewrites now explain themselves instead of bouncing** — Some Solana wallets modify a payment transaction before signing it — injecting their own fee or guard instructions — and the platform's payment verifier rightly refuses anything that isn't the exact transfer it prepared. Until now that refusal looked like a dead end: the pay button bounced with a payment-required error no matter how many times you retried. The checkout now detects the rewrite the moment the wallet hands the transaction back and says plainly that the wallet altered it and nothing was charged, so you can switch wallets instead of retrying in circles. Verify rejections and settle failures are also now counted by reason on the public health endpoint, so a streak of refused payments is visible at a glance instead of hiding in admin logs. (`/club`) `[fix, improvement]`- **Portfolio risk panel stops crying wolf on fresh wallets** — Every agent wallet holds SOL as its base currency, but the Portfolio tab used to flag a brand-new wallet holding only SOL as "100% concentration risk" in alarming red — a false alarm, since holding the base asset isn't a bet on anything. Concentration is now measured only across volatile memecoin positions, so a wallet parked in SOL or stablecoins reads correctly: a new Reserve tile shows your dry powder, and the panel tells you it's ready to deploy with minimal market risk instead of warning you about a risk that isn't there. A genuine over-concentration in one memecoin is still flagged. Applies to every agent's Portfolio view. `[fix, improvement]`diff --git a/api/_lib/agent-invocation-onchain.js b/api/_lib/agent-invocation-onchain.jsindex 7460bd1a7..8eaf5b70a 100644--- a/api/_lib/agent-invocation-onchain.js+++ b/api/_lib/agent-invocation-onchain.js@@ -24,8 +24,8 @@ import {SystemProgram,Transaction,TransactionInstruction,- sendAndConfirmTransaction,} from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import { solanaConnection } from './solana/connection.js';@@ -157,7 +157,7 @@ export async function recordInvocationReceipt({const conn = connection || solanaConnection({ network, commitment: 'confirmed' });const tx = new Transaction().add(instruction);- const signature = await sendAndConfirmTransaction(conn, tx, [invokerKeypair], {+ const signature = await sendAndConfirm(conn, tx, [invokerKeypair], {commitment: 'confirmed',});diff --git a/api/_lib/agora-human.js b/api/_lib/agora-human.jsindex 2fe9df0f2..588b84b2f 100644--- a/api/_lib/agora-human.js+++ b/api/_lib/agora-human.js@@ -16,6 +16,7 @@import { createHash } from 'node:crypto';import { sql } from './db.js';+import { confirmOrThrow, sendAndConfirm } from './solana/confirm.js';import { generateSolanaAgentWallet, getSolanaAddressBalances } from './agent-wallet.js';import { decryptSecret } from './secret-box.js';import { TOKEN_MINT, TOKEN_DECIMALS } from './token/config.js';@@ -169,7 +170,9 @@ export async function ensureDevnetBalance(connection, keypair, neededLamports) {for (let i = 0; i < chunks.length; i++) {try {const sig = await connection.requestAirdrop(keypair.publicKey, Math.max(chunks[i], LAMPORTS_PER_SOL / 50));- await connection.confirmTransaction(sig, 'confirmed');+ // HTTP-polling confirm (no WebSocket); bounded so a dropped devnet airdrop+ // falls through to the next chunk instead of hanging the confirm window.+ await confirmOrThrow(connection, sig, 'confirmed', { timeoutMs: 30_000 });const next = await connection.getBalance(keypair.publicKey);if (next >= neededLamports) return next;} catch {@@ -361,7 +364,7 @@ const MEMO_PROGRAM_ID = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';* agora_vouches edge and the 'vouched' activity row cite. Returns the tx sig.*/export async function sendOnchainAttestation({ cluster, signer, memo }) {- const { Connection, Transaction, TransactionInstruction, PublicKey, sendAndConfirmTransaction } =+ const { Connection, Transaction, TransactionInstruction, PublicKey } =await import('@solana/web3.js');const rpc = pickRpc(cluster) || (cluster === 'devnet' ? 'https://api.devnet.solana.com' : 'https://api.mainnet-beta.solana.com');const conn = new Connection(rpc, 'confirmed');@@ -372,5 +375,6 @@ export async function sendOnchainAttestation({ cluster, signer, memo }) {data: Buffer.from(String(memo).slice(0, 500), 'utf8'),});const tx = new Transaction().add(ix);- return sendAndConfirmTransaction(conn, tx, [signer], { commitment: 'confirmed' });+ // HTTP-polling send+confirm (no WebSocket subscription).+ return sendAndConfirm(conn, tx, [signer], { commitment: 'confirmed' });}diff --git a/api/_lib/attest-event.js b/api/_lib/attest-event.jsindex 9acd43310..6c8bbb1f6 100644--- a/api/_lib/attest-event.js+++ b/api/_lib/attest-event.js@@ -17,8 +17,8 @@ import {PublicKey,Transaction,TransactionInstruction,- sendAndConfirmTransaction,} from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import bs58 from 'bs58';import { sql } from './db.js';@@ -224,7 +224,7 @@ export async function mintAttestation(input) {let signature;try {signature = await withTimeout(- sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' }),+ sendAndConfirm(conn, tx, [attester], { commitment: 'confirmed' }),TX_TIMEOUT_MS,);} catch (e) {diff --git a/api/_lib/circulation.js b/api/_lib/circulation.jsindex 106cad4fa..651f0a53d 100644--- a/api/_lib/circulation.js+++ b/api/_lib/circulation.js@@ -18,6 +18,7 @@import { sql } from './db.js';import { env } from './env.js';+import { confirmOrThrow } from './solana/confirm.js';import { randomUUID } from 'node:crypto';import { scrubSecrets } from './scrub-secrets.js';import {@@ -224,8 +225,10 @@ async function transferSol(conn, fromKp, toAddress, lamports) {tx.sign([fromKp]);try {const signature = await conn.sendTransaction(tx, { maxRetries: 5 });- const conf = await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');- if (conf.value?.err) throw new Error('transfer failed on-chain: ' + JSON.stringify(conf.value.err));+ // HTTP-polling confirm — routes through the RPC failover fetch and opens+ // no WebSocket, so a throttled provider can't trigger web3.js's WS 429+ // reconnect storm. Throws on a landed-but-reverted transfer.+ await confirmOrThrow(conn, { signature, blockhash, lastValidBlockHeight }, 'confirmed');return signature;} catch (err) {const msg = err?.message || '';diff --git a/api/_lib/custody-proof.js b/api/_lib/custody-proof.jsindex 920dfabc4..c9c50ab4a 100644--- a/api/_lib/custody-proof.js+++ b/api/_lib/custody-proof.js@@ -16,8 +16,8 @@ import {PublicKey,Transaction,TransactionInstruction,- sendAndConfirmTransaction,} from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import { sql } from './db.js';import { solanaConnection } from './solana/connection.js';@@ -267,7 +267,7 @@ export async function anchorRoot({ epoch, root, walletCount }) {let signature;try {signature = await withTimeout(- sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' }),+ sendAndConfirm(conn, tx, [attester], { commitment: 'confirmed' }),TX_TIMEOUT_MS,);} catch (e) {diff --git a/api/_lib/execution-engine.js b/api/_lib/execution-engine.jsindex 71fa66a58..c1722a6d8 100644--- a/api/_lib/execution-engine.js+++ b/api/_lib/execution-engine.js@@ -45,6 +45,7 @@ import {TransactionMessage,VersionedTransaction,} from '@solana/web3.js';+import { pollConfirmation } from './solana/confirm.js';// Jito's published mainnet tip accounts. A bundle's tip must transfer SOL to one// of these — Jito only accepts a bundle that pays a tip to a known tip account.@@ -302,9 +303,14 @@ function sleep(ms) {async function sendProtected(signedTx, signature, connection, blockhashCtx, confirmTimeoutMs) {await connection.sendRawTransaction(signedTx.serialize(), { skipPreflight: false, maxRetries: 3 });- const confirmPromise = connection.confirmTransaction(+ // HTTP-polling confirm (no WebSocket) — bounded by confirmTimeoutMs and re-checked+ // on the ambiguous-timeout path below, so a throttled RPC can't spin web3.js's WS+ // 429 reconnect loop. Returns the confirmTransaction result shape this code reads.+ const confirmPromise = pollConfirmation(+ connection,{ signature, blockhash: blockhashCtx.blockhash, lastValidBlockHeight: blockhashCtx.lastValidBlockHeight },'confirmed',+ { timeoutMs: confirmTimeoutMs },);const timeout = new Promise((_, rej) =>setTimeout(() => rej(Object.assign(new Error('confirm timeout'), { code: 'CONFIRM_TIMEOUT' })), confirmTimeoutMs),diff --git a/api/_lib/ledger-anchor.js b/api/_lib/ledger-anchor.jsindex 0c86d9cb8..0c0e208ec 100644--- a/api/_lib/ledger-anchor.js+++ b/api/_lib/ledger-anchor.js@@ -17,7 +17,8 @@* existing row instead of broadcasting a duplicate.*/-import { PublicKey, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';+import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import { sql } from './db.js';import { solanaConnection } from './solana/connection.js';@@ -92,7 +93,7 @@ export async function anchorLedgerHead({ agentId, network = 'mainnet', headHash,let signature;try {signature = await withTimeout(- sendAndConfirmTransaction(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),+ sendAndConfirm(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),TX_TIMEOUT_MS,);} catch (err) {diff --git a/api/_lib/platform-treasury.js b/api/_lib/platform-treasury.jsindex bf116a909..09ba133fd 100644--- a/api/_lib/platform-treasury.js+++ b/api/_lib/platform-treasury.js@@ -14,6 +14,7 @@// degrade gracefully — nothing is ever inert-but-pretending.import { solanaConnection } from './agent-pumpfun.js';+import { confirmOrThrow } from './solana/confirm.js';const SOL = 1_000_000_000;// tx fee + compute headroom kept on the treasury beyond the amount it sends.@@ -133,13 +134,9 @@ export async function transferSol(conn, fromKp, toAddress, lamports) {let signature = null;try {signature = await conn.sendTransaction(tx, { maxRetries: 5 });- const conf = await conn.confirmTransaction(- { signature, blockhash, lastValidBlockHeight },- 'confirmed',- );- if (conf.value?.err) {- throw new Error('transfer failed on-chain: ' + JSON.stringify(conf.value.err));- }+ // HTTP-polling confirm (no WebSocket) — throws on a landed-but-reverted+ // transfer; the surrounding catch retries only the never-landed case.+ await confirmOrThrow(conn, { signature, blockhash, lastValidBlockHeight }, 'confirmed');return signature;} catch (err) {const msg = err?.message || '';diff --git a/api/_lib/review-attest.js b/api/_lib/review-attest.jsindex 8f3a5eca6..1c5d695d2 100644--- a/api/_lib/review-attest.js+++ b/api/_lib/review-attest.js@@ -17,7 +17,8 @@*/import crypto from 'node:crypto';-import { PublicKey, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';+import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import { sql } from './db.js';import { solanaConnection } from './solana/connection.js';@@ -129,7 +130,7 @@ export async function attestReview({ reviewId, updatedAt, agentId, rating, body,let signature;try {signature = await withTimeout(- sendAndConfirmTransaction(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),+ sendAndConfirm(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),TX_TIMEOUT_MS,);} catch (err) {diff --git a/api/_lib/skill-license-onchain.js b/api/_lib/skill-license-onchain.jsindex b538769bd..d1e501672 100644--- a/api/_lib/skill-license-onchain.js+++ b/api/_lib/skill-license-onchain.js@@ -26,8 +26,8 @@ import {SYSVAR_RENT_PUBKEY,Transaction,TransactionInstruction,- sendAndConfirmTransaction,} from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import bs58 from 'bs58';import { env } from './env.js';@@ -350,7 +350,7 @@ export async function mintSkillLicenseOnchain({}const tx = new Transaction().add(instruction);- const signature = await sendAndConfirmTransaction(conn, tx, [minter], {+ const signature = await sendAndConfirm(conn, tx, [minter], {commitment: 'confirmed',});return { signature, ...accounts, alreadyMinted: false };diff --git a/api/_lib/solana-validation-attest.js b/api/_lib/solana-validation-attest.jsindex ec33bd4bc..b193772ec 100644--- a/api/_lib/solana-validation-attest.js+++ b/api/_lib/solana-validation-attest.js@@ -31,8 +31,8 @@ import {PublicKey,Transaction,TransactionInstruction,- sendAndConfirmTransaction,} from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import { sql } from './db.js';import { solanaConnection } from './solana/connection.js';@@ -171,7 +171,7 @@ export async function attestValidationSolana({ network, agentAsset, glbUrl, valilet signature;try {signature = await withTimeout(- sendAndConfirmTransaction(conn, tx, [attester], { commitment: 'confirmed' }),+ sendAndConfirm(conn, tx, [attester], { commitment: 'confirmed' }),TX_TIMEOUT_MS,);} catch (err) {diff --git a/api/_lib/solana/confirm.js b/api/_lib/solana/confirm.jsindex f50d4a99d..df84fb7f5 100644--- a/api/_lib/solana/confirm.js+++ b/api/_lib/solana/confirm.js@@ -1,28 +1,127 @@-// Confirm a Solana transaction and THROW if it landed-but-reverted.+// Confirm a Solana transaction over HTTP polling — NEVER via a WebSocket subscription.//-// `Connection.confirmTransaction` resolves normally for a transaction that was-// included in a block but failed execution — the on-chain error lives in-// `result.value.err`, not in a thrown exception. Discarding that result is the-// single most dangerous money-path bug class: a reverted launch/buy/transfer-// gets persisted as `confirmed`, the spend cap is charged, and the user is told-// it succeeded. Every server-signed send path must route its confirmation+// Why not `Connection.confirmTransaction` / `sendAndConfirmTransaction`? Both open a+// web3.js `signatureSubscribe` WebSocket against the Connection's `wsEndpoint`. That+// WS path bypasses the rotating-fetch failover in `solana/connection.js` entirely, so+// when the primary RPC rate-limits the WS upgrade (HTTP 429) web3.js's internal+// rpc-websockets client reconnects in a tight background loop for the whole life of a+// warm serverless instance — the `ws error: Unexpected server response: 429` storm+// that flooded `/api/cron/pulse-tick` with thousands of errors in minutes. Polling+// `getSignatureStatuses` over HTTP goes through the failover fetch (multi-provider+// rotation + cooldowns) and opens no socket, so a throttled provider is transparently+// skipped instead of hammered.+//+// `confirmOrThrow` additionally THROWS on a landed-but-reverted transaction — the+// single most dangerous money-path bug class. `Connection.confirmTransaction` resolves+// normally for a tx that was included in a block but failed execution; the on-chain+// error lives in `result.value.err`, not in a thrown exception. Discarding that result+// records a reverted launch/buy/transfer as `confirmed`, charges the spend cap, and+// tells the user it succeeded. Every server-signed send path routes its confirmation// through this helper so a revert becomes a thrown error the caller handles.//// Drop-in: replace-// await conn.confirmTransaction(strategy, 'confirmed')+// const res = await conn.confirmTransaction(strategy, 'confirmed'); if (res.value?.err) …// with-// await confirmOrThrow(conn, strategy, 'confirmed')-// `strategy` is whatever confirmTransaction accepts — a bare signature string or-// the `{ signature, blockhash, lastValidBlockHeight }` object form.+// await confirmOrThrow(conn, strategy, 'confirmed');+// `strategy` is whatever confirmTransaction accepts — a bare signature string or the+// `{ signature, blockhash, lastValidBlockHeight }` object form. Callers that need the+// raw result without the throw-on-revert (to map their own error) use+// `pollConfirmation`. Legacy `sendAndConfirmTransaction` call sites use `sendAndConfirm`.++// Commitment ordering — a status at or above the requested level satisfies the wait.+const COMMITMENT_RANK = { processed: 0, confirmed: 1, finalized: 2 };+const POLL_INTERVAL_MS = 1_200;+const MAX_CONFIRM_MS = 90_000; // absolute ceiling, even for the bare-signature form+// Block height advances ~2.5 slots/s while a blockhash stays valid for ~150 slots+// (~60s), so checking expiry every few polls is ample and saves an RPC round-trip.+const BLOCKHEIGHT_CHECK_EVERY = 3;++const sleep = (ms) => new Promise((r) => setTimeout(r, ms));++function txExpiredError(signature) {+ return Object.assign(+ new Error(`Transaction ${signature} expired: block height exceeded`),+ { code: 'tx_expired', signature },+ );+}++function confirmTimeoutError(signature, ms) {+ return Object.assign(+ new Error(`Transaction ${signature} not confirmed within ${Math.round(ms / 1000)}s`),+ { code: 'tx_confirm_timeout', signature },+ );+}++/**+ * Poll `getSignatureStatuses` until `signature` reaches `commitment`, reverts, expires,+ * or the confirm window elapses. Opens no WebSocket. Returns a confirmTransaction-shaped+ * result `{ context: { slot }, value: { err, confirmationStatus, slot } }` — `value.err`+ * is set (not thrown) when the tx landed but reverted, so callers that map their own+ * error can inspect it. Throws `tx_expired` (blockhash no longer valid) or+ * `tx_confirm_timeout` (window elapsed) when the tx never lands.+ *+ * @param {import('@solana/web3.js').Connection} conn+ * @param {string | { signature: string, blockhash?: string, lastValidBlockHeight?: number }} strategy+ * @param {import('@solana/web3.js').Commitment} [commitment]+ * @param {{ timeoutMs?: number }} [opts]+ * @returns {Promise<{ context: { slot: number|null }, value: { err: any, confirmationStatus?: string, slot: number|null } }>}+ */+export async function pollConfirmation(conn, strategy, commitment = 'confirmed', { timeoutMs = MAX_CONFIRM_MS } = {}) {+ const signature = typeof strategy === 'string' ? strategy : strategy?.signature;+ if (!signature) throw Object.assign(new Error('confirm: missing signature'), { code: 'confirm_no_signature' });+ const lastValidBlockHeight = typeof strategy === 'object' && strategy ? strategy.lastValidBlockHeight : undefined;+ const target = COMMITMENT_RANK[commitment] ?? COMMITMENT_RANK.confirmed;+ const deadline = Date.now() + timeoutMs;++ for (let i = 0; ; i++) {+ let st = null;+ try {+ const res = await conn.getSignatureStatuses([signature]);+ st = res?.value?.[0] ?? null;+ } catch {+ // Transient RPC blip — the rotating fetch already failed over across+ // providers; treat this poll as "not yet known" and retry.+ }++ if (st) {+ // A landed-but-reverted tx carries `err`; surface it (don't throw here) so+ // confirmOrThrow / call-site logic can classify it.+ if (st.err) return { context: { slot: st.slot ?? null }, value: { err: st.err, slot: st.slot ?? null } };+ const rank = COMMITMENT_RANK[st.confirmationStatus] ?? -1;+ if (rank >= target) {+ return {+ context: { slot: st.slot ?? null },+ value: { err: null, confirmationStatus: st.confirmationStatus, slot: st.slot ?? null },+ };+ }+ }++ // Expiry only matters before the tx lands: once we've seen any status it will+ // climb to the target commitment on its own. Checked periodically to save RPC.+ if (lastValidBlockHeight != null && st == null && i % BLOCKHEIGHT_CHECK_EVERY === 0) {+ let height = null;+ try { height = await conn.getBlockHeight(commitment); } catch { /* retry next poll */ }+ if (height != null && height > lastValidBlockHeight) throw txExpiredError(signature);+ }++ if (Date.now() >= deadline) throw confirmTimeoutError(signature, timeoutMs);+ await sleep(POLL_INTERVAL_MS);+ }+}/**+ * Confirm `strategy` and THROW if it landed but reverted (code `tx_reverted`, with the+ * on-chain error attached), expired, or timed out. Returns the confirmation result on+ * success. HTTP polling only — opens no WebSocket.+ ** @param {import('@solana/web3.js').Connection} conn* @param {string | { signature: string, blockhash?: string, lastValidBlockHeight?: number }} strategy* @param {import('@solana/web3.js').Commitment} [commitment]- * @returns {Promise<import('@solana/web3.js').RpcResponseAndContext<import('@solana/web3.js').SignatureResult>>}+ * @param {{ timeoutMs?: number }} [opts]+ * @returns {Promise<{ context: { slot: number|null }, value: { err: any, confirmationStatus?: string, slot: number|null } }>}*/-export async function confirmOrThrow(conn, strategy, commitment = 'confirmed') {- const result = await conn.confirmTransaction(strategy, commitment);+export async function confirmOrThrow(conn, strategy, commitment = 'confirmed', opts = {}) {+ const result = await pollConfirmation(conn, strategy, commitment, opts);if (result?.value?.err) {const signature = typeof strategy === 'string' ? strategy : strategy?.signature;throw Object.assign(@@ -34,3 +133,39 @@ export async function confirmOrThrow(conn, strategy, commitment = 'confirmed') {}return result;}++/**+ * HTTP-polling replacement for @solana/web3.js `sendAndConfirmTransaction`. Signs the+ * legacy `Transaction` with `signers`, broadcasts it, and confirms via+ * `confirmOrThrow` — opening no WebSocket and throwing on a reverted tx. Fills in+ * `recentBlockhash` / `feePayer` when unset, mirroring web3.js. Returns the signature.+ *+ * @param {import('@solana/web3.js').Connection} conn+ * @param {import('@solana/web3.js').Transaction} tx+ * @param {import('@solana/web3.js').Signer[]} signers first entry is the fee payer when unset+ * @param {{ commitment?: import('@solana/web3.js').Commitment, skipPreflight?: boolean, maxRetries?: number, timeoutMs?: number }} [opts]+ * @returns {Promise<string>} the transaction signature+ */+export async function sendAndConfirm(conn, tx, signers, opts = {}) {+ const { commitment = 'confirmed', skipPreflight = false, maxRetries = 3, timeoutMs } = opts;+ if (!Array.isArray(signers) || signers.length === 0) {+ throw new Error('sendAndConfirm: at least one signer is required');+ }+ let lastValidBlockHeight = tx.lastValidBlockHeight;+ if (!tx.recentBlockhash) {+ const bh = await conn.getLatestBlockhash(commitment);+ tx.recentBlockhash = bh.blockhash;+ tx.lastValidBlockHeight = bh.lastValidBlockHeight;+ lastValidBlockHeight = bh.lastValidBlockHeight;+ }+ if (!tx.feePayer) tx.feePayer = signers[0].publicKey;+ tx.sign(...signers);+ const signature = await conn.sendRawTransaction(tx.serialize(), { skipPreflight, maxRetries });+ await confirmOrThrow(+ conn,+ { signature, blockhash: tx.recentBlockhash, lastValidBlockHeight },+ commitment,+ timeoutMs != null ? { timeoutMs } : {},+ );+ return signature;+}diff --git a/api/_lib/token/allowance-ops.js b/api/_lib/token/allowance-ops.jsindex 1bed14be6..67f1fab1d 100644--- a/api/_lib/token/allowance-ops.js+++ b/api/_lib/token/allowance-ops.js@@ -17,6 +17,7 @@ import {ASSOCIATED_TOKEN_PROGRAM_ID,} from '@solana/spl-token';import { solanaConnection } from '../solana/connection.js';+import { pollConfirmation } from '../solana/confirm.js';import { getRedis } from '../redis.js';import { TOKEN_MINT, ATOMICS_PER_TOKEN } from './config.js';import {@@ -385,7 +386,10 @@ export async function pullFromAllowance({ userWallet, legs, network = 'mainnet'tx.sign(delegate);const signature = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });- const confirmation = await connection.confirmTransaction(+ // HTTP-polling confirm (no WebSocket) — keeps the RPC failover in play and maps a+ // landed-but-reverted pull to the caller's `pull_failed` contract below.+ const confirmation = await pollConfirmation(+ connection,{ signature, blockhash, lastValidBlockHeight },'confirmed',);diff --git a/api/_lib/tournament-attest.js b/api/_lib/tournament-attest.jsindex 1dacb1212..508cb0788 100644--- a/api/_lib/tournament-attest.js+++ b/api/_lib/tournament-attest.js@@ -16,7 +16,8 @@* instead of broadcasting a duplicate.*/-import { PublicKey, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';+import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import { sql } from './db.js';import { solanaConnection } from './solana/connection.js';@@ -140,7 +141,7 @@ export async function attestTournamentStandings({ tournament, standings, now = Dlet signature;try {signature = await withTimeout(- sendAndConfirmTransaction(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),+ sendAndConfirm(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),TX_TIMEOUT_MS,);} catch (err) {diff --git a/api/_lib/trader-score-attest.js b/api/_lib/trader-score-attest.jsindex 48c486b03..20f20e9b7 100644--- a/api/_lib/trader-score-attest.js+++ b/api/_lib/trader-score-attest.js@@ -15,7 +15,8 @@* same day returns the existing signature instead of broadcasting a duplicate.*/-import { PublicKey, Transaction, TransactionInstruction, sendAndConfirmTransaction } from '@solana/web3.js';+import { PublicKey, Transaction, TransactionInstruction } from '@solana/web3.js';+import { sendAndConfirm } from './solana/confirm.js';import { sql } from './db.js';import { solanaConnection } from './solana/connection.js';@@ -122,7 +123,7 @@ export async function attestTraderScore({ network, wallet, agentId, metrics, winlet signature;try {signature = await withTimeout(- sendAndConfirmTransaction(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),+ sendAndConfirm(conn, new Transaction().add(ix), [attester], { commitment: 'confirmed' }),TX_TIMEOUT_MS,);} catch (err) {diff --git a/api/_lib/treasury-autopilot.js b/api/_lib/treasury-autopilot.jsindex 0d6390d33..2f17e0438 100644--- a/api/_lib/treasury-autopilot.js+++ b/api/_lib/treasury-autopilot.js@@ -24,6 +24,7 @@import { PublicKey, VersionedTransaction } from '@solana/web3.js';import { sql } from './db.js';+import { confirmOrThrow } from './solana/confirm.js';import { solUsdPrice, sendSol, explorerTxUrl, explorerAccountUrl } from './avatar-wallet.js';import { solanaConnection } from './agent-pumpfun.js';import { getSolanaAddressBalances, recoverSolanaAgentKeypair } from './agent-wallet.js';@@ -593,7 +594,9 @@ async function swapSolToToken({ keypair, lamports, outputMint, slippageBps, netwtx.sign([keypair]);const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });const bh = await conn.getLatestBlockhash();- await conn.confirmTransaction({ signature: sig, ...bh }, 'confirmed');+ // HTTP-polling confirm (no WebSocket) — throws on a landed-but-reverted swap so+ // a revert is never reported back as a successful autopilot trade.+ await confirmOrThrow(conn, { signature: sig, ...bh }, 'confirmed');return { signature: sig, outAmount: quote.outAmount, outMint: outputMint };}diff --git a/api/_lib/vault-trade.js b/api/_lib/vault-trade.jsindex 84aaed842..d262f17bf 100644--- a/api/_lib/vault-trade.js+++ b/api/_lib/vault-trade.js@@ -15,6 +15,7 @@import { PublicKey } from '@solana/web3.js';import { getAssociatedTokenAddressSync, getMint, TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token';import { solanaConnection } from './agent-pumpfun.js';+import { confirmOrThrow } from './solana/confirm.js';import { logAudit } from './audit.js';import { explorerTxUrl } from './avatar-wallet.js';import {@@ -60,13 +61,13 @@ async function signSendConfirm(conn, tx, keypair) {tx.sign([keypair]);const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });const bh = await conn.getLatestBlockhash('confirmed');- const res = await conn.confirmTransaction(+ // HTTP-polling confirm (no WebSocket) — throws `tx_reverted` on a landed-but-+ // reverted swap, so a revert is never recorded as a successful trade.+ await confirmOrThrow(+ conn,{ signature: sig, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight },'confirmed',);- if (res?.value?.err) {- throw Object.assign(new Error('transaction reverted on-chain'), { code: 'tx_reverted', signature: sig });- }return sig;}diff --git a/api/_lib/wallet-intents.js b/api/_lib/wallet-intents.jsindex a6052273c..0a661c41b 100644--- a/api/_lib/wallet-intents.js+++ b/api/_lib/wallet-intents.js@@ -23,6 +23,7 @@import { PublicKey } from '@solana/web3.js';import { sql } from './db.js';+import { confirmOrThrow } from './solana/confirm.js';import { solUsdPrice, sendSol, explorerTxUrl } from './avatar-wallet.js';import { solanaConnection } from './agent-pumpfun.js';import { getSolanaAddressBalances, recoverSolanaAgentKeypair } from './agent-wallet.js';@@ -751,7 +752,9 @@ async function swapSolToToken({ keypair, lamports, outputMint, slippageBps, conntx.sign([keypair]);const sig = await conn.sendRawTransaction(tx.serialize(), { skipPreflight: false, maxRetries: 3 });const bh = await conn.getLatestBlockhash();- await conn.confirmTransaction({ signature: sig, ...bh }, 'confirmed');+ // HTTP-polling confirm (no WebSocket) — throws on a landed-but-reverted swap so+ // a revert is never reported back as a successful intent execution.+ await confirmOrThrow(conn, { signature: sig, ...bh }, 'confirmed');return { signature: sig, outAmount: quote.outAmount };}diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.jsindex 24043facc..76490cf6a 100644--- a/api/agents/solana-wallet.js+++ b/api/agents/solana-wallet.js@@ -3,7 +3,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { confirmOrThrow } from '../_lib/solana/confirm.js';+import { confirmOrThrow, pollConfirmation } from '../_lib/solana/confirm.js';import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';@@ -368,7 +368,14 @@ async function handleWallet(req, res, id) {const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;if (!row) return error(res, 404, 'not_found', 'agent not found');- if (row.user_id !== auth.userId) return error(res, 403, 'forbidden', 'not your agent');+ // A signed-in visitor browsing someone else's agent gets the public wallet+ // card, not a 403 — the same read an unauthenticated visitor gets. Only the+ // mutating methods (POST/DELETE provision/import/wipe the keypair) are+ // owner-gated below.+ if (row.user_id !== auth.userId) {+ if (req.method === 'GET') return handlePublicWalletRead(req, res, id);+ return error(res, 403, 'forbidden', 'not your agent');+ }// Provisioning, importing, and wiping a custodial keypair all change which// keys control the agent's funds — gate the mutating methods behind CSRF so@@ -802,7 +809,8 @@ async function handleWithdraw(req, res, id) {let confirmed = true;try {- const r = await conn.confirmTransaction(+ const r = await pollConfirmation(+ conn,{ signature, blockhash: blockhashCtx.blockhash, lastValidBlockHeight: blockhashCtx.lastValidBlockHeight },'confirmed',);@@ -1289,11 +1297,8 @@ async function sendV0({ conn, payer, ixs }) {const vtx = new VersionedTransaction(msg);vtx.sign([payer]);const sig = await conn.sendRawTransaction(vtx.serialize(), { skipPreflight: false, maxRetries: 3 });- const r = await conn.confirmTransaction(- { signature: sig, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight },- 'confirmed',- );- if (r?.value?.err) throw new Error(`transaction ${sig} failed: ${JSON.stringify(r.value.err)}`);+ // HTTP-polling confirm (no WebSocket) — throws on a landed-but-reverted tx.+ await confirmOrThrow(conn, { signature: sig, blockhash: bh.blockhash, lastValidBlockHeight: bh.lastValidBlockHeight }, 'confirmed');return sig;}diff --git a/data/changelog.json b/data/changelog.jsonindex 8e599b25c..ede5f71ed 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,23 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-07-05",+ "title": "Agent wallet card now loads for signed-in visitors, not just the owner",+ "summary": "When you were signed in and viewed an agent that wasn't yours, its wallet card failed to load — the balance panel returned a permission error instead of the public wallet view an unauthenticated visitor already got. Signed-in visitors now see the same read-only wallet card (address and balance) as everyone else; provisioning, importing, or clearing a wallet stays owner-only.",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-07-05",+ "title": "Live money feed hardened — on-chain confirmations no longer stall or flood the logs",+ "summary": "The engine that confirms the platform's real on-chain transactions (funding, transfers, trades, launches, tips, and every attestation) was waiting on a WebSocket to each Solana RPC. When a provider rate-limited that socket, it reconnected in a tight loop — burying the logs in thousands of errors a minute and hanging the autonomous activity engine until it timed out, which showed up as gaps in the live feed. Confirmations now poll the chain over plain HTTP, which rides the same multi-provider failover as every other RPC call: a throttled provider is skipped instead of hammered, and a reverted transaction is always caught instead of being recorded as success. The feed stays live and the noise is gone.",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-05","title": "Agent profile page no longer collapses into a broken narrow column",diff --git a/public/changelog.json b/public/changelog.jsonindex 6ca6634d2..a08767414 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-05T22:02:38.116Z",+ "generated_at": "2026-07-05T22:46:58.570Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -79,6 +79,16 @@"fix"]},+ {+ "date": "2026-07-05",+ "type": "update",+ "title": "Agent wallet card now loads for signed-in visitors, not just the owner",+ "summary": "When you were signed in and viewed an agent that wasn't yours, its wallet card failed to load — the balance panel returned a permission error instead of the public wallet view an unauthenticated visitor already got. Signed-in visitors now see the same read-only wallet card (address and balance) as everyone else; provisioning, importing, or clearing a wallet stays owner-only.",+ "link": null,+ "tags": [+ "fix"+ ]+ },{"date": "2026-07-05","type": "update",@@ -175,6 +185,17 @@"feature"]},+ {+ "date": "2026-07-05",+ "type": "update",+ "title": "Live money feed hardened — on-chain confirmations no longer stall or flood the logs",+ "summary": "The engine that confirms the platform's real on-chain transactions (funding, transfers, trades, launches, tips, and every attestation) was waiting on a WebSocket to each Solana RPC. When a provider rate-limited that socket, it reconnected in a tight loop — burying the logs in thousands of errors a minute and hanging the autonomous activity engine until it timed out, which showed up as gaps in the live feed. Confirmations now poll the chain over plain HTTP, which rides the same multi-provider failover as every other RPC call: a throttled provider is skipped instead of hammered, and a reverted transaction is always caught instead of being recorded as success. The feed stays live and the noise is gone.",+ "link": null,+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-07-05","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex 85b72e15f..4d3a2e75f 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -62,6 +62,14 @@<category>fix</category><description>On some window sizes an agent's profile page could strand every card into a single skinny column down the left edge, leaving a huge empty gutter and a page that ran on forever. The card layout was rebuilt on a resilient grid that always tiles cards evenly across the full width and stretches to fill — so the page reads cleanly at every screen size, from ultrawide down to phone.</description></item>+ <item>+ <title>Agent wallet card now loads for signed-in visitors, not just the owner</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-05:Agent wallet card now loads for signed-in visitors, not just the owner</guid>+ <pubDate>Sun, 05 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>When you were signed in and viewed an agent that wasn't yours, its wallet card failed to load — the balance panel returned a permission error instead of the public wallet view an unauthenticated visitor already got. Signed-in visitors now see the same read-only wallet card (address and balance) as everyone else; provisioning, importing, or clearing a wallet stays owner-only.</description>+ </item><item><title>Agent wallet: a top-to-bottom polish and accessibility pass across every tab</title><link>https://three.ws/changelog</link>@@ -134,6 +142,14 @@<category>feature</category><description>The Pro plan is now a real self-serve upgrade you can buy on-chain. The pricing page checkout accepts USDC, SOL, or $THREE on Solana: pick your asset, scan a Solana Pay QR (or open it straight in your wallet), and your account upgrades the moment the payment finalizes. SOL and $THREE amounts are quoted at the live market price and pinned for the session, and paying in $THREE takes 20% off the sticker price — holding the coin already earns discounts, and now spending it does too.</description></item>+ <item>+ <title>Live money feed hardened — on-chain confirmations no longer stall or flood the logs</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-07-05:Live money feed hardened — on-chain confirmations no longer stall or flood the logs</guid>+ <pubDate>Sun, 05 Jul 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>The engine that confirms the platform's real on-chain transactions (funding, transfers, trades, launches, tips, and every attestation) was waiting on a WebSocket to each Solana RPC. When a provider rate-limited that socket, it reconnected in a tight loop — burying the logs in thousands of errors a minute and hanging the autonomous activity engine until it timed out, which showed up as gaps in the live feed. Confirmations now poll the chain over plain HTTP, which rides the same multi-provider failover as every other RPC call: a throttled provider is skipped instead of hammered, and a reverted transaction is always caught instead of being recorded as success. The feed stays live and the noise is gone.</description>+ </item><item><title>Open in Studio now previews the animation instantly</title><link>https://three.ws/animations</link>diff --git a/public/features.json b/public/features.jsonindex 0e4cb4f74..2acb6a418 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-05T22:02:38.102Z",+ "generated_at": "2026-07-05T22:46:58.558Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/agent-trade-endpoint.test.js b/tests/agent-trade-endpoint.test.jsindex 5b915449c..c77e5eca6 100644--- a/tests/agent-trade-endpoint.test.js+++ b/tests/agent-trade-endpoint.test.js@@ -120,6 +120,8 @@ function fakeCtx() {getLatestBlockhash: vi.fn(async () => ({ blockhash: PublicKey.default.toBase58(), lastValidBlockHeight: 100 })),sendRawTransaction: vi.fn(async () => connState.sendSig),confirmTransaction: vi.fn(async () => ({ value: { err: connState.confirmErr } })),+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: connState.confirmErr, confirmationStatus: 'confirmed', slot: 1 }], context: { slot: 1 } })),+ getBlockHeight: vi.fn(async () => 1),simulateTransaction: vi.fn(async () => ({ value: { err: null, unitsConsumed: 1234 } })),getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed' } })),},diff --git a/tests/agent-wallet-trade.test.js b/tests/agent-wallet-trade.test.jsindex 10ec99513..f2b2ce59c 100644--- a/tests/agent-wallet-trade.test.js+++ b/tests/agent-wallet-trade.test.js@@ -95,6 +95,8 @@ const fakeConn = {getRecentPrioritizationFees: vi.fn(async () => [{ prioritizationFee: 1_000 }, { prioritizationFee: 2_000 }]),sendRawTransaction: vi.fn(async () => { connState.sent += 1; return connState.sig; }),confirmTransaction: vi.fn(async () => ({ value: { err: connState.confirmErr } })),+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: connState.confirmErr, confirmationStatus: 'confirmed', slot: 1 }], context: { slot: 1 } })),+ getBlockHeight: vi.fn(async () => 1),getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed' } })),};vi.mock('../api/_lib/agent-pumpfun.js', () => ({diff --git a/tests/agent-wallet-withdraw.test.js b/tests/agent-wallet-withdraw.test.jsindex ff8f6ddf6..b0ea96021 100644--- a/tests/agent-wallet-withdraw.test.js+++ b/tests/agent-wallet-withdraw.test.js@@ -78,6 +78,8 @@ const fakeConn = {simulateTransaction: vi.fn(async () => connState.simulate),sendRawTransaction: vi.fn(async () => { connState.sent += 1; return connState.sendSig; }),confirmTransaction: vi.fn(async () => ({ value: { err: connState.confirmErr } })),+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: connState.confirmErr, confirmationStatus: 'confirmed', slot: 1 }], context: { slot: 1 } })),+ getBlockHeight: vi.fn(async () => 1),getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed' } })),getAccountInfo: vi.fn(async () => null),getTokenAccountBalance: vi.fn(async () => ({ value: { amount: '0', uiAmount: 0, decimals: 6 } })),diff --git a/tests/api/purchase-as-agent.test.js b/tests/api/purchase-as-agent.test.jsindex 3892c3fe8..2a531a086 100644--- a/tests/api/purchase-as-agent.test.js+++ b/tests/api/purchase-as-agent.test.js@@ -62,6 +62,8 @@ const fakeConn = {getLatestBlockhash: vi.fn(async () => ({ blockhash: 'bh', lastValidBlockHeight: 99 })),sendRawTransaction: vi.fn(async () => 'txSig'),confirmTransaction: vi.fn(async () => {}),+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: null, confirmationStatus: 'confirmed', slot: 1 }], context: { slot: 1 } })),+ getBlockHeight: vi.fn(async () => 1),};vi.mock('@solana/web3.js', async (orig) => {diff --git a/tests/api/solana-airdrop.test.js b/tests/api/solana-airdrop.test.jsindex de89209db..ae9d5490c 100644--- a/tests/api/solana-airdrop.test.js+++ b/tests/api/solana-airdrop.test.js@@ -30,6 +30,8 @@ vi.mock('../../api/_lib/usage.js', () => ({const conn = {requestAirdrop: vi.fn(async () => 'AIRDROPSIG'.padEnd(88, 'A')),confirmTransaction: vi.fn(async () => ({ value: { err: null } })),+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: null, confirmationStatus: 'confirmed', slot: 1 }], context: { slot: 1 } })),+ getBlockHeight: vi.fn(async () => 1),};vi.mock('../../api/_lib/agent-pumpfun.js', () => ({solanaConnection: vi.fn(() => conn),diff --git a/tests/api/solana-wallet-import.test.js b/tests/api/solana-wallet-import.test.jsindex d2b8b80be..15da20cac 100644--- a/tests/api/solana-wallet-import.test.js+++ b/tests/api/solana-wallet-import.test.js@@ -23,7 +23,10 @@ vi.mock('../../api/_lib/db.js', () => ({}));vi.mock('../../api/_lib/rate-limit.js', () => ({- limits: { authIp: vi.fn(async () => ({ success: true })) },+ limits: {+ authIp: vi.fn(async () => ({ success: true })),+ walletRead: vi.fn(async () => ({ success: true })),+ },clientIp: vi.fn(() => '127.0.0.1'),}));@@ -155,6 +158,29 @@ describe('POST /api/agents/:id/solana — import vanity wallet', () => {});});+describe('GET /api/agents/:id/solana — visitor read', () => {+ it('serves the public wallet card to a signed-in non-owner (200, not 403)', async () => {+ authState.session = { id: 'u1' };+ // handleWallet loads the owned row first (owned by someone else), then the+ // public read re-queries id+meta. No solana_address → wallet:null without+ // touching RPC.+ sqlState.queue.push([{ id: 'agent-1', user_id: 'someone-else', meta: {} }]);+ sqlState.queue.push([{ id: 'agent-1', meta: {} }]);+ const { status, body } = await invoke({ method: 'GET' });+ expect(status).toBe(200);+ expect(body.data.wallet).toBeNull();+ expect(body.data.chain).toBe('solana');+ });++ it('still serves the public read to an unauthenticated visitor (200)', async () => {+ authState.session = null;+ sqlState.queue.push([{ id: 'agent-1', meta: {} }]);+ const { status, body } = await invoke({ method: 'GET' });+ expect(status).toBe(200);+ expect(body.data.wallet).toBeNull();+ });+});+describe('DELETE /api/agents/:id/solana', () => {it('clears the wallet for the owner', async () => {authState.session = { id: 'u1' };diff --git a/tests/execution-engine-submit.test.js b/tests/execution-engine-submit.test.jsindex 58025827b..cc5d6dceb 100644--- a/tests/execution-engine-submit.test.js+++ b/tests/execution-engine-submit.test.js@@ -31,8 +31,11 @@ function mockConnection(captured) {captured.raw = raw;return 'sigSENT';}),- confirmTransaction: vi.fn(async () => ({ value: { err: null }, context: { slot: 7 } })),+ // HTTP-polling confirm reads getSignatureStatuses (plural); getSignatureStatus+ // (singular) backs the ambiguous-timeout re-check path.+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: null, confirmationStatus: 'confirmed', slot: 7 }], context: { slot: 7 } })),getSignatureStatus: vi.fn(async () => ({ value: { err: null, confirmationStatus: 'confirmed', slot: 7 } })),+ getBlockHeight: vi.fn(async () => 10),};}diff --git a/tests/launch-mark-enforcement.test.js b/tests/launch-mark-enforcement.test.jsindex 57743a868..22063700c 100644--- a/tests/launch-mark-enforcement.test.js+++ b/tests/launch-mark-enforcement.test.js@@ -327,6 +327,8 @@ describe('POST /api/pump/launch-agent — brand-mark enforcement', () => {getRecentPrioritizationFees: async () => [{ prioritizationFee: 1000 }],sendRawTransaction: async () => 'a'.repeat(88),confirmTransaction: async () => ({ value: { err: null }, context: { slot: 1 } }),+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: null, confirmationStatus: 'confirmed', slot: 1 }], context: { slot: 1 } })),+ getBlockHeight: vi.fn(async () => 1),};// Agent custodial keypair returned by the loadAgentForSigning mockdiff --git a/tests/solana-confirm.test.js b/tests/solana-confirm.test.jsindex 041e08de8..e101edd07 100644--- a/tests/solana-confirm.test.js+++ b/tests/solana-confirm.test.js@@ -1,40 +1,49 @@/**- * confirmOrThrow — unit tests.+ * confirmOrThrow / pollConfirmation / sendAndConfirm — unit tests.*- * Solana's `Connection.confirmTransaction` resolves normally for a transaction- * that landed in a block but reverted during execution; the on-chain error is- * carried in `result.value.err`, NOT thrown. Every server-signed money path- * routes its confirmation through confirmOrThrow so a revert becomes a thrown- * error the caller handles, instead of being silently recorded as confirmed.- *- * These tests exercise the helper against a fake Connection so no RPC is hit.+ * Confirmation happens over HTTP polling (`getSignatureStatuses`), never a WebSocket+ * subscription — that WS path bypassed the RPC failover and produced the+ * `ws error: Unexpected server response: 429` reconnect storm in production. These+ * tests assert the polling mechanism, the throw-on-revert guarantee (a landed-but-+ * reverted tx must never resolve as confirmed), and blockhash-expiry handling, all+ * against a fake Connection so no RPC is hit.*/import { describe, it, expect, vi } from 'vitest';-import { confirmOrThrow } from '../api/_lib/solana/confirm.js';+import { confirmOrThrow, pollConfirmation, sendAndConfirm } from '../api/_lib/solana/confirm.js';-function fakeConn(value) {+// A fake Connection whose getSignatureStatuses returns a scripted sequence of+// per-signature statuses. `steps` is an array of status objects (or null) returned on+// successive polls; the last entry sticks. blockHeight is a fixed value for expiry.+function fakeConn({ steps = [], blockHeight = 0 } = {}) {+ let i = 0;return {- confirmTransaction: vi.fn().mockResolvedValue({ context: { slot: 1 }, value }),+ getSignatureStatuses: vi.fn(async () => {+ const st = steps[Math.min(i, steps.length - 1)];+ i++;+ return { context: { slot: 1 }, value: [st ?? null] };+ }),+ getBlockHeight: vi.fn(async () => blockHeight),};}-describe('confirmOrThrow', () => {- it('returns the confirmation result for a successful tx (value.err === null)', async () => {- const conn = fakeConn({ err: null });+describe('pollConfirmation / confirmOrThrow', () => {+ it('resolves once the status reaches the requested commitment', async () => {+ const conn = fakeConn({ steps: [null, { confirmationStatus: 'processed', err: null, slot: 5 }, { confirmationStatus: 'confirmed', err: null, slot: 5 }] });const out = await confirmOrThrow(conn, 'sig123', 'confirmed');expect(out.value.err).toBeNull();- expect(conn.confirmTransaction).toHaveBeenCalledWith('sig123', 'confirmed');+ expect(out.value.confirmationStatus).toBe('confirmed');+ expect(conn.getSignatureStatuses).toHaveBeenCalledWith(['sig123']);});- it('throws when the tx landed but reverted (value.err set)', async () => {- const conn = fakeConn({ err: { InstructionError: [0, { Custom: 6001 }] } });+ it('throws when the tx landed but reverted (status carries err)', async () => {+ const conn = fakeConn({ steps: [{ confirmationStatus: 'confirmed', err: { InstructionError: [0, { Custom: 6001 }] }, slot: 7 }] });await expect(confirmOrThrow(conn, 'sigABC', 'confirmed')).rejects.toThrow(/reverted on-chain/);});- it('tags the thrown error with code, signature, and the on-chain err', async () => {+ it('tags the thrown revert with code, signature, and the on-chain err', async () => {const onChainErr = { InstructionError: [1, 'ProgramFailedToComplete'] };- const conn = fakeConn({ err: onChainErr });+ const conn = fakeConn({ steps: [{ confirmationStatus: 'confirmed', err: onChainErr, slot: 3 }] });await expect(confirmOrThrow(conn, 'deadbeef', 'confirmed')).rejects.toMatchObject({code: 'tx_reverted',signature: 'deadbeef',@@ -43,20 +52,60 @@ describe('confirmOrThrow', () => {});it('extracts the signature from the object strategy form', async () => {- const conn = fakeConn({ err: { foo: 'bar' } });+ const conn = fakeConn({ steps: [{ confirmationStatus: 'confirmed', err: { foo: 'bar' }, slot: 2 }] });await expect(confirmOrThrow(conn, { signature: 'objSig', blockhash: 'bh', lastValidBlockHeight: 9 }, 'confirmed'),).rejects.toMatchObject({ signature: 'objSig', code: 'tx_reverted' });});it('defaults the commitment to "confirmed"', async () => {- const conn = fakeConn({ err: null });+ const conn = fakeConn({ steps: [{ confirmationStatus: 'confirmed', err: null, slot: 1 }] });+ const out = await confirmOrThrow(conn, 'sig');+ expect(out.value.err).toBeNull();+ });++ it('throws tx_expired when the blockhash is no longer valid and the tx never landed', async () => {+ // Status stays null (never lands); block height is already past lastValidBlockHeight.+ const conn = fakeConn({ steps: [null], blockHeight: 200 });+ await expect(+ pollConfirmation(conn, { signature: 'gone', blockhash: 'bh', lastValidBlockHeight: 100 }, 'confirmed'),+ ).rejects.toMatchObject({ code: 'tx_expired', signature: 'gone' });+ });++ it('throws tx_confirm_timeout for a bare signature that never lands', async () => {+ const conn = fakeConn({ steps: [null] });+ await expect(pollConfirmation(conn, 'stuck', 'confirmed', { timeoutMs: 0 })).rejects.toMatchObject({+ code: 'tx_confirm_timeout',+ signature: 'stuck',+ });+ });++ it('never opens a WebSocket — it uses getSignatureStatuses, not confirmTransaction', async () => {+ const conn = fakeConn({ steps: [{ confirmationStatus: 'confirmed', err: null, slot: 1 }] });+ conn.confirmTransaction = vi.fn();await confirmOrThrow(conn, 'sig');- expect(conn.confirmTransaction).toHaveBeenCalledWith('sig', 'confirmed');+ expect(conn.confirmTransaction).not.toHaveBeenCalled();+ });+});++describe('sendAndConfirm', () => {+ it('signs, broadcasts, polls to confirmation, and returns the signature', async () => {+ const conn = {+ getLatestBlockhash: vi.fn(async () => ({ blockhash: 'BH', lastValidBlockHeight: 150 })),+ sendRawTransaction: vi.fn(async () => 'sigSENT'),+ getSignatureStatuses: vi.fn(async () => ({ context: { slot: 1 }, value: [{ confirmationStatus: 'confirmed', err: null, slot: 1 }] })),+ getBlockHeight: vi.fn(async () => 10),+ };+ const signer = { publicKey: { toBase58: () => 'PAYER' } };+ const tx = { serialize: () => Buffer.from('x'), sign: vi.fn() };+ const sig = await sendAndConfirm(conn, tx, [signer], { commitment: 'confirmed' });+ expect(sig).toBe('sigSENT');+ expect(tx.sign).toHaveBeenCalledWith(signer);+ expect(tx.recentBlockhash).toBe('BH');+ expect(tx.feePayer).toBe(signer.publicKey);});- it('does not swallow a genuinely thrown RPC/timeout error', async () => {- const conn = { confirmTransaction: vi.fn().mockRejectedValue(new Error('block height exceeded')) };- await expect(confirmOrThrow(conn, 'sig')).rejects.toThrow(/block height exceeded/);+ it('throws when no signer is provided', async () => {+ await expect(sendAndConfirm({}, {}, [])).rejects.toThrow(/at least one signer/);});});diff --git a/tests/treasury-autopilot.test.js b/tests/treasury-autopilot.test.jsindex 2b3dedf14..648393479 100644--- a/tests/treasury-autopilot.test.js+++ b/tests/treasury-autopilot.test.js@@ -44,6 +44,8 @@ vi.mock('../api/_lib/agent-pumpfun.js', () => ({sendRawTransaction: vi.fn(async () => 'SIG_swap'),getLatestBlockhash: vi.fn(async () => ({ blockhash: 'bh', lastValidBlockHeight: 1 })),confirmTransaction: vi.fn(async () => ({ value: { err: null } })),+ getSignatureStatuses: vi.fn(async () => ({ value: [{ err: null, confirmationStatus: 'confirmed', slot: 1 }], context: { slot: 1 } })),+ getBlockHeight: vi.fn(async () => 1),})),}));