pragma solidity ^0.4.10; contract Safebuy{ uint public price; address public seller; address public buyer; constructor() public payable{ seller = msg.sender; //uint value = msg.value / 2 ; //require(value *2 ==msg.value); price = msg.value; } enum State{Create,Block,Release} State public state; //根据函数的执行,更改条件状态--对函数方法的执行规定一定的顺序 modifier StateStatus(State _state){ require(state == _state); _; } modifier OnlyBuyer(){ require(buyer == msg.sender); _; } modifier OnlySeller(){ require(seller == msg.sender); _; } event Abort(); event Deal(); event EndDeal(); function getBalance() view public returns(uint){ return address(this).balance; //向该合约内共放入的以太币 //刚部署合约时:address(this).balance = msg.value //买家交易达成时:address(this).balance = msg.value *2 } //state = State.Release 其他函数都无法执行,该合约被终止 //abort()在其他2个函数执行之前才能调用 function abort() OnlySeller StateStatus(State.Create) public{ emit Abort(); state = State.Release; seller.transfer(address(this).balance); } //deal() 确定购买:在其他2个函数执行之前才能调用,先到先得,只执行一次 function deal() StateStatus(State.Create) payable public{ emit Deal(); buyer = msg.sender; require(msg.value == price); state = State.Block; } //endDeal 确认付款:在deal()执行之后,才能够执行该函数 function endDeal() OnlyBuyer StateStatus(State.Block)payable public{ emit EndDeal(); state = State.Release; // 注意: 这实际上允许买方和卖方阻止退款 - 应该使用取回模式 //buyer.transfer(msg.value);在执行deal函数时,已经扣掉了ether seller.transfer(address(this).balance); } }
学到的知识点:
1.enum:枚举根据改变枚举的状态,能够确定函数的执行顺序
2.address(this).balance:往该合约内注入的以太币
3.在函数执行之后,修改状态变量的值