Skip to content

Instantly share code, notes, and snippets.

@AlwaysBCoding
Last active July 12, 2019 22:33
Show Gist options
  • Save AlwaysBCoding/99a2278f7a863d463c4b3e344a10a02b to your computer and use it in GitHub Desktop.
Save AlwaysBCoding/99a2278f7a863d463c4b3e344a10a02b to your computer and use it in GitHub Desktop.
Ethereum Ðapp Development - Video 9 | Smart Contracts - Coin Flipper (Part 1)
// Config
global.config = {
rpc: {
host: "localhost",
port: "8545"
}
}
// Load Libraries
global.solc = require("solc")
global.fs = require("fs")
global.Web3 = require("web3")
// Connect Web3 Instance
global.web3 = new Web3(new Web3.providers.HttpProvider(`http://${global.config.rpc.host}:${global.config.rpc.port}`))
// Global Account Accessors
global.acct1 = web3.eth.accounts[0]
global.acct2 = web3.eth.accounts[1]
global.acct3 = web3.eth.accounts[2]
global.acct4 = web3.eth.accounts[3]
global.acct5 = web3.eth.accounts[4]
// Helper Functions
class Helpers {
contractName(source) {
var re1 = /contract.*{/g
var re2 = /\s\w+\s/
return source.match(re1).pop().match(re2)[0].trim()
}
createContract(source, options={}) {
var compiled = solc.compile(source)
var contractName = this.contractName(source)
var bytecode = compiled["contracts"][contractName]["bytecode"]
var abi = JSON.parse(compiled["contracts"][contractName]["interface"])
var contract = global.web3.eth.contract(abi)
var gasEstimate = global.web3.eth.estimateGas({ data: bytecode })
var deployed = contract.new(Object.assign({
from: global.web3.eth.accounts[0],
data: bytecode,
gas: gasEstimate,
gasPrice: 5
}, options), (error, result) => { })
return deployed
}
loadContract(name) {
var path = `./${name.toLowerCase()}.sol`
return fs.readFileSync(path, 'utf8')
}
deployContract(name, options={}) {
var source = this.loadContract(name)
return this.createContract(source, options)
}
etherBalance(contract) {
switch(typeof(contract)) {
case "object":
if(contract.address) {
return global.web3.fromWei(global.web3.eth.getBalance(contract.address), 'ether').toNumber()
} else {
return new Error("cannot call getEtherBalance on an object that does not have a property 'address'")
}
break
case "string":
return global.web3.fromWei(global.web3.eth.getBalance(contract), 'ether').toNumber()
break
}
}
}
// Load Helpers into Decypher namespace
global.decypher = new Helpers()
// Start repl
require('repl').start({})
contract Flipper {
enum GameState {noWager, wagerMade, wagerAccepted}
GameState public currentState;
modifier onlyState(GameState expectedState) { if(expectedState == currentState) { _; } else { throw; } }
function Flipper() {
currentState = GameState.noWager;
}
function makeWager() onlyState(GameState.noWager) returns (bool) {
// ...
currentState = GameState.wagerMade;
return true;
}
function acceptWager() onlyState(GameState.wagerMade) returns (bool) {
// ...
currentState = GameState.wagerAccepted;
return true;
}
function resolveBet() onlyState(GameState.wagerAccepted) returns (bool) {
// ...
currentState = GameState.noWager;
return true;
}
}
@mechanical-turk
Copy link

The code uses outdated syntax at various points. Here's a currently working version:

// Config
global.config = {
  rpc: {
    host: "localhost",
    port: "8545",
  },
};

// Load Libraries
global.solc = require("solc");
global.fs = require("fs");
global.Web3 = require("web3");

// Connect Web3 Instance
global.web3 = new Web3(new Web3.providers.HttpProvider(`http://${global.config.rpc.host}:${global.config.rpc.port}`));

// Global Account Accessors
global.acct1 = web3.eth.accounts[0];
global.acct2 = web3.eth.accounts[1];
global.acct3 = web3.eth.accounts[2];
global.acct4 = web3.eth.accounts[3];
global.acct5 = web3.eth.accounts[4];

// Helper Functions
class Helpers {

  contractName(source) {
    const re1 = /contract.*{/g;
    const re2 = /\s\w+\s/;
    return source.match(re1).pop().match(re2)[0].trim();
  }

  createContract(source, options={}) {
    const compiled = solc.compile(source);
    const contractName = this.contractName(source);
    const contractToDeploy = compiled.contracts[`:${contractName}`];
    const bytecode = contractToDeploy.bytecode;
    const abi = JSON.parse(contractToDeploy.interface);
    const contract = global.web3.eth.contract(abi);
    const gasEstimate = global.web3.eth.estimateGas({ data: bytecode });
    const contractTx = {
      from: global.web3.eth.accounts[0],
      data: bytecode,
      gas: gasEstimate,
      gasPrice: 5,
    };
    const deployed = contract.new(Object.assign(
      {},
      contractTx,
      options,
    ), (error, result) => { });
    return deployed;
  }

  loadContract(name) {
    const path = `./${name.toLowerCase()}.sol`;
    return fs.readFileSync(path, 'utf8');
  }

  deployContract(name, options={}) {
    const source = this.loadContract(name);
    return this.createContract(source, options);
  }

  etherBalance(contract) {
    switch(typeof(contract)) {
      case "object":
        if(contract.address) {
          return global.web3.fromWei(global.web3.eth.getBalance(contract.address), 'ether').toNumber();
        } else {
          return new Error("cannot call getEtherBalance on an object that does not have a property 'address'");
        }
        break
      case "string":
        return global.web3.fromWei(global.web3.eth.getBalance(contract), 'ether').toNumber();
    }
  }
}

// Load Helpers into Decypher namespace
global.decypher = new Helpers()

// Start repl
require('repl').start({})

@kmaheshwari24
Copy link

kmaheshwari24 commented Nov 24, 2017

"throw" is now deprecated, thus one can use require(condition). require(false) compiles to 0xfd which is the REVERT opcode, meaning it will refund the remaining gas. The opcode can also return a value (useful for debugging), but I don't believe that is supported in Solidity as of this moment. (2017-11-21)

modifier onlyState (GameState expectedState) { require(expectedState == currentState); _; }

@j10sanders
Copy link

Thank you @mechanical-turk

@gajeam
Copy link

gajeam commented Feb 6, 2018

You can also use assert(), but that should only be used to prevent something really bad from happening.
Here's a StackOverflow post that goes over when to use require() (usually) and when to use assert() (rarely).

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