文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
使用 Modifier
使用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);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论