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.

12.2 KB
Raw Blame
/**
 * Solana deploy flow — Metaplex Core NFT minted via the user's wallet.
 *
 * Mirrors the EVM register flow in deploy-button.js but for Solana:
 *   1. POST /api/agents/solana-register-prep    — server builds an unsigned
 *      Metaplex Core createV1 transaction (base64) for `wallet_address`.
 *      The tx is Solana transaction v1 when the connected wallet advertises v1
 *      through Wallet Standard, otherwise v0.
 *   2. Phantom (or any compatible Solana wallet) signs and submits the tx.
 *   3. POST /api/agents/solana-register-confirm — server verifies the tx and
 *      upserts the agent_identity row with chain_type='solana'.
 *
 * Wallet must be linked to the user account via SIWS first; the prep endpoint
 * returns 403 otherwise.
 */

import { Connection, Keypair, Transaction, VersionedTransaction } from '@solana/web3.js';
import { getWallets } from '@wallet-standard/app';
import { grindVanity } from '../solana/vanity/grinder.js';
import { findV1WalletStandardSigner } from '../onchain/adapters/solana.js';

/** Detect an injected Solana wallet (Phantom / Backpack / Solflare / Seeker). */
export function detectSolanaWallet() {
	if (typeof window === 'undefined') return null;
	// Seeker/Saga TWA: isPhantom=false on purpose (it isn't Phantom) — check
	// its own isThreeWs flag first, same order as
	// src/onchain/adapters/solana.js.
	if (window.threeWsWallet?.isThreeWs) return window.threeWsWallet;
	if (window.solana?.isThreeWs) return window.solana;
	if (window.phantom?.solana?.isPhantom) return window.phantom.solana;
	if (window.solana?.isPhantom) return window.solana;
	if (window.backpack?.solana) return window.backpack.solana;
	if (window.solflare?.isSolflare) return window.solflare;
	return null;
}

// Route through our same-origin proxy. The public mainnet RPC returns 403 to
// most browser origins; the proxy forwards server-side to Helius when
// HELIUS_API_KEY is set, otherwise to the public RPC from a datacentre IP.
const SOLANA_RPC_ORIGIN =
	typeof window !== 'undefined' && window.location?.origin
		? window.location.origin
		: 'https://three.ws';
export const SOLANA_RPC = {
	mainnet: `${SOLANA_RPC_ORIGIN}/api/solana-rpc`,
	devnet: `${SOLANA_RPC_ORIGIN}/api/solana-rpc?net=devnet`,
};
const RPC = SOLANA_RPC;

export function solanaTxExplorerUrl(network, sig) {
	return network === 'devnet'
		? `https://explorer.solana.com/tx/${sig}?cluster=devnet`
		: `https://solscan.io/tx/${sig}`;
}

/** @param {string} b64 */
function base64ToBytes(b64) {
	const bin = atob(b64);
	const bytes = new Uint8Array(bin.length);
	for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
	return bytes;
}

/** @param {string} b64 */
function decodeBase64Tx(b64) {
	const bytes = base64ToBytes(b64);
	// Server uses Umi's buildAndSign which produces a versioned tx.
	try {
		return VersionedTransaction.deserialize(bytes);
	} catch {
		return Transaction.from(bytes);
	}
}

// Poll signature status over HTTP. Avoids Connection.confirmTransaction, which
// opens a WebSocket subscription — public mainnet-beta refuses WS, so the
// confirm step hangs until the wallet times out.
async function waitForSolanaConfirmation(conn, signature, timeoutMs) {
	const deadline = Date.now() + timeoutMs;
	while (Date.now() < deadline) {
		const { value } = await conn.getSignatureStatuses([signature]);
		const status = value?.[0];
		if (status) {
			if (status.err) {
				throw new Error(`Tx failed: ${JSON.stringify(status.err)}`);
			}
			if (
				status.confirmationStatus === 'confirmed' ||
				status.confirmationStatus === 'finalized'
			) {
				return;
			}
		}
		await new Promise((r) => setTimeout(r, 1500));
	}
	throw new Error('Timed out waiting for Solana transaction confirmation.');
}

/**
 * Fill a browser-held signer's slot (the vanity asset key) in a v1 wire
 * transaction. @solana/web3.js cannot parse v1, so this uses @solana/kit, loaded
 * only on this path. Kit refuses a key that is not a required signer.
 * @param {Uint8Array} wireBytes
 * @param {Uint8Array} secretKey 64-byte ed25519 secret key
 * @returns {Promise<Uint8Array>}
 */
export async function cosignV1Transaction(wireBytes, secretKey) {
	const { createKeyPairFromBytes, getTransactionDecoder, getTransactionEncoder, partiallySignTransaction } =
		await import('@solana/kit');
	const keyPair = await createKeyPairFromBytes(secretKey);
	const signed = await partiallySignTransaction([keyPair], getTransactionDecoder().decode(wireBytes));
	return new Uint8Array(getTransactionEncoder().encode(signed));
}

/**
 * Wallet extensions (Phantom and Phantom-compatible injectors) throw
 * `{ code: -32603, message: 'An internal error has occurred' }` when their
 * background service worker is wedged or asleep. A second call after a short
 * pause routinely succeeds, so retry once before surfacing the failure.
 */
const WALLET_INTERNAL_ERROR = -32603;

export function isWalletInternalError(e) {
	return e?.code === WALLET_INTERNAL_ERROR
		|| /internal error has occurred/i.test(e?.message || '');
}

export async function withWalletRetry(step, fn) {
	try {
		return await fn();
	} catch (first) {
		if (!isWalletInternalError(first)) throw tagStep(first, step);
		await new Promise((r) => setTimeout(r, 800));
		try {
			return await fn();
		} catch (second) {
			throw tagStep(second, step);
		}
	}
}

const STEP_LABELS = {
	connect: 'Wallet connection failed',
	prepare: 'Could not build the mint transaction',
	sign: 'Wallet signature failed',
	send: 'Could not broadcast the transaction',
};

/** Prefix the failing step onto the error without losing code/status. */
export function tagStep(e, step) {
	if (e?.step) return e;
	const label = STEP_LABELS[step] || step;
	const err = new Error(`${label}: ${e?.message || String(e)}`);
	err.step = step;
	if (e?.code !== undefined) err.code = e.code;
	if (e?.status !== undefined) err.status = e.status;
	if (e?.txSignature !== undefined) err.txSignature = e.txSignature;
	return err;
}

/** Sign a v0/legacy prep with the injected provider. */
async function signV0({ prep, wallet, vanityKeypair }) {
	const tx = decodeBase64Tx(prep.tx_base64);
	// If we used a vanity keypair, the server built the tx with a noop signer
	// for the asset slot, so fill it in before the wallet signs.
	// VersionedTransaction.sign() only modifies signatures whose pubkey matches
	// a provided signer, so the wallet sig slot is preserved as zero for Phantom.
	if (vanityKeypair && tx instanceof VersionedTransaction) {
		tx.sign([vanityKeypair]);
	} else if (vanityKeypair && tx instanceof Transaction) {
		tx.partialSign(vanityKeypair);
	}
	const signed = await withWalletRetry('sign', () => wallet.signTransaction(tx));
	return signed.serialize();
}

/** Sign a v1 prep: vanity co-signature first, then the wallet over raw bytes. */
async function signV1({ prep, v1Signer, vanityKeypair }) {
	if (!v1Signer) {
		const err = new Error('This wallet does not advertise Solana transaction v1 signing.');
		err.code = 'TX_VERSION_UNSUPPORTED';
		throw tagStep(err, 'sign');
	}
	let bytes = base64ToBytes(prep.tx_base64);
	if (vanityKeypair) {
		try {
			bytes = await cosignV1Transaction(bytes, vanityKeypair.secretKey);
		} catch (e) {
			throw tagStep(e, 'sign');
		}
	}
	const [result] = await withWalletRetry('sign', () =>
		v1Signer.feature.signTransaction({
			account: v1Signer.account,
			transaction: bytes,
			options: { preflightCommitment: 'confirmed' },
		}),
	);
	if (!result?.signedTransaction) {
		throw tagStep(new Error('Wallet returned no signed v1 transaction.'), 'sign');
	}
	return result.signedTransaction;
}

/**
 * Run the Solana deploy flow end-to-end.
 *
 * @param {object} opts
 * @param {object} opts.agent       Agent record. Required: id, name. Optional: avatarId, description.
 * @param {'mainnet'|'devnet'} opts.network
 * @param {object} [opts.vanity]    Optional vanity prefix config.
 * @param {string} [opts.vanity.prefix]                            Base58 prefix to grind.
 * @param {(p: { attempts: number, rate: number, eta: string }) => void} [opts.vanity.onProgress]
 * @param {AbortSignal} [opts.vanity.signal]
 * @param {Uint8Array} [opts.vanity.preGroundSecretKey]            64-byte Ed25519 secret key from a CLI grinder
 *   (e.g. nirholas/solana-wallet-toolkit). When present, the in-browser grinder
 *   is skipped and this keypair is used directly. The caller is responsible for
 *   verifying the public key matches `vanity.prefix`.
 * @returns {Promise<{ assetPubkey: string, txSignature: string, network: string, agent: object, transactionVersion: 0|1, vanityPrefix?: string }>}
 */
export async function runSolanaDeploy({ agent, network, vanity }) {
	const wallet = detectSolanaWallet();
	if (!wallet) {
		const err = new Error('No Solana wallet detected. Install Phantom to continue.');
		err.code = 'NO_WALLET';
		throw err;
	}

	const conn = await withWalletRetry('connect', () => wallet.connect());
	const walletAddress = (conn?.publicKey || wallet.publicKey)?.toString();
	if (!walletAddress) throw new Error('Could not read Solana wallet address.');
	const v1Signer = findV1WalletStandardSigner(getWallets().get(), walletAddress);

	// Optional: grind a vanity asset keypair before asking the server to build the tx.
	// Or accept a pre-ground keypair from a CLI grinder (faster for prefixes >=5 chars).
	let vanityKeypair = null;
	if (vanity?.preGroundSecretKey) {
		vanityKeypair = Keypair.fromSecretKey(vanity.preGroundSecretKey);
		if (vanity.prefix && !vanityKeypair.publicKey.toBase58().startsWith(vanity.prefix)) {
			throw new Error(`Pre-ground keypair does not start with prefix "${vanity.prefix}".`);
		}
	} else if (vanity?.prefix) {
		const result = await grindVanity({
			prefix: vanity.prefix,
			onProgress: vanity.onProgress,
			signal: vanity.signal,
		});
		vanityKeypair = Keypair.fromSecretKey(result.secretKey);
	}

	const prepResp = await fetch('/api/agents/solana-register-prep', {
		method: 'POST',
		credentials: 'include',
		headers: { 'content-type': 'application/json' },
		body: JSON.stringify({
			name: agent.name || 'Agent',
			description: agent.description || '',
			avatar_id: agent.avatarId || agent.avatar_id,
			wallet_address: walletAddress,
			network,
			transaction_version: v1Signer ? 1 : 0,
			...(vanityKeypair ? {
				asset_pubkey: vanityKeypair.publicKey.toBase58(),
				vanity_prefix: vanity.prefix,
			} : {}),
		}),
	});
	if (!prepResp.ok) {
		const data = await prepResp.json().catch(() => ({}));
		const err = new Error(
			data.error_description || `solana-register-prep returned ${prepResp.status}`,
		);
		err.status = prepResp.status;
		err.code = data.error;
		throw err;
	}
	const prep = await prepResp.json();

	// Always sign locally and submit via our Helius-backed proxy. Wallet
	// `signAndSendTransaction` routes through the wallet's own RPC, which
	// returns 403 "Access forbidden" intermittently on mainnet.
	const endpoint = RPC[network] || RPC.mainnet;
	const raw = prep.transaction_version === 1
		? await signV1({ prep, v1Signer, vanityKeypair })
		: await signV0({ prep, wallet, vanityKeypair });
	const conn2 = new Connection(endpoint, 'confirmed');
	let signature;
	try {
		signature = await conn2.sendRawTransaction(raw, {
			skipPreflight: false,
			preflightCommitment: 'confirmed',
			maxRetries: 5,
		});
	} catch (e) {
		throw tagStep(e, 'send');
	}

	// Wait for confirmation before calling the server.
	const conn3 = new Connection(endpoint, 'confirmed');
	await waitForSolanaConfirmation(conn3, signature, 60_000);

	const confirmResp = await fetch('/api/agents/solana-register-confirm', {
		method: 'POST',
		credentials: 'include',
		headers: { 'content-type': 'application/json' },
		body: JSON.stringify({
			tx_signature: signature,
			asset_pubkey: prep.asset_pubkey,
			wallet_address: walletAddress,
			network,
			name: agent.name,
			description: agent.description || '',
			avatar_id: agent.avatarId || agent.avatar_id,
		}),
	});
	if (!confirmResp.ok) {
		const data = await confirmResp.json().catch(() => ({}));
		const err = new Error(
			data.error_description || `solana-register-confirm returned ${confirmResp.status}`,
		);
		err.status = confirmResp.status;
		err.code = data.error;
		err.txSignature = signature;
		throw err;
	}
	const confirmed = await confirmResp.json();
	return {
		assetPubkey: prep.asset_pubkey,
		txSignature: signature,
		network,
		agent: confirmed.agent,
		transactionVersion: prep.transaction_version === 1 ? 1 : 0,
		...(vanity?.prefix ? { vanityPrefix: vanity.prefix } : {}),
	};
}