Skip to content

Instantly share code, notes, and snippets.

@anistark
Forked from ToJen/Escrow-Smart-Contract
Last active March 28, 2018 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anistark/f82a68517b0775baaf52c591756a9708 to your computer and use it in GitHub Desktop.
Save anistark/f82a68517b0775baaf52c591756a9708 to your computer and use it in GitHub Desktop.
Example of an escrow smart contract
// package.json
{
"dependencies": {
"web3": "0.20.0",
"solc": "^0.4.19"
}
}
//Create file Ecrow.sol and create 3 variables: a buyer, a seller, and an arbiter
contract Escrow {
address public buyer;
address public seller;
address public arbiter;
function Escrow(address _seller, address _arbiter) {
buyer = msg.sender;
seller = _seller;
arbiter = _arbiter;
}
function payoutToSeller() {
if(msg.sender == buyer || msg.sender == arbiter) {
seller.send(this.balance);
}
}
function refundToBuyer() {
if(msg.sender == seller || msg.sender == arbiter) {
buyer.send(this.balance);
}
}
function getBalance() constant returns (uint) {
return this.balance;
}
}
//In node console
var source = `{{contract code}}`
//Set variables
var buyer = web3.eth.accounts[0] ; var seller = web3.eth.accounts[1] ; var arbiter = web3.eth.accounts[2]
//Compile contract
var compiled = solc.compile(source)
//Store bytecode
var bytecode = compiled.contracts.Escrow.bytecode
//Store abi
var abi = JSON.parse(compiled.contracts.Escrow.interface)
//Set contract factory
var escrowContract = web3.eth.contract(abi)
//Deploy contract
var deployed = escrowContract.new(seller, arbiter, {
from: buyer,
data: bytecode,
gas: 47000000,
gasPrice: 5,
value: web3.toWei(5, 'ether')
}, (error, contract) => { })
//Check contract address
deployed.address
//See user addresses
deployed.buyer.call()
deployed.seller.call()
deployed.arbiter.call()
//Check balance function
var balance = (acct) => { return web3.fromWei(web3.eth.getBalance(acct), 'ether').toNumber() }
//Check balances
balance(buyer)
balance(deployed.address)
//Buyer finalizes contract
deployed.payoutToSeller({from: buyer})
balance(sellter)
balance(deployed.address)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment