Writing a secure ERC-721 contract from scratch, without OpenZeppelin
When we started Quantum Genesis I made a call most people would talk me out of: no OpenZeppelin. Not because it is bad — it is the opposite, audited and battle-tested — but because this collection had a very specific shape. Fixed supply of 100, minted only by the deployer, no marketplace features, no upgrades. Inheriting the full OZ stack for that felt like pulling in a library to flip one switch.
So we wrote the Solidity ourselves. This post goes through the contract decision by decision: why we skipped the library, the custom-error tradeoff, access control, reentrancy, the ERC-721 core, EIP-2981 royalties, batch minting, and one limitation I would fix if I were deploying again. The Solidity snippets below are simplified sketches, not the deployed source; the on-chain values are checked against the live contract at 0x488fCfaEA5fDf1cF6BAED5e8A34D7858033E1a27 on Polygon.
One honest caveat up front: for a contract holding significant value, OpenZeppelin is the safer bet, full stop. This approach made sense for a small fixed-supply collection where we controlled the entire mint. Keep that context through everything below.

Why skip OpenZeppelin
Three reasons drove it:
- Bytecode size. OZ's ERC-721 pulls in a chain of inherited contracts: Context, ERC165, the interfaces, and whichever extensions you choose. For 100 tokens with no marketplace features, most of that is dead weight, and every byte costs deployment gas.
- No hidden assumptions. Inheriting OZ means inheriting their design choices. Ownable's two-step transfer is a pattern we would never use. I wanted to understand every line we deployed.
- It fit the experiment. The project started with quantum computers making art. Writing the contract by hand matched the spirit.
The result compiles to about 12.5 KB of runtime bytecode, deployed for roughly 0.08 POL. A library-based contract with the same features would have cost more to deploy and would have taught us less.
The requirements, non-negotiable
- 100 NFTs, fixed supply, enforced by the contract.
- Batch minting, so 100 tokens do not mean 100 transactions.
- 5% royalties expressed through EIP-2981.
- No pause, no proxy, no upgrade path.
- Polygon deployment, because gas should not be the main expense of an art project.
Notice what is not on the list: no allowlist, no public sale, no reveal mechanic, no admin dashboard. Every feature you do not write is a bug you cannot ship.
Storage that fits on one screen
mapping(uint256 => address) private _owners;
mapping(address => uint256) private _balances;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
string private _name = "Quantum Genesis";
string private _symbol = "QGEN";
string private _baseURI;
uint256 private _totalSupply;
uint256 public constant MAX_SUPPLY = 100;
That is the core of the state; the deployed contract also keeps the Enumerable indexes. There is no per-token URI storage, and no royalty mapping per token. Keeping the layout small is not just an aesthetic preference: fewer storage slots means cheaper mints and fewer places for an invariant to break.
Custom errors instead of strings
Solidity 0.8.4 introduced custom errors, and they are cheaper than require(condition, "message") in two ways: the string lives in the bytecode (deployment cost) and is encoded into the revert data on every failure (execution cost). A custom error is a four-byte selector.
error NotOwner();
error TokenDoesNotExist(uint256 tokenId);
error TransferToZeroAddress();
error ApprovalToCurrentOwner();
error NotApprovedOrOwner();
error MintToZeroAddress();
error TokenAlreadyMinted(uint256 tokenId);
error MaxSupplyReached(uint256 maxSupply);
Since only the owner mints, most users never hit these errors. The savings are real anyway: smaller bytecode, cheaper reverts, and error names that show up decoded in block explorers instead of a wall of hex-encoded text.
Access control without Ownable
address private _owner;
modifier onlyOwner() {
if (msg.sender != _owner) revert NotOwner();
_;
}
constructor() {
_owner = msg.sender;
}
That is the core of the ownership system. Ownership can be moved in one step with transferOwnership; there is no two-step transfer and no renounce function. The deployer is still the owner. On-chain today, owner() returns the creator wallet 0xa198032b224f6087cE83B8b499921AD64A5D2e00.
The owner's privileges are narrow by construction: mint and batch-mint until the supply is exhausted, receive EIP-2981 royalties, update the base and contract URIs, withdraw any balance held by the contract, and transfer ownership. There is no pause function and no upgrade path — neither selector exists in the deployed bytecode — so the collection cannot be stopped or migrated. That is the property I cared about most, and it is enforced by omission rather than by policy.
Reentrancy: checks, effects, interactions
Reentrancy is the oldest smart contract bug in the book. In ERC-721 the risk lives in safeTransferFrom, which calls onERC721Received on contract recipients. A malicious recipient can re-enter during that callback.
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal {
// CHECKS
if (to == address(0)) revert TransferToZeroAddress();
// EFFECTS — all state committed before any external call
_owners[tokenId] = to;
_balances[from] -= 1;
_balances[to] += 1;
delete _tokenApprovals[tokenId];
emit Transfer(from, to, tokenId);
// INTERACTIONS — external call last
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, data)
returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
revert("ERC721: transfer to non-receiver");
}
} catch {
revert("ERC721: transfer to non-receiver");
}
}
}
By the time the recipient's callback runs, the token already belongs to the new owner and the approvals are cleared. A re-entrant call finds nothing to exploit. A reentrancy guard would also work, but it costs an SSTORE on every transfer; ordering the code correctly costs nothing except discipline.
The ERC-721 core
The standard requires the usual surface: balanceOf, ownerOf, both safeTransferFrom overloads, transferFrom, approve, setApprovalForAll, getApproved, isApprovedForAll, plus name, symbol and tokenURI. The security-critical part is authorization on every transfer:
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
address tokenOwner = _owners[tokenId];
if (tokenOwner == address(0)) revert TokenDoesNotExist(tokenId);
return (
spender == tokenOwner ||
_tokenApprovals[tokenId] == spender ||
_operatorApprovals[tokenOwner][spender]
);
}
Every path that moves a token calls it. Missing one of those three branches is the most common way a hand-rolled ERC-721 gets drained, which is exactly the kind of thing audits catch and unit tests often do not.
EIP-2981 royalties
uint96 private constant ROYALTY_FEE = 500; // 5% in basis points
function royaltyInfo(uint256, uint256 salePrice)
external view returns (address receiver, uint256 royaltyAmount)
{
return (_royaltyReceiver, (salePrice * ROYALTY_FEE) / 10000);
}
function supportsInterface(bytes4 interfaceId) public pure returns (bool) {
return
interfaceId == 0x80ac58cd || // ERC-721
interfaceId == 0x5b5e139f || // ERC-721 Metadata
interfaceId == 0x2a55205a || // EIP-2981
interfaceId == 0x01ffc9a7; // ERC-165
}
On-chain, royaltyInfo(1, 10000) returns an amount of 500 — 5% — to the creator address. That is the number marketplaces read; there is no per-marketplace opt-in for an owner to toggle.
One asterisk worth repeating: EIP-2981 is advisory. A marketplace can ignore it, and some do. The standard makes the royalty visible and consistent across compliant venues; it does not enforce payment on-chain.
Batch minting, and why we kept batches small
function mintBatch(address to, uint256 count) external onlyOwner {
if (to == address(0)) revert MintToZeroAddress();
if (_totalSupply + count > MAX_SUPPLY) revert MaxSupplyReached(MAX_SUPPLY);
for (uint256 i = 0; i < count; ) {
uint256 tokenId = ++_totalSupply;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
unchecked { ++i; }
}
_balances[to] += count; // one update instead of one per token
}
Four details do the work here. The supply check happens before the loop, so a batch that would exceed 100 reverts without leaving partial state. Keeping batches to 20 tokens or fewer keeps a single transaction comfortably under the block gas limit — try 50 and you risk a revert you still pay for. The balance is updated once rather than per token, saving a cold-to-warm SSTORE per mint. And the loop counter is unchecked, which is safe because it is bounded by the batch size.
The collection minted 18 tokens individually (#1–#18, while we verified that metadata resolved correctly) and the remaining 82 in five batches: 20, 20, 14, 14, 14. The uneven tail is deliberate — 20 was a ceiling, not a target.
Deploying with web3.py
contract = w3.eth.contract(abi=abi, bytecode=bytecode)
tx = contract.constructor().build_transaction({
"from": account.address,
"nonce": w3.eth.get_transaction_count(account.address),
"gasPrice": w3.eth.gas_price,
"chainId": 137,
})
tx["gas"] = int(w3.eth.estimate_gas(tx) * 1.2)
signed = account.sign_transaction(tx)
receipt = w3.eth.wait_for_transaction_receipt(
w3.eth.send_raw_transaction(signed.raw_transaction)
)
Deployment cost about 0.08 POL. All 100 mints together cost roughly another 0.25 POL, so the whole collection landed under a dollar. The deployment walkthrough with the full script and the gas table is in the mint post.
What you can check on-chain right now
name()returnsQuantum Genesis,symbol()returnsQGEN.totalSupply()returns 100, and the contract enforcesMAX_SUPPLY = 100.tokenURI(42)returnsipfs://bafybeif7z767.../42.json.royaltyInfo(1, 10000)returns a 500 basis-point royalty to the creator.- Every value above can be read directly from the contract (for example with the web3.py calls in the deploy post), so you don't have to trust this post.
The limitation I would fix
The contract exposes a setBaseURI(string) function, and that selector is present in the deployed bytecode. It was necessary during setup — the metadata folder had to be pointed at the right CID after deployment — but it means the owner can still repoint token metadata. We have not touched it since the collection went live, and the files it points to are content-addressed, so any change would be visible as a different CID. Still, "the owner cannot change the metadata" would be too strong a claim, and I would rather state the limitation than let someone discover it.
If I were deploying again, I would either drop the setter after the initial configuration or transfer ownership to an address nobody controls. Immutability you can verify is worth more than an admin convenience you promise not to use.
Was skipping OpenZeppelin worth it?
For this collection, yes. The contract is small, the entire state fits on a screen, deployment was cheap and every decision is legible. Is it as battle-tested as OZ? No, and I will not pretend otherwise. It has one job: hold 100 fixed-supply tokens, expose royalties, and never change shape. For that job, a hand-rolled contract with a short surface area is defensible.
If your project has upgrades, a public mint, allowlists, or anything holding serious value, use the audited library. The lesson is not "roll your own"; it is "decide which state transitions you never want, and make them impossible by construction". The contract is the smallest part of this collection, and that is exactly why it works.

The metadata side — tokenURI structure, attributes and IPFS addressing — is covered in the provenance post and the ERC-721 metadata walkthrough.
Comments
Post a Comment