Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 'use strict';
- let logger = require('../Utils/Logger')('NIS');
- let nem = require('nem-sdk').default;
- /**
- * Listener for all blockchain and website events
- */
- class Blockchain
- {
- constructor() {
- this.isConnected = false;
- this.hostname = null;
- this.endpoint = null;
- this.wallet = null;
- this._onConfirmed = null;
- this._onBlock = null;
- let KeyPair = nem.crypto.keyPair.create(process.env.APP_PRIVATE_KEY);
- this.netId = process.env.NEM_NETWORK === 'testnet'
- ? nem.model.network.data.testnet.id
- : nem.model.network.data.mainnet.id;
- this.wallet = nem.model.address.toAddress(KeyPair.publicKey.toString(), this.netId);
- logger.info('Configured bot for wallet: ' + this.wallet);
- }
- start(host) {
- logger.info('Starting bot on host: ' + host);
- this.setHostname(host);
- this.connect(this.getConnector());
- }
- getConnector() {
- this.endpoint = nem.model.objects.create("endpoint")('http://'+this.hostname, nem.model.nodes.defaultPort);
- let endpointWs = nem.model.objects.create("endpoint")('http://'+this.hostname, 7778);
- return nem.com.websockets.connector.create(endpointWs, this.wallet);
- }
- setHostname(hostname) {
- this.hostname = hostname;
- }
- onBlock(callback) {
- this._onBlock = callback;
- }
- onConfirmed(callback) {
- this._onConfirmed = callback;
- }
- connect(connector) {
- if (!this.hostname || !this.wallet) {
- logger.info('Cannot connect: invalid settings!');
- this.isConnected = false;
- return false;
- }
- return connector.connect().then(() => {
- logger.info('Connected to: '+ connector.endpoint.host);
- this.isConnected = true;
- if (this._onBlock !== null) {
- logger.info('Subscribing for new blocks...');
- nem.com.websockets.subscribe.chain.blocks(connector, (res) => {
- this._onBlock(res);
- });
- }
- if (this._onConfirmed !== null) {
- logger.info('Subscribing for new transactions...');
- connector.stompClient.send('');
- nem.com.websockets.subscribe.account.transactions.confirmed(connector, (res) => {
- this._onConfirmed(res);
- }, this.wallet);
- }
- nem.com.websockets.subscribe.errors(connector, function(res){
- logger.error(res);
- });
- }, (err) => {
- logger.error('An error occured: ' + JSON.stringify(err));
- this.reconnect();
- });
- }
- reconnect() {
- this.isConnected = false;
- if (!this.hostname || !this.wallet) {
- logger.info('Cannot reconnect: invalid settings!');
- return false;
- }
- logger.info('Reconnecting to: '+ this.hostname);
- this.connect(this.getConnector());
- }
- }
- module.exports = new Blockchain();
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement