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: Solana connection migration, forge rembg/remesh endpoints, studio expansion

nirholasa39959f624a7
diff --git a/.env.example b/.env.example
index 01561844c..76b0667e7 100644
--- a/.env.example
+++ b/.env.example
@@ -644,6 +644,23 @@ SAS_AUTHORITY_SECRET=
# attestations from cron.
ATTEST_AGENT_SECRET_KEY=
+# ── three.ws Agent Collection (Metaplex Core) ──────────────────────────────────
+# Our "flavor" of Metaplex: every Solana agent is minted into a three.ws Core
+# Collection whose update authority is the keypair below, making each agent's
+# on-chain metadata editable by three.ws on the owner's behalf (authority-managed
+# edits via /api/agents/solana-edit). See api/_lib/solana-collection.js.
+#
+# Base58-encoded 64-byte secret for the collection update authority. It signs
+# collection creation, mint-into-collection, and all on-chain edits — so it must
+# hold a little SOL on each active network. Without it, mints fall back to the
+# legacy standalone (owner-managed) asset and edits are unavailable.
+SOLANA_AGENT_COLLECTION_AUTHORITY_KEY=
+# Deployed collection addresses (base58), filled in by
+# scripts/deploy-solana-agent-collection.mjs. Leave blank until deployed —
+# mints stay legacy/owner-managed while unset.
+SOLANA_AGENT_COLLECTION_MAINNET=
+SOLANA_AGENT_COLLECTION_DEVNET=
+
# Hex EVM private key for the treasury wallet that signs cron-driven USDC
# transfers on Base / EVM chains (api/_lib/evm-transfer.js). Required only
# for the cron flows that distribute or sweep on-chain — request-path code
@@ -685,11 +702,40 @@ GRADUATIONS_LIST_KEY=pf:graduations
# request. The "whsec_" prefix is stripped automatically.
REPLICATE_WEBHOOK_SIGNING_KEY=
-# ── Avatar regeneration: self-hosted GCP fallback ───────────────────────────
-# Cloud Run / Vertex endpoint that exposes a /reconstruct route accepting
-# selfies and returning a textured GLB. Used by the avatar provider auto-
-# detection (priority: replicate → gcp → huggingface). Leave unset to skip.
+# ── Google Cloud Platform — 3D pipeline + Vertex AI ──────────────────────────
+# Used for: Vertex AI Imagen text-to-image, and self-hosted Cloud Run workers
+# (avatar reconstruction, background removal, remesh, texture generation).
+#
+# Provider priority: Vertex AI Imagen > Replicate for text-to-image.
+# Worker priority: GCP Cloud Run > Replicate > HuggingFace for image-to-3D.
+#
+# Get your project id from: https://console.cloud.google.com
+GOOGLE_CLOUD_PROJECT=
+# Region for Vertex AI endpoints (default: us-central1)
+GOOGLE_CLOUD_LOCATION=us-central1
+# Vertex AI Imagen model. Options:
+# imagen-3.0-generate-001 — highest quality (~8s, ~$0.04/image)
+# imagen-3.0-fast-generate-001 — faster (~3s, ~$0.02/image)
+VERTEX_IMAGEN_MODEL=imagen-3.0-generate-001
+# Vertex AI image editing model (used by /api/forge-edit when configured)
+VERTEX_IMAGEN_EDIT_MODEL=imagen-3.0-capability-001
+# Service account JSON key (paste the full JSON as a single-line string).
+# Alternative: set GOOGLE_APPLICATION_CREDENTIALS to a file path on the server.
+GCP_SERVICE_ACCOUNT_JSON=
+
+# Shared bearer secret for all Cloud Run workers (set as GCP Secret Manager
+# secret named "avatar-reconstruction-key", or override here for local dev).
+GCP_RECONSTRUCTION_KEY=
+
+# Cloud Run service URLs — set after deploying each worker:
+# workers/avatar-pipeline-controller → avatar reconstruction (image → GLB)
GCP_RECONSTRUCTION_URL=
+# workers/rembg → background removal (image → PNG)
+GCP_REMBG_URL=
+# workers/remesh → mesh processing (GLB → clean GLB)
+GCP_REMESH_URL=
+# workers/texture → text-guided texturing (GLB + prompt → textured GLB)
+GCP_TEXTURE_URL=
# ── IPFS pinning (additional) ───────────────────────────────────────────────
# nft.storage token used by /api/erc8004/* when PINATA_JWT and
diff --git a/api/_lib/agent-pumpfun.js b/api/_lib/agent-pumpfun.js
index 382a58528..2af4e35dc 100644
--- a/api/_lib/agent-pumpfun.js
+++ b/api/_lib/agent-pumpfun.js
@@ -3,7 +3,7 @@
// Keypair derived from the agent's encrypted Solana secret.
import { sql } from './db.js';
-import { Connection } from '@solana/web3.js';
+import { solanaConnection as failoverConnection } from './solana/connection.js';
import {
generateSolanaAgentWallet,
recoverSolanaAgentKeypair,
@@ -38,11 +38,11 @@ const RPC = {
};
export function solanaConnection(network = 'mainnet') {
- return new Connection(RPC[network] || RPC.mainnet, 'confirmed');
+ return solanaConnection({ url: RPC[network] || RPC.mainnet, commitment: 'confirmed' });
}
export function solanaPublicConnection(network = 'mainnet') {
- return new Connection(RPC_PUBLIC[network] || RPC_PUBLIC.mainnet, 'confirmed');
+ return solanaConnection({ url: RPC_PUBLIC[network] || RPC_PUBLIC.mainnet, commitment: 'confirmed' });
}
/**
diff --git a/api/_lib/attest-event.js b/api/_lib/attest-event.js
index f13c20c30..cb5519185 100644
--- a/api/_lib/attest-event.js
+++ b/api/_lib/attest-event.js
@@ -10,6 +10,7 @@
// a second on-chain tx for the same logical event.
import crypto from 'node:crypto';
+import { solanaConnection } from './solana/connection.js';
import {
Connection,
Keypair,
@@ -134,7 +135,7 @@ export async function mintAttestation(input) {
});
const memo = JSON.stringify(payload);
- const conn = new Connection(RPC[network] || RPC.devnet, 'confirmed');
+ const conn = solanaConnection({ url: RPC[network] || RPC.devnet, commitment: 'confirmed' });
const ix = new TransactionInstruction({
programId: MEMO_PROGRAM_ID,
keys: [
diff --git a/api/_lib/avatar-wallet.js b/api/_lib/avatar-wallet.js
index 24a31e6a3..5a44cc626 100644
--- a/api/_lib/avatar-wallet.js
+++ b/api/_lib/avatar-wallet.js
@@ -21,6 +21,7 @@ import {
Transaction,
TransactionInstruction,
} from '@solana/web3.js';
+import { solanaConnection } from './solana/connection.js';
import bs58 from 'bs58';
const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;
@@ -118,7 +119,7 @@ export function isValidPubkey(s) {
let _connByUrl = new Map();
export function getConnection(rpcUrl) {
const url = rpcUrl || DEFAULT_MAINNET_RPC;
- if (!_connByUrl.has(url)) _connByUrl.set(url, new Connection(url, 'confirmed'));
+ if (!_connByUrl.has(url)) _connByUrl.set(url, solanaConnection({ url: url, commitment: 'confirmed' }));
return _connByUrl.get(url);
}
diff --git a/api/_lib/club/payouts.js b/api/_lib/club/payouts.js
index 40e185a22..a068ba266 100644
--- a/api/_lib/club/payouts.js
+++ b/api/_lib/club/payouts.js
@@ -20,6 +20,7 @@ import {
Transaction,
ComputeBudgetProgram,
} from '@solana/web3.js';
+import { solanaConnection } from '../solana/connection.js';
import {
getAssociatedTokenAddress,
createAssociatedTokenAccountInstruction,
@@ -65,7 +66,7 @@ export async function sendClubUsdcSolana({ recipient, amount }) {
const amt = typeof amount === 'bigint' ? amount : BigInt(amount);
if (amt <= 0n) throw new Error('amount must be > 0');
- const connection = new Connection(env.SOLANA_RPC_URL, 'confirmed');
+ const connection = solanaConnection({ url: env.SOLANA_RPC_URL, commitment: 'confirmed' });
const senderAta = await getAssociatedTokenAddress(mint, kp.publicKey);
const recipientAta = await getAssociatedTokenAddress(mint, to);
diff --git a/api/_lib/pump.js b/api/_lib/pump.js
index 4276ad9fa..b3196596e 100644
--- a/api/_lib/pump.js
+++ b/api/_lib/pump.js
@@ -18,6 +18,7 @@
// RpcFallback wrapper for read-side handlers that opt in via getRpcFallback().
import { Connection, PublicKey } from '@solana/web3.js';
+import { solanaConnection } from './solana/connection.js';
import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';
// @solana/web3.js calls console.error() on every 429 retry attempt. Those
@@ -41,7 +42,7 @@ const RPC_DEVNET = () => process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devne
export function getConnection({ network = 'mainnet', commitment = 'confirmed' } = {}) {
const url = network === 'devnet' ? RPC_DEVNET() : RPC_MAINNET();
- return new Connection(url, commitment);
+ return solanaConnection({ url: url, commitment: commitment });
}
// Returns an RpcFallback wrapper for read-only flows that benefit from
diff --git a/api/_lib/solana-attestations.js b/api/_lib/solana-attestations.js
index 493a84d02..030d4fb47 100644
--- a/api/_lib/solana-attestations.js
+++ b/api/_lib/solana-attestations.js
@@ -2,6 +2,7 @@
// Used by the cron crawler and the read endpoints.
import { Connection, PublicKey } from '@solana/web3.js';
+import { solanaConnection } from './solana/connection.js';
import { sql } from './db.js';
export const RPC = {
@@ -81,7 +82,7 @@ export function attesterFromTx(tx) {
// Crawl recent signatures for one agent and upsert into solana_attestations.
// Returns { scanned, inserted, skipped }.
export async function crawlAgentAttestations({ agentAsset, network, ownerWallet, limit = 200 }) {
- const conn = new Connection(RPC[network] || RPC.devnet, 'confirmed');
+ const conn = solanaConnection({ url: RPC[network] || RPC.devnet, commitment: 'confirmed' });
const agentKey = new PublicKey(agentAsset);
const [cursor] = await sql`
diff --git a/api/_lib/solana-transfer.js b/api/_lib/solana-transfer.js
index 290e534cf..a680de278 100644
--- a/api/_lib/solana-transfer.js
+++ b/api/_lib/solana-transfer.js
@@ -1,4 +1,5 @@
import { Connection, PublicKey, Transaction, Keypair } from '@solana/web3.js';
+import { solanaConnection } from './solana/connection.js';
import {
getAssociatedTokenAddress,
createAssociatedTokenAccountInstruction,
@@ -22,7 +23,7 @@ export async function transferSolanaUSDC({ fromWallet, toAddress, amount, mint }
const mintPubkey = new PublicKey(mint);
const recipientPubkey = new PublicKey(toAddress);
- const connection = new Connection(SOLANA_RPC, 'confirmed');
+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
const senderATA = await getAssociatedTokenAddress(mintPubkey, kp.publicKey);
const recipientATA = await getAssociatedTokenAddress(mintPubkey, recipientPubkey);
diff --git a/api/_lib/solana-wallet.js b/api/_lib/solana-wallet.js
index 5f29ae628..70b145680 100644
--- a/api/_lib/solana-wallet.js
+++ b/api/_lib/solana-wallet.js
@@ -2,6 +2,7 @@
// (pump-fun-trade, jupiter-swap, etc). Built on top of recoverSolanaAgentKeypair.
import { Connection, PublicKey, Transaction, VersionedTransaction } from '@solana/web3.js';
+import { solanaConnection } from './solana/connection.js';
import { recoverSolanaAgentKeypair } from './agent-wallet.js';
/**
@@ -42,7 +43,7 @@ export async function loadWallet(encryptedSecret) {
* Convenience: build a Connection from a URL, defaulting to mainnet.
*/
export function makeConnection(rpcUrl) {
- return new Connection(rpcUrl ?? 'https://api.mainnet-beta.solana.com', 'confirmed');
+ return solanaConnection({ url: rpcUrl ?? 'https://api.mainnet-beta.solana.com', commitment: 'confirmed' });
}
export { PublicKey };
diff --git a/api/_lib/threews-sns.js b/api/_lib/threews-sns.js
index 678b0f006..e9ca620b9 100644
--- a/api/_lib/threews-sns.js
+++ b/api/_lib/threews-sns.js
@@ -21,6 +21,7 @@ import {
storefrontUrlForLabel,
} from '../../src/solana/sns-subdomain.js';
import { Connection } from '@solana/web3.js';
+import { solanaConnection } from './solana/connection.js';
const DEFAULT_RPC_URL = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
@@ -67,7 +68,7 @@ export function hasOwnerKey() {
* subdomain has not been registered yet.
*/
export async function getSubdomainOwner(label) {
- const conn = new Connection(DEFAULT_RPC_URL, 'confirmed');
+ const conn = solanaConnection({ url: DEFAULT_RPC_URL, commitment: 'confirmed' });
const { exists, owner } = await checkSubdomainAvailability({
connection: conn,
parentDomain: PARENT_LABEL,
diff --git a/api/_lib/token/payments.js b/api/_lib/token/payments.js
index 4ef3c6887..0e8df1e3a 100644
--- a/api/_lib/token/payments.js
+++ b/api/_lib/token/payments.js
@@ -9,6 +9,7 @@
// as already_settled rather than crediting twice.
import { Connection } from '@solana/web3.js';
+import { solanaConnection } from '../solana/connection.js';
import { sql } from '../db.js';
import { env } from '../env.js';
import { verifyQuote } from './quote.js';
@@ -16,7 +17,9 @@ import { verifyQuote } from './quote.js';
const MEMO_PROGRAM = 'MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr';
function rpcUrl(network) {
- return network === 'devnet' ? env.SOLANA_RPC_URL_DEVNET : env.SOLANA_RPC_URL;
+ return network === 'devnet'
+ ? env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
+ : env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
}
function verifyError(message, status = 422, code = 'verification_failed', extra = {}) {
@@ -47,7 +50,7 @@ function creditedTo(tx, { mint, ownerAddress }) {
* @returns {Promise<{ confirmedAt: string, slot: number|null, credited: object }>}
*/
export async function verifyOnChain({ quote, txSignature, network = 'mainnet' }) {
- const connection = new Connection(rpcUrl(network), 'confirmed');
+ const connection = solanaConnection({ url: rpcUrl(network), commitment: 'confirmed' });
let tx;
try {
tx = await connection.getParsedTransaction(txSignature, {
diff --git a/api/_lib/x402-user-payer.js b/api/_lib/x402-user-payer.js
index 6bbafcc15..ef6ed1575 100644
--- a/api/_lib/x402-user-payer.js
+++ b/api/_lib/x402-user-payer.js
@@ -16,6 +16,7 @@
// handoff instead of moving funds.
import { sql } from './db.js';
+import { solanaConnection } from './solana/connection.js';
import { env } from './env.js';
import { recoverSolanaAgentKeypair } from './agent-wallet.js';
import { installSpendingCap } from './x402-spending-cap.js';
@@ -142,7 +143,7 @@ export async function getUserWalletStatus(userId) {
env.SOLANA_RPC_URL ??
(typeof process !== 'undefined' ? process.env?.SOLANA_RPC_URL : null) ??
'https://api.mainnet-beta.solana.com';
- const conn = new Connection(rpc, 'confirmed');
+ const conn = solanaConnection({ url: rpc, commitment: 'confirmed' });
const owner = new PublicKey(wallet.address);
const lamports = await conn.getBalance(owner);
sol = lamports / 1e9;
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index 35c60cfd8..fc5190dea 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -306,4 +306,208 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'remove_background',
+ title: 'Remove the background from an image',
+ description:
+ 'Strip the background from a photo or illustration using BRIA RMBG-2.0 (Apache-2.0). Returns a PNG with a transparent background — useful for preparing clean inputs before image_to_3d reconstruction.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ image_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of the source image (PNG/JPG/WebP).',
+ },
+ model: {
+ type: 'string',
+ enum: ['rmbg2', 'u2net', 'isnet', 'u2net_human_seg', 'silueta'],
+ default: 'rmbg2',
+ description: 'Background removal model. rmbg2 is highest quality; u2net_human_seg is optimised for people.',
+ },
+ },
+ required: ['image_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!(await isPublicHttpsUrl(args.image_url))) {
+ return {
+ content: [{ type: 'text', text: 'Error: image_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ const provider = regenProvider('rembg');
+ const job = await provider.submit({
+ mode: 'rembg',
+ sourceUrl: args.image_url,
+ params: { model: args.model || 'rmbg2' },
+ });
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Background removal started.\nJob ID: ${job.extJobId}\n` +
+ 'Poll with generation_status. Typically completes in 3–10 seconds.',
+ },
+ ],
+ structuredContent: {
+ job_id: job.extJobId,
+ status: 'queued',
+ source_image_url: args.image_url,
+ eta_seconds: job.eta,
+ },
+ };
+ },
+ },
+ {
+ name: 'remesh_model',
+ title: 'Remesh, simplify, repair, or convert a 3D model',
+ description:
+ 'Process an existing GLB/OBJ/STL/PLY mesh: fix holes and degenerate geometry, reduce face count via quadric decimation, or convert to a different format. Returns a clean GLB (or the requested format) job_id to poll with generation_status.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mesh_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of the source mesh (GLB/OBJ/FBX/STL/PLY).',
+ },
+ operation: {
+ type: 'string',
+ enum: ['full', 'simplify', 'repair', 'convert'],
+ default: 'full',
+ description: 'full = repair + simplify; simplify = face reduction only; repair = hole-fill + normal fix; convert = format change only.',
+ },
+ target_faces: {
+ type: 'integer',
+ minimum: 1000,
+ maximum: 500000,
+ default: 50000,
+ description: 'Target polygon count for simplification.',
+ },
+ output_format: {
+ type: 'string',
+ enum: ['glb', 'obj', 'stl', 'ply', 'usdz', '3mf'],
+ default: 'glb',
+ },
+ },
+ required: ['mesh_url'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!(await isPublicHttpsUrl(args.mesh_url))) {
+ return {
+ content: [{ type: 'text', text: 'Error: mesh_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ const provider = regenProvider('remesh');
+ const job = await provider.submit({
+ mode: 'remesh',
+ sourceUrl: args.mesh_url,
+ params: {
+ operation: args.operation || 'full',
+ target_faces: args.target_faces || 50_000,
+ output_format: args.output_format || 'glb',
+ },
+ });
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Mesh processing started (${args.operation || 'full'}).\nJob ID: ${job.extJobId}\n` +
+ 'Poll with generation_status. Typically completes in 10–60 seconds.',
+ },
+ ],
+ structuredContent: {
+ job_id: job.extJobId,
+ status: 'queued',
+ source_mesh_url: args.mesh_url,
+ operation: args.operation || 'full',
+ eta_seconds: job.eta,
+ },
+ };
+ },
+ },
+ {
+ name: 'retexture_model',
+ title: 'Paint a new texture onto a 3D model from a text prompt',
+ description:
+ 'Generate a fresh texture for an untextured or poorly-textured GLB using SDXL + ControlNet depth. Renders the mesh from 8 viewpoints, generates coherent texture views guided by your prompt, and back-projects them onto the UV atlas. Returns a job_id to poll with generation_status.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ mesh_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of the source GLB mesh.',
+ },
+ prompt: {
+ type: 'string',
+ minLength: 3,
+ maxLength: 500,
+ description: 'Texture description, e.g. "worn leather armour, dark brown, scratched metal buckles".',
+ },
+ negative_prompt: {
+ type: 'string',
+ maxLength: 200,
+ default: 'blurry, low quality, distorted, watermark',
+ },
+ num_views: {
+ type: 'integer',
+ enum: [4, 8],
+ default: 8,
+ description: '4 = faster; 8 = better coverage.',
+ },
+ texture_size: {
+ type: 'integer',
+ enum: [512, 1024, 2048],
+ default: 1024,
+ },
+ },
+ required: ['mesh_url', 'prompt'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!(await isPublicHttpsUrl(args.mesh_url))) {
+ return {
+ content: [{ type: 'text', text: 'Error: mesh_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ const provider = regenProvider('retex');
+ const job = await provider.submit({
+ mode: 'retex',
+ sourceUrl: args.mesh_url,
+ params: {
+ prompt: args.prompt,
+ negative_prompt: args.negative_prompt,
+ num_views: args.num_views || 8,
+ texture_size: args.texture_size || 1024,
+ },
+ });
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Texture generation started for "${args.prompt}".\nJob ID: ${job.extJobId}\n` +
+ 'Poll with generation_status. Typically completes in 2–5 minutes.',
+ },
+ ],
+ structuredContent: {
+ job_id: job.extJobId,
+ status: 'queued',
+ source_mesh_url: args.mesh_url,
+ prompt: args.prompt,
+ eta_seconds: job.eta,
+ },
+ };
+ },
+ },
];
diff --git a/api/actions/avatar.js b/api/actions/avatar.js
index 2684a1977..f2518e660 100644
--- a/api/actions/avatar.js
+++ b/api/actions/avatar.js
@@ -11,6 +11,7 @@
// GLB via headless chromium so X shows a live 3D-rendered portrait in the card.
import { cors, json, error, readJson, wrap } from '../_lib/http.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
import { env } from '../_lib/env.js';
export const maxDuration = 10;
@@ -87,7 +88,7 @@ async function handlePost(req, res, avatarId) {
const rpc =
process.env.SOLANA_MAINNET_RPC || 'https://api.mainnet-beta.solana.com';
- const connection = new Connection(rpc, 'confirmed');
+ const connection = solanaConnection({ url: rpc, commitment: 'confirmed' });
const { blockhash } = await connection.getLatestBlockhash();
const memo = JSON.stringify({
diff --git a/api/agents/onchain/[action].js b/api/agents/onchain/[action].js
index b3c7afbaf..720d08552 100644
--- a/api/agents/onchain/[action].js
+++ b/api/agents/onchain/[action].js
@@ -19,6 +19,7 @@ import {
createNoopSigner,
} from '@metaplex-foundation/umi';
import { Connection } from '@solana/web3.js';
+import { solanaConnection } from '../../_lib/solana/connection.js';
import { JsonRpcProvider } from 'ethers';
import { PutObjectCommand } from '@aws-sdk/client-s3';
import { CID } from 'multiformats/cid';
@@ -39,6 +40,11 @@ import {
agentRoyaltyConfig,
agentHomeUrl,
} from '../../_lib/three-brand.js';
+import {
+ getAgentCollection,
+ loadCollectionAuthorityKeypair,
+ collectionAuthoritySigner,
+} from '../../_lib/solana-collection.js';
export default wrap(async (req, res) => {
const action = req.query?.action;
@@ -165,7 +171,7 @@ const SOLANA_PUBLIC_RPC = {
devnet: 'https://api.devnet.solana.com',
};
-async function buildSolanaTx({ rpc, walletAddress, name, metadataUri, attributes }) {
+async function buildSolanaTx({ rpc, walletAddress, name, metadataUri, attributes, collectionAddr }) {
const umi = createUmi(rpc).use(mplCore());
const ownerPk = umiPublicKey(walletAddress);
const assetSigner = generateSigner(umi);
@@ -186,7 +192,15 @@ async function buildSolanaTx({ rpc, walletAddress, name, metadataUri, attributes
}]
: []),
];
- const builder = create(umi, { asset: assetSigner, owner: ownerPk, name, uri: metadataUri, plugins });
+ const createArgs = { asset: assetSigner, owner: ownerPk, name, uri: metadataUri, plugins };
+ // When the three.ws Agent Collection exists for this network, mint into it so
+ // the asset is authority-managed (three.ws holds the collection authority and
+ // co-signs the mint). Otherwise fall back to a standalone owner-managed asset.
+ if (collectionAddr) {
+ createArgs.collection = umiPublicKey(collectionAddr);
+ createArgs.authority = collectionAuthoritySigner(umi);
+ }
+ const builder = create(umi, createArgs);
const tx = await builder.buildAndSign(umi);
return { assetSigner, txBytes: umi.transactions.serialize(tx) };
}
@@ -202,6 +216,18 @@ async function prepSolana({ cluster, metadataUri, walletAddress, name, attribute
? process.env.SOLANA_RPC_URL_DEVNET || SOLANA_PUBLIC_RPC.devnet
: process.env.SOLANA_RPC_URL || SOLANA_PUBLIC_RPC.mainnet;
+ // Mint into the three.ws Agent Collection when one is deployed for this
+ // cluster; this makes the asset authority-managed (editable by three.ws).
+ const collectionAddr = getAgentCollection(cluster);
+ if (collectionAddr) {
+ try {
+ loadCollectionAuthorityKeypair();
+ } catch (e) {
+ e.code = 'authority_unconfigured';
+ throw e;
+ }
+ }
+
let assetSigner, txBytes;
try {
({ assetSigner, txBytes } = await buildSolanaTx({
@@ -210,6 +236,7 @@ async function prepSolana({ cluster, metadataUri, walletAddress, name, attribute
name,
metadataUri,
attributes,
+ collectionAddr,
}));
} catch (err) {
// If the configured RPC rejects with an auth error AND it's not already the
@@ -238,6 +265,7 @@ async function prepSolana({ cluster, metadataUri, walletAddress, name, attribute
name,
metadataUri,
attributes,
+ collectionAddr,
}));
} catch (fallbackErr) {
if (isRpcAuthError(fallbackErr)) {
@@ -257,6 +285,7 @@ async function prepSolana({ cluster, metadataUri, walletAddress, name, attribute
assetPubkey: assetSigner.publicKey,
txBase64: Buffer.from(txBytes).toString('base64'),
metadataUri,
+ collection: collectionAddr || null,
};
}
@@ -332,6 +361,9 @@ async function handlePrep(req, res) {
if (e.code === 'rpc_auth_failed') {
return error(res, 503, 'rpc_unavailable', e.message);
}
+ if (e.code === 'authority_unconfigured') {
+ return error(res, 500, 'authority_unconfigured', e.message);
+ }
throw e;
}
@@ -357,7 +389,7 @@ async function handlePrep(req, res) {
skills: body.skills || [],
...(chain.family === 'evm'
? { contract_address: familyPrep.contractAddress }
- : { asset_pubkey: familyPrep.assetPubkey, cluster: chain.cluster }),
+ : { asset_pubkey: familyPrep.assetPubkey, cluster: chain.cluster, collection: familyPrep.collection }),
})}::jsonb,
${expiresAt}
)
@@ -432,7 +464,7 @@ async function verifySolana({ cluster, txSig, expectedAsset, expectedOwner }) {
cluster === 'devnet'
? process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com'
: process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
- const conn = new Connection(rpc, 'confirmed');
+ const conn = solanaConnection({ url: rpc, commitment: 'confirmed' });
// Bounded poll — RPC may not have indexed the tx yet, especially on devnet.
const deadline = Date.now() + 20_000;
@@ -545,6 +577,19 @@ async function handleConfirm(req, res) {
...(p.chain_family === 'solana' ? { cluster: p.cluster } : {}),
};
+ // For Solana, also surface the flat fields the edit + attestation paths key on
+ // (sol_mint_address), plus the collection/authority marker so the
+ // authority-managed edit endpoint recognises this agent as editable.
+ const solanaMeta =
+ p.chain_family === 'solana'
+ ? {
+ chain_type: 'solana',
+ network: p.cluster,
+ sol_mint_address: p.asset_pubkey,
+ ...(p.collection ? { collection: p.collection, update_authority: 'threews' } : {}),
+ }
+ : {};
+
// Upsert agent_identities. If a row already exists for (user, agent), we
// merge the new onchain block in — supports redeploying across chains.
const [existing] = await sql`
@@ -557,7 +602,7 @@ async function handleConfirm(req, res) {
let agent;
if (existing) {
- const mergedMeta = { ...(existing.meta || {}), onchain };
+ const mergedMeta = { ...(existing.meta || {}), ...solanaMeta, onchain };
[agent] = await sql`
update agent_identities
set meta = ${JSON.stringify(mergedMeta)}::jsonb,
@@ -576,7 +621,7 @@ async function handleConfirm(req, res) {
${p.description},
${p.avatar_id},
${body.wallet_address},
- ${JSON.stringify({ onchain })}::jsonb
+ ${JSON.stringify({ ...solanaMeta, onchain })}::jsonb
)
returning id, name, description, wallet_address, meta, created_at
`;
diff --git a/api/agents/payments/[action].js b/api/agents/payments/[action].js
index 2f40f7364..eb2c88b6a 100644
--- a/api/agents/payments/[action].js
+++ b/api/agents/payments/[action].js
@@ -12,6 +12,7 @@
*/
import { z } from 'zod';
+import { solanaConnection } from '../../_lib/solana/connection.js';
import {
Connection,
PublicKey,
@@ -107,7 +108,7 @@ async function handleCreatePrep(req, res) {
return error(res, 403, 'forbidden', 'wallet does not match agent owner');
}
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(body.cluster), commitment: 'confirmed' });
const mint = new PublicKey(tokenMint);
const owner = new PublicKey(body.wallet_address);
const offline = PumpAgentOffline.load(mint, conn);
@@ -197,7 +198,7 @@ async function handleCreateConfirm(req, res) {
return error(res, 400, 'validation_error', 'wallet mismatch with prep');
}
- const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(prep.cluster), commitment: 'confirmed' });
const deadline = Date.now() + 30_000;
let tx;
while (Date.now() < deadline) {
@@ -285,7 +286,7 @@ async function handlePayPrep(req, res) {
}
const tokenMint = agent.meta.payments.mint;
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(body.cluster), commitment: 'confirmed' });
const pumpAgent = new PumpAgent(
new PublicKey(tokenMint),
body.cluster === 'devnet' ? 'devnet' : 'mainnet',
@@ -383,7 +384,7 @@ async function handlePayConfirm(req, res) {
return error(res, 400, 'validation_error', 'wallet mismatch');
}
- const conn = new Connection(rpcUrl(intent.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(intent.cluster), commitment: 'confirmed' });
const pumpAgent = new PumpAgent(
new PublicKey(intent.payload.token_mint),
intent.cluster === 'devnet' ? 'devnet' : 'mainnet',
@@ -453,7 +454,7 @@ const balancesSchema = z.object({
async function handleBalances(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
const body = parse(balancesSchema, { ...req.query });
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(body.cluster), commitment: 'confirmed' });
const agent = new PumpAgent(new PublicKey(body.mint), conn);
const balances = await agent.getBalances(new PublicKey(body.currency_mint));
return json(res, 200, {
@@ -476,7 +477,7 @@ async function handleDistributePrep(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
const body = parse(distributePrepSchema, await readJson(req));
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(body.cluster), commitment: 'confirmed' });
const user = new PublicKey(body.wallet_address);
const offline = PumpAgentOffline.load(new PublicKey(body.mint), conn);
const ix = await offline.distributePayments({ user, currencyMint: new PublicKey(body.currency_mint) });
@@ -502,7 +503,7 @@ async function handleDistributeConfirm(req, res) {
const body = parse(z.object({ prep_id: z.string(), tx_signature: z.string() }), await readJson(req));
const [prep] = await sql`select * from payment_configs_pending where id = ${body.prep_id} and expires_at > now() limit 1`;
if (!prep) return error(res, 404, 'not_found', 'prep expired');
- const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(prep.cluster), commitment: 'confirmed' });
let tx;
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
@@ -532,7 +533,7 @@ async function handleWithdrawPrep(req, res) {
const user = await getSessionUser(req);
if (!user) return error(res, 401, 'unauthorized', 'sign in required');
const body = parse(withdrawPrepSchema, await readJson(req));
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(body.cluster), commitment: 'confirmed' });
const spl = await import('@solana/spl-token');
const authority = new PublicKey(body.wallet_address);
const currency = new PublicKey(body.currency_mint);
@@ -563,7 +564,7 @@ async function handleWithdrawConfirm(req, res) {
const body = parse(z.object({ prep_id: z.string(), tx_signature: z.string() }), await readJson(req));
const [prep] = await sql`select * from payment_configs_pending where id = ${body.prep_id} and expires_at > now() limit 1`;
if (!prep) return error(res, 404, 'not_found', 'prep expired');
- const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(prep.cluster), commitment: 'confirmed' });
let tx;
const deadline = Date.now() + 20_000;
while (Date.now() < deadline) {
@@ -582,7 +583,7 @@ async function handleWithdrawConfirm(req, res) {
async function handleCheckWhitelist(req, res) {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
const cluster = req.query?.cluster || 'mainnet';
- const conn = new Connection(rpcUrl(cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(cluster), commitment: 'confirmed' });
const global = await new OnlinePumpSdk(conn).fetchGlobal();
const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
const mints = (global.whitelistedQuoteMints || []).map((k) => k.toBase58?.() ?? k.toString());
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index e0956a265..726d8aefd 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -6,6 +6,7 @@
import crypto from 'node:crypto';
import { z } from 'zod';
import { PublicKey, Connection } from '@solana/web3.js';
+import { solanaConnection } from '../../_lib/solana/connection.js';
import { sql } from '../../_lib/db.js';
import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';
import { limits, clientIp } from '../../_lib/rate-limit.js';
@@ -510,7 +511,7 @@ export const handleRegisterConfirm = wrap(async (req, res) => {
? (process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com')
: (process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com');
- const connection = new Connection(rpcEndpoint, 'confirmed');
+ const connection = solanaConnection({ url: rpcEndpoint, commitment: 'confirmed' });
let tx;
try { tx = await connection.getParsedTransaction(tx_signature, { maxSupportedTransactionVersion: 0, commitment: 'confirmed' }); }
catch { return error(res, 422, 'tx_not_found', 'transaction not found — try again after a few seconds'); }
diff --git a/api/agents/tokens/[action].js b/api/agents/tokens/[action].js
index d71936ecf..6131a8ca4 100644
--- a/api/agents/tokens/[action].js
+++ b/api/agents/tokens/[action].js
@@ -11,6 +11,7 @@
*/
import { z } from 'zod';
+import { solanaConnection } from '../../_lib/solana/connection.js';
import { createHash } from 'crypto';
import { sql } from '../../_lib/db.js';
@@ -186,7 +187,7 @@ async function handleLaunchPrep(req, res) {
const { Connection, Keypair, PublicKey, Transaction, ComputeBudgetProgram } =
await loadSolanaWeb3();
const { PumpSdk, OnlinePumpSdk, getBuyTokenAmountFromSolAmount, BN } = await loadPumpSdk();
- const conn = new Connection(rpcUrl(body.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(body.cluster), commitment: 'confirmed' });
const onlineSdk = new OnlinePumpSdk(conn);
const sdk = new PumpSdk();
@@ -345,7 +346,7 @@ async function handleLaunchConfirm(req, res) {
// Verify on-chain
const { Connection } = await loadSolanaWeb3();
- const conn = new Connection(rpcUrl(prep.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(prep.cluster), commitment: 'confirmed' });
const deadline = Date.now() + 30_000;
let tx;
@@ -462,7 +463,7 @@ async function handleLaunchQuote(req, res) {
try {
const { Connection } = await loadSolanaWeb3();
const { OnlinePumpSdk, getBuyTokenAmountFromSolAmount, BN } = await loadPumpSdk();
- const conn = new Connection(rpcUrl(q.cluster), 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl(q.cluster), commitment: 'confirmed' });
const onlineSdk = new OnlinePumpSdk(conn);
const global = await onlineSdk.fetchGlobal();
const lamports = new BN(Math.floor(q.initial_buy_sol * 1_000_000_000));
diff --git a/api/forge-rembg.js b/api/forge-rembg.js
new file mode 100644
index 000000000..8934cf6b2
--- /dev/null
+++ b/api/forge-rembg.js
@@ -0,0 +1,106 @@
+/**
+ * /api/forge-rembg — background removal for the forge pipeline.
+ *
+ * POST /api/forge-rembg { image_url: string, model?: string }
+ * → 202 { job_id, status }
+ *
+ * GET /api/forge-rembg?job=<id>
+ * → { job_id, status, result_url?, error? }
+ *
+ * Routes to workers/rembg (GCP Cloud Run) when GCP_REMBG_URL is set,
+ * otherwise returns 503 with an actionable configuration message.
+ *
+ * No auth required — rate-limited by client IP using the same mcp3d buckets.
+ */
+
+import { cors, json, method, readJson, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { createRegenProvider } from './_providers/gcp.js';
+
+const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;
+const VALID_MODELS = new Set(['rmbg2', 'u2net', 'isnet', 'u2net_human_seg', 'silueta']);
+
+function unconfigured(res) {
+ return json(res, 503, {
+ error: 'unconfigured',
+ message:
+ 'Background removal is not configured. Set GCP_REMBG_URL and GCP_RECONSTRUCTION_KEY ' +
+ 'to the URL and bearer secret of your deployed workers/rembg Cloud Run service.',
+ });
+}
+
+async function startJob(req, res) {
+ const ip = clientIp(req);
+ const rl = await limits.mcp3dGenerate(ip);
+ if (!rl.success) {
+ return json(res, 429, {
+ error: 'rate_limited',
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ }
+
+ const body = await readJson(req, 4_000).catch(() => null);
+ const imageUrl = typeof body?.image_url === 'string' ? body.image_url.trim() : '';
+ if (!imageUrl.startsWith('https://')) {
+ return json(res, 400, { error: 'invalid_image_url', message: 'image_url must be a public https URL.' });
+ }
+
+ const model = VALID_MODELS.has(body?.model) ? body.model : 'rmbg2';
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ if (!provider.supportsMode('rembg')) return unconfigured(res);
+ } catch {
+ return unconfigured(res);
+ }
+
+ try {
+ const job = await provider.submit({ mode: 'rembg', sourceUrl: imageUrl, params: { model } });
+ return json(res, 202, {
+ job_id: job.extJobId,
+ status: 'queued',
+ eta_seconds: job.eta,
+ });
+ } catch (err) {
+ return json(res, 502, { error: 'rembg_failed', message: err?.message || 'Background removal could not start.' });
+ }
+}
+
+async function pollJob(req, res, jobId) {
+ if (!JOB_ID_RE.test(jobId)) {
+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
+ }
+
+ const rl = await limits.mcp3dStatus(clientIp(req));
+ if (!rl.success) {
+ return json(res, 429, { error: 'rate_limited', retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ }
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ const result = await provider.status(jobId);
+ return json(res, 200, {
+ job_id: jobId,
+ status: result.status,
+ result_url: result.resultImageUrl || result.resultGlbUrl || null,
+ error: result.error || null,
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'POST') return startJob(req, res);
+
+ const url = new URL(req.url, 'http://localhost');
+ const jobId = (url.searchParams.get('job') || '').trim();
+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });
+ return pollJob(req, res, jobId);
+});
diff --git a/api/forge-remesh.js b/api/forge-remesh.js
new file mode 100644
index 000000000..451ca90e4
--- /dev/null
+++ b/api/forge-remesh.js
@@ -0,0 +1,117 @@
+/**
+ * /api/forge-remesh — mesh processing for the forge pipeline.
+ *
+ * POST /api/forge-remesh {
+ * mesh_url: string,
+ * operation?: "full"|"simplify"|"repair"|"convert",
+ * target_faces?: number,
+ * output_format?: "glb"|"obj"|"stl"|"ply"|"usdz"|"3mf"
+ * } → 202 { job_id, status }
+ *
+ * GET /api/forge-remesh?job=<id>
+ * → { job_id, status, result_url?, face_count?, error? }
+ *
+ * Routes to workers/remesh (GCP Cloud Run) when GCP_REMESH_URL is set.
+ */
+
+import { cors, json, method, readJson, wrap } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { createRegenProvider } from './_providers/gcp.js';
+
+const JOB_ID_RE = /^[A-Za-z0-9_-]{20,64}$/;
+const VALID_OPERATIONS = new Set(['full', 'simplify', 'repair', 'convert']);
+const VALID_FORMATS = new Set(['glb', 'obj', 'stl', 'ply', 'usdz', '3mf']);
+
+function unconfigured(res) {
+ return json(res, 503, {
+ error: 'unconfigured',
+ message:
+ 'Mesh processing is not configured. Set GCP_REMESH_URL and GCP_RECONSTRUCTION_KEY ' +
+ 'to the URL and bearer secret of your deployed workers/remesh Cloud Run service.',
+ });
+}
+
+async function startJob(req, res) {
+ const ip = clientIp(req);
+ const rl = await limits.mcp3dGenerate(ip);
+ if (!rl.success) {
+ return json(res, 429, {
+ error: 'rate_limited',
+ retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
+ });
+ }
+
+ const body = await readJson(req, 4_000).catch(() => null);
+ const meshUrl = typeof body?.mesh_url === 'string' ? body.mesh_url.trim() : '';
+ if (!meshUrl.startsWith('https://')) {
+ return json(res, 400, { error: 'invalid_mesh_url', message: 'mesh_url must be a public https URL.' });
+ }
+
+ const operation = VALID_OPERATIONS.has(body?.operation) ? body.operation : 'full';
+ const outputFormat = VALID_FORMATS.has(body?.output_format) ? body.output_format : 'glb';
+ const targetFaces = Math.max(1_000, Math.min(500_000, Number(body?.target_faces) || 50_000));
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ if (!provider.supportsMode('remesh')) return unconfigured(res);
+ } catch {
+ return unconfigured(res);
+ }
+
+ try {
+ const job = await provider.submit({
+ mode: 'remesh',
+ sourceUrl: meshUrl,
+ params: { operation, target_faces: targetFaces, output_format: outputFormat },
+ });
+ return json(res, 202, {
+ job_id: job.extJobId,
+ status: 'queued',
+ operation,
+ output_format: outputFormat,
+ eta_seconds: job.eta,
+ });
+ } catch (err) {
+ return json(res, 502, { error: 'remesh_failed', message: err?.message || 'Mesh processing could not start.' });
+ }
+}
+
+async function pollJob(req, res, jobId) {
+ if (!JOB_ID_RE.test(jobId)) {
+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });
+ }
+
+ const rl = await limits.mcp3dStatus(clientIp(req));
+ if (!rl.success) {
+ return json(res, 429, { error: 'rate_limited', retry_after: Math.ceil((rl.reset - Date.now()) / 1000) });
+ }
+
+ let provider;
+ try {
+ provider = createRegenProvider();
+ } catch {
+ return unconfigured(res);
+ }
+
+ const result = await provider.status(jobId);
+ return json(res, 200, {
+ job_id: jobId,
+ status: result.status,
+ result_url: result.resultGlbUrl || null,
+ face_count: result.faceCount || null,
+ error: result.error || null,
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ if (req.method === 'POST') return startJob(req, res);
+
+ const url = new URL(req.url, 'http://localhost');
+ const jobId = (url.searchParams.get('job') || '').trim();
+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });
+ return pollJob(req, res, jobId);
+});
diff --git a/api/marketplace/purchase-as-agent.js b/api/marketplace/purchase-as-agent.js
index 4be572d2e..faaf7c996 100644
--- a/api/marketplace/purchase-as-agent.js
+++ b/api/marketplace/purchase-as-agent.js
@@ -18,6 +18,7 @@
* Revenue + notifications are handled by confirmSkillPurchase (purchase-confirm.js).
*/
import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
import {
getAssociatedTokenAddressSync,
createTransferCheckedInstruction,
@@ -204,7 +205,7 @@ export default wrap(async (req, res) => {
});
// Build, sign, and submit the SPL transferChecked
- const connection = new Connection(SOLANA_RPC, 'confirmed');
+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
const mintKey = new PublicKey(price.currency_mint);
const recipKey = new PublicKey(recipientAddr);
const mintInfo = await getMint(connection, mintKey);
diff --git a/api/nft/mint-scene-confirm.js b/api/nft/mint-scene-confirm.js
index 47e6bea4d..899babf70 100644
--- a/api/nft/mint-scene-confirm.js
+++ b/api/nft/mint-scene-confirm.js
@@ -2,6 +2,7 @@ import { env } from '../_lib/env.js';
import { wrap, cors, error, json, readJson, method } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { Connection } from '@solana/web3.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
export default wrap(async (req, res) => {
if (cors(req, res)) return;
@@ -17,7 +18,7 @@ export default wrap(async (req, res) => {
return error(res, 400, 'validation_error', 'signedTxBase64 required');
const rpcUrl = env.SOLANA_RPC_URL;
- const connection = new Connection(rpcUrl, 'confirmed');
+ const connection = solanaConnection({ url: rpcUrl, commitment: 'confirmed' });
let txBytes;
try {
diff --git a/api/payments/prepare-skill-purchase.js b/api/payments/prepare-skill-purchase.js
index 410ddaa56..4c1bb5ea2 100644
--- a/api/payments/prepare-skill-purchase.js
+++ b/api/payments/prepare-skill-purchase.js
@@ -8,6 +8,7 @@
* Returns: { transaction (base64), reference, recipient, amount, currency_mint }
*/
import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
import { getAssociatedTokenAddressSync, createTransferCheckedInstruction, getMint } from '@solana/spl-token';
import { sql } from '../_lib/db.js';
@@ -97,7 +98,7 @@ export default wrap(async (req, res) => {
`;
// Build the SPL token transfer transaction
- const connection = new Connection(SOLANA_RPC, 'confirmed');
+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
const { blockhash, lastValidBlockHeight } = await connection.getLatestBlockhash('confirmed');
const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));
diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].js
index 71d8ec153..a99b4d39d 100644
--- a/api/payments/solana/[action].js
+++ b/api/payments/solana/[action].js
@@ -2,6 +2,7 @@
import { z } from 'zod';
import { Connection } from '@solana/web3.js';
+import { solanaConnection } from '../../_lib/solana/connection.js';
import { sql } from '../../_lib/db.js';
import { getSessionUser } from '../../_lib/auth.js';
import { cors, json, method, readJson, wrap, error } from '../../_lib/http.js';
@@ -75,7 +76,7 @@ async function handleConfirm(req, res) {
// A confirmed plan payment grants 30 days of paid plan — an irreversible,
// latency-tolerant, one-time grant. Require 'finalized' so a short reorg
// can't roll back the tx after we've already upgraded the account.
- const connection = new Connection(rpcUrl, 'finalized');
+ const connection = solanaConnection({ url: rpcUrl, commitment: 'finalized' });
const usdcMint = network === 'devnet' ? '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU' : SOLANA_USDC_MINT;
let tx;
try { tx = await connection.getParsedTransaction(tx_signature, { maxSupportedTransactionVersion: 0, commitment: 'finalized' }); }
diff --git a/api/portfolio/[action].js b/api/portfolio/[action].js
index a34e15ac2..9439b8245 100644
--- a/api/portfolio/[action].js
+++ b/api/portfolio/[action].js
@@ -10,6 +10,7 @@
// per-page-load fan-out.
import { cors, json, method, readJson, wrap, error, validationError } from '../_lib/http.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { getSessionUser, isSameSiteOrigin } from '../_lib/auth.js';
import { requireCsrf } from '../_lib/csrf.js';
@@ -302,7 +303,7 @@ async function sendSolana({ agent, asset, recipient, amount, userId }) {
const { Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL } = await import('@solana/web3.js');
const rpcUrl = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';
- const conn = new Connection(rpcUrl, 'confirmed');
+ const conn = solanaConnection({ url: rpcUrl, commitment: 'confirmed' });
const kp = await recoverSolanaAgentKeypair(encryptedSecret, {
userId,
diff --git a/api/purchase/skill.js b/api/purchase/skill.js
index 7d71b3fd0..48699178b 100644
--- a/api/purchase/skill.js
+++ b/api/purchase/skill.js
@@ -6,6 +6,7 @@
* QR code can fetch and sign the USDC transfer directly.
*/
import { Connection, Keypair, PublicKey, Transaction } from '@solana/web3.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
import { getAssociatedTokenAddressSync, createTransferCheckedInstruction, getMint } from '@solana/spl-token';
import { findReference } from '@solana/pay';
@@ -82,7 +83,7 @@ export default wrap(async (req, res) => {
`;
// Build transaction
- const connection = new Connection(SOLANA_RPC, 'confirmed');
+ const connection = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
const { blockhash } = await connection.getLatestBlockhash('confirmed');
const mintInfo = await getMint(connection, new PublicKey(price.currency_mint));
diff --git a/api/rider/check.js b/api/rider/check.js
index 2a3a6fddd..fbfefa895 100644
--- a/api/rider/check.js
+++ b/api/rider/check.js
@@ -1,4 +1,5 @@
import { Connection, PublicKey } from '@solana/web3.js';
+import { solanaConnection } from '../_lib/solana/connection.js';
import { cors, json, method, wrap, error } from '../_lib/http.js';
import { limits, clientIp } from '../_lib/rate-limit.js';
import { TOKEN_MINT as THREE_MINT } from '../_lib/token/config.js';
@@ -22,7 +23,7 @@ export default wrap(async (req, res) => {
return error(res, 400, 'validation_error', 'invalid Solana address');
}
- const connection = new Connection(RPC, 'confirmed');
+ const connection = solanaConnection({ url: RPC, commitment: 'confirmed' });
const accounts = await connection.getParsedTokenAccountsByOwner(owner, {
programId: TOKEN_PROGRAM,
});
diff --git a/api/tx/solana/[action].js b/api/tx/solana/[action].js
index 5babb8640..9abfe6af5 100644
--- a/api/tx/solana/[action].js
+++ b/api/tx/solana/[action].js
@@ -1,4 +1,5 @@
import { z } from 'zod';
+import { solanaConnection } from '../../_lib/solana/connection.js';
import {
Connection, PublicKey, Transaction, SystemProgram, LAMPORTS_PER_SOL,
TransactionInstruction,
@@ -38,7 +39,7 @@ async function handleBuildTransfer(req, res) {
const { sender, recipient, amount, token, memo, network } = parse(transferSchema, await readJson(req));
const rpcUrl = network === 'devnet' ? SOLANA_RPC_DEVNET : SOLANA_RPC_MAINNET;
- const connection = new Connection(rpcUrl, 'confirmed');
+ const connection = solanaConnection({ url: rpcUrl, commitment: 'confirmed' });
const senderPubkey = new PublicKey(sender);
const recipientPubkey = new PublicKey(recipient);
@@ -107,7 +108,7 @@ async function handleBuildSwap(req, res) {
const { sender, inputMint, outputMint, amount, slippageBps } = parse(swapSchema, await readJson(req));
- const connection = new Connection(SOLANA_RPC_MAINNET, 'confirmed');
+ const connection = solanaConnection({ url: SOLANA_RPC_MAINNET, commitment: 'confirmed' });
const inputMintPk = new PublicKey(inputMint);
const mintInfo = await getMint(connection, inputMintPk);
const amountInSmallestUnit = Math.round(amount * 10 ** mintInfo.decimals);
diff --git a/api/x402-checkout.js b/api/x402-checkout.js
index b46c2bf64..55f219145 100644
--- a/api/x402-checkout.js
+++ b/api/x402-checkout.js
@@ -21,6 +21,7 @@
// x402 envelope. Keeps each step short and visible.
import { z } from 'zod';
+import { solanaConnection } from './_lib/solana/connection.js';
import {
Connection,
PublicKey,
@@ -153,7 +154,7 @@ async function handlePrepare(req, res) {
}
const rpc = rpcFor(accept.network);
- const conn = new Connection(rpc, 'confirmed');
+ const conn = solanaConnection({ url: rpc, commitment: 'confirmed' });
const mint = new PublicKey(accept.asset);
const payTo = new PublicKey(accept.payTo);
const feePayer = new PublicKey(accept.extra.feePayer);
diff --git a/api/x402-pay.js b/api/x402-pay.js
index b402fd5d8..f78fcc5a7 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -19,6 +19,7 @@
// balance so the UI can show it ticking down during the demo.
import { readFileSync } from 'node:fs';
+import { solanaConnection } from './_lib/solana/connection.js';
import {
Connection, PublicKey, Keypair, TransactionMessage, VersionedTransaction,
ComputeBudgetProgram,
@@ -181,7 +182,7 @@ async function getAgentsForUser(userId) {
WHERE user_id = ${userId} AND deleted_at IS NULL
ORDER BY created_at ASC
`;
- const conn = new Connection(SOLANA_RPC, 'confirmed');
+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
return Promise.all(rows.map(async (row) => {
const address = row.meta?.solana_address || null;
const source = row.meta?.solana_wallet_source || null;
@@ -355,7 +356,7 @@ async function buildSolanaPaymentPayload({ accept, buyer, conn, resourceUrl }) {
async function getAgentBalance() {
const buyer = loadAgentKeypair();
- const conn = new Connection(SOLANA_RPC, 'confirmed');
+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
const sol = await conn.getBalance(buyer.publicKey);
let usdc = 0;
try {
@@ -394,7 +395,7 @@ function sseSend(res, event, data) {
async function runFlow({ tool, args, emit, buyer: buyerOverride, resourceUrl }) {
const buyer = buyerOverride ?? loadAgentKeypair();
- const conn = new Connection(SOLANA_RPC, 'confirmed');
+ const conn = solanaConnection({ url: SOLANA_RPC, commitment: 'confirmed' });
const requirements = paymentRequirements();
const accept = requirements.find((r) => r.network === NETWORK_SOLANA_MAINNET);
diff --git a/scripts/migrate-solana-connection.mjs b/scripts/migrate-solana-connection.mjs
new file mode 100644
index 000000000..5ecef06e3
--- /dev/null
+++ b/scripts/migrate-solana-connection.mjs
@@ -0,0 +1,82 @@
+// One-shot codemod: migrate raw `new Connection(url, commitment)` call sites to
+// the failover-aware `solanaConnection({ url, commitment })`. Network (mainnet/
+// devnet) is inferred from the resolved url inside the engine, so call sites need
+// no change beyond the constructor. Run once, then delete (repo hygiene).
+import { readFileSync, writeFileSync } from 'node:fs';
+import { relative, dirname } from 'node:path';
+
+const ENGINE = 'api/_lib/solana/connection.js';
+
+const FILES = [
+ 'api/x402-checkout.js',
+ 'api/x402-pay.js',
+ 'api/portfolio/[action].js',
+ 'api/payments/prepare-skill-purchase.js',
+ 'api/payments/solana/[action].js',
+ 'api/rider/check.js',
+ 'api/nft/mint-scene-confirm.js',
+ 'api/_lib/pump.js',
+ 'api/_lib/attest-event.js',
+ 'api/_lib/x402-user-payer.js',
+ 'api/_lib/agent-pumpfun.js',
+ 'api/_lib/token/payments.js',
+ 'api/_lib/club/payouts.js',
+ 'api/agents/tokens/[action].js',
+ 'api/agents/payments/[action].js',
+ 'api/agents/solana/_handlers.js',
+ 'api/agents/onchain/[action].js',
+ 'api/tx/solana/[action].js',
+ 'api/_lib/threews-sns.js',
+ 'api/_lib/avatar-wallet.js',
+ 'api/marketplace/purchase-as-agent.js',
+ 'api/_lib/solana-attestations.js',
+ 'api/_lib/solana-wallet.js',
+ 'api/_lib/solana-transfer.js',
+ 'api/purchase/skill.js',
+ 'api/actions/avatar.js',
+];
+
+// `new Connection(<expr>, <commitment>)` on a single line. <expr> is non-greedy;
+// <commitment> is a quoted literal or a bare identifier.
+const RE = /new Connection\((.+?),\s*('[a-z]+'|[A-Za-z_$][\w$]*)\)/g;
+
+function importPath(file) {
+ let p = relative(dirname(file), ENGINE).replace(/\\/g, '/');
+ if (!p.startsWith('.')) p = './' + p;
+ return p;
+}
+
+let total = 0;
+for (const file of FILES) {
+ let src = readFileSync(file, 'utf8');
+ const lines = src.split('\n');
+ let count = 0;
+ const out = lines.map((line) => {
+ const trimmed = line.trimStart();
+ if (trimmed.startsWith('//') || trimmed.startsWith('*')) return line; // skip comments
+ return line.replace(RE, (_m, expr, commitment) => {
+ count++;
+ return `solanaConnection({ url: ${expr}, commitment: ${commitment} })`;
+ });
+ });
+ if (count === 0) {
+ console.log(`-- ${file}: no match`);
+ continue;
+ }
+ src = out.join('\n');
+
+ // Insert the import once, right after the @solana/web3.js import if present,
+ // else after the first import statement.
+ if (!src.includes("solana/connection.js'") && !src.includes('solanaConnection }')) {
+ const imp = `import { solanaConnection } from '${importPath(file)}';`;
+ const srcLines = src.split('\n');
+ let idx = srcLines.findIndex((l) => /@solana\/web3\.js'/.test(l) && l.startsWith('import'));
+ if (idx === -1) idx = srcLines.findIndex((l) => l.startsWith('import '));
+ srcLines.splice(idx + 1, 0, imp);
+ src = srcLines.join('\n');
+ }
+ writeFileSync(file, src);
+ total += count;
+ console.log(`✓ ${file}: ${count} call(s)`);
+}
+console.log(`\nTotal: ${total} call sites migrated`);
diff --git a/vercel.json b/vercel.json
index a7cf30e98..e40d4c6e8 100644
--- a/vercel.json
+++ b/vercel.json
@@ -271,6 +271,14 @@
"src": "/api/agents/solana-metadata",
"dest": "/api/agents/solana/[action]?action=metadata"
},
+ {
+ "src": "/api/agents/solana-collection-metadata",
+ "dest": "/api/agents/solana/[action]?action=collection-metadata"
+ },
+ {
+ "src": "/api/agents/solana-edit",
+ "dest": "/api/agents/solana/[action]?action=edit"
+ },
{
"src": "/api/agents/solana-attestations",
"dest": "/api/agents/solana/[action]?action=attestations"