function(err,res){
    console.log("New Block: ", res);

    if(err != null) {
      console.error("Filter err: ",err);
      return;
    }

    var num = eth.getBlock(res).number -1;
    console.log("Block number: ", num);
    var block = rng.getPendingBlock.call(num);
    console.log(block);
    if(block[1] > web3.toWei(1, "finney")){
      var val = Math.min(block[2],web3.toWei(bet,"ether"));
      rng.initBlock(num,{from:eth.coinbase});
      rng.sha.call(num, block[3], function(err,res){
        console.log(res.toString(16));
        rng.deposit(num, "0x"+res.toString(16), {from:eth.coinbase, value: val});
        proposals[num] = res;
      });
    }

    var keys = Object.keys(proposals);
    console.log(keys);
    for(var i =0; i< keys.length; i++){
      if(parseInt(keys[i]) + 2 < num){
        console.log("Victory!!")
        if(rng.getPendingBlock(keys[i])[4] < num){
          console.log("real victory")
          rng.declareVictor(keys[i], proposals[keys[i]], {from:eth.coinbase});
          delete proposals[keys[i]];
        }
      }
    }
});
Exemple #2
0
  formatEther: function(wei) {

    // detect format and convert
    if (typeof(wei) === 'string' && wei.match(/^0x\w+/)) {
      wei = web3.toWei(wei, 'wei');
    } else if (wei) {
      wei = wei.toNumber();
    } else {
      return '-';
    }

    var value;
    var unit;

    if (wei >= 1000000000000 && wei < 1000000000000000) {
      value = wei / 1000000000000;
      unit = 'szabo';
    } else if (wei >= 1000000000000000 && wei < 1000000000000000000) {
      value = wei / 1000000000000000;
      unit = 'finney';
    } else if (wei >= 1000000000000000000) {
      value = wei / 1000000000000000000;
      unit = 'ether';
    } else {
      value = wei;
      unit = 'wei';
    }

    return +value.toFixed(5) + ' ' + unit;
  },
Exemple #3
0
  it("should be able to handle multiple transactions at once and manage nonces accordingly", function(done) {
    var expected = 5;
    var received = 0;
    var callback_called = false;

    var txHandler = function(err, result) {
      if (callback_called) {
        return;
      }

      received += 1;

      if (err || received >= expected) {
        callback_called = true;
        return done(err);
      }
    };

    // Fire off transaction at once
    for (var i = 0; i < expected; i++) {
      web3.eth.sendTransaction({
        from: accounts[0],
        to: accounts[1],
        value: web3.toWei(1, "ether")
      }, txHandler);
    }
  });
Exemple #4
0
  it("should be able to handle batch transactions", function() {
    var expected = 5;
    var received = 0;
    var callback_called = false;

    var txHandler = function(err, result) {
      if (callback_called) {
        return;
      }

      received += 1;

      if (err || received >= expected) {
        callback_called = true;
        return done(err);
      }
    };

    var batch = web3.createBatch();

    for (var i = 0; i < expected; i++) {
      batch.add(web3.eth.sendTransaction.request({
        from: accounts[0],
        to: accounts[1],
        value: web3.toWei(1, "ether")
      }), txHandler);
    }

    batch.execute();
  });
  before("send a transaction then make a checkpoint", function(done) {
    web3.eth.sendTransaction({
      from: accounts[0],
      to: accounts[1],
      value: web3.toWei(1, "ether"),
      gas: 90000
    }, function() {
      // Since transactions happen immediately, we can assert the balance.
      web3.eth.getBalance(accounts[0], function(err, balance) {
        if (err) return done(err);

        balance = web3.fromWei(balance, "ether").toNumber()

        // Assert the starting balance is where we think it is, including tx costs.
        assert(balance > 98.9 && balance < 99);

        startingBalance = balance;

        // Now checkpoint.
        provider.sendAsync({
          jsonrpc: "2.0",
          method: "evm_snapshot",
          params: [],
          id: new Date().getTime()
        }, function(err, result) {
          if (err) return done(err);
          snapshotId = result.result;
          done();
        });
      })
    });
  });
Exemple #6
0
function testRandomValueAgainstWeb3ToWei(negative) {
  const stringTestValue = `${negative ? '-' : ''}${String(Math.floor((Math.random() * 100000000000000000) + 1))}`;
  const randomunitsType = Object.keys(units.unitMap)[Math.floor((Math.random() * (totalTypes - 1)) + 1)];
  const unitsValue = units.toWei(stringTestValue, randomunitsType);
  const web3Value = new BigNumber(web3.toWei(stringTestValue, randomunitsType));

  // it(`toWei should work like web3 val ${unitsValue.toString(10)} should equal ${web3Value.toString(10)}`, () => {
  assert.deepEqual(unitsValue, web3Value);
  // });
}
.then((pk) => {
    privkey = new Buffer(pk, 'hex');
    var wallet = Wallet.fromPrivateKey(privkey);
    var from = wallet.getAddress().toString('hex');
    var tx = {
      from,
      value: web3.toWei(value, 'ether'),
      to,
    }
    return Promise.promisify(web3.eth.sendTransaction)(tx);
})
Exemple #8
0
function sendDeposit(commitment_hex_str, cb_func) {
    //var commitment = utils.sha256("asdf" + Math.random()).toString('hex');
    //commitment = web3.toBigNumber('0x' + commitment);
    //console.log('2nd deposit commitment:', commitment);
    console.log("Depositing...");
    MixerInstance.deposit.sendTransaction(
        commitment_hex_str,
        {from:web3.eth.accounts[1], value: web3.toWei('1', 'ether'), gas: 500000},
        cb_func
    );

}
Exemple #9
0
		res.on('data', (data) => {
			try {
				var obj = JSON.parse(data);
				if (!obj.data || !obj.data[0] || !obj.data[0].supply) {
					console.log("invalid response from etherchain:", obj);
					throw new Error("etherchain API response doesn't contain supply");
				}
				supply = new BigNumber(web3.toWei(obj.data[0].supply, "ether"));
			} catch (err) {
				return callback(err);
			}
			callback(null, supply);
		});
  it("rolls back successfully", function(done) {
    // Send another transaction, check the balance, then roll it back to the old one and check the balance again.
    web3.eth.sendTransaction({
      from: accounts[0],
      to: accounts[1],
      value: web3.toWei(1, "ether"),
      gas: 90000
    }, function(err, tx_hash) {
      if (err) return done(err);

      // Since transactions happen immediately, we can assert the balance.
      web3.eth.getBalance(accounts[0], function(err, balance) {
        if (err) return done(err);

        balance = web3.fromWei(balance, "ether").toNumber()

        // Assert the starting balance is where we think it is, including tx costs.
        assert(balance > 97.9 && balance < 98);

        // Now revert.
        provider.sendAsync({
          jsonrpc: "2.0",
          method: "evm_revert",
          params: [snapshotId],
          id: new Date().getTime()
        }, function(err, result) {
          if (err) return done(err);
          assert(result, "Snapshot should have returned true");

          // Now check the balance one more time.
          web3.eth.getBalance(accounts[0], function(err, balance) {
            if (err) return done(err);

            balance = web3.fromWei(balance, "ether").toNumber()

            assert(balance == startingBalance, "Should have reverted back to the starting balance");

            // Now check that the receipt is gone.
            web3.eth.getTransactionReceipt(tx_hash, function(err, receipt) {
              if (err) return done(err);

              assert.equal(receipt, null, "Receipt should be null as it should have been removed");

              done();
            });
          });
        });
      })
    });
  })
 it('should send 1 ether to the bank', function(){
     var transaction = web3.eth.sendTransaction({
         from: web3.eth.coinbase,
         to: banker.bank,
         value: web3.toWei(1, "ether")
     })
     console.log(transaction)
     
     watch(transaction, function(err, res){
         console.log(err, res)
         bankBalance = web3.eth.getBalance(banker.bank).toNumber();
         done()
     })
 })
 it('should create another wallet and transfer 1 ether', function(){
     otherWallet = new Wallet()
     var transaction = web3.eth.sendTransaction({
         from: web3.eth.coinbase,
         to: otherWallet.address,
         value: web3.toWei(1, "ether")
     })
     console.log(transaction)
     
     watch(transaction, function(err, res){
         console.log(err, res)
         done()
     })
 })
Exemple #13
0
            $http.get("abi/custodial-forward.abi").then(function(res){
                console.log("setting parameters");
                var ContractClass = web3.eth.contract(res.data);
                var contract = new ContractClass($scope.contractAddress);

                var expirationDate = $scope.expirationTime.unix();
                var contractedPrice = web3.toWei($scope.contract.contractedPrice, "ether");

                var params = [$scope.contract.amount, expirationDate, contractedPrice, oracles[$scope.oracle].address, $scope.contract.description, $scope.contract.fraction, $scope.contract.marginPercent];
                console.log("params:");
                console.dir(params);
                contract.sendTransaction({gas:300000}).setPrimaryParams($scope.contract.amount, expirationDate, contractedPrice, $scope.contract.description, $scope.contract.fraction, $scope.contract.marginPercent, oracles[$scope.oracle].address);
                $scope.contractReady = true;
                $location.path('/contract/details/' + $scope.contractAddress + '/' + $scope.node);
            });
    it('should create a app wallet and transfer 1 ether', function (done) {

        appWallet = new Wallet();
        var transaction = web3.eth.sendTransaction({
                from: web3.eth.coinbase,
                to: appWallet.address,
                value: web3.toWei(1, "ether")
            }
        )
        console.log(transaction);

        watch(transaction, function (err, res) {
            console.log(err, res);
            done();
        })

    });
Exemple #15
0
    $cordovaBarcodeScanner.scan().then(function(imageData) {
        if (imageData.format == "QR_CODE") {
          if (!imageData.cancelled) {
            var Web3 = require('web3');
            var web3 = new Web3();
            // web3.setProvider(new web3.providers.HttpProvider('http://192.168.27.101:8545'));

            web3.setProvider(new web3.providers.HttpProvider('http://203.129.252.1:8545'));

            
            web3.eth.sendTransaction({
              from: '0x66b1bad13e3708f6a3beb418de1422cf582e3d97',
              to: '0x38ec0bb24ff247452e7d3d1d5eadc2a9f5fd4a06',
              value: web3.toWei(imageData.text, "ether")
            });
            //$state.go("tab.dash");
          }
        }
    }, function(error) {
Exemple #16
0
const infuraNetworks = _.fromPairs(_.compact(networks.map((network) => {
  var envVarName = `${network.toUpperCase()}_PRIVATE_KEY`
  var privateKeyHex = process.env[envVarName];

  if(privateKeyHex) {
    var privateKey = new Buffer(process.env[envVarName], "hex")
    var wallet = Wallet.fromPrivateKey(privateKey);
    var provider = new WalletProvider(wallet, `https://${network}.infura.io/`);

    return [
      network,
      {
        host: "localhost",
        port: 8545,
        network_id: "*",
        gas: 4600000,
        gasPrice: web3.toWei(13, "gwei"),
        provider,
      }
    ];
  }
})));
var Web3 = require('web3'); web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
var eth = web3.eth

addrFrom = "0x7b3a44a832e5f2a5c0fd55a2982f050b738aed18"
addrTo   = "0x622718cce4c6b75923ca21e5b1293e9fd4dae25a"

// val = web3.toWei(19000000000000000000000000, "ether")
val = web3.toWei(1, "ether")
eth.sendTransaction({from: addrFrom, to: addrTo, value: val})

// wait the tx to be confirmed...
Number(eth.getBalance(addrTo))

var simpleStorageAbi  = '[{"constant":true,"inputs":[],"name":"data","outputs":[{"name":"","type":"bytes32"}],"type":"function"},{"constant":false,"inputs":[{"name":"_data","type":"bytes32"}],"name":"set","outputs":[],"type":"function"}]'
var simpleStorageData = "0x606060405260938060106000396000f360606040526000357c01000000000000000000000000000000000000000000000000000000009004806373d4a13a146041578063db80813f14606657603f565b005b604c6004805050607c565b604051808260001916815260200191505060405180910390f35b607a60048080359060200190919050506085565b005b60006000505481565b806000600050819055505b5056"

simpleStorageAbi = JSON.parse(simpleStorageAbi)


var SimpleStorage = eth.contract(simpleStorageAbi)

var opts = {
  data: simpleStorageData,
  from: addrFrom,
}

var simpleStorageCreationCb = (err, contract) => {
  if (err) {
    console.error(err.stack)
  } else {
    console.log("TX:")
var create = function (config, identifier, overwrite, callback) {
    try {
        
        // setup configurable properties
        var owner = config.owner;
        var namereg = config.namereg === 'default' ? web3.eth.namereg : registrar.at(config.namereg);

        // start web3.js
        web3.setProvider(new web3.providers.HttpProvider('http://' + config.jsonrpc_host + ':' + config.jsonrpc_port));

        var code = web3.eth.getCode(namereg.address);
        if (code === '0x' || !code) {
            return callback(errors.NAMEREG_IS_INCORRECT);
        }

        // validate new exchange identifier 
        if (!utils.validateIdentifier(identifier)) {
            return callback(errors.IDENTIFIER_IS_INCORRECT);
        }

        var encodedIdentifier = web3.fromAscii(identifier);

        // check if exchange with given identifier can be created
        var idOwner = namereg.owner(encodedIdentifier);
        var reserved = !utils.isEmptyAddress(idOwner);
        if (reserved) {
            if (idOwner !== owner) {
                return callback(errors.IDENTIFIER_NOT_OWNED);
            }

            if (!overwrite) {
                return callback(errors.IDENTIFIER_CANNOT_OVERWRITE);
            }
        } else {
            var reserveHash = namereg.reserve(encodedIdentifier, {from: owner, value: web3.toWei(69, 'ether')});
            var reserveReceipt = waitForReceipt(reserveHash);
            reserved = !!reserveReceipt;
        }

        // compile contract, TODO: it should use config contract location instead
        var file = fs.readFileSync(__dirname + '/contracts/SmartExchange.sol');
        var compiled = web3.eth.compile.solidity(file.toString());

        // TODO: config add contract class name to config
        var code = compiled.SmartExchange.code;
        var abi = compiled.SmartExchange.info.abiDefinition;

        // create new contract and get it's transaction hash
        // smart-exchange requires at least 267886 gas, so let's require a little more
        var transactionHash = web3.eth.contract(abi).new({data: code, from: owner, gas: 280000}).transactionHash;
        var receipt = waitForReceipt(transactionHash);

        if (receipt && reserved) {

            // after receiving transaction receipt we can assume, that contract is properly created
            namereg.setAddr(encodedIdentifier, receipt.contractAddress, {from: owner});
            callback(null, receipt.contractAddress); 
        } else {
            callback(errors.CONTRACT_DEPLOYMENT_ERROR);
        }

    } catch (err) {
        callback(errors.UNKNOWN_ERROR(err));
    }
};
Exemple #19
0
router.post('/send/', function(req,res,next) {


/*Step basic
1 get value
2 invoke web3(geth)
3 process response web3
4 response client (browser)(json)
*/
var adressfrom=req.body.adressfrom;
var adressto=req.body.adressto;
var pass=req.body.pass;


console.log(adressfrom)
console.log(adressto)
console.log(pass)
  
//web3
var web3 = new Web3(new Web3.providers.HttpProvider( global["iprpc"]));
if(web3.isConnected()) {

   // show some dialog to ask the user to start a node



    web3.personal.unlockAccount(adressfrom, pass,10);

    var transObj={
      "from": adressfrom,
      "to": adressto,
      "value":  web3.toWei(0.1, "ether")
    };

    web3.eth.sendTransaction(transObj,function(error, address) {
      if (!error)
      {
        console.log(address); 

         res.json({ "address":address});
      }
      else{
        res.status(503).json(error);
      }

    }
    
    );






} else {


   res.status(503).json({"address":"error","balance":"eerror"});

}



   
});
Exemple #20
0
if(missionPrivateKeyHex) {
  var missionPrivateKey = new Buffer(missionPrivateKeyHex, "hex")
  var missionWallet = Wallet.fromPrivateKey(missionPrivateKey);
  missionProvider = new WalletProvider(missionWallet, `https://parity.stage.compound.finance/`);
}

module.exports = {
  networks: {
    development: {
      host: "localhost",
      port: 8545,
      network_id: "*",
      gas: 4600000,
      gasPrice: 20000,
    },
    mission: {
      port: 8545,
      gas: 4612388,
      gasPrice: web3.toWei(15, "gwei"),
      network_id: "235",
      provider: missionProvider,
    },
    ...infuraNetworks,
  },
  solc: {
    optimizer: {
      enabled: true
    }
  }
};
 web3IPC.personal.unlockAccount(coinbase, coinbasePw, function(err, res) {
   console.log(res);
   web3IPC.eth.sendTransaction({from: coinbase, to: address, value: web3IPC.toWei(1000, 'ether')}, function(err, res){ console.log(address)});
 });
Exemple #22
0
 it('should hash a number stored in a string', () => {
   sha3num(web3.toWei('100')).should.equal('0xc7cc234d21c9cfbd4632749fd77669e7ae72f5241ce5895e410c45185a469273')
 })