From 0871c1803c2367bf87c0fc9b9644d01d7ffdb7bf Mon Sep 17 00:00:00 2001 From: robi Date: Fri, 12 Apr 2019 16:16:07 +0200 Subject: [PATCH 1/2] streamline experiment --- src/RatesFeeder.js | 59 +++++++++++++++++++++++----------------------- 1 file changed, 29 insertions(+), 30 deletions(-) diff --git a/src/RatesFeeder.js b/src/RatesFeeder.js index 6a19a38..a83d3b3 100644 --- a/src/RatesFeeder.js +++ b/src/RatesFeeder.js @@ -14,17 +14,14 @@ TODO: web3.eth.transactionConfirmationBlocks: ${web3.eth.transactionConfirmationBlocks} web3.eth.transactionPollingTimeout: ${web3.eth.transactionPollingTimeout} */ -require("@augmint/js/src/helpers/env.js"); -const log = require("@augmint/js/src/helpers/log.js")("ratesFeeder"); -const setExitHandler = require("@augmint/js/src/helpers/sigintHandler.js"); -const promiseTimeout = require("@augmint/js/src/helpers/promiseTimeout.js"); -const AugmintToken = require("@augmint/js/src/AugmintToken.js"); -const Rates = require("@augmint/js/src/Rates.js"); -const { cost } = require("@augmint/js/src/gas.js"); +const { Augmint, utils } = require("@augmint/js"); +const log = utils.logger("ratesFeeder"); const CCY = "EUR"; // only EUR is suported by TickerProvider providers ATM const LIVE_PRICE_DIFFERENCE_DECIMALS = 4; // rounding live price % difference to 2 decimals +utils.loadEnv(); + const median = values => { values.sort((a, b) => a - b); @@ -40,7 +37,7 @@ const median = values => { }; class RatesFeeder { - constructor(ethereumConnection, tickers) { + constructor (ethereumConnection, tickers) { this.tickers = tickers; // array of TickerProvider objects // list of tickernames: this.tickerNames = this.tickers.reduce( @@ -59,10 +56,10 @@ class RatesFeeder { this.lastTickerCheckResult = {}; this.checkTickerPriceError = null; // to store last error and supress loggin repeating errors - setExitHandler(this.exit.bind(this), "RatesFeeder"); + utils.setExitHandler(this.exit.bind(this), "RatesFeeder"); } - async init() { + async init () { this.isStopping = false; this.account = process.env.RATESFEEDER_ETHEREUM_ACCOUNT; @@ -71,8 +68,8 @@ class RatesFeeder { throw new Error("Invalid RATESFEEDER_ETHEREUM_ACCOUNT: " + this.account); } - this.rates = new Rates(); - this.augmintToken = new AugmintToken(); + this.rates = new Augmint.Rates(); + this.augmintToken = new Augmint.Token(); await Promise.all([ this.rates.connect(this.ethereumConnection), @@ -94,7 +91,7 @@ class RatesFeeder { RATESFEEDER_ETHEREUM_ACCOUNT: ${process.env.RATESFEEDER_ETHEREUM_ACCOUNT} RATESFEEDER_ETHEREUM_PRIVATE_KEY: ${ process.env.RATESFEEDER_ETHEREUM_PRIVATE_KEY ? "[secret]" : "not provided" - } + } RATESFEEDER_LIVE_PRICE_THRESHOLD_PT: ${process.env.RATESFEEDER_LIVE_PRICE_THRESHOLD_PT} RATESFEEDER_SETRATE_TX_TIMEOUT: ${process.env.RATESFEEDER_SETRATE_TX_TIMEOUT} RATESFEEDER_CHECK_TICKER_PRICE_INTERVAL: ${process.env.RATESFEEDER_CHECK_TICKER_PRICE_INTERVAL} @@ -106,7 +103,7 @@ class RatesFeeder { // check current price from different exchanges and update Augmint price on chain if difference is beyond threshold // filters out bad prices, errors, and returns with the avarage - async checkTickerPrice() { + async checkTickerPrice () { try { log.debug("==> checkTickerPrice() tickers:"); @@ -129,16 +126,16 @@ class RatesFeeder { const livePriceDifference = livePrice > 0 ? parseFloat( - (Math.abs(livePrice - currentAugmintRate.rate) / currentAugmintRate.rate).toFixed( - LIVE_PRICE_DIFFERENCE_DECIMALS - ) - ) + (Math.abs(livePrice - currentAugmintRate.rate) / currentAugmintRate.rate).toFixed( + LIVE_PRICE_DIFFERENCE_DECIMALS + ) + ) : null; log.debug( ` checkTickerPrice() currentAugmintRate[${CCY}]: ${ currentAugmintRate.rate - } livePrice: ${livePrice} livePriceDifference: ${(livePriceDifference * 100).toFixed(2)} %` + } livePrice: ${livePrice} livePriceDifference: ${(livePriceDifference * 100).toFixed(2)} %` ); const tickersInfo = this.tickers.map(t => t.getStatus()); @@ -152,7 +149,7 @@ class RatesFeeder { if (livePrice > 0) { if (livePriceDifference * 100 > parseFloat(process.env.RATESFEEDER_LIVE_PRICE_THRESHOLD_PT)) { - await promiseTimeout( + await utils.promiseTimeout( process.env.RATESFEEDER_SETRATE_TX_TIMEOUT, this.updatePrice(CCY, livePrice) ).catch(error => { @@ -188,7 +185,7 @@ class RatesFeeder { } } - calculateAugmintPrice(tickers) { + calculateAugmintPrice (tickers) { // ignore 0 or null prices (exchange down or no price info yet) const prices = tickers .filter(ticker => ticker.lastTicker && ticker.lastTicker.lastTradePrice > 0) @@ -202,7 +199,7 @@ class RatesFeeder { /* Update price on chain. price provided rounded to AugmintToken.decimals first */ - async updatePrice(currency, price) { + async updatePrice (currency, price) { try { const setRateTx = this.rates.getSetRateTx(currency, price); const encodedABI = setRateTx.encodeABI(); @@ -210,7 +207,7 @@ class RatesFeeder { const txToSign = { from: this.account, to: this.rates.address, - gas: cost.SET_RATE_GAS_LIMIT, + gas: Augmint.gas.cost.SET_RATE_GAS_LIMIT, data: encodedABI }; @@ -222,7 +219,9 @@ class RatesFeeder { log.log( `==> updatePrice() nonce: ${nonce} sending setRate(${currency}, ${price}). currentAugmintRate[${CCY}]: ${ this.lastTickerCheckResult[CCY] ? this.lastTickerCheckResult[CCY].currentAugmintRate.rate : "null" - } livePrice: ${this.lastTickerCheckResult[CCY] ? this.lastTickerCheckResult[CCY].livePrice : "null"}` + } livePrice: ${this.lastTickerCheckResult[CCY] + ? this.lastTickerCheckResult[CCY].livePrice + : "null"}` ); const tx = this.web3.eth.sendSignedTransaction(signedTx.rawTransaction); @@ -235,7 +234,7 @@ class RatesFeeder { log.debug( ` updatePrice() nonce: ${nonce} txHash: ${ receipt.transactionHash - } receipt received. gasUsed: ${receipt.gasUsed}` + } receipt received. gasUsed: ${receipt.gasUsed}` ); }) .on("confirmation", (confirmationNumber, receipt) => { @@ -243,13 +242,13 @@ class RatesFeeder { log.log( ` \u2713 updatePrice() nonce: ${nonce} txHash: ${ receipt.transactionHash - } confirmed: setRate(${currency}, ${price}) - received ${confirmationNumber} confirmations ` + } confirmed: setRate(${currency}, ${price}) - received ${confirmationNumber} confirmations ` ); } else { log.debug( ` updatePrice() nonce: ${nonce} txHash: ${ receipt.transactionHash - } Confirmation #${confirmationNumber} received.` + } Confirmation #${confirmationNumber} received.` ); } }) @@ -274,17 +273,17 @@ class RatesFeeder { } } - async stop() { + async stop () { this.isStopping = true; clearTimeout(this.checkTickerPriceTimer); } - async exit(signal) { + async exit (signal) { log.info(`*** ratesFeeder Received ${signal}. Stopping.`); await this.stop(); } - getStatus() { + getStatus () { const status = { isInitialised: this.isInitialised, account: this.account, From a8e4c4c566058c2a68a0bafdc060093570d9491c Mon Sep 17 00:00:00 2001 From: robi Date: Fri, 12 Apr 2019 17:50:41 +0200 Subject: [PATCH 2/2] using prettier augmint-js --- package.json | 2 +- src/MatchMaker/MatchMaker.js | 13 +++--- src/runFeeder.js | 40 ++++++++++--------- src/statusApi/app.js | 4 +- src/statusApi/server.js | 12 +++--- src/tickerProviders/BaseHttpTickerProvider.js | 6 ++- src/tickerProviders/BaseTickerProvider.js | 7 ++-- 7 files changed, 44 insertions(+), 40 deletions(-) diff --git a/package.json b/package.json index 96101e3..27d2b5e 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,7 @@ "yarn": "1.15.2" }, "dependencies": { - "@augmint/js": "0.0.2", + "@augmint/js": "0.0.3", "bignumber.js": "5.0.0", "cross-env": "5.2.0", "dotenv": "7.0.0", diff --git a/src/MatchMaker/MatchMaker.js b/src/MatchMaker/MatchMaker.js index 1335bdb..7f30c24 100644 --- a/src/MatchMaker/MatchMaker.js +++ b/src/MatchMaker/MatchMaker.js @@ -4,12 +4,11 @@ calls matchMultiple tx every time a new Order event received emmitted events: */ -require("@augmint/js/src/helpers/env.js"); -const log = require("@augmint/js/src/helpers/log.js")("MatchMaker"); -const EventEmitter = require("events"); -const promiseTimeout = require("@augmint/js/src/helpers/promiseTimeout.js"); +const { Augmint, utils } = require("@augmint/js"); +utils.loadEnv(); +const log = utils.logger("MatchMaker"); -const setExitHandler = require("@augmint/js/src/helpers/sigintHandler.js"); +const EventEmitter = require("events"); const Exchange = require("@augmint/js/src/Exchange.js"); class MatchMaker extends EventEmitter { @@ -31,7 +30,7 @@ class MatchMaker extends EventEmitter { this.exchangeInstance = null; this.account = null; - setExitHandler(this._exit.bind(this), "MatchMaker"); + utils.setExitHandler(this._exit.bind(this), "MatchMaker"); } async init() { @@ -92,7 +91,7 @@ class MatchMaker extends EventEmitter { this.queueNextCheck = true; // so _checkAndMatchOrders will call this fx again once finished } else { this.isProcessingOrderBook = true; - await promiseTimeout(process.env.MATCHMAKER_CHECKANDMATCHORDERS_TIMEOUT, this._checkAndMatchOrders()).catch( + await utils.promiseTimeout(process.env.MATCHMAKER_CHECKANDMATCHORDERS_TIMEOUT, this._checkAndMatchOrders()).catch( error => { // NB: it's not necessarily an error, ethereum network might be just slow. log.error("checkAndMatchOrders failed with Error: ", error); diff --git a/src/runFeeder.js b/src/runFeeder.js index 79a4c76..bdce925 100644 --- a/src/runFeeder.js +++ b/src/runFeeder.js @@ -1,6 +1,7 @@ -require("@augmint/js/src/helpers/env.js"); -const log = require("@augmint/js/src/helpers/log.js")("runFeeder"); -const EthereumConnection = require("@augmint/js/src/EthereumConnection.js"); +const { Augmint, utils } = require("@augmint/js"); +utils.loadEnv(); +const log = utils.logger("runFeeder"); + const RatesFeeder = require("src/RatesFeeder.js"); const MatchMaker = require("src/MatchMaker/MatchMaker.js"); const subscribeTickers = require("src/subscribeTickers.js"); @@ -11,7 +12,7 @@ log.info( NODE_ENV: ${process.env.NODE_ENV} LOG: ${process.env.LOG}` ); -const ethereumConnection = new EthereumConnection(); +const ethereumConnection = new Augmint.EthereumConnection(); ethereumConnection.on("connected", onEthereumConnected); ethereumConnection.on("disconnecting", onEthereumDisconnecting); @@ -62,70 +63,71 @@ ethereumConnection }); /********* EthereumConnection event handlers (for logging)*****************/ + /* eslint-disable no-unused-vars */ -function onNewOrder(event, matchMaker) { +function onNewOrder (event, matchMaker) { log.debug("New order id:", event.returnValues.orderId); } -function onOrderFill(event, matchMaker) { +function onOrderFill (event, matchMaker) { log.debug( `Order filled. buy id: ${event.returnValues.buyTokenOrderId} sell id: ${event.returnValues.sellTokenOrderId}` ); } -function onMatchMakerTxSuccess(nonce, confirmationNumber, receipt, matchMaker) { +function onMatchMakerTxSuccess (nonce, confirmationNumber, receipt, matchMaker) { log.log( ` \u2713 checkAndMatchOrders() nonce: ${nonce} txHash: ${ receipt.transactionHash - } confirmed - received ${confirmationNumber} confirmations ` + } confirmed - received ${confirmationNumber} confirmations ` ); } /*** EthereumConnection event handlers ****/ -function onEthereumConnected(ethereumConnection) { +function onEthereumConnected (ethereumConnection) { // log.info("Ethereum connected."); } -function onEthereumDisconnecting(signal, ethereumConnection) { +function onEthereumDisconnecting (signal, ethereumConnection) { // log.info(`*** EthereumConnection received ${signal}. Stopping.`); } -function onEthereumDisconnected(event, ethereumConnection) { +function onEthereumDisconnected (event, ethereumConnection) { // log.info("Ethereum disconnected"); } /********* TickerProvider event handlers *****************/ -function onTickerConnecting(data, tickerProvider) { +function onTickerConnecting (data, tickerProvider) { //log.debug(tickerProvider.name, "connecting.", data); } -function onTickerConnected(data, tickerProvider) { +function onTickerConnected (data, tickerProvider) { log.info(`${tickerProvider.name} connected at ${data.url} httpPollInterval: ${data.httpPollInterval}`); } -function onTickerDisconnecting(signal, tickerProvider) { +function onTickerDisconnecting (signal, tickerProvider) { // log.info(`*** ${tickerProvider.name} received ${signal}. Disconnecting.`); } -function onTickerDisconnected(tickerProvider) { +function onTickerDisconnected (tickerProvider) { // log.info(tickerProvider.name, "disconnected."); } -function onTickerReceived(newTicker, tickerProvider) { +function onTickerReceived (newTicker, tickerProvider) { //log.debug(tickerProvider.name, "ticker received", JSON.stringify(newTicker)); } -function onTickerUpdated(newTicker, prevTicker, tickerProvider) { +function onTickerUpdated (newTicker, prevTicker, tickerProvider) { // log.debug(tickerProvider.name, "ticker updated", JSON.stringify(newTicker), JSON.stringify(prevTicker)); } -function onTickerPriceChanged(newTicker, prevTicker, tickerProvider) { +function onTickerPriceChanged (newTicker, prevTicker, tickerProvider) { // log.debug(tickerProvider.name, "ticker price changed", JSON.stringify(newTicker), JSON.stringify(prevTicker)); } -function onTickerProviderError(error, tickerProvider) { +function onTickerProviderError (error, tickerProvider) { // NB: unique errors are logged from module with log.error log.debug(tickerProvider.name, "providerError", error); } diff --git a/src/statusApi/app.js b/src/statusApi/app.js index 1993197..f1b5d27 100644 --- a/src/statusApi/app.js +++ b/src/statusApi/app.js @@ -1,5 +1,5 @@ -require("@augmint/js/src/helpers/env.js"); -// const log = require("src/augmintjs/helpers/log.js")("statusApi"); +const { utils } = require("@augmint/js"); +utils.loadEnv(); const httplogger = require("morgan"); const createError = require("http-errors"); diff --git a/src/statusApi/server.js b/src/statusApi/server.js index 114dc07..2c311e4 100644 --- a/src/statusApi/server.js +++ b/src/statusApi/server.js @@ -1,7 +1,7 @@ -require("@augmint/js/src/helpers/env.js"); -const log = require("@augmint/js/src/helpers/log.js")("statusApi"); -const promiseTimeout = require("@augmint/js/src/helpers/promiseTimeout.js"); -const setExitHandler = require("@augmint/js/src/helpers/sigintHandler.js"); +const { utils } = require("@augmint/js"); +utils.loadEnv(); +const log = utils.logger("statusApi"); + const app = require("./app.js"); const http = require("http"); let httpServer; @@ -12,7 +12,7 @@ const CLOSE_TIMEOUT = 5000; // how much wait on close for sockets to close const serverSockets = new Set(); const DEFAULT_PORT = 30000; -setExitHandler(exit, "statusApi"); +utils.setExitHandler(exit, "statusApi"); function start(ratesFeeder) { const port = normalizePort(process.env.PORT || DEFAULT_PORT); @@ -81,7 +81,7 @@ function start(ratesFeeder) { async function exit(signal) { log.info(`*** statusApi Received ${signal}. Stopping.`); if (httpServer && httpServer.listening) { - return promiseTimeout(CLOSE_TIMEOUT, gracefulClose()).catch(error => { + return utils.promiseTimeout(CLOSE_TIMEOUT, gracefulClose()).catch(error => { log.info("statusApi httpserver.close timed out or error, force closing all sockets.", error); destroySockets(serverSockets); return; diff --git a/src/tickerProviders/BaseHttpTickerProvider.js b/src/tickerProviders/BaseHttpTickerProvider.js index 6124ac7..37444c0 100644 --- a/src/tickerProviders/BaseHttpTickerProvider.js +++ b/src/tickerProviders/BaseHttpTickerProvider.js @@ -1,5 +1,7 @@ -require("@augmint/js/src/helpers/env.js"); -const log = require("@augmint/js/src/helpers/log.js")("TickerProvider"); +const { utils } = require("@augmint/js"); +utils.loadEnv(); +const log = utils.logger("TickerProvider"); + const BaseTickerProvider = require("./BaseTickerProvider.js"); const fetch = require("node-fetch"); diff --git a/src/tickerProviders/BaseTickerProvider.js b/src/tickerProviders/BaseTickerProvider.js index 3f67a86..569f749 100644 --- a/src/tickerProviders/BaseTickerProvider.js +++ b/src/tickerProviders/BaseTickerProvider.js @@ -1,6 +1,7 @@ -const log = require("@augmint/js/src/helpers/log.js")("TickerProvider"); +const { utils } = require("@augmint/js"); +utils.loadEnv(); + const EventEmitter = require("events"); -const setExitHandler = require("@augmint/js/src/helpers/sigintHandler.js"); class BaseTickerProvider extends EventEmitter { // for each provider implement a getter for name @@ -22,7 +23,7 @@ class BaseTickerProvider extends EventEmitter { } async connect(data) { - setExitHandler(this._exit.bind(this), this.name); + utils.setExitHandler(this._exit.bind(this), this.name); this.emit("connecting", data, this); this.on("tickerreceived", this._onTickerReceived.bind(this)); // emit from provider