5

I'd like get ether balance of account in solidity. I tried the following, but it didn't work. Could you tell me how to do it?

contract MultiplyContract{
    address public buyer;
    address public seller;
    uint public price;
    function MultiplyContract(
      address _buyer,
      address _seller,
      uint _price,
      ){
      buyer = _buyer;
      seller = _seller;
      price = _price;
    }
    function Execution (address _buyer, address _seller) {
    eth.getBalance(_buyer) -=  price; 
    eth.getBalance(_seller) += price;
  }
}
10

A contract can read any balance using address.balance like: _buyer.balance

A contract can send its Ether in units of wei using address.send like: seller.send(price)

A contract cannot subtract from an arbitrary address.

Using send subtracts from the balance of the contract, so if the contract has a balance, it could do:

function Execution (address _seller) {
    seller.send(price);
}
  • You should use transfer instead. – Ender Aug 13 at 4:06
  • transfer was added later on, and yes it is safer in most cases. It is also important to be aware of cases where a contract can get stuck by using transfer: ethereum.stackexchange.com/a/74007/42 – eth yesterday
7

Please refer to address methods documentation.

You should prefer to use transfer over send:

There are some dangers in using send: The transfer fails if the call stack depth is at 1024 (this can always be forced by the caller) and it also fails if the recipient runs out of gas. So in order to make safe Ether transfers, always check the return value of send, use transfer or even better: Use a pattern where the recipient withdraws the money.

4

address.transfer()

  • throws on failure
  • forwards 2,300 gas stipend, safe against reentrancy
  • should be used in most cases as it's the safest way to send ether

address.send()

  • returns false on failure
  • forwards 2,300 gas stipend, safe against reentrancy
  • should be used in rare cases when you want to handle failure in the contract

address.call.value().gas()()

  • returns false on failure
  • forwards all available gas, allows specifying how much gas to forward
  • should be used when you need to control how much gas to forward when sending ether or to call a function of another contract

More details here https://ethereum.stackexchange.com/a/38642/18932

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.