Skip to content

Instantly share code, notes, and snippets.

@doey-default
Last active May 13, 2020 05:19
Show Gist options
  • Select an option

  • Save doey-default/f5c184ea941348dfa25776c202464c1a to your computer and use it in GitHub Desktop.

Select an option

Save doey-default/f5c184ea941348dfa25776c202464c1a to your computer and use it in GitHub Desktop.
pragma solidity ^0.4.24;
contract Escrow{
uint public value;
address public seller;
address public buyer;
string public message;
enum State {Init, Created, Locked, Sent, Complete}
State public state;
function registerItem(uint amount) public{
require(state == State.Init, "Process already started");
seller = msg.sender;
value = amount;
state = State.Created;
message = "Item registerd.";
}
function buyItem() payable public{
require(msg.value > 0);
if(state == State.Created){
if(msg.value == value){
buyer = msg.sender;
state = State.Locked;
message = "Item purchased";
} else{
message = appendUintToString("Not enough money : ", value);
}
}else{
message = "Item is not available.";
}
}
function refund() public{
if(msg.sender == seller || msg.sender == buyer){
if( state == State.Locked){
if(!buyer.send(value)){
revert();
}
else{
buyer = address(0);
state = State.Created;
}
}
}
}
function sendItem() public{
if(msg.sender == seller && state == State.Locked){
state = State.Sent;
message = "Item sent.";
}
}
function confirmItem() public{
if(msg.sender == buyer && state == State.Sent ){
if(!seller.send(value)){
revert();
}else {
state = State.Complete;
message = "Process finished";
}
}
}
function appendUintToString(string inStr, uint v) private pure returns (string str) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory inStrb = bytes(inStr);
bytes memory s = new bytes(inStrb.length + i);
uint j;
for (j = 0; j < inStrb.length; j++) {
s[j] = inStrb[j];
}
for (j = 0; j < i; j++) {
s[j + inStrb.length] = reversed[i - 1 - j];
}
str = string(s);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment