0

I'm a noob and trying to implement the balanceOf function in a solidity. The standard API is

function balanceOf (address account) public returns(uint256)

However, I suspect that it needs to read the balance from a mapping. But the mapping had not been defined. Does it need to? Would the correct way to do this be this below? Defining a mapping before the function.

 mapping(address => uint256) internal balances;

function balanceOf (address account) public returns(uint256){ 
    return balances[account];

1 Answer 1

1

I'm assuming you're using EIP-20 as a reference in your implementation.

https://eips.ethereum.org/EIPS/eip-20

With that being said it's entirely up to you to define the logic for each function. I would agree that doing a mapping of each address to a balance is a sufficient approach to implementing balanceOf, in fact this is exactly how OpenZeppelin and ConsenSys have done it. Another approach would be to use Storage contracts as shown here.

I would also add that your balanceOf function does not change state of the contract and therefore have its visibility set to view.

Your Answer

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

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