Skip to content

Instantly share code, notes, and snippets.

@mostafabahri
Created September 13, 2017 12:26
Show Gist options
  • Save mostafabahri/7e55ca38f0784d5675e8a22f02bac377 to your computer and use it in GitHub Desktop.
Save mostafabahri/7e55ca38f0784d5675e8a22f02bac377 to your computer and use it in GitHub Desktop.
pragma solidity ^0.4.11;
contract Purchase {
uint public value;
address public seller;
address public buyer;
enum State { Created, Locked, Refund, Inactive }
// state init??
State public state = State.Created;
function Purchase() 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();
/// Abort the purchase and reclaim the ether.
/// Can only be called by the seller before
/// the contract is locked.
function abort()
onlySeller
inState(State.Created)
{
aborted();
state = State.Inactive;
seller.transfer(this.balance);
}
/// Confirm the purchase as buyer.
/// Transaction has to include `2 * value` ether.
/// The ether will be locked until confirmReceived
/// is called.
function confirmPurchase()
inState(State.Created)
condition(msg.value == (2 * value))
payable
{
purchaseConfirmed();
buyer = msg.sender;
state = State.Locked;
}
/// Confirm that you (the buyer) received the item.
/// This will release the locked ether.
function confirmReceived()
onlyBuyer
inState(State.Locked)
{
itemReceived();
// It is important to change the state first because
// otherwise, the contracts called using `send` below
// can call in again here.
state = State.Inactive;
// there is a total of 4*value in balance
// buyer will receive value = (2 * value) / 2 , (paying value to seller)
buyer.transfer(value);
// seller receieves the remaining value: 3 * value
seller.transfer(this.balance);
}
/// Confirm that the seller and you (the buyer) both agree to
/// cancel the purchase; called by the seller and reclaims the item.
/// This will unlock release the locked ether.
function confirmRefunded()
onlySeller
inState(State.Locked)
{
state = State.Inactive;
// refund both parties
seller.transfer(2 * value);
buyer.transfer(2 * value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment