Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use augmint js #88

Open
wants to merge 3 commits into
base: staging
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
13 changes: 6 additions & 7 deletions src/MatchMaker/MatchMaker.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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() {
Expand Down Expand Up @@ -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);
Expand Down
59 changes: 29 additions & 30 deletions src/RatesFeeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -40,7 +37,7 @@ const median = values => {
};

class RatesFeeder {
constructor(ethereumConnection, tickers) {
constructor (ethereumConnection, tickers) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we should sync our prettier settings - do you have autoformat on save? I don't have these space added after fx name

this.tickers = tickers; // array of TickerProvider objects
// list of tickernames:
this.tickerNames = this.tickers.reduce(
Expand All @@ -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;
Expand All @@ -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),
Expand All @@ -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}
Expand All @@ -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:");

Expand All @@ -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());
Expand All @@ -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 => {
Expand Down Expand Up @@ -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)
Expand All @@ -202,15 +199,15 @@ 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();

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
};

Expand All @@ -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);
Expand All @@ -235,21 +234,21 @@ class RatesFeeder {
log.debug(
` updatePrice() nonce: ${nonce} txHash: ${
receipt.transactionHash
} receipt received. gasUsed: ${receipt.gasUsed}`
} receipt received. gasUsed: ${receipt.gasUsed}`
);
})
.on("confirmation", (confirmationNumber, receipt) => {
if (confirmationNumber === parseInt(process.env.LOG_AS_SUCCESS_AFTER_N_CONFIRMATION)) {
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.`
);
}
})
Expand All @@ -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,
Expand Down
40 changes: 21 additions & 19 deletions src/runFeeder.js
Original file line number Diff line number Diff line change
@@ -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");
Expand All @@ -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);
Expand Down Expand Up @@ -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);
}
4 changes: 2 additions & 2 deletions src/statusApi/app.js
Original file line number Diff line number Diff line change
@@ -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");
Expand Down
12 changes: 6 additions & 6 deletions src/statusApi/server.js
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -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;
Expand Down
6 changes: 4 additions & 2 deletions src/tickerProviders/BaseHttpTickerProvider.js
Original file line number Diff line number Diff line change
@@ -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");

Expand Down
Loading