Défi : Écris ton premier NFT ERC-721 sur Ethereum

Daniel KambaleDaniel Kambale
3 min read

Tu as suivi notre série jusqu'ici ? Bravo ! Tu as appris les fondamentaux d’Ethereum, les outils de dev Web3, et les meilleures pratiques pour écrire des smart contracts solides. Maintenant, il est temps de passer à la pratique.

Aujourd’hui, tu vas coder ton propre contrat de NFT ERC-721, le standard utilisé par les collections comme CryptoPunks, Bored Apes, ou encore les tickets de concert tokenisés.

On ne va pas juste copier/coller du code tumais vas comprendre chaque ligne et déployer un vrai contrat sur testnet. Prêt(e) ? Allons-y.

Prérequis

Avant de commencer, assure-toi d’avoir :

  • Node.js installé

  • Hardhat (installé globalement ou localement dans ton projet)

  • Un wallet comme MetaMask

  • Un peu de test ETH sur Goerli ou Sepolia

1️⃣ Création du projet avec Hardhat

mkdir defi-nft
cd defi-nft
npm init -y
npm install --save-dev hardhat
npx hardhat

Choisis Créer un projet TypeScript basique ou Projet JavaScript basique.

Ensuite, installe les dépendances suivantes :

npm install @openzeppelin/contracts dotenv

2️⃣ Crée ton contrat ERC-721

Crée un fichier NFT.sol dans le dossier contracts/ :

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";

contract NFTCollection is ERC721URIStorage, Ownable {
    uint256 public currentTokenId;

    constructor() ERC721("DeWeb2aWeb3 NFT", "DW3") {}

    function mintTo(address recipient, string memory tokenURI) public onlyOwner returns (uint256) {
        uint256 newItemId = currentTokenId;
        _mint(recipient, newItemId);
        _setTokenURI(newItemId, tokenURI);
        currentTokenId++;
        return newItemId;
    }
}

📌 Explication :

  • ERC721URIStorage : permet d'associer un URI unique à chaque NFT.

  • Ownable : seul le propriétaire du contrat peut minter.

  • mintTo : crée un NFT avec une URI (vers un fichier JSON stocké par ex. sur IPFS).

3️⃣ Ajoute ton script de déploiement

Dans scripts/deploy.js :

const hre = require("hardhat");

async function main() {
  const NFT = await hre.ethers.getContractFactory("NFTCollection");
  const nft = await NFT.deploy();

  await nft.deployed();

  console.log(`NFT déployé à l'adresse : ${nft.address}`);
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

4️⃣ Configure le réseau testnet

Dans hardhat.config.js :

require("@nomiclabs/hardhat-ethers");
require("dotenv").config();

module.exports = {
  solidity: "0.8.18",
  networks: {
    sepolia: {
      url: process.env.ALCHEMY_API_URL,
      accounts: [process.env.PRIVATE_KEY]
    }
  }
};

Ajoute un fichier .env :

ALCHEMY_API_URL="https://eth-sepolia.g.alchemy.com/v2/TON_API"
PRIVATE_KEY="0xTON_CLÉ_PRIVÉE"

5️⃣ Déploie ton contrat 🎉

npx hardhat run scripts/deploy.js --network sepolia

6️⃣ Minte ton premier NFT

Tu peux écrire un script mint.js :

const hre = require("hardhat");

async function main() {
  const nftAddress = "TON_ADRESSE_CONTRAT_DEPLOYE";
  const NFT = await hre.ethers.getContractAt("NFTCollection", nftAddress);

  const tx = await NFT.mintTo("TON_ADRESSE_METAMASK", "https://monlienversunmetadata.json");
  await tx.wait();

  console.log("NFT minté !");
}

main().catch((error) => {
  console.error(error);
  process.exitCode = 1;
});

Tu peux héberger le JSON de metadata sur IPFS ou Pinata.

Exemple de fichier metadata.json :

{
  "name": "DeWeb2aWeb3 Genesis NFT",
  "description": "Premier NFT minté avec amour.",
  "image": "ipfs://CID-DE-TON-IMAGE"
}

Teste ton contrat

Ajoute un test basique dans test/NFT.js :

const { expect } = require("chai");

describe("NFTCollection", function () {
  it("devrait minter un NFT", async function () {
    const [owner] = await ethers.getSigners();
    const NFT = await ethers.getContractFactory("NFTCollection");
    const nft = await NFT.deploy();

    await nft.mintTo(owner.address, "ipfs://dummy");

    expect(await nft.ownerOf(0)).to.equal(owner.address);
  });
});

Puis exécute :

npx hardhat test

Conclusion

Tu viens de :

✅ Créer un projet Hardhat
✅ Coder un smart contract ERC-721
✅ Déployer sur testnet
✅ Minter ton propre NFT
✅ Écrire un test de base

Mais ce n’est que le début.

Appel à l’action

Et toi, quel sera ton premier NFT ? Une œuvre d’art ? Un badge pour ton projet DAO ? Une preuve d’assiduité à cette série ?

💥 Poste ton NFT sur Twitter et tag @DeWeb2aWeb3
📢 Partage ce tuto avec ton pote développeur
🔥 Le Web3 se construit en codant …. ensemble, ligne par ligne.

27
Subscribe to my newsletter

Read articles from Daniel Kambale directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Daniel Kambale
Daniel Kambale

Hello! I’m Daniel, a Web3 developer specializing in Solidity and smart contract development. My journey in the blockchain space is driven by a vision of a fully decentralized world, where technology empowers individuals and transforms industries. As a Web3 ambassador , I’m committed to fostering growth and innovation in this space, helping to shape a future that values transparency and security. Fluent in both English and French, I enjoy connecting with diverse communities and sharing my insights across languages. This is why you’ll find some of my articles in French, while others are in Swahili, as I believe knowledge should be accessible to all. I use my Hashnode blog to document my learning process, explore decentralized solutions, and share practical tutorials on Web3 development. Whether it's diving deep into Solidity, discussing the latest in blockchain, or exploring new tools, I’m passionate about contributing to a decentralized future and connecting with others who share this vision. Let’s build the future together!