Deploying and Minting 100 NFTs on Polygon with web3.py
We deployed the Quantum Genesis contract and minted all 100 pieces for about 0.3 POL in gas — under a dollar at the time. On Ethereum mainnet the same operations would have cost somewhere between $500 and $2,000 depending on the day. This post is the full path we took: a self-contained ERC-721 written from scratch, compiled and deployed with Python, and batch-minted in five transactions. The gas numbers are the ones from our own receipts, not estimates.
The collection itself is 100 artworks generated from measurements on real quantum computers, so the budget needed to go into quantum time and IPFS pinning, not transaction fees. That constraint drove every choice below — and it is the honest reason a project like this ends up on Polygon instead of Ethereum.

Why Polygon: three requirements, one compromise
Before writing a line of Solidity we wrote down what the chain had to do for a 100-piece collection:
- Negligible gas. The art and its provenance should carry the project, not the transaction fees.
- Full EVM compatibility. The same Solidity contract, the same tooling, the same mental model as mainnet.
- Marketplace support. OpenSea treats Polygon as a first-class chain, so the collection appears without custom integration.
Polygon (chain ID 137) met all three. Blocks arrive roughly every two seconds, a mint confirms almost immediately, and the cost per transaction is fractions of a cent. But it would be dishonest to present that as a free lunch. Polygon PoS is a sidechain secured by around a hundred validators with periodic checkpoints to Ethereum, not by Ethereum's full validator set. For recording ownership of digital art that tradeoff is acceptable; for a contract holding millions in DeFi it would not be. We took it deliberately, and the section on security below goes into what it actually means.
Prerequisites
- Python 3.8 or newer.
- A Polygon wallet funded with a few dollars of POL — we bought $10 and used less than $1.
- The private key in an environment variable. Never in the source, never in a notebook cell that gets committed.
- A Polygon RPC endpoint: the public
https://polygon-rpc.comworks for single transactions, Alchemy or Infura if you plan to send batches (the public endpoint throttles under load). - The Solidity compiler, installed through
py-solc-x, so compile, deploy and mint all stay in Python.
pip install web3 py-solc-x python-dotenv
We used web3.py end to end — no Hardhat deploy scripts, no Remix. If you have been told a JavaScript framework is mandatory to ship a contract, this is the counterexample: web3.py talks to the chain directly, and every step stays visible.
Connecting to Polygon
import os
from web3 import Web3
RPC = os.environ.get("POLYGON_RPC", "https://polygon-rpc.com")
w3 = Web3(Web3.HTTPProvider(RPC))
assert w3.is_connected(), "Failed to connect to Polygon"
print(w3.eth.chain_id) # 137
print(w3.eth.block_number)
account = w3.eth.account.from_key(os.environ["PRIVATE_KEY"])
print(account.address)
print(w3.from_wei(w3.eth.get_balance(account.address), "ether"), "POL")
Always assert the connection before sending anything. An unconnected Web3 instance fails in confusing ways — sometimes silently, sometimes with an error that points at the wrong line.
A contract with no imports
Most NFT tutorials open with import "@openzeppelin/contracts/token/ERC721/ERC721.sol". We went the other direction: the Quantum Genesis contract is entirely self-contained. Smaller bytecode, no supply-chain surface, and every line is ours to audit. It implements ERC-721, ERC-721 Enumerable, EIP-2981 royalties at 5%, batch minting, and custom errors instead of require strings.
Here is a simplified sketch of its mint logic (not the deployed source):
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract QuantumGenesisNFT {
string public name = "Quantum Genesis";
string public symbol = "QGEN";
uint256 public constant MAX_SUPPLY = 100;
uint96 public constant ROYALTY_BPS = 500; // 5%
address public owner;
string private _baseTokenURI;
uint256 private _tokenIdCounter;
error NotOwner();
error MaxSupplyReached();
error InvalidBatchSize();
error ZeroAddress();
function mint(address to) external returns (uint256) {
if (msg.sender != owner) revert NotOwner();
if (_tokenIdCounter >= MAX_SUPPLY) revert MaxSupplyReached();
if (to == address(0)) revert ZeroAddress();
uint256 tokenId = ++_tokenIdCounter;
_safeMint(to, tokenId);
return tokenId;
}
function mintBatch(address to, uint256 count) external returns (uint256[] memory) {
if (msg.sender != owner) revert NotOwner();
if (count == 0) revert InvalidBatchSize();
if (_tokenIdCounter + count > MAX_SUPPLY) revert MaxSupplyReached();
uint256[] memory ids = new uint256[](count);
for (uint256 i = 0; i < count; i++) {
uint256 tokenId = ++_tokenIdCounter;
_safeMint(to, tokenId);
ids[i] = tokenId;
}
return ids;
}
function royaltyInfo(uint256, uint256 salePrice)
external view returns (address receiver, uint256 royaltyAmount)
{
return (owner, (salePrice * ROYALTY_BPS) / 10000);
}
}
Custom errors such as revert NotOwner() cost less gas than require(msg.sender == owner, "Not the owner"). The string in a require statement lives in the contract bytecode and is paid for twice: at deployment and on every failed call. Over 100 mints and years of secondary trading, that difference is free money. A longer walkthrough of the design, including the enumeration and metadata pieces, is in the ERC-721 contract post.
Compiling from Python
import solcx, json
from pathlib import Path
solcx.install_solc("0.8.20")
source = Path("nft-contracts/QuantumGenesisNFT.sol").read_text()
compiled = solcx.compile_source(
source,
output_values=["abi", "bin"],
solc_version="0.8.20",
)
_, iface = compiled.popitem()
Path("nft-output/abi.json").write_text(json.dumps(iface["abi"], indent=2))
Path("nft-output/bytecode.txt").write_text(iface["bin"])
print("bytecode:", len(iface["bin"]) // 2, "bytes")
Compilation takes under two seconds. The ABI describes every function and event; the bytecode is what actually gets deployed. You need both, and neither is secret.
Deploying
abi = json.loads(Path("nft-output/abi.json").read_text())
bytecode = Path("nft-output/bytecode.txt").read_text()
Factory = w3.eth.contract(abi=abi, bytecode=bytecode)
tx = Factory.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)
)
contract = w3.eth.contract(address=receipt.contractAddress, abi=abi)
print("deployed at", receipt.contractAddress, "gas", receipt.gasUsed)
Our deployment consumed about 0.08 POL. The contract is live at 0x488fCfaEA5fDf1cF6BAED5e8A34D7858033E1a27 on Polygon mainnet. Deploying the identical bytecode on Ethereum mainnet would have been 50 to 100 times more expensive.
Pointing the contract at IPFS
Before minting, the base URI has to point at the metadata folder. Ours lives under the metadata CID, and each token resolves to baseURI + tokenId + ".json":
base_uri = "ipfs://bafybeif7z767txkebwz7iqlgkvikvhxciuxt2kxenmjad4bbzx4rfioyc4/"
tx = contract.functions.setBaseURI(base_uri).build_transaction({
"from": account.address,
"nonce": w3.eth.get_transaction_count(account.address),
"gasPrice": w3.eth.gas_price,
"chainId": 137,
})
signed = account.sign_transaction(tx)
w3.eth.wait_for_transaction_receipt(w3.eth.send_raw_transaction(signed.raw_transaction))
That one transaction is the difference between a token that renders and a token that is a blank square on every marketplace. How the metadata files themselves are structured, and why the CIDs matter more than the gateway, is covered in the provenance post.
Minting in two phases
We did not mint all 100 at once, and not one at a time either. Phase one was eighteen individual mints, #1 through #18, deliberately slow: each one was checked on OpenSea for image rendering, trait parsing and royalty detection before we committed the rest. Phase two was the remaining 82 in five transactions of 20, 20, 14, 14 and 14. The uneven tail is not cosmetic — Polygon has a block gas limit, and a batch large enough to exceed it reverts after you have already paid for the attempt.
def send(func, gas_limit=None):
tx = func.build_transaction({
"from": account.address,
"nonce": w3.eth.get_transaction_count(account.address),
"gasPrice": w3.eth.gas_price,
"chainId": 137,
})
tx["gas"] = gas_limit or int(w3.eth.estimate_gas(tx) * 1.2)
signed = account.sign_transaction(tx)
return w3.eth.wait_for_transaction_receipt(
w3.eth.send_raw_transaction(signed.raw_transaction)
)
for batch in (20, 20, 14, 14, 14):
r = send(contract.functions.mintBatch(account.address, batch))
print(batch, "tokens | gas", r.gasUsed)
Total gas for the 100 mints came to roughly 0.25 POL. Add deployment and the whole collection cost about 0.33 POL — comfortably under a dollar, and less than the cost of a single Ethereum mint on a quiet afternoon.
Reading state back
Read calls cost nothing and need no signature, which makes them the cheapest form of verification available:
print(contract.functions.name().call()) # Quantum Genesis
print(contract.functions.symbol().call()) # QGEN
print(contract.functions.totalSupply().call()) # 100
owner = contract.functions.ownerOf(42).call()
uri = contract.functions.tokenURI(42).call()
receiver, amount = contract.functions.royaltyInfo(42, 10000).call()
print(owner)
print(uri) # ipfs://bafybei.../42.json
print(receiver, amount) # 500 = 5% of a 10,000 unit sale
Iterating all 100 tokens and comparing ownerOf and tokenURI against the IPFS manifest is a five-minute script, and it is the check I would run first if I were buying into any collection.
The gas bill, line by line
Ethereum gas is a moving target, so treat any figure as a snapshot. A standard ERC-721 mint runs 80,000 to 150,000 gas units. At typical mainnet prices that is $3 to $8 per mint when the network is quiet, $8 to $15 at medium traffic, $20 to $50 during a busy period, and over $100 during a drop frenzy. For 100 mints the floor is roughly $300 — and you cannot schedule around spikes, because a single popular drop can multiply prices in minutes.
Polygon uses the same gas units. The difference is the price per unit:
| Operation | Ethereum mainnet | Polygon |
|---|---|---|
| Contract deployment | $40 – $150 | ~$0.01 (0.08 POL) |
| Single ERC-721 mint | $3 – $50+ | $0.001 – $0.01 |
| 100 mints | $300 – $800 (quiet day) | ~$0.03 (0.25 POL) |
| Deploy + 100 mints | $500 – $2,000 | ~$0.04 (0.33 POL) |
We bought $10 of POL as a buffer and finished with almost all of it. The savings are not a discount on the same product — they are the difference between a project that can afford to exist and one that cannot. Every POL not spent on gas went into quantum computer time and IPFS pinning, which is where the value of this collection actually lives.
What actually goes wrong
Minting 100 tokens produced a short list of failures worth knowing about before you hit them:
- Nonce conflicts. Sending the next transaction before the previous one is mined gives
code -32000or "nonce too low". Wait for the receipt, or manage the nonce yourself. - Reverts are not retryable.
ContractLogicErrormeans the contract refused — max supply, not the owner, bad batch size. Retrying burns gas for the same answer. - Timeouts.
TimeExhaustedfromwait_for_transaction_receiptdoes not mean the transaction failed; it means it has not been mined yet. Check the hash on PolygonScan before resending. - Public RPC throttling. Batch minting against
polygon-rpc.comeventually returns rate-limit errors. We switched to Alchemy for phase two. - Underpriced gas during congestion. A transaction can sit for minutes. On Polygon this is cheap to fix by replacing it, but the script needs to handle the wait.
Security: the part the price tag hides
Ethereum mainnet is secured by hundreds of thousands of validators with tens of billions staked, has run since 2015 without a successful consensus attack, and carries the strongest censorship-resistance story in the industry. Polygon PoS is secured by a much smaller validator set with staked POL and periodic checkpoints back to Ethereum. A majority of those validators could, in theory, collude. There has been no consensus breach since 2020, but the trust assumptions are not the same, and pretending otherwise would be marketing.
For art ownership the exposure is bounded: you are recording who owns which image, not locking collateral in a lending market. The practical risk of a Polygon failure affecting a 100-piece generative art collection is very low. The risk of spending $2,000 on Ethereum gas before selling a single piece is certain. We chose the certain loss we could avoid.
When Ethereum is the right answer
Polygon is not universally correct, and the same numbers that justified it here argue the other way in other situations:
- High-end collectors. Blue-chip NFT culture still gravitates to mainnet; a 10 ETH collection reads as more serious on L1.
- High-value or utility-bearing tokens. If the token gates meaningful access or holds significant value, Ethereum's security premium is worth paying.
- DeFi composability. Anything that needs to interact with Ethereum DeFi avoids bridging entirely by staying on L1.
- Small, expensive collections. Ten pieces at 1 ETH each make $200 of gas a rounding error.
Our case was the opposite on every axis: 100 pieces (high mint count means high total gas), an experimental quantum art project, OpenSea as the primary venue, standard ERC-721. The contract is the same Solidity we would have deployed on Ethereum — the smart contract does not care which chain hosts it. Only the wallet balance cares, and that turned out to be the whole argument.
The receipts
Everything above is checkable without trusting this post. The contract is at 0x488fCfaEA5fDf1cF6BAED5e8A34D7858033E1a27, with all 100 tokens minted; every value in this post can be read back with the calls in the "Reading state back" section. The images and metadata sit on IPFS under content hashes that cannot be rewritten. The collection is on OpenSea.

If you take one thing from this: the tooling is not the barrier. A self-contained contract, two Python packages and a funded wallet are enough to deploy and mint a full collection for less than lunch. The hard part is everything that comes before the mint — generating art that is worth putting on-chain, and recording its origin well enough that a stranger can verify it years later. That part is covered in the provenance post and in the SHA-256 walkthrough.
Comments
Post a Comment