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.

fix(agora): tell a citizen their wallet is dry instead of answering 500

nirholas270b87f69542
diff --git a/api/_lib/agora-human.js b/api/_lib/agora-human.js
index 588b84b2f..0d5d39ae9 100644
--- a/api/_lib/agora-human.js
+++ b/api/_lib/agora-human.js
@@ -160,28 +160,86 @@ export function explorerTx(sig, cluster) {
: `https://explorer.solana.com/tx/${sig}?cluster=devnet`;
}
-// Top up a devnet wallet from the public faucet with backoff — mirrors the
-// roundtrip example. Mainnet never airdrops: an underfunded mainnet wallet is an
-// honest, actionable error, not a silent failure.
+// The devnet faucet lives on the PUBLIC devnet endpoint. Keyed providers
+// (Helius and friends) either rate-limit requestAirdrop into a 429 storm or
+// don't proxy it at all, so a citizen's first bounty died with a raw
+// "Attempt to debit an account but found no record of a prior credit".
+const PUBLIC_DEVNET_FAUCET = 'https://api.devnet.solana.com';
+
+// Airdrop sources to try, in order: whatever RPC we're already on, then the
+// public faucet endpoint (deduped when they're the same host).
+async function faucetSources(connection) {
+ const sources = [connection];
+ const current = String(connection?.rpcEndpoint || '').toLowerCase();
+ if (!current.includes('api.devnet.solana.com')) {
+ const { Connection } = await import('@solana/web3.js');
+ sources.push(new Connection(PUBLIC_DEVNET_FAUCET, 'confirmed'));
+ }
+ return sources;
+}
+
+// Top up a devnet wallet from the faucet with backoff — mirrors the roundtrip
+// example. Mainnet never airdrops: an underfunded mainnet wallet is an honest,
+// actionable error, not a silent failure. Returns the final balance; callers
+// that are about to sign must gate on requireFunded(), because a rate-limited
+// faucet is a normal devnet condition, not an exception.
export async function ensureDevnetBalance(connection, keypair, neededLamports) {
- const bal = await connection.getBalance(keypair.publicKey);
+ let bal = await connection.getBalance(keypair.publicKey);
if (bal >= neededLamports) return bal;
+ const sources = await faucetSources(connection);
const chunks = [LAMPORTS_PER_SOL, LAMPORTS_PER_SOL / 2, LAMPORTS_PER_SOL / 4];
for (let i = 0; i < chunks.length; i++) {
- try {
- const sig = await connection.requestAirdrop(keypair.publicKey, Math.max(chunks[i], LAMPORTS_PER_SOL / 50));
- // 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 {
- await new Promise((r) => setTimeout(r, 1500 * (i + 1)));
+ for (const src of sources) {
+ try {
+ const sig = await src.requestAirdrop(keypair.publicKey, Math.max(chunks[i], LAMPORTS_PER_SOL / 50));
+ // HTTP-polling confirm (no WebSocket); bounded so a dropped devnet airdrop
+ // falls through to the next source/chunk instead of hanging the window.
+ await confirmOrThrow(src, sig, 'confirmed', { timeoutMs: 30_000 });
+ } catch {
+ continue; // this source is dry/throttled — try the next one
+ }
+ bal = await connection.getBalance(keypair.publicKey);
+ if (bal >= neededLamports) return bal;
}
+ await new Promise((r) => setTimeout(r, 1500 * (i + 1)));
}
return connection.getBalance(keypair.publicKey);
}
+function fmtSol(lamports) {
+ return (Number(lamports) / LAMPORTS_PER_SOL).toLocaleString('en-US', { maximumFractionDigits: 4 });
+}
+
+/**
+ * Assert a wallet can cover `neededLamports` BEFORE anything is signed. An
+ * underfunded wallet is a designed, actionable state ("fund this address"), so
+ * it must never reach the RPC and come back as a raw simulation failure the
+ * caller renders as an opaque 500.
+ *
+ * Throws a typed error ({ status: 409, code: 'insufficient_funds', detail })
+ * that api/agora/act.js surfaces verbatim.
+ */
+export async function requireFunded({ connection, address, neededLamports, cluster, purpose }) {
+ const bal = await connection.getBalance(address);
+ if (bal >= neededLamports) return bal;
+ const walletAddress = address?.toBase58 ? address.toBase58() : String(address);
+ const hint = cluster === 'devnet'
+ ? 'The devnet faucet is rate-limiting airdrops right now. Send devnet SOL to this address, or try again in a few minutes.'
+ : 'Send SOL to this address to cover the network fee.';
+ throw Object.assign(
+ new Error(`Your Agora wallet needs about ${fmtSol(neededLamports)} SOL to ${purpose} and holds ${fmtSol(bal)}. ${hint}`),
+ {
+ status: 409,
+ code: 'insufficient_funds',
+ detail: {
+ walletAddress, cluster, asset: 'SOL',
+ neededSol: Number((Number(neededLamports) / LAMPORTS_PER_SOL).toFixed(6)),
+ haveSol: Number((Number(bal) / LAMPORTS_PER_SOL).toFixed(6)),
+ },
+ },
+ );
+}
+
/**
* Ensure the human citizen is registered as an AgenC agent on `cluster`, signing
* with their custodial wallet. Lazy + idempotent: returns the existing on-chain
@@ -216,10 +274,18 @@ export async function ensureRegistered({ citizen, cluster }) {
return { agentId, agentIdHex: agenCAgentIdToHex(agentId), agentPda: agentPda.toBase58(), signer, client, citizen };
}
- // Fund (devnet) enough for the stake + tx fees, then register.
+ // Fund (devnet) enough for the stake + tx fees, then register. The gate runs
+ // on BOTH clusters: registration stakes lamports and pays a fee either way,
+ // and a dry wallet must read as "fund this address", never as a simulation
+ // failure from inside the SDK.
+ const registerNeeds = MIN_STAKE_LAMPORTS + 10_000_000;
if (cluster === 'devnet') {
- await ensureDevnetBalance(client.connection, signer, MIN_STAKE_LAMPORTS + 10_000_000);
+ await ensureDevnetBalance(client.connection, signer, registerNeeds);
}
+ await requireFunded({
+ connection: client.connection, address: signer.publicKey,
+ neededLamports: registerNeeds, cluster, purpose: 'register you as a citizen on-chain',
+ });
const metadataUri = buildThreewsMetadataUri({ handle: citizen.meta?.handle || citizen.id });
const result = await registerAgenCAgent(client, {
diff --git a/api/agora/act.js b/api/agora/act.js
index 9f3338516..a25fc8623 100644
--- a/api/agora/act.js
+++ b/api/agora/act.js
@@ -25,12 +25,13 @@ import { sql } from '../_lib/db.js';
import { authWrite } from '../_lib/labor-auth.js';
import { TOKEN_MINT } from '../_lib/token/config.js';
import {
- ensureHumanCitizen, ensureRegistered, ensureDevnetBalance,
+ ensureHumanCitizen, ensureRegistered, ensureDevnetBalance, requireFunded,
projectActivity, bumpCitizenStats, citizenBalances, professionToCapabilityBits,
PROFESSION_BITS, THREE_ATOMICS_PER_TOKEN, rewardLabel, proofHashFor,
sendOnchainAttestation, explorerTx,
} from '../_lib/agora-human.js';
import { resolveCluster, checkPostSpend } from '../_lib/agora-policy.js';
+import { redactUrlSecrets as redactSecrets } from '../_lib/scrub-secrets.js';
const LAMPORTS_PER_SOL = 1_000_000_000n;
const MAX_TITLE = 140;
@@ -194,9 +195,27 @@ async function postTaskCore({ user, body, requestedCluster, hire }) {
const { getAssociatedTokenAddressSync } = await import('@solana/spl-token');
createArgs.rewardMint = new PublicKey(TOKEN_MINT);
createArgs.creatorTokenAccount = getAssociatedTokenAddressSync(new PublicKey(TOKEN_MINT), reg.signer.publicKey, false);
+ // Real money: check the $THREE the escrow will actually debit before we
+ // sign, so "you don't hold enough $THREE" is a designed state and not an
+ // SPL transfer failure surfaced as a 502.
+ const held = await citizenBalances(citizen, cluster).catch(() => ({ three: null }));
+ const needThree = Number(amountAtomic) / Number(THREE_ATOMICS_PER_TOKEN);
+ if (held.three != null && held.three < needThree) {
+ return {
+ err: [409, 'insufficient_funds',
+ `This bounty escrows ${rewardLabel(amountAtomic, cluster)} and your Agora wallet holds ${held.three.toLocaleString('en-US')} $THREE. Send $THREE to your wallet address, then post again.`,
+ { walletAddress: held.address, asset: '$THREE', cluster, needed: needThree, have: held.three }],
+ };
+ }
} else {
- // Devnet native-SOL escrow: ensure the creator can cover reward + fees.
- await ensureDevnetBalance(reg.client.connection, reg.signer, Number(amountAtomic) + 10_000_000);
+ // Devnet native-SOL escrow: top up, then gate on the real balance so a
+ // throttled faucet reads as "fund this address", not a 500.
+ const needLamports = Number(amountAtomic) + 10_000_000;
+ await ensureDevnetBalance(reg.client.connection, reg.signer, needLamports);
+ await requireFunded({
+ connection: reg.client.connection, address: reg.signer.publicKey,
+ neededLamports: needLamports, cluster, purpose: 'escrow this bounty',
+ });
}
const { createAgenCTask } = await import('@three-ws/solana-agent');
@@ -507,7 +526,17 @@ export default wrap(async (req, res) => {
return json(res, 200, result.body);
} catch (err) {
await idemRelease(userId, action, idemKey);
- console.error('[agora/act] error', action, err?.message);
+ // A typed 4xx thrown from the service layer is a DESIGNED state the user can
+ // act on (no custodial wallet yet, a dry devnet wallet the faucet wouldn't
+ // top up). Surface it verbatim; only genuinely unexpected failures collapse
+ // into an opaque 500 with a support ref.
+ const status = Number(err?.status);
+ if (Number.isInteger(status) && status >= 400 && status < 500) {
+ return error(res, status, err.code || 'agora_act_error', err.message, err.detail || {});
+ }
+ // Redact before logging: an unexpected failure here is usually an on-chain
+ // RPC error whose message carries the keyed endpoint URL.
+ console.error('[agora/act] error', action, redactSecrets(err?.message));
return serverError(res, 500, 'agora_act_error', err);
}
});
diff --git a/scripts/agora-devnet-fund.mjs b/scripts/agora-devnet-fund.mjs
new file mode 100644
index 000000000..42eb97a04
--- /dev/null
+++ b/scripts/agora-devnet-fund.mjs
@@ -0,0 +1,137 @@
+#!/usr/bin/env node
+// Spread devnet SOL across the agora-citizens fleet signers.
+//
+// Why this exists: the public devnet faucet is rate-limited per IP, so a fleet of
+// N citizens cannot each call requestAirdrop (the worker's own ensureBalance()
+// top-up gives up with a 429 after its backoff chain). Landing ONE airdrop into a
+// single bank wallet and fanning it out with plain SystemProgram transfers gets
+// the whole fleet funded from a single faucet grant.
+//
+// Usage:
+// node scripts/agora-devnet-fund.mjs <citizen-key> [<citizen-key> ...]
+// node scripts/agora-devnet-fund.mjs --list
+// node scripts/agora-devnet-fund.mjs --bank aria-sculpt echo-crier # different bank
+// node scripts/agora-devnet-fund.mjs --sol 0.05 aria-sculpt # amount per target
+//
+// A "citizen key" is the keypair cache name under workers/agora-citizens/.cache/
+// (the roster key, e.g. `aria-sculpt`), which the life engine prints on a dry run:
+// AGORA_DRY_RUN=1 AGORA_ONCE=1 node workers/agora-citizens/index.js
+//
+// Devnet only, by construction: the RPC is pinned to a devnet endpoint and the
+// script refuses to run against any other cluster. It never touches mainnet or
+// $THREE. Fund the bank first at https://faucet.solana.com (or `solana airdrop`).
+
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import {
+ Connection,
+ Keypair,
+ LAMPORTS_PER_SOL,
+ SystemProgram,
+ Transaction,
+ sendAndConfirmTransaction,
+} from '@solana/web3.js';
+
+const __dirname = path.dirname(fileURLToPath(import.meta.url));
+const CACHE_DIR = path.join(__dirname, '..', 'workers', 'agora-citizens', '.cache');
+
+const DEVNET_RPC =
+ process.env.AGENC_DEVNET_RPC_URL || process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+
+if (!/devnet/i.test(DEVNET_RPC)) {
+ console.error(`[agora-fund] refusing to run: RPC "${DEVNET_RPC}" is not a devnet endpoint. This script is devnet-only.`);
+ process.exit(2);
+}
+
+function parseArgs(argv) {
+ const out = { bank: 'agora-dispatcher', sol: 0.09, list: false, targets: [] };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--list') out.list = true;
+ else if (a === '--bank') out.bank = argv[++i];
+ else if (a === '--sol') out.sol = Number(argv[++i]);
+ else out.targets.push(a);
+ }
+ if (!Number.isFinite(out.sol) || out.sol <= 0) {
+ throw new Error('--sol must be a positive number of SOL');
+ }
+ return out;
+}
+
+function cacheKeys() {
+ if (!fs.existsSync(CACHE_DIR)) return [];
+ return fs
+ .readdirSync(CACHE_DIR)
+ .filter((f) => f.endsWith('.json'))
+ .map((f) => f.replace(/\.json$/, ''));
+}
+
+function loadKeypair(name) {
+ const file = path.join(CACHE_DIR, `${name}.json`);
+ if (!fs.existsSync(file)) {
+ throw new Error(
+ `no cached keypair "${name}". Run the engine once (AGORA_DRY_RUN=1 AGORA_ONCE=1 node workers/agora-citizens/index.js) to mint the fleet's signers, then re-run. Known: ${cacheKeys().join(', ') || '(none)'}`,
+ );
+ }
+ return Keypair.fromSecretKey(Uint8Array.from(JSON.parse(fs.readFileSync(file, 'utf8'))));
+}
+
+const args = parseArgs(process.argv.slice(2));
+const conn = new Connection(DEVNET_RPC, 'confirmed');
+
+if (args.list || args.targets.length === 0) {
+ const keys = cacheKeys();
+ if (!keys.length) {
+ console.log('[agora-fund] no cached signers yet — run the engine once to mint them.');
+ process.exit(0);
+ }
+ console.log(`[agora-fund] cached devnet signers (${DEVNET_RPC}):`);
+ for (const k of keys) {
+ const kp = loadKeypair(k);
+ const bal = await conn.getBalance(kp.publicKey);
+ console.log(` ${k.padEnd(28)} ${kp.publicKey.toBase58()} ${(bal / LAMPORTS_PER_SOL).toFixed(4)} SOL`);
+ }
+ if (!args.list) console.log('\nPass one or more signer names to fund them from the bank wallet.');
+ process.exit(0);
+}
+
+const bank = loadKeypair(args.bank);
+const perTarget = Math.floor(args.sol * LAMPORTS_PER_SOL);
+// Leave the bank enough to pay its own transfer fees and stay a working signer.
+const BANK_RESERVE_LAMPORTS = 10_000_000; // 0.01 SOL
+
+const bankStart = await conn.getBalance(bank.publicKey);
+console.log(`[agora-fund] bank ${args.bank} ${bank.publicKey.toBase58()} — ${(bankStart / LAMPORTS_PER_SOL).toFixed(4)} SOL`);
+
+let spent = 0;
+let funded = 0;
+for (const name of args.targets) {
+ if (name === args.bank) {
+ console.log(` skip ${name} (is the bank)`);
+ continue;
+ }
+ const kp = loadKeypair(name);
+ const have = await conn.getBalance(kp.publicKey);
+ if (have >= perTarget) {
+ console.log(` skip ${name} — already holds ${(have / LAMPORTS_PER_SOL).toFixed(4)} SOL`);
+ continue;
+ }
+ const need = perTarget - have;
+ if (bankStart - spent - need < BANK_RESERVE_LAMPORTS) {
+ console.error(
+ ` STOP ${name} — bank would drop below its ${(BANK_RESERVE_LAMPORTS / LAMPORTS_PER_SOL).toFixed(3)} SOL reserve. Top the bank up at https://faucet.solana.com`,
+ );
+ break;
+ }
+ const tx = new Transaction().add(
+ SystemProgram.transfer({ fromPubkey: bank.publicKey, toPubkey: kp.publicKey, lamports: need }),
+ );
+ const sig = await sendAndConfirmTransaction(conn, tx, [bank], { commitment: 'confirmed' });
+ spent += need;
+ funded++;
+ console.log(` funded ${name.padEnd(24)} ${kp.publicKey.toBase58()} +${(need / LAMPORTS_PER_SOL).toFixed(4)} SOL ${sig}`);
+}
+
+const bankEnd = await conn.getBalance(bank.publicKey);
+console.log(`[agora-fund] funded ${funded}/${args.targets.length}; bank now ${(bankEnd / LAMPORTS_PER_SOL).toFixed(4)} SOL`);