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: add dedicated cache store support and live trader fallback in leaderboard

udvk5b29a3bccd16
diff --git a/.env.example b/.env.example
index b3e83d894..4de869358 100644
--- a/.env.example
+++ b/.env.example
@@ -25,6 +25,16 @@ S3_PUBLIC_DOMAIN=https://cdn.three.ws
UPSTASH_REDIS_REST_URL=
UPSTASH_REDIS_REST_TOKEN=
+# Optional dedicated CACHE store (recommended at scale). The vars above back the
+# fail-closed rate limiter; pointing the best-effort caches (galaxy feed, pulse,
+# agent lists, …) at a SECOND Upstash store stops large cache writes from contending
+# with — and burning the command quota of — the limiter. That contention is what
+# causes the redis SET timeouts on /api/galaxy/flows. Co-locate this store with your
+# prod Vercel region for low write latency. Unset = caches share the store above (no
+# behavior change). Vercel-KV second store prefixed `cache`: cache_KV_REST_API_*.
+UPSTASH_CACHE_REST_URL=
+UPSTASH_CACHE_REST_TOKEN=
+
# Optional: Error monitoring
SENTRY_DSN=
diff --git a/api/_lib/cache.js b/api/_lib/cache.js
index ce89b3921..7ed8f7e62 100644
--- a/api/_lib/cache.js
+++ b/api/_lib/cache.js
@@ -70,8 +70,24 @@ function memDel(key) {
memCache.delete(key);
}
+// Resolve which Upstash store the cache talks to. Prefer a dedicated cache store
+// (UPSTASH_CACHE_REST_*) so the large, best-effort cache writes never contend with —
+// or burn the command quota of — the fail-closed rate limiter, which lives on
+// UPSTASH_REDIS_REST_* (api/_lib/redis.js). Fall back to the shared store for
+// back-compat, then to in-memory. Resolved per call: it's a couple of cheap env
+// reads, and resolving fresh avoids pinning stale config across env changes in tests.
+function cacheTarget() {
+ if (env.UPSTASH_CACHE_REST_URL && env.UPSTASH_CACHE_REST_TOKEN) {
+ return { url: env.UPSTASH_CACHE_REST_URL, token: env.UPSTASH_CACHE_REST_TOKEN, dedicated: true };
+ }
+ if (env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN) {
+ return { url: env.UPSTASH_REDIS_REST_URL, token: env.UPSTASH_REDIS_REST_TOKEN, dedicated: false };
+ }
+ return null;
+}
+
function redisConfigured() {
- return Boolean(env.UPSTASH_REDIS_REST_URL && env.UPSTASH_REDIS_REST_TOKEN);
+ return cacheTarget() !== null;
}
// A cache round-trip must be fast or not happen at all. Without a timeout a
@@ -84,10 +100,12 @@ function redisConfigured() {
const REDIS_CMD_TIMEOUT_MS = 3_000;
async function redisCmd(args) {
- const r = await fetch(env.UPSTASH_REDIS_REST_URL, {
+ const target = cacheTarget();
+ if (!target) throw new Error('cache redis not configured');
+ const r = await fetch(target.url, {
method: 'POST',
headers: {
- authorization: `Bearer ${env.UPSTASH_REDIS_REST_TOKEN}`,
+ authorization: `Bearer ${target.token}`,
'content-type': 'application/json',
},
body: JSON.stringify(args),
diff --git a/api/_lib/env.js b/api/_lib/env.js
index df9a755e6..fab70c17f 100644
--- a/api/_lib/env.js
+++ b/api/_lib/env.js
@@ -157,6 +157,23 @@ export const env = {
);
},
+ // Optional dedicated cache store, separate from the rate-limiter store above.
+ // The rate limiter must fail closed and lives on UPSTASH_REDIS_REST_*. The
+ // best-effort caches (cacheGet/Set/Wrap) write large bodies — e.g. the galaxy
+ // money-feed — that, sharing one free store with the limiter, both contend for
+ // connections and burn the limiter's 500k/mo command quota; that contention is
+ // the failure mode behind the SET timeouts on /api/galaxy/flows. Point these at
+ // a SECOND Upstash store (ideally co-located with the prod Vercel region) to move
+ // all cache traffic off the limiter. Unset → the cache (api/_lib/cache.js) falls
+ // back to the shared store, then to in-memory — no behavior change. The Vercel-KV
+ // marketplace names for a second store prefixed `cache` are accepted too.
+ get UPSTASH_CACHE_REST_URL() {
+ return opt('UPSTASH_CACHE_REST_URL') || opt('cache_KV_REST_API_URL');
+ },
+ get UPSTASH_CACHE_REST_TOKEN() {
+ return opt('UPSTASH_CACHE_REST_TOKEN') || opt('cache_KV_REST_API_TOKEN');
+ },
+
// ── Upstash quota-burn visibility (api/_lib/redis-usage.js) ──────────────
// The free plan ceils at 500k commands/month; when it is exhausted every
// critical limiter fails closed and all paid forge + x402 flows 503 (the
diff --git a/api/sniper/leaderboard.js b/api/sniper/leaderboard.js
index 6d7b351ae..cfc487516 100644
--- a/api/sniper/leaderboard.js
+++ b/api/sniper/leaderboard.js
@@ -21,6 +21,10 @@ import { getLeaderboard, WINDOWS, LEADERBOARD_SORTS } from '../_lib/trader-stats
const NETWORKS = new Set(['mainnet', 'devnet']);
+// kolscan publishes 24h / 7d / 30d windows; the board's "all-time" view has no
+// live analogue, so it borrows the widest available window for the fallback.
+const KOL_WINDOW = { '24h': '24h', '7d': '7d', '30d': '30d', all: '30d' };
+
function solscan(sig, network) {
if (!sig || sig === 'SIMULATED') return null;
return network === 'devnet'
@@ -28,6 +32,45 @@ function solscan(sig, network) {
: `https://solscan.io/tx/${sig}`;
}
+function shortWallet(addr) {
+ const s = String(addr || '');
+ return s.length > 10 ? `${s.slice(0, 4)}…${s.slice(-4)}` : s;
+}
+
+// Live top-trader fallback. When no three.ws agent has a provable track record in
+// the window yet, the flagship board surfaces the real, public kolscan ranking of
+// top Solana traders (realized SOL profit) so it is never an empty void — clearly
+// labelled as live market data, every wallet deep-linked to its on-chain account.
+// Real data only: a kolscan/parse/price outage degrades to [] and the page shows
+// its honest "be the first" empty state. mainnet-only — kolscan has no devnet.
+async function liveTraders({ network, window, solUsd, limit }) {
+ if (network !== 'mainnet') return [];
+ const win = KOL_WINDOW[window] || '7d';
+ let items;
+ try {
+ const { getLeaderboard: getKolLeaderboard } = await import('../../src/kol/leaderboard.js');
+ items = await getKolLeaderboard({ window: win, limit });
+ } catch {
+ return [];
+ }
+ if (!Array.isArray(items) || !items.length) return [];
+ return items.map((r) => {
+ const pnlSol = Number.isFinite(r.pnlSol)
+ ? r.pnlSol
+ : solUsd && Number.isFinite(r.pnlUsd) ? r.pnlUsd / solUsd : null;
+ return {
+ rank: r.rank,
+ wallet: r.wallet,
+ wallet_short: shortWallet(r.wallet),
+ realized_pnl_sol: pnlSol,
+ realized_pnl_usd: Number.isFinite(r.pnlUsd) ? r.pnlUsd : null,
+ win_rate: Number(r.winRate) || 0,
+ trades: Number(r.trades) || 0,
+ account_url: `https://solscan.io/account/${r.wallet}`,
+ };
+ });
+}
+
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
if (!method(req, res, ['GET'])) return;
@@ -102,12 +145,25 @@ export default wrap(async (req, res) => {
};
});
+ // Hybrid board: provable three.ws agent track records are primary. Until any
+ // agent has traded in this window, fall back to the live kolscan top-trader
+ // ranking so the flagship is real + populated from day one — never an empty
+ // void — and naturally hands back to the agent board as records accrue.
+ const hasAgents = boardResult.leaderboard.length > 0;
+ const live = hasAgents ? [] : await liveTraders({
+ network, window, solUsd: boardResult.sol_usd, limit: 100,
+ });
+ const source = hasAgents ? 'agents' : live.length ? 'live' : 'empty';
+
return json(res, 200, {
network,
window,
sort,
+ source,
sol_usd: boardResult.sol_usd,
leaderboard: boardResult.leaderboard,
+ live_traders: live,
+ live_window: source === 'live' ? (KOL_WINDOW[window] || '7d') : null,
trades,
positions,
t: Date.now(),