Skip to content

Instantly share code, notes, and snippets.

@bitgord
Created December 5, 2016 04:13
Show Gist options
  • Save bitgord/abf55f9db4fa49333ae165768daef227 to your computer and use it in GitHub Desktop.
Save bitgord/abf55f9db4fa49333ae165768daef227 to your computer and use it in GitHub Desktop.
Example of an escrow smart contract
// package.json
{
"dependencies": {
"web3": "0.17.0-alpha",
"solc": "^0.4.4"
}
}
//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 compiler = 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.ethcontract(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)
@ToJen
Copy link

ToJen commented Jan 3, 2018

Updated a few things on my fork. [email protected] is now in beta so the contract creation and deployment function calls will change.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment