[Ethereum] Gas Price Calculation

gasgas-pricesolidity

I have this code:

pragma solidity ^0.4.11;

contract Bank  {
    struct Balance {
      address owner;
      uint vault;
      uint profit;
    }

    Balance balance;
      mapping (address => uint) balances;

    function Bank() {
        balance.owner = msg.sender;
        balance = Balance(msg.sender, 0, 0);
    }

    function getBalance() constant returns (uint) {
        if(msg.sender == balance.owner) {
           return this.balance;
        }
        throw;
    }

    function withdrawOwner() returns (bool) {
        if(msg.sender == balance.owner) {
           balance.vault = balance.vault - balance.profit;
           bool sent = balance.owner.send(balance.profit);
           balance.profit = 0;
           return sent;
        }
        return false;
    }

    function withdraw() returns (bool) {
        uint customerBalance = balances[msg.sender];
        if(customerBalance == 0) {
          throw;
        }

        balance.vault -= customerBalance;

        balances[msg.sender] = 0;
        return msg.sender.send(customerBalance);
    }

    function deposit() payable returns (bool) {
        uint take = 100;

        uint depositAmount = msg.value;
        balance.vault += depositAmount;
        balance.profit += take;

        balances[msg.sender] = depositAmount - take;

        if(msg.value < 20) {
          throw;
        } 

        return true;
    }
}

Estimate gas says 4,700,000, which seems high. Is that because of the throw or the send? Judging from that with an ether price of around $200, that would cost $18?

I'm multiplying 20Gwei * 4.7e6 = 94000000000000000 = 0.094 ether

Best Answer

I've added a mock struct and mapping to your example and compiled it in Remix.

pragma solidity ^0.4.11;
// mock contracts
contract c{
 // mock mapping
 mapping (address=>uint) balances;
 // mock struct
 struct foo  {
     uint vault;
 }
function withdraw() returns (bool) {
    // init struct
    foo memory balance; 

    uint customerBalance = balances[msg.sender];
    if(customerBalance == 0) {
      throw;
    }

    balance.vault -= customerBalance;
    balances[msg.sender] = 0;
    return msg.sender.send(customerBalance);
}
}

The compiler returns. You spend your gas somewhere else. Please provide full contract.

Transaction cost: 160457 gas. Execution cost: 81525 gas.

UPD: Full contract cost

Transaction cost: 379244 gas. Execution cost: 245228 gas.

Related Topic