【问题标题】:Geth + smart contract function = bad instructionGeth + 智能合约功能 = 错误指令
【发布时间】:2018-07-03 17:39:07
【问题描述】:

玩以太坊智能合约我遇到了以下问题。合约部署在 Ropsten 上,然后我尝试在 geth 上使用以下代码调用函数“addRecipe”:

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

函数如下:

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++;
}

我得到了 TX 哈希,但在 Etherscan 中查找交易给出了

 Warning! Error encountered during contract execution [Bad instruction] 

您可以在这里查看: https://ropsten.etherscan.io/tx/0xe5999c2d122e4871e82f5986397dfd39107cee2056a9280132abeaa460c0f66d

在函数中添加 'payable' 修饰符或使用以下命令不会产生更好的结果...

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

整个合同:

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;

    }

}

【问题讨论】:

    标签: ethereum solidity contract geth


    【解决方案1】:

    recipes 是一个动态存储阵列。您需要更改数组的大小以向其中添加新元素。您可以通过显式增加数组的长度或将新元素推入数组来做到这一点。

    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++;
    }
    

    或者

    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++;
    }
    

    【讨论】:

    • Ahh ok :) 所以通过增加数字来添加另一个数组元素不会产生预期的结果。谢谢!有没有办法从 geth 或 etherscan 读取确切的错误?矿工节点在执行此代码时应该返回错误(?)非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2023-01-26
    • 2021-12-30
    • 2018-09-23
    • 2014-02-12
    • 2021-12-17
    • 2022-11-29
    • 1970-01-01
    相关资源
    最近更新 更多