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

问题描述 投票:0回答:3

我正在编写一个 NFT 智能合约,我将通过 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;
    }
}

这里我有两个公共函数:

owner
mintNFT
都返回一些值。在我的测试中,我想读取来自这两个函数的返回值。这些是我在 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',
    },
  },
};
solidity ethers.js hardhat rsk
3个回答
14
投票

从交易返回的值在 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


11
投票

您无法直接接收来自您向链外发送交易的函数的返回值。您只能在链上执行此操作 - 即当一个 SC 函数调用另一个 SC 函数时。

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

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 中,您将获得此行返回的 交易响应对象,而不是智能合约函数返回值:

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

接下来您需要通过拨打wait上的

txResponse
来获取
交易收据

const txReceipt = await txResponse.wait();

反过来,

txReceipt
包含一个
events
数组,其中包含您的交易发出的所有事件。在这种情况下,预计它会包含一个
Transfer
事件,指示第一个铸造项目从 零地址 转移到您的帐户地址。通过从
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);
    });
  });

0
投票

使用

callStatic
可以得到函数的返回值,如下所示:

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

你只需要记住,

callStatic
只模拟函数调用并返回返回值,但它不会改变合约状态(所以基本上在静态调用之后就好像它没有发生一样),所以你可以如果您想检查任何后续后果,请不要使用它。

https://docs.ethers.org/v5/api/contract/contract/#contract-callStatic

© www.soinside.com 2019 - 2024. All rights reserved.