BlockchainArticle11 min read

A token and an NFT: web3 from the contract up

Tokenizer and TokenizeArt: K42, a capped and pausable ERC-20 token live on Ethereum Sepolia, and FortyTwoNFT, an ERC-721 collection with its art on IPFS. What web3 really is, explained with my own Solidity, plus a token to play with and an NFT to mint.

By Abdeljalil El HidaouiSource code
On this page

“Web3” is usually explained with either hype or jargon. Underneath, it is a simple and slightly strange idea: a computer that nobody owns, that everybody can check, and that never forgets. I built two things on it for 42: a currency, and a collection of digital art.

Tokenizer is K42, an ERC-20 token, and TokenizeArt is FortyTwoNFT, an ERC-721 NFT collection, both written in Solidity for Ethereum. This article explains the ideas behind them from scratch, with the real contracts, and lets you play with both: move tokens around, and mint an NFT whose image address is computed in your browser.

What web3 actually is

A blockchain is a shared ledger. Thousands of computers each keep a full copy and agree, block by block, on every change. No single one can quietly edit the past, because every other copy would disagree. On Ethereum, that ledger doesn't only hold balances: it also holds programs, called smart contracts, and their data.

Account
An address controlled by a private key. Whoever signs with the key is that account; there is no password reset.
Transaction
A signed request to change something: send tokens, call a function, deploy a contract. Each one costs a small fee in gas.
Smart contract
A program stored on the chain. Its code is public, everyone runs it identically, and once deployed it can't be edited.
Token standard
A shared interface (ERC-20 for currencies, ERC-721 for unique items), so every wallet and app knows how to use any token.
Testnet
A copy of Ethereum where ETH is free. Sepolia behaves like the real network without real money.

Reading data is free and instant: anyone can ask a contract for a balance. Changing data needs a transaction, signed by your key, paid for in gas, and confirmed in a block a few seconds later.

The toolbox

Both projects use the same short toolchain, which is also what most Ethereum developers start with:

ToolWhat it does here
SolidityThe language the contracts are written in
OpenZeppelinAudited building blocks for ERC-20, ERC-721 and access control
RemixA browser IDE to compile and deploy the contracts
MetaMaskThe wallet that holds the key and signs each transaction
SepoliaThe Ethereum testnet both contracts target
EtherscanThe public explorer to inspect contracts and transactions
IPFS + PinataContent-addressed storage for the NFT's image and metadata

Part 1: an ERC-20 token

An ERC-20 token is fungible: every K42 is interchangeable with every other, like coins. The standard defines a handful of functions, such as transfer, balanceOf, approve and transferFrom, and two events. Any wallet or exchange that knows ERC-20 can handle K42 without knowing anything else about it.

The contract combines four OpenZeppelin pieces and adds one value of its own, a supply cap:

code/K42Token.solView on GitHub
contract K42Token is ERC20, ERC20Burnable, ERC20Pausable, Ownable {
    /// @notice Hard cap on total supply. Minting can never push
    ///         totalSupply() above this value, regardless of who
    ///         calls mint(). This protects holders from unlimited,
    ///         silent dilution by the owner.
    uint256 public immutable maxSupply;

The constructor runs once, at deployment. It refuses nonsense values, converts the human numbers into the token's smallest unit (ERC-20 amounts have 18 decimals, so 1 K42 is stored as 1018), fixes the cap forever, and mints the starting supply to the deployer:

code/K42Token.solView on GitHub
constructor(uint256 initialSupply, uint256 cap)
    ERC20("K42 Token", "K42")   // sets the token's name + ticker
    Ownable(msg.sender)         // makes the deployer the initial owner
{
    // Sanity checks run once, at deployment. If either fails, the
    // whole deployment transaction reverts and no contract is
    // created — better to fail loudly here than deploy a broken
    // token.
    require(cap > 0, "K42: cap must be > 0");
    require(initialSupply <= cap, "K42: initial supply exceeds cap");

    // decimals() returns 18 by default (inherited from ERC20). Token
    // amounts are always stored as whole numbers internally, so
    // "1 token" is actually stored as 1 * 10^18. We multiply the
    // human-friendly constructor inputs (e.g. 1000000) by that same
    // factor here so the rest of the contract's math stays
    // consistent with every other ERC-20 token.
    maxSupply = cap * (10 ** decimals());

    // Mint the starting supply directly to whoever deploys the
    // contract (msg.sender). This is the only place tokens are
    // created without going through the mint() function below.
    _mint(msg.sender, initialSupply * (10 ** decimals()));
}

immutable is what makes the cap a promise rather than a policy: the value is written into the deployed code itself, and nothing can change it afterwards, not even the owner. Minting checks against it every time:

code/K42Token.solView on GitHub
function mint(address to, uint256 amount) external onlyOwner {
    // onlyOwner (from Ownable) makes this function revert
    // automatically if anyone other than the current owner calls
    // it — this is the access-control test: try calling mint()
    // from a non-owner account and it should fail.
    require(totalSupply() + amount <= maxSupply, "K42: cap exceeded");
    // This check is what actually enforces the cap. Without it,
    // the owner could mint an unlimited amount despite maxSupply
    // existing — the variable alone does nothing on its own, it
    // only matters because this line checks against it every time.
    _mint(to, amount);
}

The owner also holds an emergency brake. pause() freezes every transfer, mint and burn at once, which is what you want if a key is stolen or a bug is found:

code/K42Token.solView on GitHub
function pause() external onlyOwner {
    _pause();
    // _pause() is inherited from ERC20Pausable — it flips an
    // internal boolean that every transfer/mint/burn checks via
    // the _update() override below.
}

/// @notice Resume normal token transfers. Restricted to the owner.
function unpause() external onlyOwner {
    _unpause();
}

One line of plumbing is needed because both ERC20 and ERC20Pausable define the internal function every balance change goes through. Solidity makes you say explicitly that both should run, the pause check first, then the accounting:

code/K42Token.solView on GitHub
function _update(address from, address to, uint256 value)
    internal
    override(ERC20, ERC20Pausable)
{
    super._update(from, to, value);
}

K42 is live on Sepolia. I read its state directly from the chain while writing this article (view it on Etherscan):

K42 in circulation
1,000,005
hard cap, immutable
10,000,000
decimals
18
chain ID (Sepolia)
11155111

Try the token

Here is the same contract, simulated: three accounts, the same rules, and the same errors OpenZeppelin v5 returns. Pick who is sending the transaction, call a function, and watch the events or the revert.

The K42 contract, in your browser

Try: approve as owner, then transferFrom as alice. Mint as bob. Pause, then transfer. Mint past the cap. Renounce ownership, then try to mint.

Contract state (free to read)

balanceOf(owner)1,000,005 K42
balanceOf(alice)0 K42
balanceOf(bob)0 K42

totalSupply / maxSupply1,000,005 / 10,000,000

paused()false

owner()owner

Transactions

  1. No transactions yet.

Simulated with the rules of code/K42Token.sol on OpenZeppelin v5. A reverted transaction changes nothing, but on the real network it still costs gas.

The approve then transferFrom pair is how decentralized apps move your tokens: you allow a contract to spend up to a set amount, and it pulls exactly what it needs.

Part 2: an NFT collection

An ERC-721 token is the opposite of ERC-20: each one is unique, with its own ID and exactly one owner. That is all an NFT is: a numbered entry on the chain saying “token #0 belongs to this address”, plus a link to a description of what it represents.

code/FortyTwoNFT.solView on GitHub
contract FortyTwoNFT is ERC721, ERC721URIStorage, Ownable {
    /// @dev Auto-incrementing token id counter. Starts at 0 -> first minted
    ///      token is #0.
    uint256 private _nextTokenId;

    /// @notice Emitted every time a new NFT is minted.
    event NFTMinted(address indexed to, uint256 indexed tokenId, string tokenURI);

    /// @param initialOwner The address that will own (and be allowed to mint
    ///        from) this contract. Pass your own wallet address on deploy.
    constructor(address initialOwner)
        ERC721("FortyTwoArt", "F42")
        Ownable(initialOwner)
    {}

Minting is one owner-only function. It takes the next ID, assigns the token with _safeMint (which refuses to send it to a contract that couldn't handle NFTs), stores the metadata link, and emits an event:

code/FortyTwoNFT.solView on GitHub
function safeMint(address to, string memory uri) public onlyOwner returns (uint256) {
    uint256 tokenId = _nextTokenId++;
    _safeMint(to, tokenId);
    _setTokenURI(tokenId, uri);
    emit NFTMinted(to, tokenId, uri);
    return tokenId;
}

The proof of ownership the subject asks for is a free read: ownerOf(tokenId), inherited from OpenZeppelin, returns the current holder.

Where the art lives: IPFS

Storing an image on Ethereum would cost a fortune: every node keeps every byte. So the contract stores only a short link, the token URI, pointing to a JSON file that describes the NFT and links to its image:

mint/metadata.jsonView on GitHub
{
  "name": "42 Genesis",
  "description": "First NFT minted for the 1337/42 TokenizeArt project. Includes the number 42 as required.",
  "image": "ipfs://bafybeihiw27r6p2qjwy5qudb2zjbdlhbggybpvqqmgybhbtrc5kcyhaxsa",
  "attributes": [
    { "trait_type": "Artist", "value": "abel-hid" },
    { "trait_type": "Project", "value": "TokenizeArt" },
    { "trait_type": "School", "value": "1337 / 42 Network" }
  ]
}

Both files live on IPFS, where a file's address is the hash of its content, called a CID. Change a single byte and the address changes completely. A normal URL can start serving a different image tomorrow; an IPFS link can't, because different content would have a different address.

Mint an NFT

Pick an artwork and edit its name: both content addresses are recomputed in your browser. Then mint it, and try to move it.

1Artwork

Image CID:
…

2Metadata (the token URI points here)

{
  "name": "42 Genesis",
  "description": "First NFT minted for the TokenizeArt project. Includes the number 42.",
  "image": "ipfs://…",
  "attributes": [
    {
      "trait_type": "Artist",
      "value": "abel-hid"
    },
    {
      "trait_type": "Project",
      "value": "TokenizeArt"
    }
  ]
}

Metadata CID: …

Change one letter of the name: the metadata CID changes completely, while the image CID stays the same.

3safeMint(to, uri)

asto

4Ownership

transfer to
  • Nothing minted yet.

CIDs are real: CIDv1, raw codec, SHA-256, as `ipfs add --cid-version=1` gives for a small file (Pinata wraps files differently, so its CIDs start with bafybei). Minting follows FortyTwoNFT: only the owner mints, and only a token's holder can move it.

The last rule in that demo matters: once a token is minted, the collection owner has no power over it. There is no admin burn, no forced transfer and no way to change its URI; only the holder decides.

Who controls what

On a blockchain, the code is the rulebook, so the honest question for any contract is: who can do what? For these two:

WhoK42 tokenFortyTwoNFT
OwnerMint (up to the cap), pause and unpause everythingMint new tokens
Owner, neverRaise the cap, take anyone's tokensTouch a token once minted, change its URI
Any holderTransfer, approve, burn their ownTransfer or approve their own token
AnyoneRead every balance and the supplyRead ownerOf and tokenURI

The pause is a real trade-off. It protects holders if something goes wrong, but it also means one key can freeze everyone's tokens. Both contracts make that power visible and give a way out: renounceOwnership() gives up the admin role forever, after which nobody can mint or pause again.

What I learned

  • Deployed means permanent. There is no hotfix: these contracts have no upgrade mechanism, so the code that went live is the code forever. That changes how carefully you read every line.
  • Standards are the real product. K42 shows up correctly in any wallet only because it follows ERC-20 exactly. Interoperability comes from sticking to the interface, not from clever code.
  • Decentralized doesn't mean ownerless. An owner key with mint and pause rights is a central point of control. Being explicit about it, and offering renouncement, is part of the design.
  • What I would add next: automated tests with Hardhat or Foundry instead of manual checks in Remix, verified source code on Etherscan so anyone can read it there, and a multisig wallet as the owner so no single key holds all the power.

The contracts and their documentation are on GitHub: Tokenizer and TokenizeArt.

About the project: Tokenizer & TokenizeArt

Two smart contracts in Solidity on OpenZeppelin: K42, a capped, pausable ERC-20 token live on the Ethereum Sepolia testnet, and FortyTwoNFT, an ERC-721 collection whose artwork and metadata live on IPFS.

  • ERC-20 + ERC-721
  • Live on Sepolia
  • IPFS metadata

Built with

  • Solidity
  • OpenZeppelin
  • Ethereum
  • Sepolia
  • Remix
  • MetaMask
  • IPFS
  • Etherscan