Every "mint" button is the same small pipeline: a contract that sells tokens, a front end that connects a wallet, and a handful of checks in between so that users don't pay for the wrong thing on the wrong network. Tutorials usually cover the happy path. This post covers it too, and then spends most of its time on the unglamorous parts that decide whether a mint page feels trustworthy: reading the price from the contract, checking the network, and handling a rejected transaction without a scary error.
I'll build the contract first and test it, then walk through the React component. Where I haven't been able to test something, I say so.
The contract
MintPass is a minimal ERC-721 sale built on OpenZeppelin 5. It has a maximum supply and a fixed price, both set at deployment and stored as immutable values. Anyone can mint by sending the exact price, and the owner can withdraw the proceeds.
MintPass.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
contract MintPass is ERC721, Ownable {
uint256 public immutable maxSupply;
uint256 public immutable price;
uint256 public totalMinted;
string private _base;
error SoldOut();
error WrongPayment(uint256 sent, uint256 required);
constructor(address initialOwner, uint256 maxSupply_, uint256 price_, string memory baseURI_)
ERC721("Mint Pass", "PASS")
Ownable(initialOwner)
{
maxSupply = maxSupply_;
price = price_;
_base = baseURI_;
}
function mint() external payable returns (uint256 tokenId) {
if (totalMinted >= maxSupply) revert SoldOut();
if (msg.value != price) revert WrongPayment(msg.value, price); // exact payment: no silent overpay
tokenId = ++totalMinted;
_safeMint(msg.sender, tokenId);
}
function withdraw() external onlyOwner {
(bool ok, ) = owner().call{value: address(this).balance}("");
require(ok, "withdraw failed");
}
function _baseURI() internal view override returns (string memory) {
return _base;
}
}
Design choices worth noticing:
- Exact payment.
mintreverts unlessmsg.value == price. Accepting "at least the price" is common, but it silently keeps overpayments. Exactness protects users from typos and from front ends that send the wrong amount. - Custom errors with data.
WrongPayment(sent, required)tells a developer exactly what went wrong, which makes debugging and good UI messages easier. _safeMint. It checks that a contract recipient can handle ERC-721 tokens. It also gives a receiving contract a callback, so a payable function that calls it should be treated as an external call. This version updatestotalMintedbefore minting, which is the safe order.- Public
priceandmaxSupply. They exist so the front end can read them instead of hard-coding. - OpenZeppelin 5 details.
Ownabletakes the initial owner in its constructor, which is a change from version 4.
The contract tests
MintPass.ts
import { expect } from "chai";
import { network } from "hardhat";
const { ethers, networkHelpers } = await network.create();
const PRICE = ethers.parseEther("0.01");
async function deploy() {
const [owner, alice, bob] = await ethers.getSigners();
const nft = await ethers.deployContract("MintPass", [owner.address, 2n, PRICE, "ipfs://example-cid/"]);
return { nft, owner, alice, bob };
}
describe("MintPass", function () {
it("mints with the exact price and sets ownership and tokenURI", async function () {
const { nft, alice } = await networkHelpers.loadFixture(deploy);
await expect(nft.connect(alice).mint({ value: PRICE })).to.emit(nft, "Transfer");
expect(await nft.ownerOf(1n)).to.equal(alice.address);
expect(await nft.tokenURI(1n)).to.equal("ipfs://example-cid/1");
});
it("rejects the wrong payment", async function () {
const { nft, alice } = await networkHelpers.loadFixture(deploy);
await expect(nft.connect(alice).mint({ value: PRICE - 1n })).to.be.revertedWithCustomError(nft, "WrongPayment");
await expect(nft.connect(alice).mint({ value: PRICE + 1n })).to.be.revertedWithCustomError(nft, "WrongPayment");
});
it("stops at max supply", async function () {
const { nft, alice, bob } = await networkHelpers.loadFixture(deploy);
await nft.connect(alice).mint({ value: PRICE });
await nft.connect(bob).mint({ value: PRICE });
await expect(nft.connect(alice).mint({ value: PRICE })).to.be.revertedWithCustomError(nft, "SoldOut");
});
it("only the owner can withdraw, and the balance moves", async function () {
const { nft, owner, alice } = await networkHelpers.loadFixture(deploy);
await nft.connect(alice).mint({ value: PRICE });
await expect(nft.connect(alice).withdraw()).to.be.revertedWithCustomError(nft, "OwnableUnauthorizedAccount");
await expect(nft.withdraw()).to.changeEtherBalance(ethers, owner, PRICE);
});
});
Four tests pass. They cover a successful mint (checking ownership and the token URI), a wrong payment, selling out and the owner-only withdrawal. Note what they do not cover: metadata hosting, royalties, allowlists (see the Merkle allowlist post) and reveals. Most of the real-world risk in NFT projects sits in those parts.
The React component
The front end does five things in order: check for a wallet, request account access, verify the network, read the price from the contract and send the transaction. I'll explain each step after the code.
MintButton.tsx
import { useState } from "react";
import { BrowserProvider, Contract, formatEther, isError } from "ethers";
const ABI = [
"function price() view returns (uint256)",
"function totalMinted() view returns (uint256)",
"function maxSupply() view returns (uint256)",
"function mint() payable returns (uint256)",
];
declare global {
interface Window {
ethereum?: import("ethers").Eip1193Provider;
}
}
type Props = { contractAddress: string; expectedChainId: bigint };
export function MintButton({ contractAddress, expectedChainId }: Props) {
const [status, setStatus] = useState<string>("");
const [busy, setBusy] = useState(false);
async function mint() {
if (!window.ethereum) return setStatus("No wallet found. Install a browser wallet first.");
setBusy(true);
try {
const provider = new BrowserProvider(window.ethereum);
await provider.send("eth_requestAccounts", []); // opens the wallet's connect prompt
const network = await provider.getNetwork();
if (network.chainId !== expectedChainId) {
return setStatus(`Wrong network. Switch your wallet to chain ${expectedChainId}.`);
}
const signer = await provider.getSigner();
const nft = new Contract(contractAddress, ABI, signer);
// Read the price from the contract. Never hard-code it in the UI.
const price: bigint = await nft.price();
setStatus(`Confirm the ${formatEther(price)} ETH payment in your wallet…`);
const tx = await nft.mint({ value: price });
setStatus("Waiting for confirmation…");
await tx.wait();
setStatus("Minted. Check your wallet or the block explorer.");
} catch (err) {
if (isError(err, "ACTION_REJECTED")) setStatus("You rejected the request in your wallet.");
else if (isError(err, "CALL_EXCEPTION")) setStatus(`The contract rejected the mint: ${err.reason ?? "reverted"}`);
else setStatus("Something went wrong. Check the console for details.");
console.error(err);
} finally {
setBusy(false);
}
}
return (
<div>
<button onClick={mint} disabled={busy}>{busy ? "Working…" : "Mint"}</button>
<p role="status">{status}</p>
</div>
);
}
Walking through it
- Detect a wallet. Browser wallets inject an EIP-1193 provider at
window.ethereum. The component declares its type withEip1193Providerfrom ethers, and shows a plain message if nothing is there, rather than failing silently. Remember that some users have several wallet extensions; a production app should offer a chooser. - Request access.
provider.send("eth_requestAccounts", [])opens the wallet's connect prompt. EIP-1193 explains that providers shouldn't expose accounts by default, which is why this explicit request exists. Call it in response to a click, not on page load. Unprompted pop-ups feel like phishing. - Check the network. If your contract is on Sepolia and the wallet is on mainnet, the call goes to a different chain, where the address may be empty or, worse, a different contract. The component compares
network.chainIdwith the expected chain and refuses to continue. A friendlier version would callwallet_switchEthereumChain; I've left it out to keep the code short. - Read the price from the contract. The UI asks
price()and sends exactly that value. Never hard-code the price in the front end, because the two will drift apart, and the contract is the source of truth. - Send and wait.
nft.mint({ value: price })returns once the wallet signs and broadcasts;tx.wait()resolves when it's mined. The component shows a status at each stage, since users get anxious during the wait.
Error handling users will actually hit
Three kinds of failure happen in real life, and the component distinguishes them with ethers v6's isError helper:
- The user rejects the request. EIP-1193 defines code 4001 for this, and ethers v6 surfaces it as
ACTION_REJECTED. This is not an error to scare anyone with. Say "You rejected the request" and let them try again. - The contract reverts.
CALL_EXCEPTIONcovers sold-out, wrong payment and similar cases. Show the reason if there is one. Better, decode the custom error so "SoldOut" becomes "This mint has sold out". - Everything else. Log it to the console (and to your error tracker) and show a generic message. Don't show raw RPC errors to users.
What I would add before launch
- Gas estimates and simulation. Call
mint.staticCallfirst, so a mint that will revert fails before the wallet asks for a signature. - Listening for changes. EIP-1193 specifies a
chainChangedevent, and wallets also emit account changes. Update the UI when users switch, instead of showing stale state. - Sold-out and supply display. Read
totalMintedandmaxSupplyand disable the button when finished. - Wallet connection library. For multi-wallet support, mobile wallets and good UX, most teams use an established connection library rather than raw
window.ethereum. I haven't tested any here, so I won't recommend a specific one. - Rendering safety. NFT metadata comes from outside your control. Treat names and descriptions as untrusted text, and never inject them as HTML.
- Accessibility. The status line uses
role="status"so screen readers announce updates; keep that when you restyle.
Security notes for users and builders
- A mint page only needs one transaction for a fixed price. If a site asks you to sign a blanket token approval to mint an NFT for ETH, treat it as a warning sign. The post on token approvals explains why.
- Never put private keys in front-end code or environment variables that are shipped to the browser. Anything the browser can see, users can see.
- Test on a testnet with a throwaway wallet, then verify the contract on the explorer using the verification guide before sharing the address.
Short checklist
- Exact-price mint with a supply cap and owner-only withdrawal, with tests.
- Wallet connection on click, with an explicit network check.
- Price and supply read from the contract.
- Three error classes: rejected, reverted, unknown.
- Simulate before sending, listen for chain and account changes.
- Test on a testnet, in a real browser, with a real wallet.
Launching an NFT or token project?
I build contracts and React front ends, tested end to end, including the boring parts users notice. If you need a hand, get in touch.
See services Get in touchWhat I ran this against
- Hardhat 3.22.0 (Mocha + ethers template), @openzeppelin/contracts 5.6.1, ethers 6.17.0, solc 0.8.34, Node.js 24.22.1, run on 17 November 2026 on Hardhat's in-process simulated network. The four contract tests pass (exact-price mint with ownership and tokenURI, wrong payment rejected, max supply enforced, owner-only withdrawal).
- The React component was compiled with the TypeScript compiler in strict mode (React 19.3.1, ethers 6.17.0) and bundled with esbuild without errors. I did not run it in a browser against a real wallet, so the wallet pop-ups, network switching and transaction flow are untested. Test it on a testnet before you trust it.
- Nothing was deployed to a testnet or mainnet, and the contracts are teaching examples that have not been audited.
Sources checked
- EIP-1193, Ethereum Provider JavaScript API (the
window.ethereuminterface,chainChangedevent, and error code 4001 for a rejected request): eips.ethereum.org/EIPS/eip-1193. - ethers v6 documentation, providers (
BrowserProviderwraps an EIP-1193 provider): docs.ethers.org/v6. - OpenZeppelin Contracts 5.x, ERC-721 guide: docs.openzeppelin.com.