0

Is it possible to make a function only callable by owner but restricted to view? I tried something like that.

function getUserTokenBalance(address user) public view onlyAdmin returns (uint256) {
    return balance[user];
}

Calling this method from web3 like:

contract.methods
 .getUserTokenBalance('0x06bf3b021f10712655a8786f2bFfF11ddE0ea21B')
 .call({ from: account.address })
 .then((data) => {
   console.log('balance: ', data);
 })
.catch((err) => {
  console.log('error', err);
});

returns some weird long number as string 3963877391197344453575983046348115674221700746820753546331534351508065746944

I guess it's not working because I have to send a transaction so the smart contract can verify me as the owner. However, what I want to achieve is to query some state in the smart contract without paying any fees.

1
  • Similar questions here and here. To my understanding, this is a bug in either web3.js or the node that you're communicating with. In short, don't use a require statement which contains an error-message (and I'm guessing that the onlyAdmin modifier contains such require statement) in a view function. May 11, 2020 at 6:07

1 Answer 1

0

Since everything is public on the blockchain when you deploy a smart contract, you cannot make a field that's hidden from everyone except the owner unfortunately. For more info on this, check out this question. The closest you can get is by limiting some functionality to the owner, like this for example:

  // Owner address of the contract
  address public owner;

  constructor() public {
    owner = msg.sender;
  }

   // A owner-only callable function
   function onlyOwner () public{
     require(msg.sender == owner, "This can only be called by the contract owner!");
     // Do stuff
   }

2
  • thanks. I already have something like that ` modifier onlyAdmin() { require(msg.sender == owner, 'Only owner can call this function.'); _; }`. sounds legit. why would you prevent someone from seeing something if it should be public available
    – jetblack
    May 10, 2020 at 22:30
  • 1
    @jetblack 1. Private functions reduce the contract size. 2. Private data cannot be read by other smart contracts. May 11, 2020 at 2:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.