0
votes

playing with ethereum smart contracts I encountered a following problem. The contract gets deployed on Ropsten and then I'm trying to call function 'addRecipe' with the following code on geth:

recipes.addRecipe(300, "zupa", "zupa z trupa", {from:web3.eth.accounts[0], gas: 20000000})

The function looks as following:

function addRecipe(uint256 _price, string _name, string _content) public {

    recipes[recipeCount].price = _price;
    recipes[recipeCount].name = _name;
    recipes[recipeCount].content = _content;
    recipes[recipeCount].recipeOwner = msg.sender;

    recipeCount++;
}

I get the TX hash but looking up the transaction in Etherscan gives

 Warning! Error encountered during contract execution [Bad instruction] 

You can check it up here: https://ropsten.etherscan.io/tx/0xe5999c2d122e4871e82f5986397dfd39107cee2056a9280132abeaa460c0f66d

Adding 'payable' modifier to the function or using the following command doesn't give any better results...

recipes.addRecipe.sendTransaction(300, "zupa", "zupa z trupa", {from:web3.eth.accounts[0], gas: 200000000})

The whole contract:

pragma solidity ^0.4.24;

contract Recipes {

    address owner;
    uint256 recipeCount = 0;

    struct Recipe {
        string name;
        string content;
        uint256 price;
        address recipeOwner;
    }

    Recipe[] public recipes;

    function () public {
        owner = msg.sender;
    }

    function kill() public {
        require (msg.sender == owner);
        selfdestruct(owner);
    }


    function addRecipe(uint256 _price, string _name, string _content) public {

        recipes[recipeCount].price = _price;
        recipes[recipeCount].name = _name;
        recipes[recipeCount].content = _content;
        recipes[recipeCount].recipeOwner = msg.sender;

        recipeCount++;
    }

    function showRecipes(uint256 _id) constant returns(string) {

        return recipes[_id].content;

    }

}
1

1 Answers

0
votes

recipes is a dynamic storage array. You need to change the size of the array to add new elements to it. You can either do this by explicitly increasing the length of the array or by pushing a new element into the array.

function addRecipe(uint256 _price, string _name, string _content) public {
    recipes.length++;
    recipes[recipeCount].price = _price;
    recipes[recipeCount].name = _name;
    recipes[recipeCount].content = _content;
    recipes[recipeCount].recipeOwner = msg.sender;

    recipeCount++;
}

Or

function addRecipe(uint256 _price, string _name, string _content) public {
    Recipe memory r;
    r.price = _price;
    r.name = _name;
    r.content = _content;
    r.recipeOwner = msg.sender;

    recipes.push(r);

    recipeCount++;
}