Solidity – Handling Unknown or Non-Constant Gas Requirements

gasmappingsolidity

This is a function in my contract. There is noting complex about this it shows a warning that the gas requirement is large on remix. I speculate this might be a reason why I had gas issues while trying to deploy using truffle.

First of all I need to understand the issue.

function sendEther(string data) payable {
  address sender = msg.sender;
  uint value = msg.value;
  voter[sender].data = data;
  voter[sender].amount = value;
  voterIndex[voter_count] = sender;
  voter_count = voter_count + 1;
  Deposit(sender, value);
}

Note: I found a similar issue where the user was trying to send a transaction which could be a normal address or a contract and thus had the issue. No idea why it happens to me.

EDIT: The constant keyword was a typos. But the actual question was answered precisely below.

Best Answer

Two things.

First, the use of payable and constant together is contradictory. Second, the use of a string means that the transaction payload size and the storage cost is unpredictable, owing to the variable length of the string.

I fleshed it out until it would compile, replicated the gas warning error and eliminated the warning with a change to good'ol bytes32. A further advantage of the fixed-size interface is that it can be called from other contracts.

Update:

You can pass strings between contracts with the new Solidity compilers.

pragma solidity ^0.4.15;

contract X {

    struct Voter {
        bytes32 data;
        uint amount;
    }
    mapping(address => Voter) voter;
    address[] voterIndex;
    uint voter_count;

    event Deposit(address a, uint b);

    function sendEther(bytes32 data) public payable  {
      address sender = msg.sender;
      uint value = msg.value;
      voter[sender].data = data;
      voter[sender].amount = value;
      voterIndex[voter_count] = sender;
      voter_count = voter_count + 1;
      Deposit(sender, value);
    }

}

Hope it helps.

Related Topic