1

I have made a few test contracts for this issue and I have come across the same result in all of them so it is obvious I am not understanding something.

In the following contract I keep track of the received ether in the DepositedBalance variable. I also check the value of address(this).balance via NativeBalance.

    contract BalanceChecker{

        uint256 public DepositedBalance;
        uint256 public NativeBalance = address(this).balance;
        address public ContractAddress = address(this);
        
        receive() external payable {
            DepositedBalance += msg.value;
        }
 
    // 1. This function returns correct balance
    
        function ShowDepositedBalance() public view returns(uint256){
            return DepositedBalance;
        }
    
    // 2. This function always returns zero as balance:
    
        function ShowNativeBalance() public view returns(uint256){
            return NativeBalance;
        }
    
    // 3. This function returns correct balance when called with the contract address as argument
    
        function BalanceCheck(address _addr) public view returns(uint256){
            return address(_addr).balance;
        }
    
    }

The question is that address(this).balance does never reflect any change when I send ether to the contract, it is always zero. I created the variable ContractAddress only to confirm that the address matches that of the deployed contract, which it does.

Most surprisingly, when I externally call BalanceCheck() with the contract address (ContractAddress) as an argument it does return the correct value (¿?). This openly contradicts that ContractAddress = address(this).

What am I missing here? what is wrong with address(this)?

Thanks in advance

1 Answer 1

2
uint256 public NativeBalance = address(this).balance;

This line of code just initialized NativeBalance variable while deploying the contract (same effect as you assign initial value in the costructor fucntion) and will never be updated (you didn't update anywhere), it doesn't mean NativeBalance will track value of address(this).balance; automatically .

If you want the balance, address(this).balance is your best option, as some minor cases your contract's balance will be updated without executing any of your contract's code.

1
  • any suggestions whether the address(this).balance function in this question will reflect the changes immediately after transfer() function initiated, or only after it succeeds? ethereum.stackexchange.com/q/152036/120999
    – Mila A
    Jul 2, 2023 at 9:13

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.