/product-sdk:product-sdk-nftsfrom product-sdk
Reads Scarcity NFT collections and item catalogues on Asset Hub. Covers getClaimableCollections, getCollections, getCollectionItems, getClaims, previewClaim, getVerifiedArtwork, and getInstanceDisplays with paged reads.
Ships in product-sdk. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
@parity/product-sdk-nfts reads the Scarcity catalogue on Asset Hub. Three catalogue functions,
all pure reads, none needing an identity, a purse or a second chain — plus getInstanceDisplays
for minted NFTs by instance id (see "Minted Instances" below). Also available as
@parity/product-sdk/nfts, the same code re-exported from @parity/product-sdk.
getClaimableCollections(chain, options?) reads the collections registered to accept claims. Powers a
picker. Every entry has a selection.getCollections(chain, options?) reads every collection, selection null where none is
registered. For browsing or auditing.getCollectionItems(chain, id, options?) reads one page of the item catalogue of a collection. Applies
no registry filter; a collection nobody created comes back as { tag: "NotFound" }. Pass
attributes: true for the open metadata bag.No read here is unbounded, and limit omitted does not mean "everything". It defaults to
DEFAULT_PAGE_LIMIT (100) and caps at MAX_PAGE_LIMIT (1000), both exported. Nothing bounds how
many collections exist or how many items a collection holds. The only ceilings the pallet has are
index-space exhaustion and the indices are u32. So a read defaulting to "everything" is one
that works until a deployment grows and then breaks a browser tab.
One vocabulary for all three reads, so a single pager works against any of them:
| in | out |
|---|---|
limit, fromId | idCeiling, nextId |
nextId === null is the only end signal. A page can be short of limit without being the
last, when a stretch of deleted or unregistered ids exhausts the scan budget. Follow the cursor
rather than counting results.
There is one kind of collection. Two maps in two pallets describe it:
Scarcity.Collections id -> { owner, item_count, … } the collection exists
NftClaims.CollectionMinters id -> { owner, selection } the owner opted in via
set_collection_minter
CollectionMinters is not a second type of collection. It is an opt-in flag with config, and its
keys are a subset of Scarcity.Collections' keys. So getCollections is the superset and
getClaimableCollections is what the registry leaves of it. How much that removes is per
deployment: one carries six collections and registers one, another registers most of what it
carries, so neither read stands in for the other.
Which to reach for:
getClaimableCollections. A collection with no minter entry
cannot be claimed into, so it does not belong in the list.getCollections. selection === null means "exists but accepts
no claims", and it is the only signal. There is no separate claimable boolean to drift.getCollectionItems. No registry filter either.All three are four storage reads a page, whatever the counts, so pick by which set you want.
Four reads is not four round trips: the PAPI getValues opens one storage operation per key, so
the operation count of a page scales with limit even though its bytes do not. What differs between the
three is which id space a page walks:
| Read | Walks |
|---|---|
getClaimableCollections | collection ids, keeping the registered ones |
getCollections | collection ids, keeping every live one |
getCollectionItems | the item indices of one collection |
Prefer getClaimableCollections whenever only claimable collections belong in the answer.
getCollectionsgetCollections is always paged, at 100 collections per page by default. Dumping the maps
whole would cost around 15 MB at ten thousand collections, most of it discarded, because the
metadata dump carries every key when only name is wanted.
const first = await getCollections(chain, { limit: 100 });
if (!first.ok) return;
render(first.value.collections);
// Pass the snapshot of the first page back in, so the whole walk addresses one block.
let fromId = first.value.nextId;
while (fromId !== null) {
const page = await getCollections(chain, { fromId, limit: 100, at: first.value.at });
if (!page.ok) throw page.error; // a failed page is not the end of the walk
render(page.value.collections); // 100, ascending by id
fromId = page.value.nextId; // null when the id space is exhausted
}
Pass at when you page. Without it every page pins its own finalized block, so the walk is not
a walk of any single chain state. itemCount can move under you and a collection deleted
mid-walk vanishes. at takes a BlockSnapshot straight from another result and costs no round
trip. It also takes "best", as PAPI's at does, to read the newest best block. Every read in this package accepts it, so a catalogue read can also address the block the
listing came from. The node must still have the block pinned, so reuse a recent snapshot rather
than a stale one.
Four storage reads per page, the id ceiling plus three keyed reads over the window, whatever
the chain holds; the keys per page scale with limit, the bytes do not. It works because ids are allocated
sequentially by the runtime (create_collection takes no id) and never reused
(delete_collection says so), so Scarcity.NextCollectionId bounds the space and every id in a
window can be read by exact key.
Two consequences worth knowing:
nextId rather than counting:
nextId === null is the only end signal. Stepping over holes costs one extra record read; a hole
never gets a name or registry lookup.getClaimableCollections takes the same limit, fromId, nextId and at. One difference:
nextId set. A short page is not the end. Follow
nextId, and on a registry that sparse the rest of it arrives in a few more pages.itemCount from either listing read tells you the size of a collection without reading its items.
Nothing caps the size of a collection. The only item ceiling the pallet has is index-space
exhaustion. TooManyItems is documented as "the per-collection item index space is exhausted", and
the index is a u32. So there is no configured limit to rely on, and 10,000 items (≈70,000 metadata
rows, about 14 MB in one response) is an afternoon of work for a collection owner.
const first = await getCollectionItems(chain, id, { limit: 100 });
if (!first.ok || first.value.tag !== "Found") return;
const at = first.value.at; // pin the whole walk to one block
let page = first.value;
for (;;) {
render(page.collection.items);
if (page.nextId === null) break; // the only end signal
const result = await getCollectionItems(chain, id, { limit: 100, fromId: page.nextId, at });
if (!result.ok) throw result.error; // a failed page is not the end of the walk
if (result.value.tag !== "Found") break; // deleted mid-walk: a real answer
page = result.value;
}
A page carries the typed fields; attributes is opt-in. ItemMetadata is keyed
(collection, item, key), so keys the SDK can name (name, image, rarity) come back for a whole
window in one exact-key read. The keys of the open bag are unknowable in advance, so filling it means a
prefix scan of the item metadata of the whole collection. That is still one read, but bytes proportional to
the catalogue rather than to the page. Pass attributes: true for a collection you know is small, or
when a caller genuinely needs app-specific keys. Left off, attributes is null, meaning "not fetched",
a different claim from an empty bag meaning "this item has no metadata".
Collection-level defaults are inherited either way, so an item resolves name / image / rarity
from its collection where it does not override them. idCeiling counts every item index ever
allocated (indices are never reused); itemCount counts the live ones.
The two disagree in one edge case, in opposite directions. A minter entry whose
Scarcity.Collections record is missing appears in getClaimableCollections with itemCount and
owner null, and cannot appear in getCollections, which enumerates the records
themselves. The runtime clears registrations through pallet_scarcity::OnCollectionDeleted, so it
should not arise. It is reported rather than papered over.
Any owner can register a collection for claims, so the claim registry is not a list to show players.
getApprovedCollections(network) returns the collections apps offer, as plain ids in display order.
It is static data shipped with the package: no chain read, no Result, nothing that can fail.
import { getApprovedCollections } from "@parity/product-sdk-nfts";
const offered = getApprovedCollections("paseo");
A network without a list returns an empty array. For names or item counts, read the collections with the reads above and keep the approved ids.
import { getChainAPI } from "@parity/product-sdk-chain-client";
import { getClaimableCollections, getCollectionItems } from "@parity/product-sdk-nfts";
const chain = await getChainAPI("paseo");
const registry = await getClaimableCollections(chain);
if (registry.ok) {
for (const collection of registry.value.collections) {
// id, name | null, selection, itemCount | null, owner | null
console.log(collection.id, collection.name ?? `Collection ${collection.id}`);
}
}
const catalogue = await getCollectionItems(chain, 3);
if (catalogue.ok && catalogue.value.tag === "Found") {
for (const item of catalogue.value.collection.items) {
console.log(item.index, item.name, `${item.liveSupply}/${item.supply}`);
}
}
Both take an optional { signal }, forwarded into every underlying pull so an aborted caller
stops the whole batch. No deadline is applied for you.
A chain client, not a typed API. NftsChain asks for six storage entries and
raw.assetHub, a BlockSource with getFinalizedBlock() and getBestBlocks(), because each read
pins one block before it touches storage. A PAPI PolkadotClient fits as it is. Its hodlBlock,
optional on a BlockSource, keeps that block pinned until the read settles. Without it a block
finalized mid-read unpins the one the read is on, and inside a container the next round trip fails
with "is not pinned".
// Either of these satisfies NftsChain whole:
const preset = await getChainAPI("paseo");
const byod = await createChainClient({ chains: { assetHub: paseo_asset_hub } });
// A TypedApi does NOT, however complete its query surface is: it has no `raw`,
// so `chain.raw.assetHub` is undefined and the read fails before it queries.
const api = rawClient.getTypedApi(paseo_asset_hub);
An app that keeps only the typed API in its own session type (a common shape: { assetHub, people }) has to thread the client, or at least its raw, through to call these reads.
The contract is structural on purpose, no genesis hash is pinned to read a catalogue, and it is
checked at compile time from @parity/product-sdk, in packages/sdk/src/nfts/contract.test.ts.
These reads touch six entries:
query.Scarcity.NextCollectionId query.Scarcity.Collections
query.Scarcity.ItemDefs query.Scarcity.CollectionMetadata
query.Scarcity.ItemMetadata query.NftClaims.CollectionMinters
An app that prunes its own descriptors with a PAPI whitelist (.papi/whitelist.ts) must list all
six, including the ones its own code never reads. An app resolving display metadata through
ScarcityApi.metadata_batch typically carries none of the three metadata/ItemDefs entries, so
this bites on the first call.
getInstanceDisplays touches two, api.ScarcityApi.metadata_batch and query.Scarcity.ItemDefs
(the second shared with the catalogue reads); previewClaim adds api.NftClaimsApi.preview_mints,
and getClaims its own set (see the package doc). Whitelist per read you call.
The symptom is the PAPI Incompatible runtime entry Storage(Scarcity.CollectionMetadata), which
reads like descriptor drift and is not. These reads report it as NftsChainEntryError, which names
the entry in its message, carries it on error.entry for programmatic handling, and keeps PAPI's
error as the cause.
Two follow-ons that cost real time:
file: dependency
("@polkadot-api/descriptors": "file:.papi/descriptors"). The package manager keeps serving the
copy in its store until a forced reinstall (pnpm install --force).devnet-asset-hub carries neither Scarcity nor NftClaims, so nothing here can run against
the devnet preset. That failure is also a NftsChainEntryError, from the other PAPI message
(Runtime entry Storage(...) not found).Scarcity stores metadata as untyped Vec<u8> keys to Vec<u8> values in three layers, each overriding the
last for the same key. A catalogue read merges the first two, collection defaults underneath and the
item overrides on top. InstanceMetadata is deliberately not consulted by the catalogue reads: it
keys on an instance id, so it describes a minted NFT rather than a catalogue entry — that layer
belongs to getInstanceDisplays, which merges all three.
Nothing in the runtime declares the keys or their types.
name and rarity are lifted into typed fields, and every key is also passed through in
attributes.0x-hex otherwise.energy holds the
two ASCII characters 2 and 1. The chain stored the text "21" there, not a binary number.
Parse the string yourself and decide what a malformed one means.imageRef is an ImageRef: the same bytes as hex (always) and as text (null when they
are not readable). Deployments disagree, one stores a 32-byte content digest and another an ASCII
IPFS CID, and nothing says which, so pick by your own convention:const src = item.imageRef?.text // an ASCII CID, when that is what is stored
?? cidFromDigest(item.imageRef?.hex); // your own digest to CID step otherwise
transferability is Transferable or Soulbound, from ItemDefs. A soulbound instance stays
with its first owner, so do not offer to send one.Every read returns a Result, so failures arrive on the err channel rather than as throws.
const catalogue = await getCollectionItems(chain, 9);
if (!catalogue.ok) {
// ProductNftsError; NftsChainEntryError or NftsDecodeError when it is one of those
return;
}
if (catalogue.value.tag === "NotFound") {
// A collection nobody created. The chain was asked and answered, not an error.
return;
}
catalogue.value.collection.items;
getClaimableCollections is driven by NftClaims.CollectionMinters, not by Scarcity.Collections: a
collection with no minter entry cannot be claimed into, so it does not belong in a picker even
though its catalogue exists. How much that removes is per deployment. One carries six collections
and registers one, another registers most of what it carries, so do not assume the registry is
tiny, or that it matches the catalogue.
Narrow errors with isErrorOf(e, NftsChainEntryError) from @parity/result, or recognise any SDK
error with isSdkError(e) from @parity/product-sdk-errors.
Every value in one result is read at a single pinned finalized block, reported as at
({ blockHash, blockNumber }). Two reads in sequence pin two blocks. A walk can outlive its pinned block. When a page fails on the err channel mid-walk, drop at, read again from the last nextId, and continue on the new snapshot.
Three more reads, for the claim side of the same pallets.
getClaims(chain, { claimant }) reads every NFT claim credit one claimant holds. A credit is
awarded on the People chain and spent on Asset Hub, so this is the one read here that spans two
chains: it takes NftsChain & NftsCreditsChain, pins one block on each, and reports both in at.
A claimant is { tag: "Account", address } or { tag: "Person", alias }, and the pallet keys the
two apart with nothing linking them, so a player who moved from account to alias has to be read
twice. Each credit carries a state:
state | Meaning |
|---|---|
earned | Awarded, and the award block has no root on Asset Hub yet. A claim would be refused. |
claimable | The root arrived and the leaf is unspent. |
claimed | The leaf is spent and the item it minted exists. Stays claimed after the last claim removes the tree and after the People chain drops the root; then it has a leaf index but no time or game index. After the expiry sweep the block reads as unprovable. |
unprovable | The awards of the block are gone, pruned or expired, or the tree is finished and leaves are unspent. One entry per block, hash: null. |
An earned entry with hash: null is a block still to come. Pass only non-null hashes to
previewClaim.
previewClaim(chain, { credit, collections }) answers what that credit would mint in each
collection, with one NftClaimsApi.preview_mints call per 32 collections. It runs the real claim
selector, so for a Random collection the preview is the item the claim will produce, and
switching collection is the only way to change it. A collection the credit cannot mint into is a
Fails outcome with the reason, not an error. The item that would mint is resolved through the
same exact-key metadata path a catalogue page uses, so its name, rarity and imageRef agree
with getCollectionItems.
const registry = await getClaimableCollections(chain);
if (!registry.ok) return;
const preview = await previewClaim(chain, {
credit,
collections: registry.value.collections.map((c) => c.id),
at: registry.value.at,
});
getVerifiedArtwork(imageRef, { source }) turns an ImageRef into bytes, and only when the bytes
hash to the digest the reference names. Where the bytes come from is the caller's source:
preimageSource(manager) over the host preimage manager, whose key is the digest, or
gatewaySource(baseUrl) over an IPFS gateway by CID. The four outcomes are all on the ok channel:
Verified with the bytes, Missing, Mismatch with the bytes withheld, and Unreadable when the
reference decodes to no address or names a multihash other than blake2b-256 or sha2-256.
getInstanceDisplays(chain, instances, options?) reads the display metadata of minted NFTs by
instance id — what somebody holds, where the catalogue reads describe what a collection
defines. It is positional like previewClaim: displays[i] answers instances[i]. The chain
contract is its own, NftsInstancesChain — ScarcityApi.metadata_batch plus Scarcity.ItemDefs,
and the raw client; a getChainAPI client satisfies it whole.
const result = await getInstanceDisplays(chain, [1n, 2n, 404n]);
if (result.ok) {
for (const display of result.value.displays) {
if (display.tag === "NotFound") continue; // burned, or never minted
// instance, collection, item, transferability, supply, liveSupply,
// name | null, collectionName | null, rarity | null, imageRef | null, attributes
const title = display.name ?? display.collectionName ?? `Instance ${display.instance}`;
console.log(title, display.collection, display.item);
if (display.transferability === "Transferable") offerSend(display);
}
}
Things that differ from the catalogue reads, each for a reason:
Found / NotFound. An instance nobody minted, or one already burned, is a
NotFound display on the ok channel. The signal is the runtime declining to resolve the query,
not an empty bag: a freshly claim-minted instance carries no metadata at all on the live
chain and is still Found, with null typed fields and an empty attributes.collection and item come back resolved. The runtime reports which (collection, item) each
instance was minted from, so a shelf can group by collection, or join getCollectionItems,
without a second lookup.attributes is always filled, all three layers merged (instance over item over collection,
the pallet's own precedence). No attributes: true flag: metadata_batch returns whole layers
whether or not anyone wants them, so withholding the bag would save nothing. Deployment
conventions beyond name / image / rarity — an identity hash, a manifest CID — are in
the bag for you to lift.name is the instance's own, and collectionName is separate. Unlike CollectionItem.name,
this read does not inherit the collection's name into the item's. Inheriting is right for
image and rarity, where the collection sets a default for its items, and wrong for name,
where the collection layer holds the name of a different thing. A deployment that names its
collection and titles items by archetype would otherwise see every item called "Hearth". The
merged attributes bag still carries both, so nothing is hidden.transferability, supply and liveSupply come from the item definition, which is not
metadata, so a second keyed ItemDefs read fills them. Also not optional, and for a sharper
reason than the bag: whether an instance is Soulbound decides whether your UI may offer to
send it, and the keys are the (collection, item) the instance already resolved to — deduped,
so one hop and no bytes beyond what you asked about. The three are null together, and
only when the item definition is gone from under a live instance. That is a real chain state,
not "not fetched" — the opposite of how null reads on CollectionItem.attributes.MAX_INSTANCES_PER_READ (128) instances per call, refused above
that. Every other read here walks a space the chain sizes, so it hands back a cursor; this one
answers a list you already hold, so a cursor would page you over your own input. Split the list
instead. The cap is this package's contract, not a reading of the chain — it coincides with the
metadata_batch cap of the live runtime, which is why a full read is one runtime call there. A
deployment configured lower rejects the call, and the read fails whole.getInstanceDisplay(chain, instance, options?) is the same read for one id, for a detail view.
Looping it over a shelf forfeits the batching; pass the list.
Instance ids are u64 bigints, as PAPI returns them. Where ids come from is the caller's
business — a transfer record, an indexer, a purse walk the app does itself — which is exactly why
this read is not blocked on the purse primitive below.
getOwnedNfts, getNextEmptyPurse and findPurseHolding need a purse
primitive shared across apps, which the wallet does not expose. App-scoped product-account
derivation is not a substitute: it is keyed by productId, so nothing derived under it can be
shared between two apps. getInstanceDisplays already answers the display half of an owned read;
once a purse primitive can enumerate what is held, the owned read composes on it.TypedApi. The reads pin a block first, so they need the client. The failure is
a TypeError about reading assetHub of undefined, wrapped as ProductNftsError.Incompatible runtime entry as descriptor drift.imageRef.hex on a CID deployment (or .text on a digest one). Check which
field is populated rather than assuming.NotFound as an error. It is on the ok channel, with the block it was
established at.result.tag instead of result.ok first. The tag is inside result.value.itemCount as items.length. They are separate writes and can disagree while a
definition is being removed. Both are reported as the chain has them.ClaimableCollection has a Scarcity.Collections record. itemCount and owner
are null when it does not, which signals an inconsistency rather than an empty collection.attributes values as numbers without handling text that is not numeric.rarity or name to be set. Most collections on a live deployment set neither.attributes bag from getInstanceDisplays as "no such instance". A
claim-minted instance carries no metadata and is still Found; the miss signal is the
NotFound tag.getInstanceDisplay over a shelf. One call with the list is a single runtime
operation for up to 128 instances; the loop is one per instance.getInstanceDisplays to page a list over 128. It refuses rather than
truncating or handing back a cursor. Slice the list yourself — it is yours.What SKILL.md sets; muted values are Claude Code's defaults
npx claudepluginhub paritytech/product-sdk --plugin product-sdk11 skills in this plugin
/migrating-to-product-sdkUse when migrating a product codebase to @parity/product-sdk — detects legacy stacks (polkadot-apps, novasamatech, hand-rolled crypto/IPFS, polkadot-api 1.x) in the target repo, decides which migration areas apply, writes a per-repo migration spec, then hands off to writing-plans.
/product-sdk-app-builderEnd-to-end scaffolding and implementation of Polkadot applications using @parity/product-sdk packages. Use when: creating a new Polkadot project, building a dApp, scaffolding chain interactions, choosing which @parity/product-sdk packages to install, or when a user says "build me a Polkadot app". Handles both developer-guided and fully autonomous (non-developer) workflows.
/product-sdk-chain-connectionUse when connecting to Polkadot chains, querying chain state, subscribing to storage, working with typed APIs, or choosing between preset and BYOD paths. Covers @parity/product-sdk-chain-client and @parity/product-sdk-descriptors.
/product-sdk-cloud-storageUse when uploading or retrieving data via Cloud Storage, working with CID-based decentralized storage, or the CloudStorageClient SDK. Covers the store() upload builder, chunked uploads, container-only reads (fetch/query), CID helpers, and authorization.
/product-sdk-contractsUse when interacting with smart contracts (PolkaVM/Solidity) on Asset Hub, using ContractManager with cdm.json manifests, createContract for ad-hoc contracts, ContractRuntime creation, or contract type codegen. Covers @parity/product-sdk-contracts.
/product-sdk-individualityUse when reading a person's personhood or membership standing on the individuality chain from a DotNS username or an account address, when reading the usernames an account holds, or when sending a transaction that must run under a person, lite-person or score-participant origin instead of an account origin. Covers readPersonhoodState, lookupUsername, the seven-state PersonhoodState union, the pure derivation without a chain client and the decode helpers for raw Score.Participants and Resources.Consumers values; the game surface, its prize draws, claiming and sign-up with its airdrop VRFs; productContext, personhoodContext, peopleRing, litePeopleRing and readScoreContext for the ring-VRF proof contexts; withAsPerson, withLiteAlias and the RestrictOrigins requirement that otherwise fails every call; the two-transaction lite personhood bind then sign-up flow with buildLiteAliasBindTx, readLiteSignUpRequirement and signUpWithLiteInviteTx; game registration in one call with registerForGame, readGameSeat, deriveSeat, bindGameSeat and the /host entry's hostGameRegistrationCapabilities; and full-personhood registration with registerMessage, Score.register and withScoreParticipant.
Other plugins' skills for the same job