Balance of Contract in Solidity

Published by Mario Oettler on

Last Updated on 12. June 2023 by Mario Oettler

Getting the balance of a contract can be useful for example when someone wants to transfer all funds from a contract to another address. The command is:

uint256 balance = address(this).balance;

The key word “this” refers to the instance of the called smart contract.

Example

The following example shows a smart contract that returns the balance of itself. Notice the payable keyword for the constructor in line 5 to be able to send funds to the smart contract during deployment:

pragma solidity 0.8.20;

contract BalanceTest{

    constructor() payable{

    }
    
    function getBalance() public view returns(uint256 _balance){
        uint256 balance = address(this).balance;
        return balance;
    }
}
Categories:

https://blockchain-academy.hs-mittweida.de/wp-content/uploads/2021/04/logo_bcam_rgb_gross.png

Welcome

Blockchain Academy

Continue with credential

No account yet?

Powered by Hidy

Register with Hidy


Register
Sign in

We need the following credential to register:

please select:

To create a new account, we need the following data from you:

We would appreciate the following additional information from you for the creation of your account:

Welcome

Blockchain Academy

Continue with credential

Already have an account?

Powered by Hidy

Sign in with Hidy


Register
Sign in

We need the following credential to log in:

please select: