Function for returning a wallet balance

24 views Asked by At

I am trying to create a function that returns the balance of my sepolia testnet metamask wallet.

I wrote this function:

    function getBalance() external view onlyOwner returns (uint256) {
        return address(this).balance;
    }

but it returns 0 all the time. Note that my smart contract is already connected to my metamask wallet and other functions are working good.

1

There are 1 answers

0
Petr Hejda On

address(this) returns the address of the contract.

Address of whoever executes the function is msg.sender. So in this case: return msg.sender.balance;

Few notes:

  • msg.sender reflects whoever executes the function. It might be the end user, it might be some other contract that calls this function.
  • Your function has the view modifier, which makes it read-only. Some apps (e.g. Etherscan without connected MetaMask wallet) might fallback to making the call from the zero address (msg.sender == address(0)) if they don't know the actual caller address.
  • Your function has the onlyOwner modifier. Assuming it's from the OpenZeppelin Ownable library, the function reverts and doesn't return any value (not even zero) if it's not called from the owner address.