Created
December 5, 2016 04:13
-
-
Save bitgord/abf55f9db4fa49333ae165768daef227 to your computer and use it in GitHub Desktop.
Example of an escrow smart contract
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Updated a few things on my fork.
[email protected]
is now in beta so the contract creation and deployment function calls will change.