Chase.Works
教學Tutorials2024

AscCatSamurai NFT 白名單合約教學AscCatSamurai NFT Allowlist Contract Tutorial

喵武士(AscCatSamurai)NFT 的 ERC-721 白名單鑄造合約,以 Solidity 0.8.20 撰寫、建立在 OpenZeppelin Contracts v5.0.2 上,附展平版與編譯產物,並以章節說明從環境準備、撰寫合約到部署與操作的完整流程。A step-by-step tutorial built on the ERC-721 allowlist-minting contract of the AscCatSamurai NFTs, written in Solidity 0.8.20 on OpenZeppelin Contracts v5.0.2, shipped with a flattened version and compiled artifacts, covering environment setup, writing the contract, deploying and interacting with it.

1. 1. 認識專案:ERC-721 白名單合約

本教學以喵武士 AscCatSamurai 的 NFT 合約為例:ERC-721(Enumerable、Pausable)、最大供應量 500、名單內地址可免費鑄造一次,以 Solidity 0.8.20 撰寫並建立在 OpenZeppelin Contracts v5.0.2 上。

2. 2. 準備環境與編譯設定

合約使用帶版本號的匯入路徑(@openzeppelin/contracts@5.0.2/...),可直接在 Remix 編譯,不必另外安裝套件;專案 artifacts 使用編譯器 0.8.24、EVM 版本 shanghai、Optimizer 關閉(runs 200)。

3. 3. 繼承 OpenZeppelin 建立合約骨架

pragma 設為 ^0.8.20,匯入 ERC721、ERC721Enumerable、ERC721Pausable、Ownable、Strings,讓合約同時繼承四個模組並以 using Strings for uint256 擴充數字轉字串。

4. 4. 狀態變數與建構子

宣告 _nextTokenId、_baseTokenURI、maxSupply = 500、publicMintOpen 與 allowListMintOpen 兩個鑄造窗口、allowList 對照表與 allowListAddresses 陣列;建構子設定名稱 asc cat samurai、代號 acs,並以 initialOwner 指定擁有者。

5. 5. Metadata:setBaseURI 與 tokenURI

擁有者以 setBaseURI 設定基礎網址;覆寫 tokenURI,在 baseURI 不為空時回傳 <baseURI><tokenId>.json,否則回傳空字串,市場(如 OpenSea)即由此讀取 metadata。

6. 6. 白名單與鑄造窗口

setAllowList 讓擁有者批次加入地址(重複地址略過),editMintWindows 分別開關公開鑄造與白名單鑄造,這些管理函式都以 onlyOwner 保護。

7. 7. 鑄造函式 allowListMint

依序檢查白名單窗口已開、呼叫者在名單內、msg.value 為 0,再呼叫 internalMint(檢查 totalSupply() 小於 500,_safeMint 下一個編號),最後把呼叫者移出名單,每個地址只能鑄造一次;publicMint 目前只檢查窗口與 20 ETH,鑄造邏輯尚未實作。

8. 8. 暫停、提款與必要的覆寫

pause / unpause 可暫停所有轉移與鑄造;withdraw 把合約餘額轉給擁有者;因為同時繼承多個模組,必須覆寫 _update、_increaseBalance 與 supportsInterface,Solidity 才能編譯。

9. 9. 編譯與部署

在 Remix 編譯 AscCatSamurai.sol 後部署,傳入擁有者地址作為 initialOwner;若使用 Hardhat 或 Foundry,改用展平版 AscCatSamurai_flattened.sol,或把匯入改成 @openzeppelin/contracts/... 並安裝 5.0.2 版。

10. 10. 部署後的操作順序

依序呼叫 setBaseURI 設定 metadata 網址、setAllowList 加入白名單地址,再以 editMintWindows(false, true) 開放白名單鑄造;白名單用戶送 0 ETH 呼叫 allowListMint 即可鑄造。

11. 11. 讀取狀態與驗證結果

用 allowList(address) 查詢是否在名單、allowListAddresses 查歷史名單、publicMintOpen 與 allowListMintOpen 查窗口狀態,並透過 ERC721Enumerable 的 totalSupply、tokenByIndex、tokenOfOwnerByIndex 列舉代幣。

12. 12. 已知限制與延伸練習

publicMint 未實作鑄造且錯誤訊息與原因不符、maxSupply 固定 500 無 setter、只實作 ERC-721;這些都是可延伸練習的方向,完整流程另可參考教學影片與 OpenSea 專案頁。

架構Architecture

flowchart LR
    O[擁有者] -- setAllowList / editMintWindows / setBaseURI / pause / withdraw --> C[AscCatSamurai ERC721 + Enumerable + Pausable + Ownable]
    U[白名單用戶] -- allowListMint 0 ETH --> C
    C -- _safeMint --> T[(NFT tokenId 0..499)]
    M[市場 OpenSea] -- tokenURI --> C
    C -. baseURI + tokenId + .json .-> J[Metadata JSON]

技術Tech stack

Solidity 0.8.20OpenZeppelin Contracts 5.0.2ERC-721RemixEVM shanghai