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.
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.senderreflects whoever executes the function. It might be the end user, it might be some other contract that calls this function.viewmodifier, 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.onlyOwnermodifier. 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 theowneraddress.