7

Apparently, solidity creates getter functions for public variables. How does one call them using javascript? (for testing within truffle)

1 Answer 1

11

You just call them as you would any other function. The getter function has the same name as the state variable, so if you have:

uint256 public foo;

then you can read its value in JavaScript with:

contract.foo()

See https://programtheblockchain.com/posts/2018/01/02/making-smart-contracts-with-public-variables/.

3
  • 3
    let foo = await contract.foo() if you want the actual web3.BigNumber object rather than a Promise object. Feb 21, 2018 at 14:34
  • Yes, or contract.foo.then(...) or, via web3.js 0.2x.x, contract.foo.call(callback), etc. It's just the same as calling any other function.
    – user19510
    Feb 21, 2018 at 14:39
  • Here's the Solidity documentation reference for those interested: docs.soliditylang.org/en/latest/contracts.html#getter-functions May 12, 2021 at 18:24

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.