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(solana): guard the transfer, payout, treasury and reserve reads that still hard-failed on an RPC blip

nirholas314bde9d2a40
diff --git a/api/_lib/agent-purchase.js b/api/_lib/agent-purchase.js
index 354ecf30f..c2312b35e 100644
--- a/api/_lib/agent-purchase.js
+++ b/api/_lib/agent-purchase.js
@@ -33,10 +33,10 @@ import {
getAssociatedTokenAddressSync,
createTransferCheckedInstruction,
createAssociatedTokenAccountIdempotentInstruction,
- getMint,
} from '@solana/spl-token';
import { sql } from './db.js';
+import { mintDecimals } from './solana/read-guards.js';
import { submitProtected } from './execution-engine.js';
import { ensureAgentWallet, recoverSolanaAgentKeypair } from './agent-wallet.js';
@@ -168,14 +168,14 @@ export async function sendAgentPurchaseTransfer({
}) {
const mintKey = new PublicKey(currencyMint);
const recipKey = new PublicKey(recipient);
- const mintInfo = await getMint(connection, mintKey);
+ const decimals = await mintDecimals(connection, mintKey);
const fromAta = getAssociatedTokenAddressSync(mintKey, keypair.publicKey);
const toAta = getAssociatedTokenAddressSync(mintKey, recipKey);
const transferIx = createTransferCheckedInstruction(
fromAta, mintKey, toAta, keypair.publicKey,
- BigInt(amountAtomics), mintInfo.decimals,
+ BigInt(amountAtomics), decimals,
);
// The reference key is a non-signer, non-writable account on the transfer so
// findReference() can locate this exact payment on-chain afterwards.
diff --git a/api/_lib/club/payouts.js b/api/_lib/club/payouts.js
index 0ace52ffb..ecebc0b51 100644
--- a/api/_lib/club/payouts.js
+++ b/api/_lib/club/payouts.js
@@ -19,10 +19,11 @@ import {
PublicKey,
} from '@solana/web3.js';
import { solanaConnection } from '../solana/connection.js';
+import { ataExists } from '../solana/read-guards.js';
import { submitProtected } from '../execution-engine.js';
import {
getAssociatedTokenAddress,
- createAssociatedTokenAccountInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
createTransferInstruction,
} from '@solana/spl-token';
import {
@@ -70,9 +71,12 @@ export async function sendClubUsdcSolana({ recipient, amount }) {
const recipientAta = await getAssociatedTokenAddress(mint, to);
const instructions = [];
- const recipientInfo = await connection.getAccountInfo(recipientAta);
- if (!recipientInfo) {
- instructions.push(createAssociatedTokenAccountInstruction(kp.publicKey, recipientAta, to, mint));
+ // Idempotent create paired with the fail-open probe: when the chain cannot be
+ // read the probe answers "missing", and an unnecessary create is a no-op
+ // rather than a transaction-killing error. It also closes the race where the
+ // ATA appears between the probe and the submit.
+ if (!(await ataExists(connection, recipientAta))) {
+ instructions.push(createAssociatedTokenAccountIdempotentInstruction(kp.publicKey, recipientAta, to, mint));
}
instructions.push(createTransferInstruction(senderAta, recipientAta, kp.publicKey, amt));
diff --git a/api/_lib/platform-treasury.js b/api/_lib/platform-treasury.js
index 09ba133fd..5f8a5e3a0 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 { blockhashKey, getRecentBlockhashInfo, readBalanceOrNull, rpcUnavailableError } from './solana/read-guards.js';
import { confirmOrThrow } from './solana/confirm.js';
const SOL = 1_000_000_000;
@@ -95,7 +96,9 @@ export async function getTreasuryKeypair(overrideEnv) {
/** Lamport balance of an address on the treasury's connection. */
export async function lamportBalance(conn, address) {
const { PublicKey } = await import('@solana/web3.js');
- return BigInt(await conn.getBalance(new PublicKey(address), 'confirmed'));
+ const lamports = await readBalanceOrNull(conn, new PublicKey(address), 'confirmed');
+ if (lamports == null) throw rpcUnavailableError(null, `treasury balance for ${address} is unreadable right now`);
+ return BigInt(lamports);
}
/**
@@ -116,7 +119,14 @@ export async function transferSol(conn, fromKp, toAddress, lamports) {
const MAX_ATTEMPTS = 2;
let lastErr;
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
- const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');
+ // The retry exists to escape an expired blockhash, so it forces a fresh
+ // read; the first attempt may take the cached one, and a chain that cannot
+ // be read at all still yields a hash inside its validity window.
+ const { blockhash, lastValidBlockHeight } = await getRecentBlockhashInfo(
+ conn,
+ blockhashKey({ network: treasuryNetwork() }),
+ { forceFresh: attempt > 0 },
+ );
const message = new TransactionMessage({
payerKey: fromKp.publicKey,
recentBlockhash: blockhash,
diff --git a/api/_lib/premium.js b/api/_lib/premium.js
index a10406295..a35345c54 100644
--- a/api/_lib/premium.js
+++ b/api/_lib/premium.js
@@ -40,6 +40,7 @@ import { usdToUsdcAtomics, USDC_DECIMALS } from './subscription-pricing.js';
import { createSubscription } from './x402/api-keys.js';
import { siwxStorage } from './siwx-storage.js';
import { solanaConnection } from './solana/connection.js';
+import { blockhashKey, getRecentBlockhashInfo } from './solana/read-guards.js';
import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';
import { NETWORK_SOLANA_MAINNET } from './x402-spec.js';
@@ -248,7 +249,7 @@ export async function createQuote({ wallet, asset, planId = 'developer', userId
}
const conn = solanaConnection();
- const { blockhash } = await conn.getLatestBlockhash('confirmed');
+ const { blockhash } = await getRecentBlockhashInfo(conn, blockhashKey({ network: 'mainnet' }));
const message = new TransactionMessage({
payerKey: buyer,
recentBlockhash: blockhash,
diff --git a/api/_lib/solana-transfer.js b/api/_lib/solana-transfer.js
index 4e200b150..aeb243286 100644
--- a/api/_lib/solana-transfer.js
+++ b/api/_lib/solana-transfer.js
@@ -1,9 +1,10 @@
import { PublicKey, Keypair, SystemProgram } from '@solana/web3.js';
import { solanaConnection } from './solana/connection.js';
+import { ataExists } from './solana/read-guards.js';
import { submitProtected } from './execution-engine.js';
import {
getAssociatedTokenAddress,
- createAssociatedTokenAccountInstruction,
+ createAssociatedTokenAccountIdempotentInstruction,
createTransferInstruction,
} from '@solana/spl-token';
import bs58 from 'bs58';
@@ -30,9 +31,12 @@ export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }
const recipientATA = await getAssociatedTokenAddress(mintPubkey, recipientPubkey);
const instructions = [];
- const recipientAccount = await connection.getAccountInfo(recipientATA);
- if (!recipientAccount) {
- instructions.push(createAssociatedTokenAccountInstruction(kp.publicKey, recipientATA, recipientPubkey, mintPubkey));
+ // Idempotent create paired with the fail-open probe: when the chain cannot be
+ // read the probe answers "missing", and an unnecessary create is a no-op
+ // rather than a transaction-killing error. It also closes the race where the
+ // ATA appears between the probe and the submit.
+ if (!(await ataExists(connection, recipientATA))) {
+ instructions.push(createAssociatedTokenAccountIdempotentInstruction(kp.publicKey, recipientATA, recipientPubkey, mintPubkey));
}
instructions.push(createTransferInstruction(senderATA, recipientATA, kp.publicKey, BigInt(amount)));
diff --git a/api/_lib/swarms.js b/api/_lib/swarms.js
index cc2764a16..6c3328bad 100644
--- a/api/_lib/swarms.js
+++ b/api/_lib/swarms.js
@@ -20,6 +20,7 @@ import { sql } from './db.js';
import { ensureAgentWallet, getOrCreateAgentSolanaWallet, recoverSolanaAgentKeypair } from './agent-wallet.js';
import { transferNativeSol } from './solana-transfer.js';
import { solanaConnection } from './solana/connection.js';
+import { readBalanceOrNull, rpcUnavailableError } from './solana/read-guards.js';
import { recordCustodyEvent } from './agent-trade-guards.js';
const LAMPORTS_PER_SOL = 1_000_000_000;
@@ -128,7 +129,11 @@ export function parseContributionLamports(body = {}) {
export async function treasuryBalanceLamports(address, network = 'mainnet') {
const { PublicKey } = await import('@solana/web3.js');
const conn = solanaConnection({ network, commitment: 'confirmed' });
- const lamports = await conn.getBalance(new PublicKey(address), 'confirmed');
+ // "Balance unknown" is the honest answer to an outage, and a caller must
+ // never read it as zero, so this raises a typed retryable error instead of
+ // letting a raw transport failure escape as a 500.
+ const lamports = await readBalanceOrNull(conn, new PublicKey(address), 'confirmed');
+ if (lamports == null) throw rpcUnavailableError(null, `treasury balance for ${address} is unreadable right now`);
return BigInt(lamports);
}
diff --git a/api/_lib/trust/proof-of-reserves.js b/api/_lib/trust/proof-of-reserves.js
index 23a8c6c21..110a9db2a 100644
--- a/api/_lib/trust/proof-of-reserves.js
+++ b/api/_lib/trust/proof-of-reserves.js
@@ -21,6 +21,7 @@ import { PublicKey } from '@solana/web3.js';
import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from '@solana/spl-token';
import { sql } from '../db.js';
import { solanaConnection } from '../agent-pumpfun.js';
+import { readBalanceOrNull, rpcUnavailableError } from '../solana/read-guards.js';
import { solanaMintUsdPrice } from '../balances.js';
import { solUsdPrice, explorerTxUrl, explorerAccountUrl } from '../avatar-wallet.js';
import { cacheGet, cacheSet } from '../cache.js';
@@ -73,7 +74,14 @@ async function readReservesLive(address, network) {
const conn = solanaConnection(network);
const owner = new PublicKey(address);
- const lamports = await conn.getBalance(owner, 'confirmed');
+ // A reserve line the chain cannot answer for is UNVERIFIED, which is a
+ // different claim from "zero" and from "the endpoint is broken". Throwing a
+ // raw transport error blanked the whole proof over one unreachable RPC; a
+ // typed rpc_unavailable lets the caller mark the line and retry.
+ const lamports = await readBalanceOrNull(conn, owner, 'confirmed');
+ if (lamports == null) {
+ throw rpcUnavailableError(null, `reserves for ${address} are unverifiable right now: the chain could not be read`);
+ }
const sol = lamports / 1e9;
const usdcMint = USDC_MINT_BY_CLUSTER[network];