I'm having trouble getting the values from my Smart Contract. The Contract looks like this:
//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;
}
}
The Method getFoodPrice() e.g. works and returns 5 . But if I try out getFoodAmount() I'll get [object Object] .
I tried JSON.stringify() on the returned value. That gave me this:
{"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}
I can't seem to find my value somewhere there. "hex":"0x00" would be wrong, because I'm aspecting 1. Is there any way of getting a clean integer in the frist place?
The issue here is that you're sending a transaction instead of calling a method.
Indeed getFoodAmount()
isn't a view
function, and your provider is sending a transaction and returning its receipt. The receipt doesn't contain the return value of function.
The only way to do it is to add a view
function to your contract and call that.
See also: How to get return values when a non view function is called?