Skip to content

Commit

Permalink
refactor: type checking for BalanceAlert event
Browse files Browse the repository at this point in the history
  • Loading branch information
sangaman committed Dec 22, 2020
1 parent 0f95df4 commit da42e0a
Show file tree
Hide file tree
Showing 5 changed files with 41 additions and 34 deletions.
31 changes: 18 additions & 13 deletions lib/alerts/Alerts.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand Down Expand Up @@ -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);
Expand Down
15 changes: 8 additions & 7 deletions lib/alerts/types.ts
Original file line number Diff line number Diff line change
@@ -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. */
Expand All @@ -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;
12 changes: 6 additions & 6 deletions lib/connextclient/ConnextClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, {
Expand All @@ -15,7 +15,7 @@ import SwapClient, {
PaymentStatus,
SwapClientInfo,
WalletBalance,
WithdrawArguments,
WithdrawArguments
} from '../swaps/SwapClient';
import { CloseChannelParams, OpenChannelParams, SwapCapacities, SwapDeal } from '../swaps/types';
import { XudError } from '../types';
Expand All @@ -42,7 +42,7 @@ import {
GetBlockByNumberResponse,
OnchainTransferResponse,
ProvidePreimageEvent,
TransferReceivedEvent,
TransferReceivedEvent
} from './types';

interface ConnextClient {
Expand All @@ -51,15 +51,15 @@ 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;
emit(event: 'initialized'): boolean;
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 => {
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 4 additions & 5 deletions lib/lndclient/LndClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -20,22 +21,21 @@ import SwapClient, {
ClientStatus,
PaymentState,
SwapClientInfo,
WithdrawArguments,
WithdrawArguments
} from '../swaps/SwapClient';
import { CloseChannelParams, OpenChannelParams, SwapCapacities, SwapDeal } from '../swaps/types';
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;
on(event: 'htlcAccepted', listener: (rHash: string, amount: number) => void): this;
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;

Expand All @@ -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 = {
Expand Down Expand Up @@ -257,7 +257,6 @@ class LndClient extends SwapClient {
totalBalance,
alertThreshold,
this.currency,
this.emit.bind(this),
);
})
.catch(async (err) => {
Expand Down
8 changes: 5 additions & 3 deletions lib/swaps/SwapClient.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand Down Expand Up @@ -72,8 +73,10 @@ export type WithdrawArguments = {
interface SwapClient {
on(event: 'connectionVerified', listener: (swapClientInfo: SwapClientInfo) => void): this;
once(event: 'initialized', listener: () => void): this;
on(event: 'lowTradingBalance', listener: (alert: BalanceAlertEvent) => void): this;
emit(event: 'connectionVerified', swapClientInfo: SwapClientInfo): boolean;
emit(event: 'initialized'): boolean;
emit(event: 'lowTradingBalance', alert: BalanceAlertEvent): boolean;
}

/**
Expand Down Expand Up @@ -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,
Expand All @@ -247,7 +249,7 @@ abstract class SwapClient extends EventEmitter {
}

if (remoteBalance < alertThreshold) {
emit('lowTradingBalance', {
this.emit('lowTradingBalance', {
totalBalance,
currency,
side: ChannelSide.Remote,
Expand Down

0 comments on commit da42e0a

Please sign in to comment.