Incorrect supply-cap check - uses token_id instead of total_supply - in _base_mint
The mint function checked the supply cap against the token ID plus one rather than the actual minted count. An attacker or unlucky user could pick a large token ID and cause legitimate mints to revert, blocking minting even when supply is below the cap.
Belong
Originally disclosed on Immunefi
57656 sc insight incorrect supply cap check uses token id instead of total supply in base mint
- Submitted on: Oct 27th 2025 at 21:57:31 UTC by @iehnnkta
- Report ID: #57656
- Report Type: Smart Contract
- Report severity: Insight
- Target: https://github.com/immunefi-team/audit-comp-belong/blob/feat/cairo/src/nft/nft.cairo
- Impacts: Permanent freezing of NFTs
Description
Brief / Intro
The _base_mint function enforces max_total_supply by comparing token_id + 1 to the cap rather than the actual minted count. This couples the cap to the token ID range, causing legitimate mints to revert and making the configured cap unreachable when IDs aren’t 0-indexed and contiguous.
Vulnerability Details
- Root cause: admission control ties the cap to
token_id(token_id + 1) instead of the real supply (total_supply + 1). - According to the docs, the
tokenIdcan be anything. In many codebases token IDs may be derived from user addresses (or other non-contiguous values). If token IDs are non-sequential or large, the current check can permanently DoS the minting process. - Even if token IDs are sequential in some deployments, this enforcement is inconsistent with how supply is normally tracked, causing operational mismatches (e.g., a first user mints a high token ID and prevents subsequent valid mints).
Impact
{% hint style="danger" %}
- Denial-of-Service on minting: valid mints can be blocked even when supply is below the cap if IDs aren’t in the range 0..max_total_supply-1.
- Operational inconsistencies: sales/airdrops/logic keyed off
total_supplymay stall or misreport because enforcement usestoken_idinstead of the actual minted count. {% endhint %}
References
- Vulnerable code location: https://github.com/immunefi-team/audit-comp-belong/blob/a17f775dcc4c125704ce85d4e18b744daece65af/src/nft/nft.cairo#L352-L355
Mitigation
Replace the token_id-based cap check with a total_supply-based check. Example patch:
{% code title="Suggested fix (Cairo snippet)" %}
{% endcode %}
```cairo fn _base_mint( ref self: ContractState, token_id: u256, recipient: ContractAddress, token_uri: felt252, ) { assert( - token_id + 1 <= self.nft_parameters.max_total_supply.read(), + self.nft_node.total_supply.read() + 1 <= self.nft_parameters.max_total_supply.read(), super::Errors::TOTAL_SUPPLY_LIMIT, );
self.nft_node.total_supply.write(self.nft_node.total_supply.read() + 1);
self.nft_node.metadata_uri.write(token_id, token_uri);
self.erc721.safe_mint(recipient, token_id, array![].span());
}
Ensure `total_supply` is the authoritative counter for minted NFTs and is incremented atomically when minting.
## Proof of Concept
<details>
<summary>Test case demonstrating the issue (expandable)</summary>
Include the below test case function in `test_nft.cairo`:
```rust
#[test]
#[should_panic(expected: 'Total supply limit reached')]
fn test_mintStaticPrice_token_id_above_cap_reverts() {
let signer = deploy_account_mock();
let (_, _nft, _, erc20mock) = deploy_factory_nft_receiver_erc20(signer, false, true);
let nft = INFTDispatcher { contract_address: _nft };
let receiver = signer;
// here we took token_id as some large number greater than max total supply, but in actual it will be u256 conversion of receiver address
let token_id: u256 = 100000; // well above typical MAX_TOTAL_SUPPLY
let whitelisted: bool = false;
let token_uri = constants::TOKEN_URI();
let static_price_hash = StaticPriceHash { receiver, token_id, whitelisted, token_uri };
start_cheat_caller_address_global(signer);
let signature: Span<felt252> = sign_message(static_price_hash.get_message_hash(_nft)).into();
stop_cheat_caller_address_global();
let static_params = StaticPriceParameters { receiver, token_id, whitelisted, token_uri, signature };
let mut static_params_array = array![static_params];
start_cheat_caller_address(_nft, signer);
// Should revert because implementation incorrectly checks token_id+1 <= max_total_supply,
// rejecting high token IDs even when total_supply is still below the cap.
nft.mintStaticPrice(static_params_array, erc20mock, constants::MINT_PRICE());
}
Observed test run:
$ snforge test test_mintStaticPrice_token_id_above_cap_reverts
Compiling snforge_scarb_plugin v0.51.1 (git+https://github.com/foundry-rs/starknet-foundry.git?tag=v0.51.1#6f5a02e54c76c2e740c0756568448265e12a6f2d)
Finished `release` profile [optimized] target(s) in 0.07s
Compiling test(nft_unittest) nft v0.1.0 (/Users/sainikethan/Documents/Immunefi/checkin-contracts/Scarb.toml)
Finished `dev` profile target(s) in 4 seconds
Collected 1 test(s) from nft package
Running 1 test(s) from src/
[PASS] nft::tests::test_nft::test_mintStaticPrice_token_id_above_cap_reverts (l1_gas: ~0, l1_data_gas: ~4608, l2_gas: ~5078152)
Tests: 1 passed, 0 failed, 0 ignored, 45 filtered out
Incorrect supply-cap check in _base_mint: comparing token_id instead of total_supply
Context
The target is the NFT contract of the Belong project, written in Cairo for Starknet. The file under review is src/nft/nft.cairo, and the function at the centre of the report is _base_mint, the internal routine that every mint path funnels through. It is responsible for writing the metadata URI, incrementing the supply counter and calling safe_mint on the underlying ERC721 component.
Before doing any of that, _base_mint performs admission control: it checks that the mint would not push the collection past max_total_supply, a value stored in nft_parameters. The report argues that this check is written against the wrong quantity, and that as a result the configured cap does not behave as a cap on supply at all.
Setup
The finding was produced against the Cairo implementation in the audit-comp-belong repository, at commit [redacted], with the vulnerable lines identified as L352-L355 of src/nft/nft.cairo.
The proof of concept is a unit test added to test_nft.cairo and run with Starknet Foundry's snforge. The test uses the project's own deployment helpers (deploy_account_mock, [redacted]) and cheatcodes (start_cheat_caller_address_global, start_cheat_caller_address, stop_cheat_caller_address_global). The toolchain version visible in the output is snforge_scarb_plugin v0.51.1.
No accounts, roles or on-chain state beyond the test fixtures are involved: this is a source-level review backed by a local test.
Finding it
The researcher read the admission control in _base_mint and noticed that the value compared against max_total_supply is derived from the token_id argument, not from the contract's own supply counter. The check is effectively token_id + 1 <= max_total_supply.
That is wrong for two reasons given in the report:
- The documentation states that the
tokenIdcan be anything. Token IDs are not guaranteed to be 0-indexed or contiguous, and in many codebases they are derived from user addresses or other non-sequential values. - Supply is normally tracked by a counter (
total_supply), which the function already maintains. Tying the cap to the ID range instead means the two notions of "how many have been minted" can diverge.
The consequence the researcher highlights is that a large or non-sequential token ID makes a legitimate mint revert even when the collection is far below its cap. Conversely, the configured cap becomes unreachable in the sense that it constrains IDs rather than the number of tokens.
Exploitation
There is no remote exploitation here; the report demonstrates the behaviour with a test. The steps below reproduce it.
Step 1: write a test that mints with a token ID above the cap
The test is added to test_nft.cairo. It is annotated #[should_panic(expected: 'Total supply limit reached')], so it passes when the mint reverts with the supply-limit error.
#[test]
#[should_panic(expected: 'Total supply limit reached')]
fn test_mintStaticPrice_token_id_above_cap_reverts() {
let signer = deploy_account_mock();
let (_, _nft, _, erc20mock) = [redacted](signer, false, true);
let nft = INFTDispatcher { contract_address: _nft };
let receiver = signer;
// here we took token_id as some large number greater than max total supply, but in actual it will be u256 conversion of receiver address
let token_id: u256 = 100000; // well above typical MAX_TOTAL_SUPPLY
let whitelisted: bool = false;
let token_uri = constants::TOKEN_URI();
let static_price_hash = StaticPriceHash { receiver, token_id, whitelisted, token_uri };
start_cheat_caller_address_global(signer);
let signature: Span<felt252> = sign_message(static_price_hash.get_message_hash(_nft)).into();
stop_cheat_caller_address_global();
let static_params = StaticPriceParameters { receiver, token_id, whitelisted, token_uri, signature };
let mut static_params_array = array![static_params];
start_cheat_caller_address(_nft, signer);
// Should revert because implementation incorrectly checks token_id+1 <= max_total_supply,
// rejecting high token IDs even when total_supply is still below the cap.
nft.mintStaticPrice(static_params_array, erc20mock, constants::MINT_PRICE());
}
The important parts:
token_idis set to100000, described in the comment as well above a typicalMAX_TOTAL_SUPPLY. The comment also notes that in a real deployment the ID would be theu256conversion of the receiver address, which is likewise a large, non-sequential number.- The parameters are hashed and signed by the
signeraccount, then passed tomintStaticPricetogether with the ERC20 used for payment and the mint price. This means the call is a fully authorised, correctly signed mint, not a malformed one. - The caller address is set to the signer for the duration of the call, so the mint is made by the account that signed the parameters.
Step 2: run the test
$ snforge test test_mintStaticPrice_token_id_above_cap_reverts
The observed output:
Compiling snforge_scarb_plugin v0.51.1 (git+https://github.com/foundry-rs/starknet-foundry.git?tag=v0.51.1#[redacted])
Finished `release` profile [optimized] target(s) in 0.07s
Compiling test(nft_unittest) nft v0.1.0 (/Users/sainikethan/Documents/Immunefi/checkin-contracts/Scarb.toml)
Finished `dev` profile target(s) in 4 seconds
Collected 1 test(s) from nft package
Running 1 test(s) from src/
[PASS] nft::tests::test_nft::test_mintStaticPrice_token_id_above_cap_reverts (l1_gas: ~0, l1_data_gas: ~4608, l2_gas: ~5078152)
Tests: 1 passed, 0 failed, 0 ignored, 45 filtered out
The [PASS] line is the evidence: the mint reverted with the supply-limit panic. The test passes precisely because the expected panic occurred.
Root cause
The admission control in _base_mint compares token_id + 1 against max_total_supply instead of comparing the real supply, total_supply + 1. The report's suggested patch shows the two lines side by side:
fn _base_mint(
ref self: ContractState,
token_id: u256,
recipient: ContractAddress,
token_uri: felt252,
) {
assert(
- token_id + 1 <= self.nft_parameters.max_total_supply.read(),
+ self.nft_node.total_supply.read() + 1 <= self.nft_parameters.max_total_supply.read(),
super::Errors::TOTAL_SUPPLY_LIMIT,
);
self.nft_node.total_supply.write(self.nft_node.total_supply.read() + 1);
self.nft_node.metadata_uri.write(token_id, token_uri);
self.erc721.safe_mint(recipient, token_id, array![].span());
}
The contract already keeps an authoritative counter: total_supply is incremented on every successful mint. The check simply does not use it. Because the documentation allows arbitrary token IDs, the ID range and the supply are independent, and a check on one cannot enforce a limit on the other.
Impact
The report lists two consequences:
- Denial of service on minting. Valid mints are blocked even when supply is below the cap, whenever IDs are not in the range
0..max_total_supply-1. The report lists permanent freezing of NFTs among its impacts. - Operational inconsistencies. Sales, airdrops and other logic keyed off
total_supplymay stall or misreport, because enforcement usestoken_idrather than the actual minted count.
The report also gives a concrete scenario: if the first user mints a high token ID, subsequent valid mints are prevented. The severity assigned by the researcher is Insight, and the practical reach depends on how token IDs are actually assigned in a given deployment.
Fix
The recommendation is to replace the token_id-based check with a total_supply-based one, as in the diff above, and to treat total_supply as the authoritative counter for minted NFTs, incremented atomically when minting. The report presents this as a suggested patch.
Variants to test
- Other cap checks in the same contract family. Look for any
assertorrequirethat compares a user-supplied identifier (token ID, order ID, nonce) against a limit that is meant to count objects. A positive result is a limit that can be bypassed or that blocks valid operations depending on the identifier chosen. - Mint paths that bypass
_base_mint. If any mint function writes supply or callssafe_mintdirectly, check whether it enforces the cap at all. A positive result is a mint that succeeds pastmax_total_supply. - Counter and identifier divergence. In systems where IDs come from addresses, hashes or timestamps, test with a very large ID on a fresh collection. A positive result is a revert with the supply-limit error while
total_supplyis still zero or low. - Off-by-one on the boundary. Mint exactly at
max_total_supplyand one past it, with both low and high IDs, to confirm which quantity the boundary actually tracks.
Hunting notes
This class of bug hides in admission control that is written against an input rather than against state. In NFT and token contracts, the giveaway is a cap check that mentions token_id, id or a caller-supplied number while the contract also maintains a total_supply or minted counter nearby. During review, read the mint entry points and follow every call down to the shared internal mint function, then compare the condition there with the counter that is incremented on success.
The documentation matters: if it says IDs can be arbitrary, any check on the ID range is suspect. The report's own test comment points at the realistic trigger, an ID derived from the receiver address, which is large and non-sequential by construction.
The report demonstrates the behaviour with a unit test using the project's deployment helpers, a signed mint request and a token ID above the cap. That is the pattern to copy when a finding is a logic error rather than a memory-safety issue: drive the real code path with valid inputs and let the unexpected revert be the evidence.
What happened, in plain words
Belong is a project that runs an NFT collection on Starknet, a blockchain network. An NFT is a digital item that a contract keeps track of: each one has a number, called a token ID, and the contract records who owns it. The contract is a program that lives on the blockchain and runs the same way for everyone. This contract is written in a programming language called Cairo, and the file in question is src/nft/nft.cairo.
The collection has a limit on how many NFTs can ever exist, a number stored under the name max_total_supply. Every time someone mints (creates) an NFT, the contract is supposed to check that the collection is not already full. The researcher found that this check looks at the wrong number. Instead of counting how many NFTs have actually been minted so far, it looks at the token ID of the NFT being created. If token IDs can be any number, as the project's own documentation says, then a perfectly valid mint can be refused even when the collection is nearly empty.
The report labels this an Insight, a logic problem worth fixing. The report lists permanent freezing of NFTs among its impacts.
Background you need first
A few ideas come up again and again, so here they are from zero.
- Smart contract. A program deployed on a blockchain. Nobody can edit it after deployment, and anyone can call the functions it exposes. Think of a vending machine bolted to the pavement: the rules are fixed and every customer gets the same behaviour.
- NFT. A unique entry in a contract's records, identified by a number (the token ID) and owned by an address. Think of a numbered ticket in a book of tickets, where the contract is the book.
- Mint. The act of creating a new NFT and assigning it to someone. The test calls a function called
mintStaticPrice, which takes payment in an ERC20 token and a cryptographic signature. - Signature. A cryptographic proof that a particular account approved a particular request. It is like a wax seal on a letter: anyone can check it came from the right person, and nobody can forge it.
- Token ID. The number that names one NFT. The report stresses that the project's documentation allows this number to be anything, not just 0, 1, 2, 3 in order. In many systems the ID is derived from the owner's address, which produces a huge, scattered number.
- Supply counter. A separate number the contract keeps, called
total_supply, which goes up by one every time an NFT is successfully created. This is the honest answer to "how many exist?". - Cap. A maximum.
max_total_supplyis meant to be the ceiling on how many NFTs the collection can contain. - Assert. A check inside a program that stops everything with an error message if the condition is false. In Cairo it looks like
assert(condition, error). If the condition fails, the whole transaction is undone, as if it never happened. - Revert. What happens when an assert fails: the transaction is cancelled and any changes are rolled back. The user's mint does not go through.
- Denial of service (DoS). A situation where something that should work is made to fail. It does not steal anything; it stops the service. Think of a shop that refuses to serve customers who arrive with a ticket number above 100, even though only three items have been sold.
- Unit test. A small program written to call one function and check what it does. It runs on the developer's own machine, not on the live blockchain.
- Starknet Foundry and
snforge. A toolkit for writing and running tests for Starknet contracts.snforgeis the command that runs them. - Cheatcode. A special instruction in a test that lets you pretend to be a particular account or change the state of the test world. It exists only in tests, never on the real network.
The context of the finding
The target is the NFT contract of the Belong project, written in Cairo for Starknet. The file under review is src/nft/nft.cairo, and the function at the centre of the report is _base_mint. This is an internal routine: users never call it directly, but every public mint path ends up inside it. It is responsible for three things: writing the metadata URI (a link describing the NFT's picture and details), incrementing the supply counter, and calling safe_mint on the underlying ERC721 component (the standard machinery that actually records ownership).
Before doing any of that, _base_mint performs admission control: it checks that the mint would not push the collection past max_total_supply, a value stored in nft_parameters. The report argues that this check is written against the wrong quantity, and that as a result the configured cap does not behave as a cap on supply at all.
Setup
The finding was produced against the Cairo implementation in the audit-comp-belong repository, at commit [redacted], with the vulnerable lines identified as L352-L355 of src/nft/nft.cairo. A commit is a fixed snapshot of the code, so anyone can go back and look at exactly the same version.
The proof of concept is a unit test added to test_nft.cairo and run with Starknet Foundry's snforge. The test uses the project's own deployment helpers (deploy_account_mock, [redacted]) and cheatcodes (start_cheat_caller_address_global, start_cheat_caller_address, stop_cheat_caller_address_global). The toolchain version visible in the output is snforge_scarb_plugin v0.51.1.
No accounts, roles or on-chain state beyond the test fixtures are involved: this is a source-level review backed by a local test. The researcher read the code and wrote a test that shows the mint reverting.
Finding it
The researcher read the admission control in _base_mint and noticed that the value compared against max_total_supply is derived from the token_id argument, not from the contract's own supply counter. The check is effectively token_id + 1 <= max_total_supply.
That is wrong for two reasons given in the report:
- The documentation states that the
tokenIdcan be anything. Token IDs are not guaranteed to be 0-indexed or contiguous, and in many codebases they are derived from user addresses or other non-sequential values. - Supply is normally tracked by a counter (
total_supply), which the function already maintains. Tying the cap to the ID range instead means the two notions of "how many have been minted" can diverge.
The consequence the researcher highlights is that a large or non-sequential token ID makes a legitimate mint revert even when the collection is far below its cap. Conversely, the configured cap becomes unreachable in the sense that it constrains IDs rather than the number of tokens.
Exploitation
There is no remote exploitation here; the report demonstrates the behaviour with a test. The steps below reproduce it.
Step 1: write a test that mints with a token ID above the cap
The test is added to test_nft.cairo. It is annotated #[should_panic(expected: 'Total supply limit reached')], so it passes when the mint reverts with the supply-limit error. This is a slightly upside-down idea at first: the test is written to expect a failure, and it counts as a success when the failure happens. The point is to prove that a mint which should have worked instead gets refused.
#[test]
#[should_panic(expected: 'Total supply limit reached')]
fn test_mintStaticPrice_token_id_above_cap_reverts() {
let signer = deploy_account_mock();
let (_, _nft, _, erc20mock) = [redacted](signer, false, true);
let nft = INFTDispatcher { contract_address: _nft };
let receiver = signer;
// here we took token_id as some large number greater than max total supply, but in actual it will be u256 conversion of receiver address
let token_id: u256 = 100000; // well above typical MAX_TOTAL_SUPPLY
let whitelisted: bool = false;
let token_uri = constants::TOKEN_URI();
let static_price_hash = StaticPriceHash { receiver, token_id, whitelisted, token_uri };
start_cheat_caller_address_global(signer);
let signature: Span<felt252> = sign_message(static_price_hash.get_message_hash(_nft)).into();
stop_cheat_caller_address_global();
let static_params = StaticPriceParameters { receiver, token_id, whitelisted, token_uri, signature };
let mut static_params_array = array![static_params];
start_cheat_caller_address(_nft, signer);
// Should revert because implementation incorrectly checks token_id+1 <= max_total_supply,
// rejecting high token IDs even when total_supply is still below the cap.
nft.mintStaticPrice(static_params_array, erc20mock, constants::MINT_PRICE());
}
Line by line, in plain words:
#[test]marks the function below as a test that the runner should execute.#[should_panic(expected: 'Total supply limit reached')]says: this test is only correct if the code stops with that exact error message. If the mint succeeded, the test would be marked as failed, because the bug would not be there.fn test_mintStaticPrice_token_id_above_cap_reverts() {starts the test function. The name says what it does: mint at a static price with a token ID above the cap, and expect a revert.let signer = deploy_account_mock();creates a pretend account in the test world. This account will both pay for and receive the NFT.let (_, _nft, _, erc20mock) = [redacted](signer, false, true);deploys the NFT contract and a mock ERC20 payment token using the project's own helper. The underscores are placeholders for values the test does not need.let nft = INFTDispatcher { contract_address: _nft };wraps the deployed contract's address in a dispatcher, which is the object you call functions on. Think of it as saving the vending machine's address in your phone so you can ring it.let receiver = signer;says the NFT will go to the same account that signs the request.- The comment explains the choice of ID: in a real deployment the ID would be the
u256conversion of the receiver's address, which is also a very large number.u256is an unsigned integer type that can hold enormous values. let token_id: u256 = 100000;sets the ID to one hundred thousand, far above a typical maximum supply.let whitelisted: bool = false;says this mint is not on a special allow-list. It is an ordinary public mint.let token_uri = constants::TOKEN_URI();fetches the metadata link used by the project's tests.let static_price_hash = StaticPriceHash { receiver, token_id, whitelisted, token_uri };bundles the request details into a structure that can be hashed. Hashing turns the details into a short fingerprint, so the signature covers exactly these values and cannot be reused for different ones.start_cheat_caller_address_global(signer);tells the test environment to pretend that the signer is the one making calls, so the signature can be produced as if by that account.let signature: Span<felt252> = sign_message(static_price_hash.get_message_hash(_nft)).into();signs the fingerprint of the request.felt252is Cairo's basic number type, andSpanis a view over a list of them. The result is the wax seal mentioned earlier.stop_cheat_caller_address_global();ends the pretence, so later calls are not automatically attributed to the signer.let static_params = StaticPriceParameters { receiver, token_id, whitelisted, token_uri, signature };builds the actual argument the mint function expects, now including the signature.let mut static_params_array = array![static_params];puts it in a list, because the mint function accepts a batch of requests.start_cheat_caller_address(_nft, signer);makes the next call to the NFT contract appear to come from the signer. This matters because the contract checks who is asking.- The comment restates the bug: the implementation checks
token_id + 1 <= max_total_supply, so a high ID is rejected even when the real supply is low. nft.mintStaticPrice(static_params_array, erc20mock, constants::MINT_PRICE());performs the mint, paying with the mock ERC20 at the project's mint price. This is a fully authorised, correctly signed request. Nothing about it is malformed.
Why this step: the only way to show a logic bug like this is to send a request that should be accepted and watch it be refused. Using the project's own helpers and a real signature removes any doubt that the refusal is caused by the ID check rather than by a bad request.
Step 2: run the test
$ snforge test test_mintStaticPrice_token_id_above_cap_reverts
This command asks the test runner to run only the named test. The observed output:
Compiling snforge_scarb_plugin v0.51.1 (git+https://github.com/foundry-rs/starknet-foundry.git?tag=v0.51.1#[redacted])
Finished `release` profile [optimized] target(s) in 0.07s
Compiling test(nft_unittest) nft v0.1.0 (/Users/sainikethan/Documents/Immunefi/checkin-contracts/Scarb.toml)
Finished `dev` profile target(s) in 4 seconds
Collected 1 test(s) from nft package
Running 1 test(s) from src/
[PASS] nft::tests::test_nft::test_mintStaticPrice_token_id_above_cap_reverts (l1_gas: ~0, l1_data_gas: ~4608, l2_gas: ~5078152)
Tests: 1 passed, 0 failed, 0 ignored, 45 filtered out
What each part means:
- The first two lines show the test plugin being compiled, then finishing. Compiling means turning the source code into something the machine can run.
- The next two lines compile the test package itself. The path in brackets is where the project sits on the researcher's own computer.
Collected 1 test(s)andRunning 1 test(s)confirm that only the chosen test was run.[PASS]is the evidence. The test passed, and because the test was written to expect a panic with the supply-limit message, passing means the mint reverted with that message.- The numbers in brackets are gas figures, a measure of computing effort. They are not important to the finding.
Tests: 1 passed, 0 failed, 0 ignored, 45 filtered outsays one test ran and the other 45 in the project were skipped because of the filter in the command.
Root cause
The admission control in _base_mint compares token_id + 1 against max_total_supply instead of comparing the real supply, total_supply + 1. The report's suggested patch shows the two lines side by side:
fn _base_mint(
ref self: ContractState,
token_id: u256,
recipient: ContractAddress,
token_uri: felt252,
) {
assert(
- token_id + 1 <= self.nft_parameters.max_total_supply.read(),
+ self.nft_node.total_supply.read() + 1 <= self.nft_parameters.max_total_supply.read(),
super::Errors::TOTAL_SUPPLY_LIMIT,
);
self.nft_node.total_supply.write(self.nft_node.total_supply.read() + 1);
self.nft_node.metadata_uri.write(token_id, token_uri);
self.erc721.safe_mint(recipient, token_id, array![].span());
}
Reading it in plain words:
fn _base_mint(begins the internal function.ref self: ContractStatemeans it can read and change the contract's stored data. The other three arguments are the NFT's number, who receives it, and its metadata link.- The
assert(block is the admission check. The line marked with a minus is the current, wrong version: it takes the token ID, adds one, and compares that to the cap. The line marked with a plus is the suggested replacement: it takes the stored supply counter, adds one, and compares that to the cap. In a diff, a minus line is what is being removed and a plus line is what is being added. super::Errors::TOTAL_SUPPLY_LIMIT,is the error message shown if the check fails. This is the message the test expects.self.nft_node.total_supply.write(self.nft_node.total_supply.read() + 1);reads the supply counter, adds one, and writes it back. This is the honest count of how many NFTs exist.self.nft_node.metadata_uri.write(token_id, token_uri);stores the metadata link under this token ID.self.erc721.safe_mint(recipient, token_id, array![].span());hands the actual creation of the NFT to the standard ERC721 component, giving it to the recipient with the chosen ID.
The contract already keeps an authoritative counter: total_supply is incremented on every successful mint. The check simply does not use it. Because the documentation allows arbitrary token IDs, the ID range and the supply are independent, and a check on one cannot enforce a limit on the other.
Impact
The report lists two consequences:
- Denial of service on minting. Valid mints are blocked even when supply is below the cap, whenever IDs are not in the range
0..max_total_supply-1. - Operational inconsistencies. Sales, airdrops and other logic keyed off
total_supplymay stall or misreport, because enforcement usestoken_idrather than the actual minted count. An airdrop is a distribution of free NFTs to a list of addresses.
The report also gives a concrete scenario: if the first user mints a high token ID, subsequent valid mints are prevented. The severity assigned by the researcher is Insight, and the practical reach depends on how token IDs are actually assigned in a given deployment.
Fix
The recommendation is to replace the token_id-based check with a total_supply-based one, as in the diff above, and to treat total_supply as the authoritative counter for minted NFTs, incremented atomically when minting. Atomically here means in the same step as the mint, so the count can never drift out of step with reality. The report presents this as a suggested patch.
Variants to test
These are follow-up ideas for anyone reviewing similar code.
- Other cap checks in the same contract family. Look for any
assertorrequirethat compares a user-supplied identifier (token ID, order ID, nonce) against a limit that is meant to count objects. A positive result is a limit that can be bypassed or that blocks valid operations depending on the identifier chosen. - Mint paths that bypass
_base_mint. If any mint function writes supply or callssafe_mintdirectly, check whether it enforces the cap at all. A positive result is a mint that succeeds pastmax_total_supply. - Counter and identifier divergence. In systems where IDs come from addresses, hashes or timestamps, test with a very large ID on a fresh collection. A positive result is a revert with the supply-limit error while
total_supplyis still zero or low. - Off-by-one on the boundary. Mint exactly at
max_total_supplyand one past it, with both low and high IDs, to confirm which quantity the boundary actually tracks. Off-by-one means a mistake of exactly one at the edge of a range.
Hunting notes
This class of bug hides in admission control that is written against an input rather than against state. In NFT and token contracts, the giveaway is a cap check that mentions token_id, id or a caller-supplied number while the contract also maintains a total_supply or minted counter nearby. During review, read the mint entry points and follow every call down to the shared internal mint function, then compare the condition there with the counter that is incremented on success.
The documentation matters: if it says IDs can be arbitrary, any check on the ID range is suspect. The report's own test comment points at the realistic trigger, an ID derived from the receiver address, which is large and non-sequential by construction.
The report demonstrates the behaviour with a unit test using the project's deployment helpers, a signed mint request and a token ID above the cap. That is the pattern to copy when a finding is a logic error rather than a memory-safety issue: drive the real code path with valid inputs and let the unexpected revert be the evidence.
Glossary
- Airdrop: a distribution of free tokens or NFTs to a list of addresses.
- Assert: a check in a program that stops execution with an error if its condition is false.
- Atomic: done in a single indivisible step, so it cannot be half-finished.
- Cairo: the programming language used to write Starknet smart contracts.
- Cap: a maximum allowed amount.
- Cheatcode: a test-only instruction that lets a test pretend to be an account or alter the test environment.
- Commit: a fixed snapshot of a code repository at a point in time.
- Compile: turn source code into a form the machine can run.
- Denial of service (DoS): making a service fail for legitimate users without stealing anything.
- Diff: a side-by-side display of removed (minus) and added (plus) lines of code.
- Dispatcher: an object in a test that lets you call functions on a deployed contract at a given address.
- ERC20: a standard for fungible tokens on Ethereum-style networks, commonly used as money.
- ERC721: a standard for NFTs, where each token is unique and has an owner.
felt252: Cairo's basic numeric type, used for small values and short strings.- Gas: a measure of computing effort, used to price transactions.
- Hash: a short fingerprint computed from data, so the data can be checked without being repeated.
- Insight: the lowest severity label on the platform, for a logic issue worth fixing rather than an active attack.
- Metadata URI: a link describing an NFT's name, picture and other details.
- Mint: create a new NFT and assign it to an owner.
- NFT: a unique digital item recorded in a smart contract, identified by a token ID.
- Off-by-one: a mistake of exactly one at the edge of a range.
- Revert: cancel a transaction and roll back its changes because a check failed.
- Signature: a cryptographic proof that a particular account approved particular data.
- Smart contract: a program deployed on a blockchain whose rules are fixed and callable by anyone.
snforge: the command-line test runner from Starknet Foundry.Span: a Cairo type that is a view over a list of values.- Starknet: a blockchain network where these contracts run.
- Starknet Foundry: a toolkit for testing Starknet contracts.
- Supply counter (
total_supply): a stored number that goes up by one on every successful mint. - Token ID: the number that names one NFT.
u256: an unsigned integer type that can hold very large values.- Unit test: a small program that calls one function and checks the result.
- Whitelist: a list of addresses allowed to do something that others cannot.