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.

1.7 KB
Raw Blame
import { PublicKey, type Connection } from "@solana/web3.js";
import { TOKEN_PROGRAM_ID, TOKEN_2022_PROGRAM_ID } from "@solana/spl-token";

// A mint's owning program is fixed for the life of the mint, so caching by mint
// pubkey is always safe and turns a per-transfer RPC into a one-time lookup.
const programCache = new Map<string, PublicKey>();

/**
 * Resolve which SPL token program owns a mint — classic SPL Token vs Token-2022.
 *
 * Any helper hardcoded to TOKEN_PROGRAM_ID derives the wrong associated-token
 * address and builds against the wrong program for a Token-2022 mint, so the
 * transfer fails (or a balance lookup misses) for tokens that genuinely exist in
 * the wallet — including $THREE, which is a Token-2022 mint. The mint account's
 * owner is the canonical, on-chain way to tell the two programs apart. The result
 * is memoized for the process, so repeated transfers of the same mint hit RPC once.
 *
 * @throws if the mint account doesn't exist or isn't owned by either SPL program.
 */
export async function resolveTokenProgramId(
  connection: Connection,
  mint: PublicKey,
): Promise<PublicKey> {
  const key = mint.toBase58();
  const cached = programCache.get(key);
  if (cached) return cached;

  const info = await connection.getAccountInfo(mint);
  if (!info) throw new Error(`Mint not found: ${key}`);

  let programId: PublicKey;
  if (info.owner.equals(TOKEN_2022_PROGRAM_ID)) programId = TOKEN_2022_PROGRAM_ID;
  else if (info.owner.equals(TOKEN_PROGRAM_ID)) programId = TOKEN_PROGRAM_ID;
  else
    throw new Error(
      `Not an SPL token mint (owner ${info.owner.toBase58()}): ${key}`,
    );

  programCache.set(key, programId);
  return programId;
}