Solidity
從合約中返回一個 uint256 數組,並在測試中解析
我有一個鑄造 NFT 的 ERC721 合約。我添加了一個函式,可以在一次呼叫中生成多個 NFT。我嘗試從該函式返回令牌 ID,但我無法編寫測試程式碼來獲取它們。
程式碼:
//@dev mint token for user function mintToken() public payable returns(uint256) { require(_deactivated == false, "Token sale is deactivated"); uint256 price = calculatePrice(msg.sender); require(msg.value >= price, "Insufficient ETH sent"); //get token id _tokenIds.increment(); uint256 tokenId = _tokenIds.current(); //get uri string memory uri = randomUri(); //mint and set uri _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, uri); return tokenId; } //@dev mint multiple tokens for user function mintMultipleTokens(uint numberOfTokens) public payable returns(uint256[] memory) { require(_deactivated == false, "Token sale is deactivated"); uint256 price = calculatePrice(msg.sender).mul(numberOfTokens); require(msg.value >= price, "Insufficient ETH sent"); uint256[] memory tokenIds = new uint256[](numberOfTokens); for(uint index = 0; index < numberOfTokens; index++) { tokenIds[index] = mintToken(); } return tokenIds; }
在我的測試中,當我執行時:
const tokenIds = await token.connect(user3).mintMultipleTokens(numberOfTokens, {value: price});
我收到以下內容tokenIds
:{ hash: '0x8eab2571a37a17c481e9ede9c4d5eb99b410a743d9459dc1017e393500e67d72', type: 2, accessList: [], blockHash: '0xbbbda0142bbea68b403dc8bfc910cc037260dce00725aa1b8f6cd53c52f1c8b7', blockNumber: 42, transactionIndex: 0, confirmations: 1, from: '0x90F79bf6EB2c4f870365E785982E1f101E93b906', gasPrice: BigNumber { _hex: '0x3c1214ea', _isBigNumber: true }, maxPriorityFeePerGas: BigNumber { _hex: '0x3b9aca00', _isBigNumber: true }, maxFeePerGas: BigNumber { _hex: '0x3c895fd4', _isBigNumber: true }, gasLimit: BigNumber { _hex: '0x01bad518', _isBigNumber: true }, to: '0x09635F643e140090A9A8Dcd712eD6285858ceBef', value: BigNumber { _hex: '0x06f05b59d3b20000', _isBigNumber: true }, nonce: 1, data: '0xe1dffcb90000000000000000000000000000000000000000000000000000000000000005', r: '0x6f8717d164eebdd6578218c4d8c5cce95e2244f7b6f218e15e846d32688bddb7', s: '0x616dc1810a7dcf4574e5254df4f144c0a6d1f30b3f9398637e28e0c899cfc768', v: 1, creates: null, chainId: 31337, wait: [Function (anonymous)] }
如何正確接收 ids 數組,以便結束測試?
我使用的是 Hardhat 2.6.8、Solidity 0.8.4、Node 17.0.1。
沒有辦法直接獲得交易的返回值。這通常是如何完成的,是通過以下兩種方式之一(或兩者):
- 使用所需數據發出事件,並擷取這些事件
- 通過
view
函式獲取所需的數據。因此主函式將結果儲存在狀態變數中,並且該數據在單獨的view
函式中讀取。view
函式可以直接返回數據,因為它們是通過本地呼叫而不是真正的事務呼叫的。您可以在此處閱讀有關此內容的更多資訊:return function value instead of transaction receipt with web3