From 3469df20bfa7efae345962db186eea1352d80a60 Mon Sep 17 00:00:00 2001 From: Daniel McNally Date: Tue, 22 Dec 2020 02:10:47 -0500 Subject: [PATCH] refactor: type checking for BalanceAlert event --- lib/alerts/Alerts.ts | 31 +++++++++++++++++------------- lib/alerts/types.ts | 15 ++++++++------- lib/connextclient/ConnextClient.ts | 8 ++++---- lib/lndclient/LndClient.ts | 7 +++---- lib/swaps/SwapClient.ts | 8 +++++--- 5 files changed, 38 insertions(+), 31 deletions(-) diff --git a/lib/alerts/Alerts.ts b/lib/alerts/Alerts.ts index adfac556f..9ade5b5cb 100644 --- a/lib/alerts/Alerts.ts +++ b/lib/alerts/Alerts.ts @@ -1,9 +1,9 @@ import { EventEmitter } from 'events'; -import { Alert, BalanceAlert } from './types'; -import SwapClientManager from '../swaps/SwapClientManager'; -import Logger from '../Logger'; -import { AlertType, ChannelSide } from '../constants/enums'; import { satsToCoinsStr } from '../cli/utils'; +import { AlertType, ChannelSide } from '../constants/enums'; +import Logger from '../Logger'; +import SwapClientManager from '../swaps/SwapClientManager'; +import { Alert, BalanceAlertEvent } from './types'; interface Alerts { on(event: 'alert', listener: (alert: Alert) => void): this; @@ -35,20 +35,25 @@ class Alerts extends EventEmitter { swapClientManager.connextClient?.on('lowTradingBalance', this.onLowTradingBalance); } - private onLowTradingBalance = (balanceAlert: BalanceAlert) => { + private onLowTradingBalance = (balanceAlertEvent: BalanceAlertEvent) => { // TODO don't use JSON.stringify instead find a way to define unique ids per alert and keep in the map to avoid memory issues - const stringRepresentation = JSON.stringify(balanceAlert); + const stringRepresentation = JSON.stringify(balanceAlertEvent); this.logger.trace(`received low trading balance alert ${stringRepresentation}`); if (this.alerts.get(stringRepresentation) === undefined || this.checkAlertThreshold(stringRepresentation)) { this.logger.trace(`triggering low balance alert ${stringRepresentation}`); - balanceAlert.message = `${ChannelSide[balanceAlert.side || 0]} trading balance (${satsToCoinsStr( - balanceAlert.sideBalance || 0, - )} ${balanceAlert.currency}) is lower than 10% of trading capacity (${satsToCoinsStr( - balanceAlert.totalBalance || 0, - )} ${balanceAlert.currency})`; - balanceAlert.type = AlertType.LowTradingBalance; - balanceAlert.date = Date.now(); + const message = `${ChannelSide[balanceAlertEvent.side || 0]} trading balance (${satsToCoinsStr( + balanceAlertEvent.sideBalance || 0, + )} ${balanceAlertEvent.currency}) is lower than 10% of trading capacity (${satsToCoinsStr( + balanceAlertEvent.totalBalance || 0, + )} ${balanceAlertEvent.currency})`; + + const balanceAlert = { + ...balanceAlertEvent, + message, + type: AlertType.LowTradingBalance, + date: Date.now(), + }; this.alerts.set(stringRepresentation, balanceAlert.date); this.emit('alert', balanceAlert); diff --git a/lib/alerts/types.ts b/lib/alerts/types.ts index aa880d1bd..fadbc9a80 100644 --- a/lib/alerts/types.ts +++ b/lib/alerts/types.ts @@ -1,8 +1,12 @@ import { AlertType, ChannelSide } from '../constants/enums'; -export type Alert = BalanceAlert; +type BaseAlert = { + type: AlertType; + message: string; + date: number; +}; -export type BalanceAlert = BaseAlert & { +export type BalanceAlertEvent = { /** The total balance of the channel when the alert is triggered. */ totalBalance: number; /** The side of the balance either local or remote. */ @@ -14,9 +18,6 @@ export type BalanceAlert = BaseAlert & { /** The currency of the channel. */ currency: string; }; +export type BalanceAlert = BaseAlert & BalanceAlertEvent; -type BaseAlert = { - type: AlertType; - message: string; - date: number; -}; +export type Alert = BalanceAlert; diff --git a/lib/connextclient/ConnextClient.ts b/lib/connextclient/ConnextClient.ts index 2a4b9f323..4e6844e71 100644 --- a/lib/connextclient/ConnextClient.ts +++ b/lib/connextclient/ConnextClient.ts @@ -3,9 +3,9 @@ import assert from 'assert'; import http from 'http'; import { combineLatest, defer, from, fromEvent, interval, Observable, of, Subscription, throwError, timer } from 'rxjs'; import { catchError, distinctUntilChanged, filter, mergeMap, mergeMapTo, pluck, take, timeout } from 'rxjs/operators'; +import { BalanceAlertEvent } from '../alerts/types'; import { SwapClientType, SwapRole, SwapState } from '../constants/enums'; import { CurrencyInstance } from '../db/types'; -import { Alert } from '../alerts/types'; import Logger from '../Logger'; import swapErrors from '../swaps/errors'; import SwapClient, { @@ -51,7 +51,7 @@ interface ConnextClient { on(event: 'htlcAccepted', listener: (rHash: string, amount: number, currency: string) => void): this; on(event: 'connectionVerified', listener: (swapClientInfo: SwapClientInfo) => void): this; on(event: 'depositConfirmed', listener: (hash: string) => void): this; - on(event: 'lowTradingBalance', listener: (alert: Alert) => void): this; + on(event: 'lowTradingBalance', listener: (alert: BalanceAlertEvent) => void): this; once(event: 'initialized', listener: () => void): this; emit(event: 'htlcAccepted', rHash: string, amount: number, currency: string): boolean; emit(event: 'connectionVerified', swapClientInfo: SwapClientInfo): boolean; @@ -59,7 +59,7 @@ interface ConnextClient { emit(event: 'preimage', preimageRequest: ProvidePreimageEvent): void; emit(event: 'transferReceived', transferReceivedRequest: TransferReceivedEvent): void; emit(event: 'depositConfirmed', hash: string): void; - emit(event: 'lowTradingBalance', alert: Alert): boolean; + emit(event: 'lowTradingBalance', alert: BalanceAlertEvent): boolean; } const getRouterNodeIdentifier = (network: string): string => { @@ -343,7 +343,7 @@ class ConnextClient extends SwapClient { const totalBalance = remoteBalance + localBalance; const alertThreshold = totalBalance * 0.1; - this.checkLowBalance(remoteBalance, localBalance, totalBalance, alertThreshold, currency, this.emit.bind(this)); + this.checkLowBalance(remoteBalance, localBalance, totalBalance, alertThreshold, currency); } } catch (e) { this.logger.error('failed to update total outbound capacity', e); diff --git a/lib/lndclient/LndClient.ts b/lib/lndclient/LndClient.ts index 4b1e003a9..f6df35dcf 100644 --- a/lib/lndclient/LndClient.ts +++ b/lib/lndclient/LndClient.ts @@ -2,6 +2,7 @@ import assert from 'assert'; import crypto from 'crypto'; import { promises as fs, watch } from 'fs'; import grpc, { ChannelCredentials, ClientReadableStream } from 'grpc'; +import { BalanceAlertEvent } from 'lib/alerts/types'; import path from 'path'; import { SwapClientType, SwapRole, SwapState } from '../constants/enums'; import Logger from '../Logger'; @@ -27,7 +28,6 @@ import { deriveChild } from '../utils/seedutil'; import { base64ToHex, hexToUint8Array } from '../utils/utils'; import errors from './errors'; import { Chain, ChannelCount, ClientMethods, LndClientConfig, LndInfo } from './types'; -import { Alert } from '../alerts/types'; interface LndClient { on(event: 'connectionVerified', listener: (swapClientInfo: SwapClientInfo) => void): this; @@ -35,7 +35,7 @@ interface LndClient { on(event: 'channelBackup', listener: (channelBackup: Uint8Array) => void): this; on(event: 'channelBackupEnd', listener: () => void): this; on(event: 'locked', listener: () => void): this; - on(event: 'lowTradingBalance', listener: (alert: Alert) => void): this; + on(event: 'lowTradingBalance', listener: (alert: BalanceAlertEvent) => void): this; once(event: 'initialized', listener: () => void): this; @@ -45,7 +45,7 @@ interface LndClient { emit(event: 'channelBackupEnd'): boolean; emit(event: 'locked'): boolean; emit(event: 'initialized'): boolean; - emit(event: 'lowTradingBalance', alert: Alert): boolean; + emit(event: 'lowTradingBalance', alert: BalanceAlertEvent): boolean; } const GRPC_CLIENT_OPTIONS = { @@ -257,7 +257,6 @@ class LndClient extends SwapClient { totalBalance, alertThreshold, this.currency, - this.emit.bind(this), ); }) .catch(async (err) => { diff --git a/lib/swaps/SwapClient.ts b/lib/swaps/SwapClient.ts index 5f8d14b36..fe02fcf16 100644 --- a/lib/swaps/SwapClient.ts +++ b/lib/swaps/SwapClient.ts @@ -1,4 +1,5 @@ import { EventEmitter } from 'events'; +import { BalanceAlertEvent } from 'lib/alerts/types'; import { ChannelSide, SwapClientType } from '../constants/enums'; import Logger from '../Logger'; import { setTimeoutPromise } from '../utils/utils'; @@ -71,8 +72,10 @@ export type WithdrawArguments = { interface SwapClient { on(event: 'connectionVerified', listener: (swapClientInfo: SwapClientInfo) => void): this; + on(event: 'lowTradingBalance', listener: (alert: BalanceAlertEvent) => void): this; once(event: 'initialized', listener: () => void): this; emit(event: 'connectionVerified', swapClientInfo: SwapClientInfo): boolean; + emit(event: 'lowTradingBalance', alert: BalanceAlertEvent): boolean; emit(event: 'initialized'): boolean; } @@ -234,10 +237,9 @@ abstract class SwapClient extends EventEmitter { totalBalance: number, alertThreshold: number, currency: string, - emit: Function, ) => { if (localBalance < alertThreshold) { - emit('lowTradingBalance', { + this.emit('lowTradingBalance', { totalBalance, currency, side: ChannelSide.Local, @@ -247,7 +249,7 @@ abstract class SwapClient extends EventEmitter { } if (remoteBalance < alertThreshold) { - emit('lowTradingBalance', { + this.emit('lowTradingBalance', { totalBalance, currency, side: ChannelSide.Remote,