该示例中买家支付并确认交易后,交易进入锁定状态,待买家确认收货后,交易完成,合约将退回押金给买家和转账交易金额给卖家。其中在不同的交易环节过程中会触发不同的事件发生。
与中心化交易相比,由于失去了类似某宝的中间人角色,需要在交易中添加对买卖双方的保障:
- 对于买方而已,在支付交易金额后,交易会进入锁定状态,交易金额会被冻结,只有在买家确认满意收货后,卖方才会收到货款;
- 对于卖方而已,买方需要在支付交易金额的同时多支付一倍的押金,俗称“买一押一”,同时卖方可以根据情况在交易锁定前提出取消交易。
pragma solidity ^0.4.21;
contract Purchase {
uint public value;
address public seller;
address public buyer;
enum State { Created, Locked, Inactive }
State public state;
function Purchase() public payable {
seller = msg.sender;
value = msg.value / 2;
require((2 * value) == msg.value);
}
modifier condition(bool _condition) {
require(_condition);
_;
}
modifier onlyBuyer() {
require(msg.sender == buyer);
_;
}
modifier onlySeller() {
require(msg.sender == seller);
_;
}
modifier inState(State _state) {
require(state == _state);
_;
}
event Aborted();
event PurchaseConfirmed();
event ItemReceived();
function abort()
public
onlySeller
inState(State.Created)
{
emit Aborted();
state = State.Inactive;
seller.transfer(this.balance);
}
function confirmPurchase()
public
inState(State.Created)
condition(msg.value == (2 * value))
payable
{
emit PurchaseConfirmed();
buyer = msg.sender;
state = State.Locked;
}
function confirmReceived()
public
onlyBuyer
inState(State.Locked)
{
emit ItemReceived();
state = State.Inactive;
buyer.transfer(value);
seller.transfer(this.balance);
}
}
文章参考 https://blog.csdn.net/qq_33829547/article/details/80377386
|