UNPKG

xud

Version:
207 lines (206 loc) 9.09 kB
/// <reference types="node" /> import { EventEmitter } from 'events'; import { SwapClientType } from '../constants/enums'; import Logger from '../Logger'; import { CloseChannelParams, OpenChannelParams, Route, SwapCapacities, SwapDeal } from './types'; declare enum ClientStatus { /** The starting status before a client has initialized. */ NotInitialized = 0, /** The client has been initialized but has not attempted to connect to the server yet. */ Initialized = 1, /** The client is permanently disabled. */ Disabled = 2, /** The server cannot be reached or is not responding properly. */ Disconnected = 3, /** The server is reachable and operational. */ ConnectionVerified = 4, /** The server is reachable but is not ready pending completion of blockchain or network sync. */ OutOfSync = 5, /** The server is reachable but needs to be unlocked before it accepts calls. */ WaitingUnlock = 6, /** The server has been unlocked, but its status has not been verified yet. */ Unlocked = 7, /** The client could not be initialized due to faulty configuration. */ Misconfigured = 8, /** The server is reachable but hold invoices are not supported. */ NoHoldInvoiceSupport = 9 } declare type ChannelBalance = { /** The cumulative balance of open channels denominated in satoshis. */ balance: number; /** The cumulative balance of pending channels denominated in satoshis. */ pendingOpenBalance: number; /** The cumulative balance of inactive channels denominated in satoshis. */ inactiveBalance: number; }; declare type WalletBalance = { /** The balance of the wallet. */ totalBalance: number; /** The confirmed balance of a wallet (with >= 1 confirmations). */ confirmedBalance: number; /** The unconfirmed balance of a wallet (with 0 confirmations). */ unconfirmedBalance: number; }; export declare type SwapClientInfo = { newIdentifier?: string; newUris?: string[]; }; export declare enum PaymentState { Succeeded = 0, Failed = 1, Pending = 2 } export declare type PaymentStatus = { state: PaymentState; preimage?: string; }; export declare type WithdrawArguments = { currency: string; destination: string; amount?: number; all?: boolean; fee?: number; }; interface SwapClient { on(event: 'connectionVerified', listener: (swapClientInfo: SwapClientInfo) => void): this; once(event: 'initialized', listener: () => void): this; emit(event: 'connectionVerified', swapClientInfo: SwapClientInfo): boolean; emit(event: 'initialized'): boolean; } /** * A base class to represent an external swap client such as lnd or connext. */ declare abstract class SwapClient extends EventEmitter { logger: Logger; protected disable: boolean; /** * The number of blocks of lock time to expect on the final hop of an incoming swap payment. */ abstract readonly finalLock: number; abstract readonly type: SwapClientType; /** Time in milliseconds between attempts to recheck connectivity to the client. */ static readonly RECONNECT_INTERVAL = 5000; protected status: ClientStatus; protected reconnectionTimer?: NodeJS.Timer; private updateCapacityTimer?; /** The maximum amount of time we will wait for the connection to be verified during initialization. */ private static INITIALIZATION_TIME_LIMIT; /** Time in milliseconds between updating the maximum outbound capacity. */ private static CAPACITY_REFRESH_INTERVAL; constructor(logger: Logger, disable: boolean); abstract get minutesPerBlock(): number; abstract get label(): string; /** * Returns the total balance available across all channels and updates the maximum * outbound capacity. * @param currency the currency whose balance to query for, otherwise all/any * currencies supported by this client are included in the balance. */ abstract channelBalance(currency?: string): Promise<ChannelBalance>; /** * Returns total unspent outputs (confirmed and unconfirmed), * all confirmed unspent outputs * and all unconfirmed unspent outputs under control of the wallet). * @param currency the currency whose balance to query for, otherwise all/any * currencies supported by this client are included in the balance. */ abstract walletBalance(currency?: string): Promise<WalletBalance>; /** * Returns and updates the maximum outbound and inbound capacities for a distinct channel. * @param currency the currency whose trading limits to query for, otherwise all/any * currencies supported by this client are included in the trading limits. */ abstract swapCapacities(currency?: string): Promise<SwapCapacities>; abstract setReservedInboundAmount(reservedInboundAmount: number, currency?: string): void; protected abstract updateCapacity(): Promise<void>; verifyConnectionWithTimeout: () => Promise<void>; init: () => Promise<void>; protected abstract initSpecific(): Promise<void>; protected setConnected: (newIdentifier?: string | undefined, newUris?: string[] | undefined) => Promise<void>; protected setStatus: (newStatus: ClientStatus) => void; private updateCapacityTimerCallback; private reconnectionTimerCallback; private setTimers; /** * Verifies that the swap client can be reached and is in an operational state * and sets the [[ClientStatus]] accordingly. */ protected abstract verifyConnection(): Promise<void>; /** * Sends payment according to the terms of a swap deal. * @returns the preimage for the swap */ abstract sendPayment(deal: SwapDeal): Promise<string>; /** * Sends the smallest amount supported by the client to the given destination. * Throws an error if the payment fails. * @returns the preimage for the payment hash */ abstract sendSmallestAmount(rHash: string, destination: string, currency: string): Promise<string>; /** * Gets routes for the given currency, amount, and swap identifier. * @param units the capacity the route must support denominated in the smallest units supported by its currency * @param destination the identifier for the receiving node * @returns routes */ abstract getRoute(units: number, destination: string, currency: string, finalCltvDelta?: number): Promise<Route | undefined>; /** * Checks whether it is possible to route a payment to a node. This does not test or guarantee * that a payment can be routed successfully, only whether it is possible to do so currently * given the state of the network and graph - without creating new channels or edges. */ abstract canRouteToNode(destination: string, currency?: string): Promise<boolean>; /** * Notifies that swap client to expect a payment. * @param rHash the hash of the preimage * @param units the amount of the invoice denominated in the smallest units supported by its currency * @param expiry * @param currency */ abstract addInvoice({ rHash, units, expiry, currency }: { rHash: string; units: number; expiry?: number; currency?: string; }): Promise<void>; abstract settleInvoice(rHash: string, rPreimage: string, currency?: string): Promise<void>; abstract removeInvoice(rHash: string): Promise<void>; /** * Checks to see whether we've made a payment using a given rHash. * @returns the preimage for the payment, or `undefined` if no payment was made */ abstract lookupPayment(rHash: string, currency?: string, destination?: string): Promise<PaymentStatus>; /** * Gets the block height of the chain backing this swap client. */ abstract getHeight(): Promise<number>; /** * Opens a payment channel. */ abstract openChannel({ remoteIdentifier, units, currency, uris, pushUnits, fee }: OpenChannelParams): Promise<string>; /** * Closes a payment channel. */ abstract closeChannel({ remoteIdentifier, units, currency, destination, force, fee }: CloseChannelParams): Promise<string[]>; /** Gets a deposit address. */ abstract deposit(): Promise<string>; /** Withdraws from the onchain wallet of the client and returns the transaction id or transaction hash in case of Ethereum */ abstract withdraw(args: WithdrawArguments): Promise<string>; isConnected(): boolean; isDisabled(): boolean; isMisconfigured(): boolean; /** * Returns `true` if the client is enabled and configured properly. */ isOperational(): boolean; isDisconnected(): boolean; isWaitingUnlock(): boolean; isNotInitialized(): boolean; isOutOfSync(): boolean; hasNoInvoiceSupport(): boolean; /** Ends all connections, subscriptions, and timers for for this client. */ close(): void; protected abstract disconnect(): void; } export default SwapClient; export { ClientStatus, ChannelBalance, WalletBalance };