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.

refactor: Solana handlers cleanup, remove migration script

nirholascf3472af82ec
diff --git a/api/_lib/pump.js b/api/_lib/pump.js
index b3196596e..39ba6298c 100644
--- a/api/_lib/pump.js
+++ b/api/_lib/pump.js
@@ -17,7 +17,7 @@
// SOLANA_RPC_FALLBACK_URLS (comma-separated) enables the multi-endpoint
// RpcFallback wrapper for read-side handlers that opt in via getRpcFallback().
-import { Connection, PublicKey } from '@solana/web3.js';
+import { PublicKey } from '@solana/web3.js';
import { solanaConnection } from './solana/connection.js';
import { rpcFallbackFromEnv } from './solana/rpc-fallback.js';
diff --git a/api/_lib/threews-sns.js b/api/_lib/threews-sns.js
index 1bf9d33bd..30bdb1b0e 100644
--- a/api/_lib/threews-sns.js
+++ b/api/_lib/threews-sns.js
@@ -12,7 +12,6 @@
// records argument.
import { checkSubdomainAvailability, createNamedSubdomain, getParentDomain, getStorefrontOrigin, loadParentOwnerKeypair, normalizeLabel as normalizeLabelRaw, 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';
diff --git a/api/agents/onchain/[action].js b/api/agents/onchain/[action].js
index d77331229..819a4eb07 100644
--- a/api/agents/onchain/[action].js
+++ b/api/agents/onchain/[action].js
@@ -14,7 +14,6 @@ import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
import { mplCore, create, ruleSet } from '@metaplex-foundation/mpl-core';
import {
generateSigner, publicKey as umiPublicKey, signerIdentity, 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';
diff --git a/api/agents/solana/_handlers.js b/api/agents/solana/_handlers.js
index ae3bcf756..659a3f6d3 100644
--- a/api/agents/solana/_handlers.js
+++ b/api/agents/solana/_handlers.js
@@ -608,7 +608,7 @@ export const handleEdit = wrap(async (req, res) => {
try { new PublicKey(asset_pubkey); } catch { return error(res, 400, 'validation_error', 'invalid asset pubkey'); }
// Ownership: the agent must belong to the signed-in user.
- const [agent] = await sql`select id, name, description, skills, avatar_id, wallet_address, meta from agent_identities where (meta->>'sol_mint_address') = ${asset_pubkey} and user_id = ${user.id} and deleted_at is null limit 1`;
+ const [agent] = await sql`select id, name, description, avatar_id, wallet_address, meta from agent_identities where (meta->>'sol_mint_address') = ${asset_pubkey} and user_id = ${user.id} and deleted_at is null limit 1`;
if (!agent) return error(res, 404, 'not_found', 'agent not found for your account');
const collectionAddr = agent.meta?.collection || null;
@@ -621,11 +621,12 @@ export const handleEdit = wrap(async (req, res) => {
if (!av) return error(res, 404, 'not_found', 'avatar not found');
}
- // Merge requested edits over current values.
+ // Merge requested edits over current DB values. Skills are stored on-chain in
+ // the Attributes plugin (and in the off-chain manifest), not as an
+ // agent_identities column, so they are not written to the DB here.
const next = {
name: body.name ?? agent.name,
description: body.description ?? agent.description,
- skills: body.skills ?? agent.skills ?? [],
avatar_id: body.avatar_id === undefined ? agent.avatar_id : body.avatar_id,
};
@@ -645,41 +646,54 @@ export const handleEdit = wrap(async (req, res) => {
const collectionPk = umiPublicKey(collectionAddr);
const passportUrl = `${env.APP_ORIGIN}/agent-passport.html?asset=${asset_pubkey}&network=${network}`;
+ // Only name/skills live in the on-chain Attributes plugin (and name in the
+ // asset's name field). Description/avatar are served dynamically from the
+ // metadata endpoint via the asset URI, so they need no on-chain write.
+ const nameChanged = body.name !== undefined && body.name !== agent.name;
+ const skillsChanged = body.skills !== undefined;
+
const signatures = {};
- try {
- // 1) Rewrite the on-chain Attributes plugin with the new curated fields.
- const attributeList = buildAgentOnchainAttributes({
- name: next.name,
- agentUrl: passportUrl,
- skills: next.skills,
- createdAt: new Date().toISOString(),
- });
- const attrRes = await updatePlugin(umi, {
- asset: assetPk,
- collection: collectionPk,
- plugin: { type: 'Attributes', attributeList },
- }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
- signatures.attributes = base58Sig(attrRes.signature);
-
- // 2) If the display name changed, update the asset's on-chain name too.
- if (body.name !== undefined && body.name !== agent.name) {
- const [onchainAsset, onchainCollection] = await Promise.all([
- fetchAsset(umi, assetPk),
- fetchCollection(umi, collectionPk),
- ]);
- const nameRes = await update(umi, {
- asset: onchainAsset,
- collection: onchainCollection,
+ if (nameChanged || skillsChanged) {
+ try {
+ // Read current on-chain attributes so unedited fields (skills, the
+ // original created timestamp) are preserved rather than dropped.
+ const onchainAsset = await fetchAsset(umi, assetPk);
+ const existingAttrs = onchainAsset.attributes?.attributeList || [];
+ const attrMap = new Map(existingAttrs.map((a) => [a.key, a.value]));
+ const existingSkills = attrMap.get('skills')
+ ? String(attrMap.get('skills')).split(',').filter(Boolean)
+ : [];
+
+ const attributeList = buildAgentOnchainAttributes({
name: next.name,
+ agentUrl: passportUrl,
+ skills: body.skills ?? existingSkills,
+ createdAt: attrMap.get('created') || undefined,
+ });
+ const attrRes = await updatePlugin(umi, {
+ asset: assetPk,
+ collection: collectionPk,
+ plugin: { type: 'Attributes', attributeList },
}).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
- signatures.name = base58Sig(nameRes.signature);
+ signatures.attributes = base58Sig(attrRes.signature);
+
+ // If the display name changed, update the asset's on-chain name too.
+ if (nameChanged) {
+ const onchainCollection = await fetchCollection(umi, collectionPk);
+ const nameRes = await update(umi, {
+ asset: onchainAsset,
+ collection: onchainCollection,
+ name: next.name,
+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
+ signatures.name = base58Sig(nameRes.signature);
+ }
+ } catch (e) {
+ return error(res, 502, 'onchain_edit_failed', `on-chain edit failed: ${e?.message || e}`);
}
- } catch (e) {
- return error(res, 502, 'onchain_edit_failed', `on-chain edit failed: ${e?.message || e}`);
}
- // Keep the off-chain row in sync with what we just wrote on-chain.
- const [updated] = await sql`update agent_identities set name=${next.name}, description=${next.description}, skills=${next.skills}, avatar_id=${next.avatar_id}, updated_at=now() where id=${agent.id} returning id, name, description, skills, avatar_id, wallet_address, meta, updated_at`;
+ // Keep the off-chain row in sync (name/description/avatar are real columns).
+ const [updated] = await sql`update agent_identities set name=${next.name}, description=${next.description}, avatar_id=${next.avatar_id}, updated_at=now() where id=${agent.id} returning id, name, description, avatar_id, wallet_address, meta, updated_at`;
return json(res, 200, {
ok: true,
diff --git a/api/nft/mint-scene-confirm.js b/api/nft/mint-scene-confirm.js
index 899babf70..856ca1adf 100644
--- a/api/nft/mint-scene-confirm.js
+++ b/api/nft/mint-scene-confirm.js
@@ -1,7 +1,6 @@
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) => {
diff --git a/api/payments/solana/[action].js b/api/payments/solana/[action].js
index a99b4d39d..3840bfed1 100644
--- a/api/payments/solana/[action].js
+++ b/api/payments/solana/[action].js
@@ -1,7 +1,6 @@
// Consolidated Solana payment endpoints (checkout + confirm).
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';
diff --git a/scripts/migrate-solana-connection.mjs b/scripts/migrate-solana-connection.mjs
deleted file mode 100644
index 5ecef06e3..000000000
--- a/scripts/migrate-solana-connection.mjs
+++ /dev/null
@@ -1,82 +0,0 @@
-// 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`);