简体   繁体   English

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

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

I'm testing my contract in Truffle.我正在 Truffle 测试我的合同。 I enabled the contract to receive ERC721 tokens:我启用了合约以接收 ERC721 代币:

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

    return 0x150b7a02;
}

Is there a way to simulate a token being sent to this contract using Mocha and Chai?有没有办法使用 Mocha 和 Chai 模拟发送到该合约的代币?

Outside of EVM (for example in a JS test), there's no way to check a return value of a transaction.在 EVM 之外(例如在 JS 测试中),无法检查事务的返回值。 Only its status (succeeded/reverted), emitted events (in your case non) and few other metadata.只有它的状态(成功/恢复),发出的事件(在你的情况下不是)和其他一些元数据。 And you can also check return value of a call, as in the assert.equal statements.您还可以检查调用的返回值,如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);
    });
});

Docs:文件:

  • Truffle contract instead of Mocha describe - docs松露contract而不是 Mocha describe - 文档
  • The receipt status - Truffle docs , Web3 docs (the link to Web3 in the Truffle docs is outdated)收据状态 - Truffle docs 、Web3 docs (Truffle docs 中指向 Web3 的链接已过时)
  • Not having to use .send() or .call() in Truffle, because it choses the tx or call automatically from the contract ABI - docs不必在 Truffle 中使用.send()或 .call( .call() ,因为它会从合约 ABI 中自动选择 tx 或调用 - 文档

I do test this using an ERC721 mock contract in my tests too.我也在我的测试中使用 ERC721 模拟合约对此进行了测试。 So I deploy both contracts and create new instances for them, then from the ERC721 call the mint function to the contract under test address.所以我部署两个合约并为它们创建新实例,然后从 ERC721 调用 mint 函数到被测合约地址。 Then check the balance of ERC721 with:然后检查 ERC721 的余额:

ERC721.balanceOf(underTest.address, 1)

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

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