使用Modifier

不知道你有没有注意

var commodity = warehouse[msg.sender];
require(commodity.seller != 0x0);

这两句重复的次数非常繁多,是代码冗余,不如在这里用到modifier 帮助我们简化代码:

modifier commodityExist(address seller){
    var commodity =  warehouse[seller];
    require(commodity.seller != 0x0);
    _;
}

顾名思义,这个modifier是来检查有没有指定货物的,这样一来,像removeCommodity和 confirmFinish 方法就可以省一些代码了。比如:

function removeCommodity() commodityExist(msg.sender){
    delete warehouse[msg.sender];
}

function confirmFinish(address seller) commodityExist(seller){
    require(warehouse[seller].buyer == msg.sender);

    warehouse[seller].isFinish = true;
    seller.transfer(warehouse[seller].price);
}

修改之后的完整代码:

pragma solidity ^0.4.14;

contract Market{

    struct Commodity{
        string name;
        string url;
        uint price;
        address seller;
        address buyer;
        uint time;
        bool isFinish;
    }

    mapping(address => Commodity) warehouse;

    modifier commodityExist(address seller){
        var commodity =  warehouse[seller];
        assert(commodity.seller != 0x0);
        _;
    }

    function buy(address seller) commodityExist(seller) payable returns (uint) {
        warehouse[seller].buyer = msg.sender;
        return this.balance;
    }

    function addCommodity(string name, string url, uint price){
        require(bytes(name).length > 0);
        require(bytes(url).length > 0);

        warehouse[msg.sender] = Commodity(name, url, price/(1 ether), msg.sender, 0x0, now, false);
    }

    function removeCommodity() commodityExist(msg.sender){
        delete warehouse[msg.sender];
    }

    function updateCommodity(string name, uint price) commodityExist(msg.sender){
        warehouse[msg.sender].name = name;
        warehouse[msg.sender].price = price/(1 ether);
        warehouse[msg.sender].time = now;
    }

    function confirmFinish(address seller) commodityExist(seller){
        require(warehouse[seller].buyer == msg.sender);

        warehouse[seller].isFinish = true;
        seller.transfer(warehouse[seller].price);
    }
}

results matching ""

    No results matching ""