Ejemplo n.º 1
0
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;
}
Ejemplo n.º 2
0
Node.prototype.isActive = function()
{
	this._tries++;

	try {
		var peers = web3.toDecimal(web3.net.peerCount);

		if(peers !== null)
		{
			this.stats.peers = peers;
			this.stats.active = true;

			return true;
		}
	}
	catch (err) {
		console.error("peerCount:", err);
	}

	this.stats.active = false;
	this.stats.listening = false;
	this.stats.mining = false;
	this.stats.peers = 0;
	this._down++;

	return false;
}
Ejemplo n.º 3
0
    mainWeb3.eth.getBlockNumber(function(err, result) {
      if (err) return done(err);

      assert.equal(mainWeb3.toDecimal(result), 5);

      // Now lets get a block that exists on the forked chain.
      mainWeb3.eth.getBlock(0, function(err, mainBlock) {
        if (err) return done(err);

        // And compare it to the forked chain's block
        forkedWeb3.eth.getBlock(0, function(err, forkedBlock) {
          if (err) return done(err);

          // Block hashes should be the same.
          assert.equal(mainBlock.hash, forkedBlock.hash);

          // Now make sure we can get the block by hash as well.
          mainWeb3.eth.getBlock(mainBlock.hash, function(err, mainBlockByHash) {
            if (err) return done(err);

            assert.equal(mainBlock.hash, mainBlockByHash.hash);
            done();
          });
        });
      });
    });
Ejemplo n.º 4
0
    _client.getLastMarketID( function(lastMarketID) {
      // Get last opened market ID
      var lastOpenedMarketID = 1;
      try {
        lastOpenedMarketID = web3.toDecimal(_client.getHex('EtherEx', 'market'));
      }
      catch(e) {
        _client.putHex('EtherEx', 'market', web3.fromDecimal(lastOpenedMarketID));
      }

      // Get favorites
      var favorites = [];
      try {
        var favs = JSON.parse(_client.getString('EtherEx', 'favorites'));
        if (favs)
          favorites = favs;
      }
      catch (e) {
        _client.putString('EtherEx', 'favorites', '[]');
      }

      this.dispatch(constants.market.UPDATE_MARKETS, {
        lastMarketID: lastMarketID,
        lastOpenedMarketID: lastOpenedMarketID,
        favorites: favorites
      });

      this.dispatch(constants.market.LOAD_MARKETS);

      // Load markets
      for (var id = 1; id <= lastMarketID; id++)
        this.flux.actions.market.loadMarket(id, true);

    }.bind(this), function(error) {
Ejemplo n.º 5
0
      example.value({from: mainAccounts[0]}, function(err, result) {
        if (err) return done(err);
        assert.equal(mainWeb3.toDecimal(result), 25);

        // Now call back to the forked to ensure it's value stayed 5
        forkedExample.value({from: forkedAccounts[0]}, function(err, result) {
          if (err) return done(err);
          assert.equal(forkedWeb3.toDecimal(result), 7);
          done();
        })
      });
Ejemplo n.º 6
0
 self.get('https://api.etherscan.io/api?module=proxy&action=eth_blockNumber', (err, data) => {
   if (!err) {
     const newBlockNumber = web3.toDecimal(data.result);
     if (newBlockNumber > 0) {
       self.blockNumber = newBlockNumber;
     }
     callback(null, self.blockNumber);
   } else {
     callback(null, self.blockNumber);
   }
 });
Ejemplo n.º 7
0
    example.value({from: mainAccounts[0]}, function(err, result){
      if (err) return done(err);
      assert.equal(mainWeb3.toDecimal(result), 7);

      // Make the call again to ensure caches updated and the call still works.
      example.value({from: mainAccounts[0]}, function(err, result){
        if (err) return done(err);
        assert.equal(mainWeb3.toDecimal(result), 7);
        done(err);
      });
    });
Ejemplo n.º 8
0
      forkedExample.value({from: forkedAccounts[0]}, function(err, result) {
        if (err) return done(err);
        assert.equal(forkedWeb3.toDecimal(result), 800);

        // Now lets check the value on the main chain. It shouldn't be 800.
        example.value({from: mainAccounts[0]}, function(err, result) {
          if (err) return done(err);

          assert.equal(mainWeb3.toDecimal(result), 5);
          done();
        })
      })
Ejemplo n.º 9
0
    forkedWeb3.eth.getBlock(forkBlockNumber, function(err, forkedBlock) {
      if (err) return done(err);

      var parentHash = forkedBlock.hash;

      var mainGenesisNumber = mainWeb3.toDecimal(forkBlockNumber) + 1;
      mainWeb3.eth.getBlock(mainGenesisNumber, function(err, mainGenesis) {
        if (err) return done(err);

        assert.equal(mainGenesis.parentHash, parentHash);
        done();
      })
    });
Ejemplo n.º 10
0
 self.getCall(self.contractToken, addr, 'decimals', [], (errDecimals, dataDecimals) => {
   if (!errSymbol && !errDecimals) {
     try {
       const symbol = web3.toAscii(dataSymbol.result).replace(/[\u{0000}-\u{0020}]/gu, '');
       const decimals = web3.toDecimal(dataDecimals.result);
       self.tokens[addr] = {
         addr,
         decimals,
         name: symbol,
       };
     } catch (err) {
       console.log('Error getting token', addr);
     }
     callback(null, self.tokens[addr]);
   } else {
     callback('Failed to get token', null);
   }
 });
Ejemplo n.º 11
0
Node.prototype.getInfo = function()
{
	console.info('==>', 'Getting info');
	console.time('Got info');

	try {
		this.info.coinbase = web3.eth.coinbase;
		this.info.node = web3.version.client;
		this.info.net = web3.version.network;
		this.info.protocol = web3.toDecimal(web3.version.ethereum);
		this.info.api = web3.version.api;

		console.timeEnd('Got info');
		console.info(this.info);

		return true;
	}
	catch (err) {
		console.error("Couldn't get version");
	}

	return false;
}
Ejemplo n.º 12
0
 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)';
 });
Ejemplo n.º 13
0
  this.updateEthereumClient = function () {
    var configState = this.flux.stores.config.getState();
    var debug = configState.debug;

    var clientParams = {
      address: configState.address,
      host: configState.host,
      range: configState.range,
      rangeEnd: configState.rangeEnd,
      si: configState.si,
      debug: debug,
      flux: this.flux
    };

    var ethereumClient = new EthereumClient(clientParams);

    // Reload configs from client on first run
    if (!configState.ethereumClient && ethereumClient.isAvailable()) {
      var configs = {
        'range': configState.range,
        'rangeEnd': configState.rangeEnd,
        'si': configState.si,
        'storeBlockFee': configState.storeBlockFee,
        'timeout': configState.timeout,
        'debug': debug
      };
      if (debug)
        utils.log("CONFIGS", configs);

      // Check the client's network version
      ethereumClient.getNetwork(function(network) {
        if (debug)
          utils.log("NETWORK ID", network);
        this.dispatch(constants.config.UPDATE_CONFIG, {
          network: network
        });
      }.bind(this));

      // Load / set default configs in web3.db
      for (var key in configs) {
        var result = null;

        try {
          result = web3.toDecimal(ethereumClient.getHex('EtherEx', key));
          configs[key] = result;
        }
        catch(e) {
          ethereumClient.putHex('EtherEx', key, web3.fromDecimal(configs[key]));
        }
      }

      // Update debug handler
      this.flux.actions.config.updateConfig({
        debug: configs.debug,
        init: true
      });

      // Update SI, storeBlockFee, timeout and debug configs
      this.dispatch(constants.config.UPDATE_CONFIG, {
        si: configs.si,
        storeBlockFee: configs.storeBlockFee,
        timeout: configs.timeout,
        debug: configs.debug
      });

      // Update ethereumClient with ranges and debug
      if (configs.range || configs.rangeEnd || configs.debug) {
          clientParams = {
            host: configState.host,
            address: configState.address,
            range: configs.range,
            rangeEnd: configs.rangeEnd,
            debug: configs.debug,
            error: this.flux.actions.config.failed,
            flux: this.flux
          };
          ethereumClient = new EthereumClient(clientParams);

          this.dispatch(constants.config.UPDATE_CONFIG, {
            range: configs.range,
            rangeEnd: configs.rangeEnd
          });
      }
    }
    // // Transfer our previous filters to the new instance
    // else if (ethereumClient.isAvailable()) {
    //   // ethereumClient.filters = configState.ethereumClient.filters;
    // }

    this.dispatch(constants.config.UPDATE_ETHEREUM_CLIENT_SUCCESS, {
      ethereumClient: ethereumClient
    });
  };
Ejemplo n.º 14
0
function Node()
{
	var self = this;

	try {
		ETH_VERSION = web3.version.client;
		NET_VERSION = web3.version.network;
		PROTOCOL_VERSION = web3.toDecimal(web3.version.ethereum);
		API_VERSION = web3.version.api;
	}
	catch (err) {
		console.error("Couldn't get version");
	}

	this.info = {
		name: INSTANCE_NAME || (process.env.EC2_INSTANCE_ID || os.hostname()),
		contact: (process.env.CONTACT_DETAILS || ""),
		node: ETH_VERSION,
		net: NET_VERSION,
		protocol: PROTOCOL_VERSION,
		api: API_VERSION,
		port: (process.env.LISTENING_PORT || 30303),
		os: os.platform(),
		os_v: os.release(),
		client: pjson.version
	};

	this.id = _.camelCase(this.info.name);

	console.info(this.info);

	this.stats = {
		active: false,
		listening: false,
		mining: false,
		peers: 0,
		pending: 0,
		gasPrice: 0,
		block: {},
		blocktimeAvg: 0,
		difficulty: [],
		txDensity: [],
		blockTimes: [],
		gasSpending: [],
		miners: [],
		uptime: 0
	};
	this._lastStats = JSON.stringify(this.stats);

	this._tries = 0;
	this._down = 0;
	this._lastSent = 0;
	this._latency = 0;

	this.blocks = [];

	this._Registrar = null;
	this._knownMiners = [];

	this._socket = null;
	this.pendingFilter = false;
	this.chainFilter = false;
	this.updateInterval = false;
	this.pingInterval = false;

	socket.on('open', function open() {
		socket.emit('hello', { id: self.id, info: self.info, secret: WS_SECRET });
		console.info('The connection has been opened.');
		console.info('Trying to login');
	})
	.on('end', function end() {
		self._socket = false;
		console.error('Socket connection closed');
	})
	.on('error', function error(err) {
		console.error("socket:", err);
	})
	.on('reconnecting', function reconnecting(opts) {
		console.warn('We are scheduling a reconnect operation', opts);
	})
	.on('node-pong', function(data) {
		var latency = Math.ceil(((new Date()).getTime() - self._latency)/2);
		socket.emit('latency', { id: self.id, latency: latency });
	})
	.on('data', function incoming(data) {
		console.info('Received some data', data);
	});

	socket.on('ready', function()
	{
		self._socket = true;
		self.sendUpdate(true);

		console.info('The connection has been established.');
	});

	this.init();

	return this;
}
Ejemplo n.º 15
0
        example.value({from: mainAccounts[0]}, function(err, result) {
          if (err) return done(err);

          assert.equal(mainWeb3.toDecimal(result), 5);
          done();
        })
Ejemplo n.º 16
0
 forkedExample.value({from: forkedAccounts[0]}, function(err, result) {
   if (err) return done(err);
   assert.equal(forkedWeb3.toDecimal(result), 7);
   done();
 })
Ejemplo n.º 17
0
 mainWeb3.eth.getStorageAt(contractAddress, contract.position_of_value, function(err, result) {
   if (err) return done(err);
   assert.equal(mainWeb3.toDecimal(result), 7);
   done();
 });