繁体   English   中英

如何测试合约接收 ERC721 代币的能力?

[英]How to test a contract's ability to receive an ERC721 token?

我正在 Truffle 测试我的合同。 我启用了合约以接收 ERC721 代币:

function onERC721Received(address, address _from, uint256 _tokenId, bytes calldata) external override returns(bytes4) {
    nftContract = ERC721(msg.sender);
    tokenId = _tokenId;
    tokenAdded = true;

    return 0x150b7a02;
}

有没有办法使用 Mocha 和 Chai 模拟发送到该合约的代币?

在 EVM 之外(例如在 JS 测试中),无法检查事务的返回值。 只有它的状态(成功/恢复),发出的事件(在你的情况下不是)和其他一些元数据。 您还可以检查调用的返回值,如assert.equal语句。

contract('MyContract', () => {
    it('receives a token', async () => {
        const tx = await myContract.onERC721Received(
            '0x123',      // address
            '0x456',      // address _from
            1,            // uint256 _tokenId
            [0x01, 0x02]  // bytes calldata
        );

        assert.equal(tx.receipt.status, true); // tx succeeded

        assert.equal(await contract.nftContract, '0x123');
        assert.equal((await contract.tokenId).toNumber(), 1);
        assert.equal(await contract.tokenAdded, true);
    });
});

文件:

  • 松露contract而不是 Mocha describe - 文档
  • 收据状态 - Truffle docs 、Web3 docs (Truffle docs 中指向 Web3 的链接已过时)
  • 不必在 Truffle 中使用.send()或 .call( .call() ,因为它会从合约 ABI 中自动选择 tx 或调用 - 文档

我也在我的测试中使用 ERC721 模拟合约对此进行了测试。 所以我部署两个合约并为它们创建新实例,然后从 ERC721 调用 mint 函数到被测合约地址。 然后检查 ERC721 的余额:

ERC721.balanceOf(underTest.address, 1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM