How to create an NFT allowlist (whitelist)

GoldRush TeamUpdated 14 min read

Build an NFT allowlist mint in Solidity three ways: an address mapping, a Merkle root with OpenZeppelin MerkleProof, or EIP-712 signed vouchers.

An NFT allowlist (also called a whitelist) is a list of wallet addresses allowed to mint from a collection, usually before the public sale or for free. The mint contract has to check the list on every mint, and there are three standard ways to do it: store every address in a mapping, store one Merkle root and have each minter send a proof, or have a server sign a voucher for each eligible wallet. This guide builds all three in Solidity with OpenZeppelin, then builds the list itself from the holders of another collection.

What an NFT allowlist does

An allowlist gates one function: the mint. Projects use it to reward holders of an earlier collection or community members, to give early supporters a lower price or a guaranteed spot before the public mint, and to keep bots out of a launch. It's a different job from token gating, which decides who can enter a site or channel after the fact; for that, see how to verify NFT ownership.

Whatever the method, an allowlist mint has to answer two questions onchain:

  1. Is the caller on the list? The contract checks msg.sender, never an address passed as an argument, so nobody can mint on someone else's spot.
  2. Have they already used their spot? Without a claimed record, an allowlisted wallet can mint again and again.

Three ways to store the list

Address mapping Merkle root Signed vouchers (EIP-712)
What the contract holds Every address One 32-byte root One signer address
Who pays to load it The project, per address The project, one transaction Nobody
What the minter sends Nothing A Merkle proof A signature from your server
Changing the list A transaction per batch Publish a new root Change the server's rules
Can be checked publicly Yes Yes, if you publish the list No
Main risk Cost of writing a large list Leaf encoding must match the contract A leaked signing key mints for anyone
Best for A few dozen addresses A fixed list, such as a holder snapshot Rules checked at mint time, or lists that change

All three contracts below are OpenZeppelin Contracts 5 ERC721s with one mint per wallet. They were compiled with Solidity 0.8.28 against OpenZeppelin Contracts 5.1.0. Compile them in Remix (it resolves the @openzeppelin/contracts imports for you; import @openzeppelin/contracts@5.1.0/... to pin the version there) or in Foundry or Hardhat after installing the same version, test on a testnet such as Sepolia, and add your public mint, price and supply cap on top.

The JavaScript later in this guide was run on Node.js 22 with these versions. Install everything with:

npm install @openzeppelin/contracts@5.1.0 @openzeppelin/merkle-tree@1.0.7 viem@2.21.0

Option 1: an address mapping

The simplest allowlist is a mapping(address => bool) the owner fills in. It's easy to read and to change, but every address is a storage write in a transaction the project pays for, so it only suits short lists.

// SPDX-License-Identifier: MITpragma solidity ^0.8.24; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; contract MappingAllowlistNFT is ERC721, Ownable {    mapping(address => bool) public allowlist;    mapping(address => bool) public claimed;    uint256 public nextTokenId;     error NotOnAllowlist();    error AlreadyClaimed();     constructor() ERC721("Allowlist NFT", "ALNFT") Ownable(msg.sender) {}     // Every address written here is one storage write the owner pays gas for.    function setAllowlist(address[] calldata accounts, bool allowed) external onlyOwner {        for (uint256 i = 0; i < accounts.length; i++) {            allowlist[accounts[i]] = allowed;        }    }     function allowlistMint() external {        if (!allowlist[msg.sender]) revert NotOnAllowlist();        if (claimed[msg.sender]) revert AlreadyClaimed();        claimed[msg.sender] = true;        _safeMint(msg.sender, nextTokenId++);    }}

claimed is set before _safeMint, because _safeMint calls back into a contract recipient and a contract could otherwise re-enter allowlistMint before its spot is spent.

Option 2: a Merkle root

A Merkle tree hashes every address into one 32-byte root. The contract stores only the root; each minter sends a short proof, the hashes that link their address to the root, and the contract recomputes the root from it. The cost of the list moves from the project's one-off storage writes to a little calldata in each mint, and a list of any size costs the same to publish. This is the usual choice for a fixed list.

// SPDX-License-Identifier: MITpragma solidity ^0.8.24; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; contract MerkleAllowlistNFT is ERC721, Ownable {    bytes32 public merkleRoot;    mapping(address => bool) public claimed;    uint256 public nextTokenId;     error NotOnAllowlist();    error AlreadyClaimed();     constructor(bytes32 root) ERC721("Allowlist NFT", "ALNFT") Ownable(msg.sender) {        merkleRoot = root;    }     // Replace the whole list in one transaction: publish a new root.    function setMerkleRoot(bytes32 root) external onlyOwner {        merkleRoot = root;    }     function allowlistMint(bytes32[] calldata proof) external {        if (claimed[msg.sender]) revert AlreadyClaimed();        // The leaf StandardMerkleTree builds for ["address"]: keccak256 twice over the ABI-encoded value.        bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(msg.sender))));        if (!MerkleProof.verifyCalldata(proof, merkleRoot, leaf)) revert NotOnAllowlist();        claimed[msg.sender] = true;        _safeMint(msg.sender, nextTokenId++);    }}

Build the tree off-chain with OpenZeppelin's @openzeppelin/merkle-tree library. Its StandardMerkleTree hashes each leaf twice, which is what the contract's leaf line reproduces, and sorts each pair of hashes, which is what MerkleProof expects. Hashing twice matters: with a single hash, an attacker could present an inner node of the tree as if it were a leaf.

Each JavaScript block in this guide is an ES module: save it as a .mjs file (this one as build-tree.mjs) and run it with node build-tree.mjs on Node.js 22.

import { StandardMerkleTree } from "@openzeppelin/merkle-tree";import { writeFileSync } from "node:fs"; // Your list: any case, duplicates allowed.const addresses = ["0x1111111111111111111111111111111111111111", "0x2222222222222222222222222222222222222222"]; const allowlist = [...new Set(addresses.map((a) => a.toLowerCase()))];const tree = StandardMerkleTree.of(    allowlist.map((address) => [address]),    ["address"]); console.log("Merkle root:", tree.root); // deploy with this, or pass it to setMerkleRootwriteFileSync("allowlist.json", JSON.stringify(tree.dump()));

Deploy the contract with tree.root. Your site then loads the saved tree and hands each wallet its proof, which the mint button passes as the only argument to allowlistMint:

import { StandardMerkleTree } from "@openzeppelin/merkle-tree";import { readFileSync } from "node:fs"; const tree = StandardMerkleTree.load(JSON.parse(readFileSync("allowlist.json", "utf8"))); // The proof a wallet passes to allowlistMint, or null if it isn't on the list.function proofFor(wallet) {    for (const [i, [address]] of tree.entries()) {        if (address === wallet.toLowerCase()) return tree.getProof(i);    }    return null;}

A proof only works for the address it was built for, because the contract hashes msg.sender into the leaf: anyone can read every proof, and none of them helps a wallet that isn't on the list. Publish allowlist.json or the address list so holders can check the root themselves.

Option 3: signed vouchers with EIP-712

Here the contract stores no list at all, only the address of a signer your server controls. When an eligible wallet asks to mint, the server signs a voucher for that wallet, and the contract checks the signature. Eligibility can be anything the server can check at that moment, including "holds a token of collection X right now", and changing the rules needs no transaction.

EIP-712 typed data makes the voucher safe to reuse nowhere else: its domain names the contract and the chain ID, so a voucher signed for your testnet deployment or another project's contract fails here. The voucher names the minting wallet (to, checked against msg.sender) and carries a deadline.

// SPDX-License-Identifier: MITpragma solidity ^0.8.24; import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract SignedAllowlistNFT is ERC721, EIP712, Ownable {    bytes32 private constant MINT_TYPEHASH = keccak256("Mint(address to,uint256 deadline)");     address public signer;    mapping(address => bool) public claimed;    uint256 public nextTokenId;     error NotOnAllowlist();    error AlreadyClaimed();    error VoucherExpired();     constructor(address signer_) ERC721("Allowlist NFT", "ALNFT") EIP712("AllowlistNFT", "1") Ownable(msg.sender) {        signer = signer_;    }     function setSigner(address signer_) external onlyOwner {        signer = signer_;    }     function allowlistMint(uint256 deadline, bytes calldata signature) external {        if (block.timestamp > deadline) revert VoucherExpired();        if (claimed[msg.sender]) revert AlreadyClaimed();        // The domain binds the voucher to this contract on this chain; `to` binds it to the caller.        bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(MINT_TYPEHASH, msg.sender, deadline)));        if (ECDSA.recover(digest, signature) != signer) revert NotOnAllowlist();        claimed[msg.sender] = true;        _safeMint(msg.sender, nextTokenId++);    }}

The server side signs with viem. The domain's name and version must match the contract's EIP712("AllowlistNFT", "1"), and verifyingContract is the deployed address, read from ALLOWLIST_CONTRACT. Save this as voucher-server.mjs. It calls holdsCollection, which is in Check eligibility at mint time below: paste that block, with the API and headers lines from the snapshot block, above mintVoucher in the same file.

import { isAddress } from "viem";import { privateKeyToAccount } from "viem/accounts"; const CONTRACT = process.env.ALLOWLIST_CONTRACT; // your deployed SignedAllowlistNFTif (!isAddress(CONTRACT ?? "")) throw new Error("Set ALLOWLIST_CONTRACT to the deployed contract's address");const signer = privateKeyToAccount(process.env.ALLOWLIST_SIGNER_KEY); // Call this only for a wallet the user has proved they control (Sign-In with Ethereum).async function mintVoucher(wallet) {    if (!isAddress(wallet)) throw new Error("Expected a 0x address");    if (!(await holdsCollection("eth-mainnet", wallet, REQUIRED_COLLECTION))) return null;     const deadline = BigInt(Math.floor(Date.now() / 1000) + 15 * 60); // valid for 15 minutes    const signature = await signer.signTypedData({        domain: { name: "AllowlistNFT", version: "1", chainId: 1, verifyingContract: CONTRACT },        types: {            Mint: [                { name: "to", type: "address" },                { name: "deadline", type: "uint256" },            ],        },        primaryType: "Mint",        message: { to: wallet, deadline },    });    return { deadline: deadline.toString(), signature };}

The minter sends deadline and signature to allowlistMint. Keep the signing key out of the frontend and the repository, give it no funds and no other role, and rotate it with setSigner if it leaks: whoever holds it can mint for any wallet.

Build the list from another collection's holders

A common allowlist is "everyone who held collection X at block N". The GoldRush token holders endpoint returns every address holding an ERC-721 collection, at the latest block or at a past one, so the snapshot is one paginated call. This loop is the one from how to get token holder data, pinned to a block. Save it and the next block in one file, snapshot.mjs, in this order, set GOLDRUSH_API_KEY, and run node snapshot.mjs:

const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; // Every holder of a collection at one block, 1,000 per request, until has_more is false.async function holdersAtBlock(chain, collection, blockHeight) {    const holders = [];    for (let page = 0; ; page++) {        const qs = new URLSearchParams({            "block-height": String(blockHeight),            "page-size": "1000",            "page-number": String(page),        });        const res = await fetch(`${API}/${chain}/tokens/${collection}/token_holders_v2/?${qs}`, { headers });        if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);        const { data } = await res.json();        holders.push(...data.items);        if (!data.pagination.has_more) return holders;    }}

Then, in the same file, feed the addresses into the Merkle tree from Option 2:

import { StandardMerkleTree } from "@openzeppelin/merkle-tree";import { writeFileSync } from "node:fs"; const COLLECTION = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"; // Bored Ape Yacht Clubconst SNAPSHOT_BLOCK = 21000000; // announce it before you take itconst EXCLUDE = new Set(["0x000000000000000000000000000000000000dead"]); const holders = await holdersAtBlock("eth-mainnet", COLLECTION, SNAPSHOT_BLOCK); // One leaf per address: lowercase, deduplicate, drop addresses you don't want (burn, treasury, marketplaces).const allowlist = [...new Set(holders.map((h) => h.address.toLowerCase()))].filter((a) => !EXCLUDE.has(a)); const tree = StandardMerkleTree.of(    allowlist.map((address) => [address]),    ["address"]);console.log(allowlist.length, "addresses, root", tree.root);writeFileSync("allowlist.json", JSON.stringify(tree.dump()));

You need a GoldRush API key: sign up for the 14-day free trial, which includes 25,000 credits. Each holder returned costs 0.02 credits, so snapshotting a collection with 10,000 holders costs 200 credits. Past blocks work on the Foundational chains, which include Ethereum and Base; elsewhere, call without block-height for the latest holders. See Token Holders chain support and the Token Holders API for the chains and fields.

A holder list includes contracts: marketplace escrow, staking and vault contracts hold tokens for their users. Their depositors drop off the list, and the contracts themselves can't usually mint. Decide whether staked holders count, and if they do, add their depositors from the staking contract's records.

Check eligibility at mint time

A snapshot is fixed; a voucher server can check the rule live. The GoldRush collection ownership check returns which of a collection's tokens a wallet holds, so "holds at least one" is a single request. This is the holdsCollection the voucher server above calls:

// Goes in voucher-server.mjs, above mintVoucher, with the API and headers lines from snapshot.mjs.const REQUIRED_COLLECTION = "0xbc4ca0eda7647a8ab7c2061c2e118a18a936f13d"; // Does the wallet hold at least one token of the collection right now?async function holdsCollection(chain, wallet, collection) {    const res = await fetch(`${API}/${chain}/address/${wallet}/collection/${collection}/`, { headers });    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);    const { data } = await res.json();    return data.items.some((item) => BigInt(item.balance ?? 0) > 0n);}

The check is billed in credits, 1 per call, and works on 6 chains; it takes ERC-721 and ERC-1155 collections, and traits-filter and values-filter narrow it to tokens with one trait. Two rules keep a live check honest:

  • Prove the wallet first. Anyone can type a holder's address. Sign the voucher only for the address that signed in with Ethereum; how to verify NFT ownership shows the Sign-In with Ethereum check.
  • One token, one spot. A live check lets a holder mint, send the NFT to a second wallet and mint again. The contract's claimed mapping stops the same wallet twice, not the same token. If that matters, put the token ID in the voucher and record claimed token IDs instead of wallets, or use a snapshot.

These ownership and holder endpoints are part of the GoldRush NFT API.

Handle errors from the GoldRush API

Both functions throw on any non-2xx status and include the body in the message. A failed call returns the same envelope as a successful one, with data set to null, error set to true and the reason in error_message; error_code is a JSON number equal to the HTTP status. The docs show this body for a chain name the API doesn't recognize:

{ "data": null, "error": true, "error_message": "Chain nosuchchain-mainnet not supported.", "error_code": 501 }

A 501 means the request was well formed but the chain or endpoint can't serve it, so retrying it unchanged won't help. For a snapshot, the common failure is a 400: passing block-height on a chain that isn't a Foundational chain is rejected, so drop the parameter there and take the latest holders. A 401 means the key is missing or wrong; with no Authorization header at all, the edge proxy returns an HTML 401 page rather than JSON, which res.text() still reads. Failed requests cost no credits. Every code is listed in the error handling docs.

NFT allowlist pitfalls

  • Encoding mismatches. The Merkle leaf in the contract must hash exactly what the tree hashed: the same types, in the same order, hashed twice. Add a field (say, a per-wallet mint limit) and both sides change: ["address", "uint256"] in the tree, abi.encode(msg.sender, limit) in the contract.
  • Checking an argument instead of msg.sender. A mint function that takes the allowlisted address as a parameter lets anyone mint on any spot.
  • Reusable signatures. A voucher without the minting wallet, the chain ID and the contract address in what's signed can be replayed by someone else, on another chain or on your next drop. EIP-712's domain covers the last two; the to field covers the first.
  • Address case. Lists collected from forms mix checksummed and lowercase addresses. Lowercase before deduplicating and before looking up a proof, or one wallet gets two leaves and the lookup misses.
  • Contract wallets. _safeMint reverts for a contract recipient that doesn't implement onERC721Received. If your allowlist includes multisigs or smart accounts, test a mint from one.
  • Changing the root during a mint. Proofs made for the old root stop working the moment setMerkleRoot lands. Regenerate and serve the new proofs at the same time.

Frequently asked questions

What is an NFT allowlist?

An NFT allowlist is a list of wallet addresses that may mint from a collection, usually before the public mint, at a lower price or with a guaranteed spot. The mint contract checks the caller against the list, stored as a mapping, a Merkle root or a signer address.

Is an allowlist the same as a whitelist?

Yes. "Whitelist" was the original term in NFT launches, and most projects and tools now say "allowlist" for the same thing: a list of addresses allowed to mint.

What is the cheapest way to store an NFT allowlist onchain?

A Merkle root. The contract stores one 32-byte value whatever the list's size, and each minter sends a short proof with their mint. Signed vouchers store even less, a signer address, but depend on a server and a signing key.

How do I make an allowlist of holders of another NFT collection?

Take a snapshot of the collection's holders at one block, for example with the GoldRush token holders endpoint and its block-height parameter, deduplicate the addresses, and build a Merkle tree from them. Deploy the mint contract with the tree's root and serve each holder their proof.

Can I update an NFT allowlist after deployment?

Yes. With a mapping, the owner adds or removes addresses in a transaction. With a Merkle tree, rebuild the tree and call the owner-only function that sets the new root. With signed vouchers, change the server's rules; nothing onchain changes.

How do people get on an NFT allowlist?

Each project sets its own rules: holding another collection, taking part in the community, winning a raffle or registering early. The rules end up as a list of addresses the project loads into the mint contract.

Next steps

Get new guides by email

New tutorials and best practices for building with blockchain data, sent as they're published.