Solidity 映射 returns object.object

Solidity mapping returns object.object

我无法从我的智能合约中获取值。合同如下所示:

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

import "hardhat/console.sol";

contract Shop {
  mapping(address=>bool) customerKnown;
  mapping(address=>uint) Food;
  uint public foodprice = 5;

  function check_init() private {
      if (customerKnown[msg.sender] != true) {
        customerKnown[msg.sender] = true;
        Food[msg.sender] = 1;
    }  
  }

  function buyFood(uint amount) external {
    check_init();  
    Food[msg.sender] += amount;
  }

  function getFoodAmount() external returns(uint) {
    check_init();
    return Food[msg.sender];
  }
  
   function getFoodPrice()  external view returns(uint){
    return foodprice;
  }
  
}

方法 getFoodPrice() 例如作品和 returns 5 。 但是如果我尝试 getFoodAmount() 我会得到 [object Object] .

我在返回值上尝试了 JSON.stringify()。这给了我这个:

{"type":2,"chainId":5,"nonce":92,"maxPriorityFeePerGas":{"type":"BigNumber","hex":"0x59682f00"},"maxFeePerGas":{"type":"BigNumber","hex":"0x59682f0e"},"gasPrice":null,"gasLimit":{"type":"BigNumber","hex":"0x653f"},"to":"0xd16a37d991C58FD685DBff66D050351b09d58267","value":{"type":"BigNumber","hex":"0x00"},"data":"0x5ad60993","accessList":[],"hash":"0x1361301cef71e2e382c1e1b518da390e7b224b0eb4425f115c876bf9c1bb3d3e","v":0,"r":"0xc11df23ce83b6816719198da0103d4575e79516959619a8f2f93e633c818d2cc","s":"0x186ec7af1bc4e58d36f83c9e368e6e68171ce5b68f79bcd897ef2e28007b1d5c","from":"0xbC3B1AB18C47F0C41d086d44446135332C102056","confirmations":0}

我似乎无法在那里找到我的价值。 "hex":"0x00" 是错误的,因为我的相位是 1。 有没有办法在第一个地方得到一个干净的整数?

这里的问题是您发送的是交易而不是调用方法。

确实 getFoodAmount() 不是 view 函数,您的提供商正在发送交易并 return 收据。收据不包含函数的 return 值。

唯一的方法是在您的合约中添加一个 view 函数并调用它。

另请参阅:How to get return values when a non view function is called?

  • 确保你await函数调用

  • 您的函数可能 return 一个 BigNumber

A BigNumber is an object which safely allows mathematical operations on numbers of any magnitude.

Most operations which need to return a value will return a BigNumber and parameters which accept values will generally accept them.

每个包都有不同的实用方法将大数转换为数字。将大数转换为数字。