如何接收 Solidity 智能合约交易函数返回的值?

我正在编写一个 NFT smart contract ,我将通过 Hardhat 对其进行测试并部署在 RSK 上。

//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";

contract MyNFT is ERC721URIStorage {
    uint private _counter;
    address private _owner;

    constructor() ERC721("My NFT", "MNFT") {
      _owner = msg.sender;
    }

    function owner() public view returns (address) {
      return _owner;
    }

    function mintNFT(address recipient, string memory tokenURI)
        public returns (uint256)
    {
        require(msg.sender == owner(), "Only owner is allowed to mint");
        uint newItemId = ++_counter;
        ERC721._mint(recipient, newItemId);
        ERC721URIStorage._setTokenURI(newItemId, tokenURI);

        return newItemId;
    }
}

这里我有两个公共函数: ownermintNFT 都返回一些值。在我的测试中,我想读取来自这两个函数的返回值。这些是我在 Hardhat 上运行的测试:

const { expect } = require("chai");
const { ethers } = require("hardhat");

describe("My NFT", () => {
  let deployer;
  let myNFT;

  // deploy NFT before the tests
  before(async () => {
    [deployer] = await ethers.getSigners();
    const MyNFT = await ethers.getContractFactory('MyNFT');
    myNFT = await MyNFT.deploy();
    await myNFT.deployed();
  });

  describe('Receiving a value returned by a view function', () => {
    it('The deployer should be the s/c owner', async  () => {
      const owner = await myNFT.owner();
      expect(owner).to.equal(deployer.address);
    });
  });

  describe('Receiving a value returned by a transacting function', () => {
    it('Should return a correct ID of the newly minted item', async () => {
      const newMintItem = {
        id: 1,
        uri: 'ipfs://Qme3QxqsJih5psasse4d2FFLFLwaKx7wHXW3Topk3Q8b14',
      };
      const newItemId = await myNFT.mintNFT(deployer.address, newMintItem.uri);
      expect(newItemId).to.equal(newMintItem.id);
    });
  });
});

owner 函数的情况下,我得到了我所期望的:它返回我的帐户地址,并且第一个测试成功通过。然而,当涉及到 mintNFT 函数时,我没有得到我所期望的:我得到的不是新创建的项目 ID,而是非常不同的东西,我的第二个测试失败了。

为什么两个非常相似的测试会给我不同的结果?如何从发送交易的函数中获取返回值?作为参考,这是我正在使用的 hardhat.config.js 文件:

require("@nomiclabs/hardhat-waffle");

module.exports = {
  solidity: "0.8.4",
  defaultNetwork: 'rskregtest',
  networks: {
    rskregtest: {
      chainId: 33,
      url: 'http://localhost:4444',
    },
  },
};
stack overflow How to receive a value returned by a Solidity smart contract transacting function?
原文答案

答案:

作者头像

从事务返回的值在 EVM 之外不可用。

您可以发出一个事件,或者创建该值的公共 view getter 函数。

contract MyNFT is ERC721URIStorage {
    // `public` visibility autogenerates view function named `_counter()`
    uint public _counter;
    event NFTMinted(uint256 indexed _id);

    function mintNFT(address recipient, string memory tokenURI)
        public returns (uint256)
    {
        // ...
        emit NFTMinted(newItemId);
        return newItemId;
    }
}
it('Should return a correct ID of the newly minted item', async () => {
    const newMintItem = {
        id: 1,
        uri: 'ipfs://Qme3QxqsJih5psasse4d2FFLFLwaKx7wHXW3Topk3Q8b14',
    };

    // testing the emitted event
    await expect(myNFT.mintNFT(deployer.address, newMintItem.uri))
        .to.emit(myNFT, "NFTMinted")
        .withArgs(newMintItem.id);

    // testing the getter value
    const counter = await myNFT._counter();
    expect(counter).to.equal(newMintItem.id);
});

文档: https://ethereum-waffle.readthedocs.io/en/latest/matchers.html#emitting-events

作者头像

您不能直接接收来自您正在将交易发送到链下的函数的返回值。你只能在链上这样做——即当一个 SC 函数调用另一个 SC 函数时。

但是,在这种特殊情况下,您可以通过事件获取值,因为 ERC721 specification 包含一个 Transfer 事件:

    /// @dev This emits when ownership of any NFT changes by any mechanism.
    ///  This event emits when NFTs are created (`from` == 0) and destroyed
    ///  (`to` == 0). Exception: during contract creation, any number of NFTs
    ///  may be created and assigned without emitting Transfer. At the time of
    ///  any transfer, the approved address for that NFT (if any) is reset to none.
    event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);

在您已经在安全帽测试中使用的 Ethers.js 中,而不是智能合约函数返回值,您会在此行返回 transaction response object

const txResponse = await myNFT.mintNFT(deployer.address, newMintItem.uri);

接下来,您需要通过在 transaction receipt 上调用 wait 来获得 txResponse

const txReceipt = await txResponse.wait();

反过来, txReceipt 包含一个 events 数组,其中包含您的事务发出的所有事件。在这种情况下,期望它包含一个 Transfer 事件,指示第一个铸造项目从 zero address 转移到您的帐户地址。通过从 events 数组中提取第一个元素来获取此事件:

const [transferEvent] = txReceipt.events;

接下来从 tokenId 参数中获取 transferEvent 属性,这将是您新铸造的 NFT 的 Id:

const { tokenId } = transferEvent.args;

整个测试应如下所示:

describe('Receiving a value returned by a transacting function', () => {
    it('Should return a correct ID of the newly minted item', async () => {
      const newMintItem = {
        id: 1,
        uri: 'ipfs://QmY6KX35Rg25rnaffmZzGUFb3raRhtPA5JEFeSSWQA4GHL',
      };
      const txResponse = await myNFT.mintNFT(deployer.address, newMintItem.uri);
      const txReceipt = await txResponse.wait();
      const [transferEvent] = txReceipt.events;
      const { tokenId } = transferEvent.args;
      expect(tokenId).to.equal(newMintItem.id);
    });
  });