80

How do I get the balance of a contract with solidity? I know geth has web3.eth.getBalance(), but that's to get the contract balance after it has been deployed.

Is there a standard way of doing this, or do I have to have a separate var that uint256 that keeps track of the total balance?

9 Answers 9

105

You can do this by calling address.balance. To get the contract's balance, just do this.balance. Read the docs.

Update: As of Solidity ^0.4.24, you need to do:

address(this).balance

(Copied from answer by Paul Berg)

3
  • Can i set address(this).balance = 0 in withdraw function to prevent re-enterancy before transfer call. It gives me " Expression has to be an lvalue" on doing so
    – 0xAnon
    Commented Oct 23, 2021 at 13:51
  • You cannot. Balance is not a variable that can be changed on command, it is the amount of Ether the address owns. The only way to set that to zero would be to give away all the Ether. However setting it to zero probably wouldn't prevent reentrancy anyways so you're good
    – Meriadoc
    Commented Mar 16, 2022 at 12:47
  • You cannot do address(this).balance = 0 , because address(this).balance is a number not a variable. You can refer to this clickHere for reentrancy Modifier. Commented Aug 21, 2022 at 8:01
29

Small update from my side:

enter image description here

You want to use the following, address(this).balance;

22

As of Solidity ^0.4.24, you need to do:

address(this).balance

You can see an example here.

Alternatively, if you need to read the balance of a separate contract:

address(contractVar).balance
7

In case of invalid opcode, use a local variable of type address payable as workaround:

        address payable self = address(this);
        uint256 balance = self.balance;

In solidity 0.5.14, I get an invalid opcode, debugging showed me, that it is exactly here:

address(this).balance

Test result:

     Error: Returned error: VM Exception while processing transaction: invalid opcode
     at PromiEvent (node_modules/truffle/build/webpack:/packages/contract/lib/promievent.js:6:1)                                                              
      at TruffleContract.destroy (node_modules/truffle/build/webpack:/packages/contract/lib/execute.js:158:1)                                                 
      at Context.it (test/1_PactaTest.js:108:17)                                                                                                              
      at web3.eth.getBlockNumber.then.result (node_modules/truffle/build/webpack:/packages/core/lib/testing/testrunner.js:161:1)                              
      at <anonymous>                                                                                                                                          
      at process._tickCallback (internal/process/next_tick.js:188:7)                                                                                          

Debugging:

debug(development:0x7655ecf8...)> 

Pacta.sol:

115:     // move whole balance to the owner
116:     function withdraw() public managers isActive {
117:         uint256 part = address(this).balance / beneficiaries.length;
                            ^^^^^^^^^^^^^^^^^^^^^                        

debug(development:0x7655ecf8...)> 

Transaction halted with a RUNTIME ERROR.

This is likely due to an intentional halting expression, like assert(), require() or revert(). It can also be due to out-of-gas exceptions. Please inspect your transaction parameters and contract code to determine the meaning of this error.
2
  • This solution throws an error TypeError: Type address is not implicitly convertible to expected type address payable. address payable self = address(this);
    – Dziugas
    Commented Apr 4, 2020 at 21:01
  • 7
    use payable(address(this)).balance Commented Jun 7, 2020 at 6:20
1

uint256 contractBalance = address(this).balance;

1

I think the code should looks like this:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Balance {

  function balance() public returns (uint256){
    return payable(address(this)).balance;
  }
}
2
  • 2
    The cast to payable isn't needed.
    – Ismael
    Commented Mar 17, 2022 at 4:40
  • For some reasons, for me, it HAS to be CASTED to payable. the normal address(this).balance didn't work for me. But this payable(address(this)).balance works.
    – jlee88my
    Commented Jun 15, 2022 at 4:22
1

address(this) give address of current deployed smart contract

<address>.balance give balance of any address. e.g. 0x9812j3....kh1298n.balance

to get balance of contract from contract itself. use this code:

function getBalance() public view returns(uint){
   return address(this).balance;
}

to get balace of any contracts/person of the whole blockchain, use this code:

function getBalance(address ContractAddress) public view returns(uint){
    return ContractAddress.balance;
}

ref: https://docs.soliditylang.org/en/latest/control-structures.html?highlight=address%20initial#salted-contract-creations-create2

0

Create a simple function which accept the address and in return it just return back amount of eth u hold

function balance(address owner) public view returns(uint accountBalance)
{
   accountBalance = owner.balance;
}
0

Important thing is add this two agregators to your function public and view for show it and access it to every one.

//                       |      |
//                       v      v
function showBalance() public view returns(uint) {
   return address(this).balance;
}

Regards

1
  • You don't need the cast to payable.
    – Ismael
    Commented Nov 3, 2022 at 6:22

Your Answer

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