library / Integrations / Serverless and edge / I0059
Cloudflare R2 NFT image cache
Plan an R2 cache for NFT metadata from chain state: each mint's URI hash becomes the object key and its isMutable flag sets Cache-Control, so a pass lists what to keep, fetch and recheck.
The two halves
A backend that shows NFTs should hit each origin host once and then answer from its own bucket. Two things decide that: which URL each NFT points to, and whether that URL can still change. Both sit on chain, in the Token Metadata account of every mint, so the cache policy can come from chain state.
The work splits in two. main.ts is the chain half. It collects mints, reads their metadata accounts through the Carbium RPC endpoint and prints one plan row per mint: the object key, the Cache-Control value and an action. The R2 half lives in your own service. It reads those rows, fetches the URI for every row marked fetch or recheck, and writes the bytes into the bucket under the row's key with the row's Cache-Control.
Reading name, URI and the flag
A mint's name, symbol and URI sit in a Token Metadata account at an address derived from the seed metadata, the program address and the mint. The account is Borsh: a key byte (4 for a metadata account), a 32-byte update authority, a 32-byte mint, then name, symbol and URI as length-prefixed strings. Two bytes of seller fee basis points follow, then the creator list: an option byte and, when it is 1, a 4-byte count and 34 bytes per creator.
The two bytes right after the creator list are primarySaleHappened and isMutable. The edition nonce, token standard, collection, uses and more come after them, and the account is padded to a fixed size, so the code reads the flag by position and ignores the tail. Strings are NUL-padded to 32, 10 and 200 bytes, and the reader trims them.
One getMultipleAccounts call at confirmed commitment fetches up to 100 of these accounts. Carbium charges 10 cells per pubkey, so 100 pubkeys cost 1000 cells. A rate class absorbs bursts up to 1,024 cells or one second of its rate, whichever is larger. On Free, Dev and Business that is 1,024 cells, and it caps a call at 100 pubkeys. Pro's burst is larger, and a Pro call takes up to 300 pubkeys. Code written for any plan sends at most 100.
Key and policy table
The object key is the SHA-256 of the URI in hex, under meta/. A key built from the URI hash changes whenever the URI does, so a pass never reads a stale copy of an old URI. The Cache-Control value comes from isMutable.
| isMutable | Cache-Control | What chain state says |
|---|---|---|
| false | public, max-age=31536000, immutable | Nobody can change the name, symbol or URI any more, so the key stays valid for good. |
| true | public, max-age=3600 | The update authority can point the account at a new URI, which moves the key. |
The JSON at the URI names an image. The R2 half keys that image by the SHA-256 of its URL and gives it the Cache-Control of the row it came from, so one pass plans the JSON and the picture behind it.
The pass against the bucket listing
Export the bucket's key list to a file, one key per line, from any S3 client pointed at R2, for example the meta/ prefix of a list-objects-v2 call. main.ts reads bucket-keys.txt from its working directory, and a missing file reads as an empty bucket. Each row then gets one action.
| Action | When | What the R2 half does |
|---|---|---|
| fetch | The key is missing from the listing | GET the URI and PUT the bytes with the row's Cache-Control and the origin's ETag. |
| keep | The key is listed and isMutable is false | Nothing. |
| recheck | The key is listed and isMutable is true | After max-age, send a conditional GET with the stored ETag and PUT only when the origin answers with new bytes. |
Recheck exists because the chain can tell you a URI is unchanged and can never tell you what the host serves behind it. When the owner edits the URI, the key moves and the row turns into a fetch by itself.
The chain half
Install 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 CARBIUM_RPC_URL is optional. Mints given as arguments are planned as they are. With none, main.ts takes the newest signatures of the Token Metadata program, reads up to 12 of those transactions as version 1 with jsonParsed, and collects the mints whose token balance has 0 decimals, up to 25.
// I0059 · Cloudflare R2 NFT image cache// https://carbium.sh/library/integrate/cloudflare-r2-nft-image-cache// Copyright (c) Carbium Corporation. MIT License (LICENSE). Keep this notice.// SPDX-License-Identifier: MITimport { createHash } from "node:crypto";import { readFileSync } from "node:fs";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 PROGRAM = kit.address("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");const CAP = 25; // mints per passconst WALK = 12; // newest transactions to read when no mint is givenconst CACHE = { immutable: "public, max-age=31536000, immutable", mutable: "public, max-age=3600" };const encoder = kit.getAddressEncoder();// Mints with 0 decimals from the program's newest transactions; each lookup may fail alone.async function discover(): Promise<string[]> { const sigs = await rpc.getSignaturesForAddress(PROGRAM, { limit: 40 }).send(); const mints = new Set<string>(); for (const s of sigs.filter((x) => x.err === null).slice(0, WALK)) { if (mints.size >= CAP) break; try { const tx = await rpc .getTransaction(s.signature, { encoding: "jsonParsed", maxSupportedTransactionVersion: 1 }) .send(); for (const b of tx?.meta?.postTokenBalances ?? []) if (b.uiTokenAmount.decimals === 0) mints.add(b.mint); } catch (e) { console.error("getTransaction failed:", e instanceof Error ? e.message : e); } } return [...mints].slice(0, CAP);}// Key 4, authority (32), mint (32), name, symbol, uri, fee (2), creators, then primarySaleHappened and isMutable.function read(data: Buffer) { let at = 65; const str = () => { const n = data.readUInt32LE(at); at += 4 + n; return data.subarray(at - n, at).toString("utf8").replace(/\0+$/, ""); }; str(); str(); const uri = str(); at += 2; if (data[at++] === 1) at += 4 + 34 * data.readUInt32LE(at); return { uri, mutable: data[at + 1] === 1 };}let listed = new Set<string>();try { listed = new Set(readFileSync("bucket-keys.txt", "utf8").split("\n").filter(Boolean));} catch {}const mints = (process.argv.length > 2 ? process.argv.slice(2) : await discover()).slice(0, 100);if (!mints.length) { console.log("no decimals-0 mint in the newest transactions; pass mints as arguments"); process.exit(0);}const metadata = await Promise.all( mints.map(async (m) => { const seeds = ["metadata", encoder.encode(PROGRAM), encoder.encode(kit.address(m))]; return (await kit.getProgramDerivedAddress({ programAddress: PROGRAM, seeds }))[0]; }),);const res = await rpc.getMultipleAccounts(metadata, { commitment: "confirmed", encoding: "base64" }).send();const tally: Record<string, number> = {};res.value.forEach((acct, i) => { try { if (!acct || acct.owner !== PROGRAM) throw new Error("no metadata account"); const data = Buffer.from(acct.data[0], "base64"); if (data[0] !== 4) throw new Error(`key byte ${data[0]}`); const { uri, mutable } = read(data); if (!uri) throw new Error("empty uri"); const key = `meta/${createHash("sha256").update(uri).digest("hex")}.json`; const action = !listed.has(key) ? "fetch" : mutable ? "recheck" : "keep"; tally[action] = (tally[action] ?? 0) + 1; console.log(mints[i], key, mutable ? CACHE.mutable : CACHE.immutable, action); } catch (e) { tally.skip = (tally.skip ?? 0) + 1; console.log(mints[i], "skip:", e instanceof Error ? e.message : e); }});console.log(`slot ${res.context.slot}`, JSON.stringify(tally));
run: node main.ts
Discovery spends one getSignaturesForAddress call (50 cells) and at most 12 getTransaction calls (50 cells each), then the account read costs 10 cells per mint. A pass of 25 mints spends 50 cells in address signatures, at most 600 in transaction lookups and 250 in account reads, each under its own class's 1,024-cell burst. maxSupportedTransactionVersion: 1 keeps a version 1 transaction from answering -32015, and the two lookups that leave commitment out run at confirmed, because kit fills it in.
Run it
node main.ts prints one line per mint with the mint, the object key, its Cache-Control and the action, then the slot of the read and a count per action. Pass your own mints as arguments to plan a known list. Write the bucket listing to bucket-keys.txt first and the next pass shows keep and recheck rows where fetch stood before.
Where it ends
- Immutable fixes the name, symbol and URI only. Other fields in the account, such as collection verification, can still change.
- Only the bytes behind a plain https URI can change, and only the host can tell you that. A recheck row asks the host; a keep row trusts the first copy.
- It reads Token Metadata accounts only. A Token-2022 mint that keeps its name inside the mint has no such account and prints a skip row; see Token-2022 metadata lookup.
- Discovery samples the newest transactions of the program. It lists no collection; for a known list pass mints as arguments, and for wide reads see Bulk NFT metadata reader.
- It reads at confirmed, so a mint created seconds ago can print no metadata account until its account is written.
- The chain half writes nothing and signs nothing. The bucket write, the origin fetch and the image step are yours.
When it goes wrong
| what goes wrong | what to do |
|---|---|
| Every row prints skip: no metadata account. | The argument is not a mint, or the NFT is seconds old at confirmed commitment. A wallet or token account address derives a metadata address where nothing lives, so pass the mint. |
| The run prints that no 0-decimals mint was found in the newest transactions. | The newest transactions of the program were fungible tokens or edits of existing accounts. Run it again a little later, or pass mints as arguments. |
| The run stops with an error about an invalid address before any row prints. | One mint argument is not a base58 address of 32 bytes, so kit.address throws before the account read goes out. Look for a typo, a cut-off paste or a stray character in each argument and run again. |
| A repeat pass answers HTTP 429 or waits. | The class a repeat pass drains is transaction lookups: a discovery pass spends up to 600 of its 1,024 cells, and they refill at 0.24 req/s on Free. Lower WALK and CAP, space the passes, and remember limits are per account, so every key shares one budget. |
| A mutable row never refreshes after the owner edits the NFT. | An edit of the URI changes the key, and the next pass prints fetch. If the key stayed the same, the host changed the bytes behind one URI, and the recheck row is the one that catches it. |
| The call answers 401 with UNKNOWN_KEY. | Carbium does not know the key. Put the whole key in CARBIUM_KEY. |
Questions
Why key by the URI hash when the mint is shorter?
Two mints can share one URI, and one mint can change its URI. A key from the hash stores the bytes once per URI and changes the moment the URI does.
Does the plan cover the image too?
The chain half plans the JSON at the URI. The R2 half reads the image field from the fetched JSON, keys that URL the same way and reuses the row's Cache-Control.
What about ipfs:// URIs?
The hash covers whatever string is on chain. The R2 half maps ipfs:// to a gateway you trust before it fetches, and the key stays the hash of the on-chain string.
How many mints can one pass plan?
Up to 100 per call, since the burst caps a call there below Pro. The sample here stops at 25 so the whole pass fits the burst; above 100, send more calls and watch your plan's account-read rate.