应用方最佳实践示例合约
下面是一个使用ERC721标准创建的数字藏品智能合约。具备创建数字资产,用户数字资产转账,应用平台方代理用户数字资产转账等功能。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MyERC721 is ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
Counters.Counter private _tokenIds;
constructor() ERC721("MyERC721", "MyERC721") {}
function mint(
address to,
string memory tokenURI
) external onlyOwner returns (uint256) {
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
_mint(to, newItemId);
_setTokenURI(newItemId, tokenURI);
return newItemId;
}
/**
* @dev safe transfer from token owner with the signature of token owner.
* only contract owner can call this method to help token owner transfer token.
*/
function safeTransferWithSignature(
address from,
address to,
uint256 tokenId,
uint256 timeLimit,
bytes memory signature
) external onlyOwner {
// verify signature
require(from != address(0), "ERC721: transfer from the zero address");
require(
block.timestamp < timeLimit,
"block timestamp exceeds timeLimit"
);
bytes32 hash = keccak256(abi.encode(from, to, tokenId, timeLimit));
require(
ECDSA.recover(ECDSA.toEthSignedMessageHash(hash), signature) ==
from,
"verify signature failed"
);
_transfer(from, to, tokenId);
}
}
示例合约继承自ERC721URIStorage, 可以保存用户自定义的每个数字资产的属性。你也可以根据实际设计在合约中添加更多逻辑。
Last updated