如果我们不想使用其他方法,智能契约是否可以使用tokenURI令牌的令牌Is自动生成erc721。我是新手,所以需要一些指导。
发布于 2021-04-07 06:00:19
是的,这是可能的,因为您有_mint()和_setTokenURI()函数。
下面是一个简单的例子,目的是做同样的事情:
// contracts/GameItem.sol
// SPDX-License-Identifier: MIT
pragma solidity <0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract GameItem is ERC721 {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
string private tempURI;
constructor(
string memory name,
string memory symbol,
string memory _tempURI
) ERC721(name, symbol) {
tempURI = _tempURI;
}
function awardItem(address player) public returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(player, newItemId);
_setTokenURI(
newItemId,
string(abi.encodePacked(tempURI, uintToString(newItemId)))
);
return newItemId;
}
function uintToString(uint256 v) internal pure returns (string memory str) {
uint256 maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint256 i = 0;
while (v != 0) {
uint256 remainder = v % 10;
v = v / 10;
reversed[i++] = bytes1(uint8(48 + remainder));
}
bytes memory s = new bytes(i);
for (uint256 j = 0; j < i; j++) {
s[j] = reversed[i - 1 - j];
}
str = string(s);
}
}const GameItem = artifacts.require("GameItem");
contract("Redroad", async (addresses) => {
const [admin, _] = addresses;
it("works correctly.", async () => {
let id = [];
const gItem = await GameItem.new(
"Invincible Collectible",
"ICB",
"http://www.myserver.com/tokenId="
);
await gItem.awardItem(admin);
await gItem.awardItem(admin);
console.log(await gItem.tokenURI("1"));
console.log(await gItem.tokenURI("2"));
});
});以下是truffle test的输出:
Contract: GameItem
http://www.myserver.com/tokenId=1
http://www.myserver.com/tokenId=2
✓ works correctly. (229ms)参考资料摘自:
https://ethereum.stackexchange.com/questions/96817
复制相似问题