library / Integrations / I0040
Android NFT metadata endpoint
A small Node endpoint that reads an NFT's metadata account through Carbium, decodes name, symbol and uri with a length check before every read, and answers the Android app in JSON. No byte decoding runs on the phone.
What the exception says
java.nio.BufferUnderflowException comes from ByteBuffer. A relative get asked for more bytes than remain between the buffer's position and its limit. It is thrown on the phone, in the code that decodes the account, after the HTTP call has already returned. The node did not send it, and it says nothing about the key or the endpoint.
An NFT's name, symbol and image link do not sit in the mint. They sit in a separate Metaplex Token Metadata account, stored as Borsh: one key byte (4 for a metadata account), a 32-byte update authority, a 32-byte mint, then three strings in a row for name, symbol and uri. Each string is a 4-byte little-endian length followed by that many bytes. An underflow means the reader walked past the end of the data.
- The account does not exist. getAccountInfo answers null for an address with no account, and a client that turns that into an empty byte array starts its first read on zero bytes.
- The address is the mint. An SPL Token mint is 82 bytes of supply and authorities. The metadata lives at another address derived from the mint, and strings read out of a mint's bytes run off the end.
- The byte order is wrong. Borsh writes integers little-endian and ByteBuffer reads big-endian until you call order(ByteOrder.LITTLE_ENDIAN). A length of 32 then reads as 536,870,912 and the next get fails.
- The data was decoded with the wrong codec. Base58 is meant for small accounts, and a metadata account is hundreds of bytes, so ask for base64 and decode it as base64.
- The account is a different kind. An edition or a token record has another key byte and another layout, so a fixed walk over it ends early.
The endpoint does the walk on a server and checks the remaining length before every read. When the data is short it reports the offset of the read that failed and the data's length, and the app gets that back as JSON.
The account read
The endpoint sends one getAccountInfo per request to the Carbium RPC endpoint at https://services.carbium.sh, with the key in the request header x-api-key. It asks for base64 encoding at confirmed commitment. Finding the metadata address needs no call: it is a program derived address from the seed metadata, the metadata program's address and the mint, computed in code.
A getAccountInfo call counts as an account read, which costs 10 cells. The rate you get depends on the plan, and it sets how many NFTs a list screen can resolve per second.
| Plan | Account reads per second |
|---|---|
| Free | 0.5 |
| Dev | 15 |
| Business | 50 |
| Pro | 400 |
Limits are per account, so every key and every user of your app draws on the same budget. A screen that lists 20 NFTs makes 20 account reads, which is 200 cells and fits inside the burst, which is at least 1,024 cells on every plan. The limit bites when a list keeps scrolling past the burst. After that a Free account refills one account read every 2 s, so the app should cache results by mint.
The endpoint
Install the one dependency with npm install @solana/[email protected] and set "type": "module" in package.json. Node 24 strips the types on load. CARBIUM_KEY is required and the file exits with a message when it is unset. CARBIUM_RPC_URL, HOST (default 127.0.0.1) and PORT (default 8788) are optional. A mint as the first argument turns on a startup check.
// I0040 · Android NFT metadata endpoint// https://carbium.sh/library/integrate/android-nft-metadata-endpoint// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createServer } from "node:http";import * as kit from "@solana/kit";const apiKey = process.env.CARBIUM_KEY;if (!apiKey) { console.error("Set CARBIUM_KEY to your Carbium key."); process.exit(1);}const rpc = kit.createSolanaRpcFromTransport( kit.createDefaultRpcTransport({ url: process.env.CARBIUM_RPC_URL ?? "https://services.carbium.sh", headers: { "x-api-key": apiKey }, }),);const METADATA_PROGRAM = kit.address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");const encoder = kit.getAddressEncoder();type Fail = { status: number; error: string; retryAfter?: string };function fail(status: number, error: string, retryAfter?: string): never { throw { status, error, retryAfter };}// Carbium or the network said no: keep a 429 and its hint, call the rest a bad gateway.function upstream(e: unknown): never { if (kit.isSolanaError(e, kit.SOLANA_ERROR__RPC__TRANSPORT_HTTP_ERROR)) { const code = e.context.statusCode; return fail(code === 429 ? 429 : 502, `Carbium answered HTTP ${code}`, e.context.headers.get("retry-after") ?? undefined); } return fail(502, e instanceof Error ? e.message : "call failed");}// Key byte 4, update authority (32), mint (32), then name, symbol and uri as length-prefixed text.function parse(data: Buffer) { let at = 0; const take = (n: number, what: string) => { if (at + n > data.length) fail(422, `${what} at byte ${at} needs ${n} bytes, data has ${data.length}`); at += n; return data.subarray(at - n, at); }; if (data[0] !== 4) fail(422, `not a metadata account (${data.length} bytes, key ${data[0]})`); take(65, "header"); const str = () => take(take(4, "length").readUInt32LE(), "string").toString("utf8").replace(/\0+$/, ""); return { name: str(), symbol: str(), uri: str() };}async function lookup(mint: string) { if (!kit.isAddress(mint)) fail(400, "not a Solana address"); const [metadata] = await kit.getProgramDerivedAddress({ programAddress: METADATA_PROGRAM, seeds: ["metadata", encoder.encode(METADATA_PROGRAM), encoder.encode(mint)], }); const res = await rpc .getAccountInfo(metadata, { commitment: "confirmed", encoding: "base64" }) .send({ abortSignal: AbortSignal.timeout(5_000) }) .catch(upstream); const acct = res.value; if (!acct || acct.owner !== METADATA_PROGRAM) fail(404, "no metadata account"); return { mint, metadata, ...parse(Buffer.from(acct.data[0], "base64")), slot: String(res.context.slot) };}async function answer(mint?: string): Promise<{ status: number; body: object; retryAfter?: string }> { try { if (!mint) fail(404, "GET /metadata/<mint>"); return { status: 200, body: await lookup(mint) }; } catch (e) { const f = e as Partial<Fail>; return { status: f.status ?? 502, body: { error: f.error ?? String(e) }, retryAfter: f.retryAfter }; }}if (process.argv[2]) { const r = await answer(process.argv[2]); console.log("startup check", r.status, JSON.stringify(r.body)); if (r.status !== 200) process.exit(1);}const host = process.env.HOST ?? "127.0.0.1";const port = Number(process.env.PORT ?? 8788);createServer(async (req, res) => { const match = /^\/metadata\/([1-9A-HJ-NP-Za-km-z]{32,44})$/.exec((req.url ?? "").split("?")[0] ?? ""); const r = await answer(req.method === "GET" ? match?.[1] : undefined); res.writeHead(r.status, { "content-type": "application/json", ...(r.retryAfter ? { "retry-after": r.retryAfter } : {}) }); res.end(JSON.stringify(r.body));}).listen(port, host, () => console.log(`endpoint listening on ${host}:${port}`));
run: node main.ts
parse is the part that replaces your ByteBuffer code. Its take helper keeps a position, and every call compares the bytes it needs with the data length before it slices, so a short account ends in a 422 that gives the offset of the failed read and the data's length. On-chain strings are padded with NUL bytes to a fixed size (32 for the name, 10 for the symbol, 200 for the uri), so the decoder trims them before they reach the app.
The Kotlin side
The app calls GET /metadata/<mint> and reads JSON. Nothing in the app touches a byte array, so no ByteBuffer and no Borsh code is left to underflow. OkHttp or HttpURLConnection both work, and the call has to run off the main thread, for example on Dispatchers.IO, or Android throws NetworkOnMainThreadException. slot arrives as a string, and org.json.JSONObject or kotlinx.serialization reads the rest.
| Status | When | Body |
|---|---|---|
| 200 | The metadata account decoded. | mint, metadata, name, symbol, uri, slot, all strings. |
| 400 | The string in the path has the shape of an address but does not decode to one. | error |
| 404 | The mint has no Metaplex metadata account, or the path is not GET /metadata/<mint>. | error |
| 422 | The account exists but does not decode, because it is short or is not a metadata account. | error, with the offset of the failed read and the data's length. |
| 429 | Carbium rate-limited the call. | error, and the retry-after header when Carbium sent one. |
| 502 | Any other failure between the endpoint and Carbium, a timeout after 5 seconds included. | error |
Keep a map from mint to result in the app, with an expiry. Metadata changes only when its update authority edits it, so a result stays good for a long time, and every cached mint is one account read the app does not spend from its plan's rate.
The uri field points to an off-chain JSON file that holds the image link and attributes. The app fetches that file with its own HTTP client, and Carbium is not in that path. On the emulator, the machine running the endpoint is 10.0.2.2. Android blocks plain HTTP by default since API 28, so a device needs the endpoint behind TLS.
Run it and test from curl
Start it with node main.ts <mint>. The startup check resolves that mint once, prints the status, name, symbol and uri, and exits with code 1 when the status is not 200, so a wrong key stops the process before it serves. Then run curl http://127.0.0.1:8788/metadata/<mint> on the same machine.
If curl returns the JSON and the app still throws BufferUnderflowException, the app is still decoding bytes somewhere. Search the project for ByteBuffer.wrap and Base64.decode around the account call and delete that path. If curl returns 404 or 422, the message names the case from the list above.
Where it ends
- It decodes the Metaplex Token Metadata account only. A Token-2022 mint that keeps its name only inside the mint has no such account and gets 404; see Token-2022 metadata lookup.
- It returns name, symbol and uri. Creators, royalty basis points and collection fields sit after the uri in the same account and are not decoded here.
- It reads one mint per call. A collection mint has its own metadata account, so the endpoint returns the collection's own record, and each member mint takes its own call; for many mints at once, see Bulk NFT metadata reader.
- It reads at confirmed, so a mint created seconds ago can answer 404 until its metadata account is written.
- It has no cache and no login. Every app request is one account read, and the app's cache is what keeps the count down.
- It does not fetch the off-chain JSON at the uri, and it signs and sends nothing.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| The endpoint answers 404 with no metadata account. | A wallet or token account address in the path derives a metadata address where no account exists, so put the NFT's mint address in the path. If the path already holds a mint that shows a name elsewhere, the token probably keeps its name only inside a Token-2022 mint, or the mint is brand new. See Token-2022 metadata lookup. |
| The endpoint answers 422 with a message such as string at byte 69 needs 40 bytes, data has 72. | The account at the derived address has key byte 4 but is shorter than its own length prefixes claim. The byte number is where the failing read started, and data has 72 is the account's length, so here the length prefix at bytes 65 to 68 promised 40 bytes and only 3 remain. An account with any other key byte gets the not a metadata account message instead. |
| curl returns the metadata and the app still throws BufferUnderflowException. | A decoder is still running in the app. Remove the ByteBuffer path around the account call and read the endpoint's JSON instead. |
| A list screen shows some rows blank and the endpoint answers the app with 429. | Account reads cost 10 cells and a Free account gets 0.5 per second. Cache each mint in the app and resolve rows as they scroll into view. Read the retry-after header before you retry. |
| The endpoint answers 502 with Carbium answered HTTP 401. | Carbium does not know the key. Put the whole key in CARBIUM_KEY. |
| The name shows trailing blanks or odd characters in the app. | On-chain strings are padded with NUL bytes. The endpoint trims them, so a name that still looks wrong is coming from a decoder in the app. |
Questions
Can I decode the account on the phone instead?
Yes. Read integers little-endian, check the remaining bytes before every read and ask for base64. The endpoint keeps that logic in one place you can test with curl, and it keeps the Carbium key off the device.
Do I pass the mint or the metadata account address?
The mint. The endpoint derives the metadata address from it, so the app only ever holds the address it already knows from a wallet or a listing.
Does this work for a collection NFT?
It returns the collection mint's own record, since a collection NFT is a mint with its own metadata account. Its members are other mints, each with a record of its own.
Why does the app read a slot at all?
The slot tells you which state the read saw. Two reads that return the same slot came from the same moment, and a higher slot is newer.