Solidity中的映射就像任何其他語言的哈希表或字典一樣。這些用於以鍵值對的形式存儲數據,鍵可以是任何內置數據類型,但不允許引用類型,而值可以是任何類型的。映射主要用於將唯一的乙太坊地址與關聯的值類型相關聯, Azuki.sol
也是類似的用法:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// import ...
contract Azuki is Ownable, ERC721A, ReentrancyGuard {
mapping(address => uint256) public allowlist;
//...
function allowlistMint() external payable callerIsUser {
uint256 price = uint256(saleConfig.mintlistPrice);
require(price != 0, "allowlist sale has not begun yet");
require(allowlist[msg.sender] > 0, "not eligible for allowlist mint");
require(totalSupply() + 1 <= collectionSize, "reached max supply");
allowlist[msg.sender]--;
_safeMint(msg.sender, 1);
refundIfOver(price);
}
//...
}
很淺白易懂,這邊宣告了一個 allowlist
型別為 mapping
,並且是將唯一的以太坊地址對應到可以 mint 的數量,在白單鑄造流程中,函數 allowlistMint
就會用 require(allowlist[msg.sender] > 0
檢查該為鑄造者(msg.sender
)在哈希表對應的數值是什麼,如果大於 0 才會進行下一步的檢查