76

在合约中如何判断一个合约是不是标准ERC20合约或者ERC721合约?

 3 years ago
source link: https://learnblockchain.cn/question/2067
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

在合约中如何判断一个合约是不是标准ERC20合约或者ERC721合约?

在合约中调用IERC712(address).safeTransferFrom的话,

IERC721(address)可以是实现IERC721接口的任何合同地址
因此,在函数中调用IERC721(address)safetransferfrom(msg sender,address(this)nfttokenid)可能会带来危险的影响.

那么如何检查并确保address指定的合同是一个标准IERC721合约.?

最佳答案 2小时前

判断一个地址符不符合某个标准,就是看他是否实现了对应的函数。

ERC721 实现了 ERC165 标准, 因此可以查询用 supportsInterface(bytes4 _interfaceId) 查询到其实现了哪些接口。

ERC721 有这些接口:

bytes4 private constant _InterfaceId_ERC721 = 0x80ac58cd;
/*
 * 0x80ac58cd ===
 *   bytes4(keccak256('balanceOf(address)')) ^
 *   bytes4(keccak256('ownerOf(uint256)')) ^
 *   bytes4(keccak256('approve(address,uint256)')) ^
 *   bytes4(keccak256('getApproved(uint256)')) ^
 *   bytes4(keccak256('setApprovalForAll(address,bool)')) ^
 *   bytes4(keccak256('isApprovedForAll(address,address)')) ^
 *   bytes4(keccak256('transferFrom(address,address,uint256)')) ^
 *   bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
 *   bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
 */
IERC721(contractAddress).supportsInterface(0x80ac58cd)

ERC20 没有很好的方法, 只能尝试调用(用call 调用),检查返回值,看看有没有对应的方法。

Tiny熊 - 布道者
擅长:智能合约,以太坊 | 采纳率 39% | 回答于 3小时前

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK