【问题标题】:How to test a contract's ability to receive an ERC721 token?如何测试合约接收 ERC721 代币的能力?
【发布时间】:2021-07-07 16:21:23
【问题描述】:

我正在 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 模拟发送到该合约的代币?

【问题讨论】:

    标签: javascript mocha.js ethereum solidity truffle


    【解决方案1】:

    在 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 而不是摩卡咖啡 describe - docs
    • 收据状态 - Truffle docs, Web3 docs(Truffle 文档中指向 Web3 的链接已过时)
    • 不必在 Truffle 中使用 .send() 或 .call(),因为它会自动从合约 ABI 中选择 tx 或调用 - docs

    【讨论】:

    • 我不知道为什么我会得到expected [Function] to equal 1 for assert.equal(await contract.tokenId, 1);
    • @Kevvv 哦,它在 JS 中返回一个 BigNumber 实例,因为它在 Solidity 中是一个 uint256。您可以使用 (await contract.tokenId).toNumber() 将 BN 转换为整数。
    【解决方案2】:

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

    ERC721.balanceOf(underTest.address, 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 2022-12-12
      • 2017-08-03
      • 2021-12-22
      • 2021-11-14
      • 2021-11-08
      相关资源
      最近更新 更多