Options
All
  • Public
  • Public/Protected
  • All
Menu

Hierarchy

  • EventEmitter
    • Swaps

Index

Constructors

constructor

Properties

Private deals

deals: Map<string, { completeTime?: undefined | number; createTime: number; destination?: undefined | string; errorMessage?: undefined | string; executeTime?: undefined | number; failureReason?: SwapFailureReason; isBuy: boolean; localId: string; makerAmount: number; makerCltvDelta?: undefined | number; makerCurrency: string; makerUnits: number; orderId: string; pairId: string; peerPubKey: string; phase: SwapPhase; price: number; proposedQuantity: number; quantity?: undefined | number; rHash: string; rPreimage?: undefined | string; role: SwapRole; state: SwapState; takerAmount: number; takerCltvDelta: number; takerCurrency: string; takerMaxTimeLock?: undefined | number; takerPubKey?: undefined | string; takerUnits: number }> = new Map<string, SwapDeal>()

A map between payment hashes and swap deals.

Private logger

logger: Logger

Private models

models: Models

Private pool

pool: Pool

Private repository

repository: SwapRepository

Private sanitySwaps

sanitySwaps: Map<string, {} & { currency: string }> = new Map<string, SanitySwap>()

A map between payment hashes and pending sanity swaps.

Private strict

strict: boolean

swapClientManager

swapClientManager: SwapClientManager

Private swapRecovery

swapRecovery: SwapRecovery

Private timeouts

timeouts: Map<string, number> = new Map<string, number>()

A map between payment hashes and timeouts for swaps.

Private usedHashes

usedHashes: Set<string> = new Set<string>()

Static Private Readonly SANITY_SWAP_COMPLETE_TIMEOUT

SANITY_SWAP_COMPLETE_TIMEOUT: 10000 = 10000

The maximum time in milliseconds we will wait for a swap to be completed before failing it.

Static Private Readonly SANITY_SWAP_INIT_TIMEOUT

SANITY_SWAP_INIT_TIMEOUT: 3000 = 3000

The maximum time in milliseconds we will wait to receive an expected sanity swap init packet.

Static Private Readonly SWAP_ABUSE_TIME_LIMIT

SWAP_ABUSE_TIME_LIMIT: 60000 = 60000

The time threshold in milliseconds after which we consider a counterparty abusive if they settle payment for a timed out swap.

Static Private Readonly SWAP_ACCEPT_TIMEOUT

SWAP_ACCEPT_TIMEOUT: 10000 = 10000

The maximum time in milliseconds we will wait for a swap to be accepted before failing it.

Static Private Readonly SWAP_COMPLETE_MAKER_BUFFER

SWAP_COMPLETE_MAKER_BUFFER: 5000 = 5000

Additional time that the maker will wait for a swap to be completed before considering it timed out. This exists because the maker starts timing sooner and ends timing later than the taker. The maker starts timing as soon as it sends its SwapAccepted packet, but taker starts upon receiving that packet some short time later. Furthermore, the taker stops the timer as soon as it reveals the preimage and settles its incoming payment, whereas the maker doesn't stop until it receives the preimage.

Static Private Readonly SWAP_COMPLETE_TIMEOUT

SWAP_COMPLETE_TIMEOUT: 90000 = 90000

The maximum time in milliseconds we will wait for a swap to be completed before failing it.

Static defaultMaxListeners

defaultMaxListeners: number

Static Readonly errorMonitor

errorMonitor: keyof symbol

This symbol shall be used to install a listener for only monitoring 'error' events. Listeners installed using this symbol are called before the regular 'error' listeners are called.

Installing a listener using this symbol does not change the behavior once an 'error' event is emitted, therefore the process will still crash if no regular 'error' listener is installed.

Methods

acceptDeal

  • Accepts a proposed deal for a specified amount if a route and CLTV delta could be determined for the swap. Stores the deal in the local collection of deals.

    Parameters

    Returns Promise<boolean>

    A promise resolving to true if the deal was accepted, false otherwise.

addDeal

addListener

  • addListener(event: string | symbol, listener: (...args: any[]) => void): this
  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

Private beginSwap

Private bind

  • bind(): void

checkInactiveCurrencyClients

  • checkInactiveCurrencyClients(pairId: string): string | undefined
  • Checks if there are connected swap clients for both currencies in a given trading pair.

    Parameters

    • pairId: string

    Returns string | undefined

    undefined if both currencies are active, otherwise the ticker symbol for an inactive currency.

close

  • close(): void

emit

  • emit(event: "swap.accepted", swapSuccess: SwapAccepted): boolean
  • emit(event: "swap.paid", swapSuccess: SwapSuccess): boolean
  • emit(event: "swap.failed", deal: SwapDeal): boolean
  • emit(event: "swap.recovered", recoveredSwap: SwapDealInstance): boolean

eventNames

  • eventNames(): Array<string | symbol>
  • Returns Array<string | symbol>

executeSanitySwap

  • executeSanitySwap(currency: string, peer: Peer): Promise<boolean>
  • Executes a sanity swap with a peer for a specified currency.

    Parameters

    • currency: string
    • peer: Peer

    Returns Promise<boolean>

    true if the swap succeeds, otherwise false

executeSwap

Private failDeal

  • failDeal(__namedParameters: { deal: { completeTime?: undefined | number; createTime: number; destination?: undefined | string; errorMessage?: undefined | string; executeTime?: undefined | number; failureReason?: SwapFailureReason; isBuy: boolean; localId: string; makerAmount: number; makerCltvDelta?: undefined | number; makerCurrency: string; makerUnits: number; orderId: string; pairId: string; peerPubKey: string; phase: SwapPhase; price: number; proposedQuantity: number; quantity?: undefined | number; rHash: string; rPreimage?: undefined | string; role: SwapRole; state: SwapState; takerAmount: number; takerCltvDelta: number; takerCurrency: string; takerMaxTimeLock?: undefined | number; takerPubKey?: undefined | string; takerUnits: number }; errorMessage: undefined | string; failedCurrency: undefined | string; failureReason: SwapFailureReason; paymentState: undefined | Succeeded | Failed | Pending; peer: undefined | Peer; reqId: undefined | string }): Promise<void>
  • Fails a deal and optionally sends a SwapFailurePacket to a peer, if provided.

    Parameters

    • __namedParameters: { deal: { completeTime?: undefined | number; createTime: number; destination?: undefined | string; errorMessage?: undefined | string; executeTime?: undefined | number; failureReason?: SwapFailureReason; isBuy: boolean; localId: string; makerAmount: number; makerCltvDelta?: undefined | number; makerCurrency: string; makerUnits: number; orderId: string; pairId: string; peerPubKey: string; phase: SwapPhase; price: number; proposedQuantity: number; quantity?: undefined | number; rHash: string; rPreimage?: undefined | string; role: SwapRole; state: SwapState; takerAmount: number; takerCltvDelta: number; takerCurrency: string; takerMaxTimeLock?: undefined | number; takerPubKey?: undefined | string; takerUnits: number }; errorMessage: undefined | string; failedCurrency: undefined | string; failureReason: SwapFailureReason; paymentState: undefined | Succeeded | Failed | Pending; peer: undefined | Peer; reqId: undefined | string }
      • deal: { completeTime?: undefined | number; createTime: number; destination?: undefined | string; errorMessage?: undefined | string; executeTime?: undefined | number; failureReason?: SwapFailureReason; isBuy: boolean; localId: string; makerAmount: number; makerCltvDelta?: undefined | number; makerCurrency: string; makerUnits: number; orderId: string; pairId: string; peerPubKey: string; phase: SwapPhase; price: number; proposedQuantity: number; quantity?: undefined | number; rHash: string; rPreimage?: undefined | string; role: SwapRole; state: SwapState; takerAmount: number; takerCltvDelta: number; takerCurrency: string; takerMaxTimeLock?: undefined | number; takerPubKey?: undefined | string; takerUnits: number }
        • Optional completeTime?: undefined | number

          The time when the swap either completed successfully or failed.

        • createTime: number

          The time when we created this swap deal locally.

        • Optional destination?: undefined | string

          The identifier for the payment channel network node we should pay to complete the swap.

        • Optional errorMessage?: undefined | string

          The reason for being in the current state.

        • Optional executeTime?: undefined | number

          The time when we began executing the swap for an accepted deal.

        • Optional failureReason?: SwapFailureReason
        • isBuy: boolean

          Whether the maker order is a buy order.

        • localId: string

          The local id of the own order involved in the swap.

        • makerAmount: number

          The amount the maker is expecting to receive denominated in satoshis.

        • Optional makerCltvDelta?: undefined | number

          The CLTV delta from the current height that should be used to set the timelock for the final hop when sending to maker.

        • makerCurrency: string

          The currency the maker is expecting to receive.

        • makerUnits: number

          The number of the smallest base units of the currency (like satoshis or wei) the maker is expecting to receive.

        • orderId: string

          The global order id in the XU network for the maker order being executed.

        • pairId: string

          The trading pair for the swap. The pairId together with the orderId are needed to find the maker order in the order book.

        • peerPubKey: string

          The xud node pub key of the counterparty to this swap deal.

        • phase: SwapPhase

          The most updated deal phase

        • price: number

          The price of the order that's being executed.

        • proposedQuantity: number

          The quantity of the order to execute as proposed by the taker.

        • Optional quantity?: undefined | number

          The quantity of the order to execute as accepted by the maker.

        • rHash: string

          The hex-encoded hash of the preimage.

        • Optional rPreimage?: undefined | string

          The hex-encoded preimage.

        • role: SwapRole

          Our role in the swap.

        • state: SwapState

          The most updated deal state. State works together with phase to indicate where the deal is in its life cycle and if the deal is active, errored, or completed.

        • takerAmount: number

          The amount the taker is expecting to receive denominated in satoshis.

        • takerCltvDelta: number

          The CLTV delta from the current height that should be used to set the timelock for the final hop when sending to taker.

        • takerCurrency: string

          The currency the taker is expecting to receive.

        • Optional takerMaxTimeLock?: undefined | number

          The maximum time lock from the maker to the taker in blocks.

        • Optional takerPubKey?: undefined | string

          Taker's lnd pubkey on the taker currency's network.

        • takerUnits: number

          The number of the smallest base units of the currency (like satoshis or wei) the maker is expecting to receive.

      • errorMessage: undefined | string
      • failedCurrency: undefined | string
      • failureReason: SwapFailureReason
      • paymentState: undefined | Succeeded | Failed | Pending
      • peer: undefined | Peer
      • reqId: undefined | string

    Returns Promise<void>

getDeal

  • getDeal(rHash: string): SwapDeal | undefined
  • Gets a deal by its rHash value.

    Parameters

    • rHash: string

      The rHash value of the deal to get.

    Returns SwapDeal | undefined

    A deal if one is found, otherwise undefined.

getMaxListeners

  • getMaxListeners(): number

getPendingSwapHashes

  • getPendingSwapHashes(): string[]

Private handleHtlcAccepted

  • handleHtlcAccepted(swapClient: SwapClient, rHash: string, amount: number, currency: string): Promise<void>

handleResolveRequest

  • handleResolveRequest(resolveRequest: ResolveRequest): Promise<string>

Private handleSwapAccepted

  • Handles a response from a peer to confirm a swap deal and updates the deal. If the deal is accepted, initiates the swap.

    Parameters

    Returns Promise<void>

Private handleSwapFailed

Private handleSwapTimeout

init

  • init(): Promise<void>

listenerCount

  • listenerCount(type: string | symbol): number
  • Parameters

    • type: string | symbol

    Returns number

listeners

  • listeners(event: string | symbol): Function[]
  • Parameters

    • event: string | symbol

    Returns Function[]

off

  • off(event: string | symbol, listener: (...args: any[]) => void): this
  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

on

  • on(event: "swap.accepted", listener: (swapSuccess: SwapAccepted) => void): this
  • on(event: "swap.paid", listener: (swapSuccess: SwapSuccess) => void): this
  • on(event: "swap.failed", listener: (deal: SwapDeal) => void): this
  • on(event: "swap.recovered", listener: (recoveredSwap: SwapDealInstance) => void): this

once

  • once(event: string | symbol, listener: (...args: any[]) => void): this
  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

Private persistDeal

  • persistDeal(deal: SwapDeal): Promise<void>
  • Saves deal to database and deletes it from memory if it is no longer active.

    Parameters

    Returns Promise<void>

prependListener

  • prependListener(event: string | symbol, listener: (...args: any[]) => void): this
  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

prependOnceListener

  • prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this
  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

rawListeners

  • rawListeners(event: string | symbol): Function[]
  • Parameters

    • event: string | symbol

    Returns Function[]

removeAllListeners

  • removeAllListeners(event?: string | symbol): this
  • Parameters

    • Optional event: string | symbol

    Returns this

removeListener

  • removeListener(event: string | symbol, listener: (...args: any[]) => void): this
  • Parameters

    • event: string | symbol
    • listener: (...args: any[]) => void
        • (...args: any[]): void
        • Parameters

          • Rest ...args: any[]

          Returns void

    Returns this

resolveHash

  • resolveHash(rHash: string, amount: number, htlcCurrency?: undefined | string): Promise<string>
  • Resolves the hash for an incoming HTLC to its preimage.

    Parameters

    • rHash: string

      the payment hash to resolve

    • amount: number

      the amount in satoshis

    • Optional htlcCurrency: undefined | string

      the currency of the HTLC

    Returns Promise<string>

    the preimage for the provided payment hash

Private resolveSanitySwap

  • resolveSanitySwap(rHash: string, amount: number, htlcCurrency?: undefined | string): Promise<string>
  • Attempts to resolve the preimage for the payment hash of a pending sanity swap.

    Parameters

    • rHash: string
    • amount: number
    • Optional htlcCurrency: undefined | string

    Returns Promise<string>

Private sendErrorToPeer

  • sendErrorToPeer(__namedParameters: { errorMessage: undefined | string; failureReason: SwapFailureReason; peer: Peer; rHash: string; reqId: undefined | string }): Promise<void>
  • Sends a swap failed packet to the counterparty peer in a swap with details about the error that caused the failure. Sets reqId if packet is a response to a request.

    Parameters

    • __namedParameters: { errorMessage: undefined | string; failureReason: SwapFailureReason; peer: Peer; rHash: string; reqId: undefined | string }
      • errorMessage: undefined | string
      • failureReason: SwapFailureReason
      • peer: Peer
      • rHash: string
      • reqId: undefined | string

    Returns Promise<void>

Private setDealPhase

  • Updates the phase of a swap deal and handles logic directly related to that phase change, including persisting the deal state to the database.

    Parameters

    Returns Promise<void>

setMaxListeners

  • setMaxListeners(n: number): this
  • Parameters

    • n: number

    Returns this

Private validateResolveRequest

  • Verifies that the resolve request is valid. Checks the received amount vs the expected amount.

    Parameters

    Returns boolean

    true if the resolve request is valid, false otherwise

Private verifyExecution

  • Checks if a swap for two given orders can be executed by ensuring both swap clients are active and if there exists a route to the maker.

    Parameters

    Returns Promise<void>

    void if the swap can be executed, throws a SwapFailureReason otherwise

Static calculateInboundOutboundAmounts

  • calculateInboundOutboundAmounts(quantity: number, price: number, isBuy: boolean, pairId: string): { inboundAmount: number; inboundCurrency: string; inboundUnits: number; outboundAmount: number; outboundCurrency: string; outboundUnits: number }
  • Calculates the incoming and outgoing currencies and amounts of subunits/satoshis for an order if it is swapped.

    Parameters

    • quantity: number

      The quantity of the order

    • price: number

      The price of the order

    • isBuy: boolean

      Whether the order is a buy

    • pairId: string

    Returns { inboundAmount: number; inboundCurrency: string; inboundUnits: number; outboundAmount: number; outboundCurrency: string; outboundUnits: number }

    An object with the calculated incoming and outgoing values. The quote currency amount is returned as zero if the price is 0 or infinity, indicating a market order.

    • inboundAmount: number
    • inboundCurrency: string
    • inboundUnits: number
    • outboundAmount: number
    • outboundCurrency: string
    • outboundUnits: number

Static Private calculateLockBuffer

  • calculateLockBuffer(secondLegLockDuration: number, secondLegMinutesPerBlock: number, firstLegMinutesPerBlock: number): number
  • Calculates the minimum expected lock delta for the final hop of the first leg to ensure a very high probability that it won't expire before the second leg payment. We use a Poisson distribution to model the possible block times of two independent chains, first calculating a probabilistic upper bound for the lock time in minuntes of the second leg then a probabilistic lower bound for the number of blocks for the lock time extended to the final hop of the first leg.

    Parameters

    • secondLegLockDuration: number

      The lock duration (aka time lock or cltv delta) of the second leg (maker to taker) denominated in blocks of that chain.

    • secondLegMinutesPerBlock: number
    • firstLegMinutesPerBlock: number

    Returns number

    A number of blocks for the chain of the first leg that is highly likely to take more time in minutes than the provided second leg lock duration.

Static Private calculateMakerTakerAmounts

  • calculateMakerTakerAmounts(quantity: number, price: number, isBuy: boolean, pairId: string): { makerAmount: number; makerCurrency: string; makerUnits: number; takerAmount: number; takerCurrency: string; takerUnits: number }
  • Calculates the currencies and amounts of subunits/satoshis each side of a swap should receive.

    Parameters

    • quantity: number

      The quantity being swapped

    • price: number

      The price for the swap

    • isBuy: boolean

      Whether the maker order in the swap is a buy

    • pairId: string

    Returns { makerAmount: number; makerCurrency: string; makerUnits: number; takerAmount: number; takerCurrency: string; takerUnits: number }

    An object with the calculated maker and taker values.

    • makerAmount: number
    • makerCurrency: string
    • makerUnits: number
    • takerAmount: number
    • takerCurrency: string
    • takerUnits: number

Static listenerCount

  • listenerCount(emitter: EventEmitter, event: string | symbol): number
  • deprecated

    since v4.0.0

    Parameters

    • emitter: EventEmitter
    • event: string | symbol

    Returns number

Static validateSwapRequest

  • validateSwapRequest(__namedParameters: { proposedQuantity: number; rHash: string }): boolean
  • Checks if a swap request is valid. This is a shallow check that only detects critical inconsistencies and verifies only whether the request can possibly lead to a successful swap.

    Parameters

    • __namedParameters: { proposedQuantity: number; rHash: string }
      • proposedQuantity: number
      • rHash: string

    Returns boolean

    true if the request is valid, otherwise false

Object literals

Static Private Readonly UNITS_PER_CURRENCY

UNITS_PER_CURRENCY: object

Number of smallest units per currency.

BTC

BTC: number = 1

DAI

DAI: number = 10 ** 10

ETH

ETH: number = 10 ** 10

LTC

LTC: number = 1

USDT

USDT: number = 10 ** -2

WETH

WETH: number = 10 ** 10

XUC

XUC: number = 10 ** 10

Generated using TypeDoc