var waitForReceipt = function (transactionHash) {
    var receipt = null;
    var counter = 0;
    while ((receipt = web3.eth.getTransactionReceipt(transactionHash)) === null) {
        if (counter++ > 120) {
            break;
        }
        sleep.sleep(1);
    }
    return receipt;
};
Node.prototype.setWatches = function()
{
	var self = this;

	this.pendingFilter = web3.eth.filter('pending');
	this.pendingFilter.watch( function(log) {
		if(PENDING_WORKS) {
			debounce(function() {
				self.updatePending();
			}, 50);
		}
	});

	this.chainFilter = web3.eth.filter('latest');
	this.chainFilter.watch(function(log) {
		debounce(function() {
			self.update();
		}, 50);
	});

	this.updateInterval = setInterval(function(){
		self.update();
	}, UPDATE_INTERVAL);

	this.pingInterval = setInterval(function(){
		self.ping();
	}, PING_INTERVAL);
}
Example #3
0
    it("should return block given the block hash", function() {
      block = manager.blockchain.blocks[0];
      block = web3.eth.getBlock(0);
      var blockHash = web3.eth.getBlock(block.hash);

      resultHash = {
        number: 0,
        hash: blockHash.hash,
        parentHash: '0x0000000000000000000000000000000000000000000000000000000000000000',
        nonce: '0x0',
        sha3Uncles: '0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347',
        logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
        transactionsRoot: undefined,
        stateRoot: '0x0000000000000000000000000000000000000000000000000000000000000000',
        receiptsRoot: '0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421',
        miner: '0x0000000000000000000000000000000000000000',
        difficulty: { s: 1, e: 0, c: [ 0 ] },
        totalDifficulty: { s: 1, e: 0, c: [ 0 ] },
        extraData: '0x0',
        size: 1000,
        gasLimit: 3141592,
        gasUsed: 0,
        timestamp: blockHash.timestamp,
        transactions: [],
        uncles: []
      };

      assert.deepEqual(blockHash, resultHash);
    });
Example #4
0
          }, function(error, txHash) {
            var receipt = web3.eth.getTransactionReceipt(txHash);

            web3.eth.call({
              from: account,
              data: '0x6d4ce63c',
              to: receipt.contractAddress

            }, function(error, _callResult) {
              callResult = _callResult;
              done();
            });
          });
Example #5
0
 getBlocks: function(current, last) {
   var blocks = [];
   for(;current <= last;current++) {
     var block = web3.eth.getBlock(current, false);
     if (block) {
       blocks.unshift(web3.eth.getBlock(current, false));
     } else {
       blocks.unshift({number: current, timestamp: 0, hash: '0xN/A', transactions: []});
       console.log("error: no data for block " + current + "!");
     }
   }
   return blocks;
 },
Example #6
0
  web3.eth.getBalance(web3.eth.coinbase, function(err, balance) {
    var sendAmount = web3.toBigNumber(Math.min(config.max, balance * percent));
    if (amount > 0 && amount < sendAmount) sendAmount = web3.toBigNumber(amount);

    logger.info(web3.fromWei(balance, 'ether').toString(), '=>', web3.fromWei(sendAmount, 'ether').toString(), '=>', addr, '(' + web3.fromWei(web3.eth.getBalance(addr), 'ether') + ')');

    web3.eth.sendTransaction({
      from: web3.eth.coinbase,
      to: addr,
      value: sendAmount.floor()
    }, function(err, hash) {
      if (err) hash = err;
      res.send(hash);
    });
  });
Node.prototype.getBlock = function(number)
{
	var block = {
		number: 0,
		hash: '?',
		difficulty: 0,
		timestamp: 0
	};

	if(typeof number === 'undefined'){
		try {
			number = web3.eth.blockNumber;

			if(number === this.stats.block.number)
				return this.stats.block;
		}
		catch (err) {
			console.error("blockNumber:", err);
		}
	}

	try {
		block = web3.eth.getBlock(number, true);

		if(block.hash != '?' && typeof block.difficulty !== 'undefined')
		{
			block.difficulty = web3.toDecimal(block.difficulty);
		}
	}
	catch (err) {
		console.error("getBlock(" + number + "):", err);
		if(number > 0){
			try {
				number -= 1;
				block = web3.eth.getBlock(number, true);

				if(block.hash != '?' && typeof block.difficulty !== 'undefined')
				{
					block.difficulty = web3.toDecimal(block.difficulty);
				}
			} catch (err) {
				console.error("getBlock(" + number + "):", err);
			}
		}
	}

	return block;
}
Example #8
0
 getBlocks: function(current, last) {
   var blocks = [];
   for(;current <= last;current++) {
     blocks.unshift(web3.eth.getBlock(current, false));
   }
   return blocks;
 },
Node.prototype.getStats = function()
{
	if(this._socket)
		this._lastStats = JSON.stringify(this.stats);

	if(this.isActive())
	{
		var block = this.getBlock();

		if(block.hash !== '?') {
			this.stats.block = block;
			// Get last MAX_BLOCKS_HISTORY blocks for calculations
			if(this.stats.block.number > 0)
				this.getLatestBlocks();

			if(PENDING_WORKS) {
				try {
					this.stats.pending = web3.eth.getBlockTransactionCount('pending');
				} catch (err) {
					PENDING_WORKS = false;
					console.error("getBlockTransactionCount('pending'):", err);
				}
			}

			this.stats.mining = web3.eth.mining;
			this.stats.gasPrice = web3.toBigNumber(web3.eth.gasPrice).toString(10);
		} else {
			console.error("getStats: couldn't fetch block...");
		}
	}

	this.uptime();
}
  web3.eth.getTransactionCount(tx.from, (err, nonce) => {
    if (err) { return callback(err); }
    debug(`got nonce, ${nonce}`);

    debug('looking up current gas price...');
    web3.eth.getGasPrice((innerErr, currentGasPrice) => {
      if (innerErr) { return callback(innerErr); }

      debug(`current gas price is ${currentGasPrice}`);

      // const gasLimit = '200000';
      // const gasPrice = +currentGasPrice ? currentGasPrice : '10000';
      const to = `0x${KRAKEN_ADDRESS}`;

      const gasPrice = '0x110c8f7d8de';
      const gasLimit = `0x${(22000).toString(16)}`;

      const rawTx = txToRaw({ ...tx, nonce, gasPrice, gasLimit, to });
      debug(`raw transaction: ${JSON.stringify(rawTx, null, 4)}`);

      const txToSign = new Tx(rawTx);
      txToSign.sign(privKey);

      const serializedTx = '0x' + txToSign.serialize().toString('hex');
      debug(`serialized transaction: ${serializedTx}`);

      web3.eth.sendRawTransaction(serializedTx, callback);
    });
  });
Example #11
0
app.get('/addr/:address',function(req, res){
  web3.eth.getTransactionCount(req.params.address, function(error, result){
    if (!error) {
      
    }
  })  
})
var transactions = function (config, identifier, options, callback) {
    try {

        // setup configurable properties
        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));
        if (!utils.validateIdentifier(identifier)) {
            return callback(errors.IDENTIFIER_IS_INCORRECT);
        }

        var encodedIdentifier = web3.fromAscii(identifier);

        // validate exchange identifier
        var address = namereg.addr(encodedIdentifier);
        if (utils.isEmptyAddress(address)) {
            return callback(errors.IDENTIFIER_NO_ADDRESS);
        }
    
        var SmartExchange = web3.eth.contract(abi).at(address);
        var transactions = SmartExchange.allEvents(options).get();
        callback(null, transactions);
    } catch(err) {
        callback(errors.UNKNOWN_ERROR(err));
    }
};
Example #13
0
Node.prototype.getPending = function()
{
	var self = this;
	var now = _.now();

	if (this._web3)
	{
		console.stats('==>', 'Getting Pending')

		web3.eth.getBlockTransactionCount('pending', function (err, pending)
		{
			if (err) {
				console.error('xx>', 'getPending error: ', err);
				return false;
			}

			var results = {};
			results.end = _.now();
			results.diff = results.end - now;

			console.sstats('==>', 'Got', chalk.reset.red(pending) , chalk.reset.bold.green('pending tx'+ (pending === 1 ? '' : 's') + ' in'), chalk.reset.cyan(results.diff, 'ms'));

			self.stats.pending = pending;

			if(self._lastPending !== pending)
				self.sendPendingUpdate();

			self._lastPending = pending;
		});
	}
}
Example #14
0
function faucetRequest(req, res) {
  var params = getParams(req);
  var addr = params.address || '';
  if (!addr || !addr.length || !web3.isAddress(addr)) return res.send('invalid address');
  var amount = Number(params.amount) || 0;
  var amount = Math.min(amount, config.max);

  var percent = config.percent >= 1 ? 0.99 : config.percent;

  web3.eth.getBalance(web3.eth.coinbase, function(err, balance) {
    var sendAmount = web3.toBigNumber(Math.min(config.max, balance * percent));
    if (amount > 0 && amount < sendAmount) sendAmount = web3.toBigNumber(amount);

    logger.info(web3.fromWei(balance, 'ether').toString(), '=>', web3.fromWei(sendAmount, 'ether').toString(), '=>', addr, '(' + web3.fromWei(web3.eth.getBalance(addr), 'ether') + ')');

    web3.eth.sendTransaction({
      from: web3.eth.coinbase,
      to: addr,
      value: sendAmount.floor()
    }, function(err, hash) {
      if (err) hash = err;
      res.send(hash);
    });
  });
}
 (function(account){
   web3.eth.watch({altered: {at: accounts[i], id: contractAddress}}).changed(function() {
     web3.eth.stateAt(contractAddress, account).then(function(result){
       if(isNaN(result)) document.getElementById(account).innerText='(no registered asset)';
       else document.getElementById(account).innerText = '(' + web3.toDecimal(result) + ' registered assets)';
     });
   });
 })(account);
Example #16
0
 manager.ethersim_setBalance(account, 100000000, function () {
   web3.eth.sendTransaction({
     from: account,
     data: code
   }, function(err, result) {
     transactionHash = result;
     done();
   });
 });
Example #17
0
app.get('/api/block-index/:blockindex', function(req, res){
  web3.eth.getBlock(req.params.blockindex, true, function(error, result){
    if(!error) {
          res.json(result)
    }  else {
          res.json(error)
    }
  })
})
Example #18
0
 beforeEach(function (done) {
   web3.eth.sendTransaction({
     from: account,
     to: web3.eth.accounts[1],
     value: 12345
   }, function(error, result) {
     transactionHash = result;
     done();
   });
 });
Example #19
0
      beforeEach(function(done) {
        var code = '60606040525b60646000600050819055505b60c280601e6000396000f30060606040526000357c0100000000000000000000000000000000000000000000000000000000900480632a1afcd914604b57806360fe47b114606a5780636d4ce63c14607b576049565b005b6054600450609a565b6040518082815260200191505060405180910390f35b607960048035906020015060a3565b005b608460045060b1565b6040518082815260200191505060405180910390f35b60006000505481565b806000600050819055505b50565b6000600060005054905060bf565b9056';

        web3.eth.sendTransaction({
          from: account,
          data: code
        }, function(err, txHash) {
          transactionHash = txHash;
          done();
        });
      });
Example #20
0
        transaction.run(block, function(result) {
          transactionResult = result;

          result = web3.eth.call({
            data: '0x6d4ce63c',
            to: transactionResult.address
          }, function(error, results) {
            transactionResult = results;
            done();
          });
        });
Node.prototype.updatePending = function()
{
	if(PENDING_WORKS) {
		try {
			this.stats.pending = web3.eth.getBlockTransactionCount('pending');
			this.sendUpdate();
		} catch (err) {
			PENDING_WORKS = false;
			console.error("getBlockTransactionCount('pending'):", err);
		}
	}
}
Example #22
0
app.post('/api/tx/send',function(req, res){  
  web3.eth.sendRawTransaction(req.body.rawtx, function(error, result){    
    console.log(req.body.rawtx)
    console.log(error)
    console.log(result)
    if(!error) {
          res.json(result)
    }  else {
          res.json(error)
    }
  })
})
Example #23
0
        beforeEach(function(done) {
          var account = web3.eth.accounts[0];
          manager.blockchain.addAccount({balance: '00000'});

          transactionHash = web3.eth.sendTransaction({
            from: account,
            to: web3.eth.accounts[1],
            value: 12345
          }, function(error, results) {
            done();
          })
        });
Example #24
0
	this._latestQueue = async.queue(function (hash, callback)
	{
		var timeString = 'Got block ' + chalk.reset.red(hash) + chalk.reset.bold.white(' in') + chalk.reset.green('');

		console.time('==>', timeString);

		web3.eth.getBlock(hash, false, function (error, result)
		{
			self.validateLatestBlock(error, result, timeString);

			callback();
		});
	}, 1);
function createTransaction() {
  var receiverAddress = document.querySelector('#receiverAddress').value;
  if (receiverAddress.substring(0,1)!="0x") receiverAddress = "0x"+receiverAddress;
  var amount = document.querySelector('#amount').value;

  var checked = getCheckedBox("account");
  if (!checked) alert("check a sender");
  else {
    var from=checked;
    var data = [from, receiverAddress, amount];
    web3.eth.transact({to: contractAddress, data: data, gas: 5000});
  }
}
Example #26
0
            $http.get("abi/custodial-forward.sol").then(function(res){
                var compiled = web3.eth.compile.solidity(res.data);
                if(!compiled){
                    $log.error("compilation error!");
                    return;
                }
                var address = web3.eth.sendTransaction({gas:900000, code: compiled});
                if(address){
                    $scope.contractAddress = address;
                    console.log("contract created at " + address);
                }


            });
function registerFile(hashcode) {
  var entry=document.getElementsByName(hashcode)[0];
  var filename=entry.getAttribute('filename');
  var date=entry.getAttribute('date');
  var size=entry.getAttribute('size');
  var type=entry.getAttribute('type');
  var checked = getCheckedBox("account");
  if (!checked) alert("check an id before registering");
  else {
    var data = ['0x1', hashcode];
    web3.eth.transact({to: contractAddress, data: data, from: checked, gas: 5000});
    alert(filename + " registered");
  }
}
Example #28
0
Node.prototype.getLatestBlock = function ()
{
	var self = this;

	if(this._web3)
	{
		var timeString = 'Got block in' + chalk.reset.red('');
		console.time('==>', timeString);

		web3.eth.getBlock('latest', false, function(error, result) {
			self.validateLatestBlock(error, result, timeString);
		});
	}
}
Example #29
0
 loadContract(name, function(cObj) {
     web3.eth.sendTransaction({
         from: adminAddr,
         data: cObj.binary,
         gas: 3000000,
         gasPrice: 100000000000000
     }, function(err, res) {
         if (err) throw err;
         console.log("Contract created at address: ", res);
         cObj.addr = res;
         contracts[name] = cObj;
         // Wait for block
         setTimeout(cb, 20000);
     });
 });
Example #30
-1
        $scope.updateStatus = function(){
            var account = web3.eth.accounts[0];
            $scope.web3.block = web3.eth.blockNumber;
            $scope.web3.balance = web3.fromWei(web3.eth.getBalance(account), "ether").toNumber();
            $scope.web3.timestamp = web3.eth.getBlock(web3.eth.blockNumber).timestamp * 1000;
            console.log('updated status. block: ' + web3.eth.blockNumber);
            try{
                $scope.$digest();
            }catch(e){

            }

        };