library / AI and blockchain / RAG and embeddings / SI0120
Search query type router
A Node script classifies a pasted string by shape, sends it to getBlockTime, getSignatureStatuses or getAccountInfo, hands free text to a name index, and checks every name hit on chain before it reports a mint.
One box, four kinds of input
A search box that takes one string has to guess what the string is. Solana gives that guess a lot to work with, because the things people paste have different shapes. A slot is digits. A signature is 86 to 88 base58 characters. An address is 32 to 44 base58 characters. Everything else is free text, and the chain holds no index of free text at all.
That last gap sits behind a complaint like a token that cannot be found by its name. The ledger holds mints, token accounts and metadata accounts. It has no lookup from BONK to a mint. A box that sends a name straight to an RPC method gets an error or an empty result, and the user concludes the token is missing. A router in front of the lookups fixes this: classify first, call the one method that fits, and send names to an index you built yourself.
| Input shape | Lookup | What comes back |
|---|---|---|
| Digits only, up to 12 | getBlockTime | The block time, or an error for a skipped slot |
| 86 to 88 base58 characters | getSignatureStatuses | Confirmation status and whether the transaction failed |
| 32 to 44 base58 characters | getAccountInfo | The kind of account: wallet, program, mint or token account |
| Anything else | Name index | Candidate mints to verify through the address route |
The router
Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. CARBIUM_KEY is required, and the script exits with a message when it is unset. CARBIUM_RPC_URL is optional. Arguments are the strings to route. The script also adds a recent slot and the newest signature of the token program, so one run exercises every shape.
// SI0120 · Search query type router// https://carbium.sh/library/si/search-query-type-router// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { address, createDefaultRpcTransport, createSolanaRpcFromTransport, signature } from "@solana/kit";import type { Slot } from "@solana/kit";const key: string = process.env.CARBIUM_KEY ?? "";if (!key) { console.error("Set CARBIUM_KEY to your Carbium API key."); process.exit(1);}const url = process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh";const rpc = createSolanaRpcFromTransport(createDefaultRpcTransport({ url, headers: { "x-api-key": key } }));const TOKEN = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";const TOKEN_PROGRAMS = new Set([TOKEN, "TokenzQdBNbLqP5VEhdkAS6EPFLC1PHnBqCXEpPxuEb"]);const SYSTEM = "11111111111111111111111111111111";// A stand-in for a real name index: lower-case symbol to mint.const NAMES = new Map([ ["usdc", "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"], ["usdt", "Es9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB"], ["wsol", "So11111111111111111111111111111111111111112"],]);const B58 = "[1-9A-HJ-NP-Za-km-z]";const SIG = new RegExp(`^${B58}{86,88}$`);const ADDR = new RegExp(`^${B58}{32,44}$`);async function route(q: string, depth = 0): Promise<string> { if (/^\d{1,12}$/.test(q)) { const t = await rpc.getBlockTime(BigInt(q) as Slot).send(); return `slot -> getBlockTime ${t === null ? "no block time" : new Date(Number(t) * 1000).toISOString()}`; } if (SIG.test(q)) { const { value } = await rpc.getSignatureStatuses([signature(q)], { searchTransactionHistory: true }).send(); const s = value[0]; return `signature -> getSignatureStatuses ${s ? `${s.confirmationStatus ?? "?"}, ${s.err ? "failed" : "ok"}` : "unknown signature"}`; } if (ADDR.test(q)) { const { value } = await rpc.getAccountInfo(address(q), { encoding: "jsonParsed", commitment: "confirmed" }).send(); if (!value) return "address -> no account (unfunded wallet or closed)"; if (value.executable) return "address -> program"; const parsed = (value.data as unknown as { parsed?: { type?: string; info?: { mint?: string } } }).parsed; if (TOKEN_PROGRAMS.has(value.owner)) { if (parsed?.type === "mint") return "address -> token mint"; if (parsed?.type === "account") return `address -> token account of mint ${parsed.info?.mint}`; } return value.owner === SYSTEM ? "address -> wallet" : `address -> account owned by ${value.owner.slice(0, 8)}`; } const hit = NAMES.get(q.toLowerCase()); if (hit && depth === 0) return `name index -> ${hit}; then ${await route(hit, 1)}`; return "text -> name index, no match";}const queries = process.argv.slice(2);if (queries.length === 0) queries.push("USDC");// Two live samples so a run shows the slot and signature routes too.try { const slot = await rpc.getSlot().send(); queries.push(String(slot - 150n)); const [newest] = await rpc.getSignaturesForAddress(address(TOKEN), { limit: 1 }).send(); if (newest) queries.push(newest.signature);} catch (e) { console.error(`live sample failed: ${e instanceof Error ? e.message : e}`);}for (const q of queries) { try { console.log(`${q.slice(0, 16)}: ${await route(q)}`); } catch (e) { console.error(`${q.slice(0, 16)}: ${e instanceof Error ? e.message : e}`); }}
run: node main.ts
Each query prints one line that starts with the route taken. The shape tests run first and make no network call. A text query that matches the small name index prints the mint, then runs that mint through the address route, so a name hit is always checked on chain before anyone relies on it.
What an address turns out to be
A pasted address can be several different things, and one getAccountInfo call with jsonParsed encoding tells them apart. No account at all means an unfunded wallet or a closed account. An executable account is a program. An account owned by a token program is a mint or a token account, and the parsed type field says which. An account owned by the system program is a plain wallet. Anything else belongs to some other program, and the router prints the first characters of that owner. The call names confirmed commitment itself, so the answer never depends on a client default.
The split between mint and token account is where many failed searches start. A wallet can own more than one token account for one mint, and each has its own address. A user who copies the address from a wallet's token list often copies a token account, and a search for it as a mint finds nothing. The router prints token account of mint followed by the mint address, and that mint is the address the search should have used. Token program detection covers telling the two token programs apart.
Names need their own index
Free text goes to an index you keep. The sample file holds a three-entry Map, enough to show the hand-off. A real one is a table of mints with symbol, name and a short description, filled from the metadata accounts you read. A legacy token keeps its name in a metadata account of its own. A Token-2022 mint can hold the name inside the mint, but only after the metadataPointer extension names the mint itself as the place. A mint with neither has no name anywhere on chain, so no index can find it by name. That explains some tokens that cannot be found by name, and a search box should tell the user so.
For a RAG pipeline the name index has two stages. Exact match on symbol and name comes first because it is cheap and precise. An embedding search over name and description comes second and catches misspellings and loose descriptions such as the dog coin. Embeddings return candidates with scores and never an answer. Two mints can carry one symbol, and a close lookalike can score higher than the original.
What a route costs
The shape tests are free, and a name query costs nothing until a candidate is verified. The address route spends one getAccountInfo, an account read at 10 cells a call: 0.5 req/s on Free, 15 on Dev, 50 on Business and 400 on Pro. On Free that is one verified address every two seconds, so a router behind a public box wants a cache of verified mints in front of it. The slot sample uses getSlot, a cheap read at 1 cell. Everything goes to the RPC endpoint, https://services.carbium.sh, with the key in the x-api-key header.
Where it ends
- A string that passes the address shape can still be a typo. getAccountInfo answers no account for it, and the router cannot tell a typo from an unfunded wallet.
- A signature with no status can be one that never landed, was dropped, or is older than the node holds. Absence from one call proves nothing about the chain.
- A slot that answers with an error in place of a time was skipped, or sits outside what the node holds. Try the next one.
- The name index is only as good as what you put in it. The sample has three entries and no embeddings.
- Embedding scores rank candidates. They do not tell you which mint the user meant.
- The script reads only. For a full account breakdown after routing, see the address type explainer.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The line reads address -> no account (unfunded wallet or closed) for an address the user swears is a token. | The user pasted a mistyped address, a closed account or a wallet that never held SOL. Ask for the mint from the token's own page, and check the characters again before blaming the index. |
| The line reads address -> token account of mint X. | The user copied a token account from a wallet list. Route X instead, and tell the user which address they sent. |
| A signature prints unknown signature. | The transaction never landed, was dropped, or is older than the node reports. Wait a few seconds and ask again before telling the user it failed. |
| Text prints text -> name index, no match. | The mint has no name in an indexed metadata account, or your index has not seen it. Ask for the address, and do not guess from the closest name. |
| The call fails with HTTP 401. | The key is unknown or cut short. Attach the whole key in CARBIUM_KEY. |
| A burst of lookups ends in HTTP 429. | Read the retry-after hint on the 429 and wait that long. Cache verified mints so a repeated search makes no call. |
Questions
Why does a block explorer fail to find a token by name?
The chain stores no lookup from names to mints. A name search needs an index that someone built from metadata accounts, and a mint with no metadata is not in it.
Do I need embeddings for this?
Only for the text path. Addresses, signatures and slots route by shape, and exact match covers most names. Embeddings help with misspellings and descriptions, and their hits still need the on-chain check.
How does the router tell a signature from an address?
By length. A signature is 86 to 88 base58 characters and an address is 32 to 44, so the two ranges never overlap.
Why call getAccountInfo and not getTokenSupply on every address?
getAccountInfo answers for any account kind in one call, while a supply read only works on a mint and errors on the rest. Use the supply read after the router says mint.