1

Important:

  • Using Solidity IDE with Web3 provider
  • Test RPC and web3 installed
  • Testing with 10 Ether accounts with enough Ether (100 ETH) per account.

I am testing a simple contract that receives Ether from one account, splits the value and transfers it to 3 other accounts.

contract testContract {

    address[] employees = [
        0x4cd28d9a0d66216382ad3e1c993797989d1a8e05,
        0xb871e16d7192cbaa2b5be32f85c1a19f61b8a50d,
        0x5e5527378c42b91e95fee2cfbe974259d983a99e
    ];

    function testContract() payable {

    }

    function () payable {
        uint amountPerEmployee = msg.value / employees.length;

        for(uint i = 0; i <= employees.length; i++) {
            employees[i].transfer(amountPerEmployee);
        }
    }

} 

When running the callback function with the loop I get an error:

callback contain no result Error: Error: VM Exception while executing eth_estimateGas: invalid opcode at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:59368:17 at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:69306:5 at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:11335:9 at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:7895:16 at replenish (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:8415:25) at iterateeCallback (/usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:8405:17) at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:8380:16 at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:11332:13 at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:69302:9 at /usr/local/lib/node_modules/ethereumjs-testrpc/build/cli.node.js:63982:7

When testing the callback function like below, everything goes well:

function () payable {
    uint amountPerEmployee = msg.value / employees.length;

    // Test with only the first item in the array, no loop
    employees[0].transfer(amountPerEmployee);
}

What is going on here? Is it the loop that is using too much gas?

3

You're walking off the end of the array with

for(uint i = 0; i <= employees.length; i++)

employees[] has exactly 3 rows, which are: 0, 1, 2.

You let i be 3 which does not exist so it isn't happy.

A related tip for later as you go forward. You'll want to refactor the loop out of the picture completely for scalability reasons.

Hope it helps.

  • Thanks a lot! That fixed the problem. And thanks for the tip as well. – Robbert Sep 5 '17 at 20:21

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.