Ethereum/Solidity: Do we need to implement an own "balance"-variable in Contracts?

Viewed 592

In order to manage balances of a smart contract with Solidity, do we still need to implement the balance-keeper by ourselves?

In the following blogpost, the author is doing so:

https://medium.com/daox/three-methods-to-transfer-funds-in-ethereum-by-means-of-solidity-5719944ed6e9

contract Sender {
  function send(address _receiver) payable {
    _receiver.call.value(msg.value).gas(20317)();
  }
}

contract Receiver {
   uint public balance = 0;

   function () payable {
      balance += msg.value;
   }
 }

According to the docs, it seems to already built in: https://solidity.readthedocs.io/en/develop/units-and-global-variables.html#address-related (although it was implemented in the address-property which can be cast from this, don't know if I understand it correctly)

Can someone Experienced please clarify a bit?

PS: sorry for bad formatting of my question. Safari doesn't show the formatting-toolbar of stackoveflow anymore properly.

1 Answers

The two do different things. You can always check the balance of a contract via <address>.balance from a contract or eth_getBalance via JSON-RPC.

But the balance state variable in the contract you shared might be different from that number. For example, the contract address may have ether in it before deployment, or another contract might call selfdestruct(<address>) and add to this contract's ether that way. In both cases, the address's balance will reflect that, but the balance state variable in the code will not, because it only increases when the fallback function is invoked.

So it sort of depends... if you just want to know how much ether a contract holds, you should use the built-in <address>.balance, but if you want to track some other number, you'll need to do it yourself.

Related