How can contract (Solidity function) know how many Ethers contract holds?


Every transaction in Ethereum can send Ether to an address. Calling a contract method is a transaction. The contract will accept any sent Ether if the invoked method is marked as payable.

To check the contract balance in a method you can call "this.balance":

function getMyBalance() returns (uint) { return this.balance; }

You need to be a bit more specific with your question but for a contract to be able to accept Eth you need to implement a fallback function - function() payable {}.


This is a good function to know how much ether a contract has

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

There are three possible ways to send ether to a contract. The standard one is to use address.transfer/send or similar. For this to work the contract needs to have a payable function.

Then there are two methods that work regardless of a contract having implemented the payable function. The first is to fund a contract with ether and then executing selfdestruct(address). The second is to mine ether into a contract.

  • Sure - when mining ether the mining reward goes to the etherbase account. By default that is your main account but can be configured to be any valid ethereum address. Hence you can specify a contract address and mine ether into it. This works even if the contract has no payable function. See github.com/ethereum/go-ethereum/wiki/Mining for details. – Steve Jul 11 '17 at 19:42
  • yes it's correct, the ethers reward are only added to the contract account not sent via a new transaction so no need for a payable function, i hope you add this clarification to your answer and more details about the other option to make it clear for the new users. – Badr Bellaj Jul 11 '17 at 19:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.