Developing an NFT Rarity System: Algorithms and On-Chain Verification

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Developing an NFT Rarity System: Algorithms and On-Chain Verification
Medium
~2-3 days
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Developing an NFT Rarity System: Algorithms and On-Chain Verification

Without a well-designed rarity system, a collection of 10,000 tokens trades as a homogeneous mass where price is determined solely by floor price. With a proper system, the top 1% of the collection can be worth 10–50 times the floor — directly impacting liquidity and trader interest. The task consists of two parts: off-chain generation and ranking, and on-chain verification via Merkle tree or metadata storage. We develop such systems turnkey: from algorithm selection to marketplace integration. With over 5 years on the market and dozens of completed NFT projects, our experience guarantees transparency at every stage.

How to Choose the Rarity Score Algorithm?

Statistical rarity (Rarity Tools method)

The classic approach: for each attribute, the frequency of occurrence in the collection is calculated. Score = sum of 1 / trait_frequency across all attributes of the token.

# Pseudocode calculation
for nft in collection:
    score = 0
    for trait_type, trait_value in nft['attributes']:
        frequency = count(trait_value) / total_supply
        score += 1 / frequency
    nft['rarity_score'] = score

Problem with statistical rarity: trait count bias. A token with 10 common attributes can get a higher score than a token with 5 attributes, one of which is unique (1/10000). This is counterintuitive for users.

Information content rarity (Rarity Sniper method)

Uses an information-theoretic approach: each attribute contributes proportionally to its information content -log2(probability).

IC(trait) = -log2(count(trait) / total_supply)

Information content rarity outperforms statistical rarity by 2–3 times in ranking fairness — it does not suffer from trait count bias.

Normalized score for single-attribute rarities

If the collection has a trait type like "background" with 20 variants and a trait "special" with 2 variants (one of which occurs in 1 token), normalization allows comparing contributions of different trait types on a single scale:

normalized_score(trait) = rarity_score(trait) / max_rarity_score(trait_type)

Why On-Chain Verification Matters?

Generation and calculation (off-chain)

Python script with three stages:

  1. Trait analysis — parse all JSON metadata, build frequency table for each trait_type/trait_value
  2. Score calculation — selected algorithm, normalization, ranking
  3. Output — updated JSON files with added fields rarity_score, rarity_rank

Key point: metadata is updated before uploading to IPFS. After pinning on IPFS, the CID is fixed — changing rarity score without changing CID is impossible. Transparency and immutability are mandatory for project trust.

Merkle-based on-chain verification

For projects that want on-chain rarity verification (e.g., for issuing bonuses to top-100 holders):

// Merkle proof verification of rarity rank
function verifyRarityRank(
    uint256 tokenId, 
    uint256 rank,
    bytes32[] calldata proof
) external view returns (bool) {
    bytes32 leaf = keccak256(abi.encodePacked(tokenId, rank));
    return MerkleProof.verify(proof, rarityMerkleRoot, leaf);
}

Gas costs for on-chain verification via Merkle tree are less than $10 per update — saving about 90% compared to full storage. That means a collection with 10,000 tokens can save over $90,000 in gas over its lifetime.

API for aggregators

Rarity Tool, Rarity Sniper, OpenSea — all read metadata from tokenURI(). It is important to correctly format the attributes field:

{
  "attributes": [
    {"trait_type": "Background", "value": "Gold"},
    {"trait_type": "Eyes", "value": "Laser"},
    {"display_type": "number", "trait_type": "Rarity Rank", "value": 42},
    {"display_type": "number", "trait_type": "Rarity Score", "value": 847.3}
  ]
}

display_type: "number" allows OpenSea and other marketplaces to show rarity rank as a numeric field with sorting.

Comparison of Rarity Score Algorithms

Statistical rarity is simple and widely supported but suffers from trait count bias; it's best for collections with equal number of attributes. Information content rarity avoids bias and is mathematically fair, making it suitable for variable attribute counts. Normalized score eases comparison but depends on max score, ideal for single-attribute rarities. Overall, information content rarity is often the best choice for most modern collections, outperforming statistical rarity by 2–3 times in fairness.

Development Stages and Timelines

Stage Duration Result
Trait structure analysis 0.5–1 day Algorithm selection, frequency table
Script development 1–2 days Python pipeline, CSV, JSON with rank
On-chain component (if needed) 1 day Merkle tree, verification contract
Marketplace integration 0.5 day Check display on OpenSea, Blur
View calculation code (Python pseudocode)
for nft in collection:
    score = 0
    for trait_type, trait_value in nft['attributes']:
        frequency = count(trait_value) / total_supply
        score += 1 / frequency
    nft['rarity_score'] = score

Typical Mistakes in Rarity System Development

  • Trait count not accounted for. Tokens with different numbers of attributes (some NFTs may lack certain trait_type) get an unfair score. Solution: treat None as a separate value with its frequency.
  • Score calculated before final generation. If the artist adds new variants after the score calculation, the entire table becomes invalid. Rarity is calculated once on the final collection, before any changes.
  • Lack of tiebreaker. Tokens with the same score receive the same rank. Standard approach: tiebreak by tokenId (smaller ID = higher rank for equal scores).

What's Included in the Work

  • Documentation of the algorithm and calculation process
  • Updated JSON metadata with rarity score and rank
  • CSV export of rare tokens
  • Merkle tree and verification contract (if needed)
  • Support after implementation for 2 weeks

Timelines: 2–3 days for collections up to 10,000 tokens. For larger collections or non-standard algorithms, up to 5 days. Typical development costs range from $2,000 to $5,000 depending on complexity. Contact us — we'll evaluate your case and offer the optimal solution.

Why does NFT marketplace development require a comprehensive approach?

We see that at first glance, an NFT contract looks simple: ERC-721, mint(), IPFS for metadata — that's it. In practice, it's this 'simplicity' that hides most problems — from bots buying out the entire mint in the first block to broken royalties on the secondary market. We often hear: Make a collection like others in a week — and a month later it turns out gas has tripled due to an unoptimized for loop, or OpenSea cannot see metadata after reveal. We know each of these pitfalls and build processes to avoid them.

Over 5 years of working with blockchains, we have implemented 40+ NFT projects, including marketplaces with dynamic attributes and cross-chain bridges. We have accumulated a library of proven templates — some of which we break down below.

Which standard to choose: ERC-721 or ERC-1155?

ERC-721 — each token is unique, one owner. Suitable for collections where each NFT has individual attributes and a direct owner → tokenId mapping.
ERC-1155 — multi-token standard: one contract holds both fungible and non-fungible tokens. It uses balanceOf(address, tokenId) instead of ownerOf(tokenId). A single transaction can transfer multiple different tokens via safeBatchTransferFrom. This saves gas on bulk operations — important for game items, tickets, edition collections. ERC-1155 is 2–3× more gas-efficient than ERC-721 for batch transfers.

Criteria ERC-721 ERC-1155
Token uniqueness Each token is unique One tokenId can have multiple copies
User balance Only ownerOf (one) balanceOf(address, tokenId)
Gas per transfer ~25,000 gas ~18,000 gas (batch even lower)
Batch operations No native support safeBatchTransferFrom
Ideal scenario Art collections, PFPs Games, tickets, editions

Specific case: a game project with 50 types of items, each with a supply of 10,000. ERC-721 — 500,000 unique tokens, huge overhead on mappings. ERC-1155 — 50 tokenIds, balanceOf per player. Gas per transfer is 2–3 times lower, contract deployment is cheaper. For such tasks, we use OpenZeppelin ERC-1155 with custom modifications.

Metadata: on-chain vs IPFS vs centralized

The standard route is tokenURI() returning a link to a JSON with fields name, description, image, attributes. Three storage options:

  • Centralized server — cheapest and most flexible. Risk: server goes down, company closes — NFT loses metadata. Not suitable for collections claiming long-term value.
  • IPFS + Pinning — content-addressed storage, the link is bound to the content hash. Pinata or NFT.Storage provide pinning. Important: IPFS does not guarantee availability by itself — an active pinning service is needed. If it shuts down, data may disappear if no one keeps a copy.
  • On-chain metadata — base64-encoded SVG or JSON directly in tokenURI. Maximum reliability, but expensive: for a collection of 10,000 tokens, gas costs may exceed $5,000. Suitable for generative art projects where visuals are generated from on-chain attributes (Nouns, Loot).

For most collections, we choose IPFS with Pinata for images + on-chain attributes for traits — a good balance. We validate files against a JSON Schema before upload; a typical mistake is unescaped quotes, causing marketplaces to display a blank screen.

Typical JSON metadata format
{
  "name": "Token #1",
  "description": "A unique NFT",
  "image": "ipfs://QmHash/image.png",
  "attributes": [{"trait_type": "Background", "value": "Red"}]
}

Dynamic NFT: metadata that changes

Dynamic NFT updates metadata in response to external events — match results, character levels, real-world data via Chainlink. Architecturally, it's a combination: the smart contract stores state → tokenURI() generates metadata from the state on-chain. Caching problem: OpenSea and other marketplaces aggressively cache. The standard invalidation mechanism is a MetadataUpdate(tokenId) event from ERC-4906. OpenSea listens to this event and clears the cache. Without it, updated metadata may not appear for weeks.

Chainlink Automation (formerly Keepers) for automatically updating state on the contract on a schedule or condition — a standard solution for dynamics.

How to protect mint from bots?

Allowlist via Merkle tree — standard. The list of addresses is hashed into a Merkle root, stored in the contract. During mint, the user provides a Merkle proof — the contract verifies without storing the full list. We use OpenZeppelin MerkleProof library.

Reveal mechanism — on mint, a placeholder is issued; real traits are revealed after the sale ends. Otherwise, bots can scan pending transactions and snipe rare traits via frontrunning. But reveal requires a commitment scheme — the random seed must be fixed before mint or use Chainlink VRF.

Chainlink VRF for fair randomization of traits. VRF request at mint → callback with verifiable random number → assign traits. This adds ~2 transactions and latency but guarantees fairness. Chainlink VRF v2.5.

Rate limiting — require(mintedPerWallet[msg.sender] < maxPerWallet). Does not protect against multi-wallets but raises attack cost. For premium projects, we often add proof-of-work directly in the contract (via EIP-2612 signatures).

Royalties: the real market state

ERC-2981 — on-chain royalty standard. The contract returns (recipient, amount) for any sale price via royaltyInfo(tokenId, salePrice). Marketplaces query this on each sale. Problem: adherence to royalties is voluntary for marketplaces. Blur launched with zero royalties, triggering a wave of other platforms. The situation has partially stabilized: OpenSea supports ERC-2981, Blur added optional ones. Royalty payments can represent 5–10% of secondary sale volume, so getting them right matters.

Attempts to enforce royalties on-chain by restricting transfers only to approved marketplaces (operator filtering) were proposed by OpenSea via OperatorFilterRegistry. This breaks composability — you cannot transfer an NFT through a custom contract. Most serious projects have abandoned this approach. For projects where royalties are critical, we build a custom marketplace within the ecosystem plus an incentive structure for users to trade there.

Lazy minting and gas-free mint

Gas-free mint via signature: the creator signs a voucher (tokenId, tokenURI, price, signature), the buyer provides the voucher in mint() — the contract verifies the signature via ECDSA.recover() and mints. Works on OpenSea via their Seaport protocol. Seaport is an optimized contract with minimal gas usage. Understanding its mechanics is important when integrating custom marketplace logic.

Stack for NFT projects

  • Contracts: Solidity 0.8.x, OpenZeppelin ERC721Enumerable or ERC721A (Azuki) for gas-optimized batch mint, ERC1155 from OpenZeppelin
  • VRF and automation: Chainlink VRF v2.5, Chainlink Automation
  • Storage: Pinata (IPFS pinning), NFT.Storage, Arweave for permanent storage
  • Marketplace: OpenSea Seaport protocol, custom integration
  • Frontend: wagmi v2 + viem, RainbowKit for wallet connection, React + TypeScript

Development process

  1. Mint mechanics design — allowlist, public sale, price curve (Dutch auction or fixed), limits per wallet
  2. Contracts — with Foundry fuzz tests on mint limits, Merkle proof verification, royalty calculations
  3. IPFS deployment — upload metadata and images before reveal, pin on at least two services
  4. Reveal — if using Chainlink VRF, test on testnet mandatory: VRF subscription must be funded with LINK tokens
  5. Marketplace integration — verify collection on OpenSea, configure royalties, test MetadataUpdate events
  6. Deployment and monitoring — Tenderly for reentrancy detection, Etherscan API for contract verification, set up event alerts

Deliverables

  • Source code of smart contracts (Solidity, Rust for Solana) with comments
  • Test suite (Foundry/Hardhat) with ≥90% coverage
  • Deployment documentation and integration instructions
  • Access to pinning services (Pinata/Pinfluence)
  • Metadata generation scripts (Python/JS)
  • Support during marketplace verification
  • 30 days of technical support after deployment

Timeline

Task type Approximate timeline
Basic ERC-721 without reveal from 2 weeks
NFT collection with allowlist, reveal, VRF from 5 weeks
ERC-1155 with marketplace and royalties from 6 weeks
Dynamic NFT with external data from 8 weeks

Cost is calculated individually after auditing your task. Send a brief with your project description — we will provide a transparent estimate within 3 business days. For regular clients, there is a flexible discount system on batch orders. If you need a gas-optimized contract, order a free gas analysis. Get a consultation on marketplace architecture — leave a request, and we will evaluate your project in three days.