Solidity
ERC-721 上的外部變數
我對智能合約相當陌生,我想知道如何將外部變數傳遞給我的
ERC-721
合約。例如,我希望以下函式返回一個外部變數:function _baseURI() override internal view virtual returns (string memory) { return my_variable_here; }
我正在remix.ethereum.org編譯契約,我想在左側鍵入變數,如下所示:
上圖只是一個範例,因為我要傳遞的真正變數是一個 IPFS url,我不想對其進行硬編碼。
接觸
pragma solidity ^0.8.16; import "erc721a/contracts/ERC721A.sol"; contract test123 is ERC721A { constructor() ERC721A("test123", "test123") {} function mint(uint256 quantity) external payable { // `_mint`'s second argument now takes in a `quantity`, not a `tokenId`. _mint(msg.sender, quantity); } function _baseURI() override internal view virtual returns (string memory) { return "ipfs://bafybeigshu4xqcajjkbqw24cea6shz2vh7dibp7yowjmxo4yg32aoma123/"; } }
你有幾個選擇:
- 您可以在建構子中傳遞它並將其設置為狀態變數:
contract test123 is ERC721A { string public baseUri; constructor(string memory _baseUri) ERC721A("test123", "test123") { baseUri = _baseUri; } function mint(uint256 quantity) external payable { // `_mint`'s second argument now takes in a `quantity`, not a `tokenId`. _mint(msg.sender, quantity); } function _baseURI() override internal view virtual returns (string memory) { return baseUri; } }
- 您可以創建一個 setter 方法來動態更改它,只有所有者可以呼叫:
import "erc721a/contracts/ERC721A.sol"; contract test123 is ERC721A { string public baseUri; address public owner; constructor() ERC721A("test123", "test123") { owner = msg.sender; } function mint(uint256 quantity) external payable { // `_mint`'s second argument now takes in a `quantity`, not a `tokenId`. _mint(msg.sender, quantity); } function _baseURI() override internal view virtual returns (string memory) { return baseUri; } function getBaseURI(string memory _baseUri) external onlyOwner { baseUri = _baseUri; } modifier onlyOwner() { require(owner == msg.sender, "Not owner"); _; } }
- 或者兩者兼而有之,在建構子中設置它並且還能夠動態更改它:
contract test123 is ERC721A { string public baseUri; address public owner; constructor(string memory _baseUri) ERC721A("test123", "test123") { baseUri = _baseUri; owner = msg.sender; } function mint(uint256 quantity) external payable { // `_mint`'s second argument now takes in a `quantity`, not a `tokenId`. _mint(msg.sender, quantity); } function _baseURI() override internal view virtual returns (string memory) { return baseUri; } function getBaseURI(string memory _baseUri) external onlyOwner { baseUri = _baseUri; } modifier onlyOwner() { require(owner == msg.sender, "Not owner"); _; } }
從
_baseURI
函式中,您只需返回此baseUri
狀態變數。