All files / src ptokens-swap.ts

95.45% Statements 63/66
100% Branches 10/10
92.85% Functions 26/28
96.82% Lines 61/63

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162  2x 2x 2x                 2x                         5x 5x 5x 5x 5x       17x       1x       1x       22x       4x   4x   12x 8x       4x 12x 12x 8x 4x 4x     4x     4x     4x       4x   4x   9x 8x   4x     4x 9x 9x 8x 4x 4x 4x 4x 4x     1x     4x     4x               4x   4x 4x 4x   4x 3x             1x             4x   3x     4x     4x   4x 4x   4x   4x     4x   4x           4x      
import { pTokensAsset } from 'ptokens-entities'
import { pTokensNode, Status, InnerTransactionStatus } from 'ptokens-node'
import PromiEvent from 'promievent'
import polling from 'light-async-polling'
import BigNumber from 'bignumber.js'
 
export type DestinationInfo = {
  asset: pTokensAsset
  destinationAddress: string
  userData?: Uint8Array
}
 
export class pTokensSwap {
  private _node: pTokensNode
  private _sourceAsset: pTokensAsset
  private _destinationAssets: Array<DestinationInfo>
  private _amount: BigNumber
  private controller: AbortController
 
  constructor(
    node: pTokensNode,
    sourceAsset: pTokensAsset,
    destinationAssets: Array<DestinationInfo>,
    amount: BigNumber
  ) {
    this._node = node
    this._sourceAsset = sourceAsset
    this._destinationAssets = destinationAssets
    this._amount = amount
    this.controller = new AbortController()
  }
 
  public get sourceAsset(): pTokensAsset {
    return this._sourceAsset
  }
 
  public get destinationAssets(): Array<pTokensAsset> {
    return this._destinationAssets.map((_el) => _el.asset)
  }
 
  public get amount(): string {
    return this._amount.toFixed()
  }
 
  public get node(): pTokensNode {
    return this._node
  }
 
  private monitorInputTransactions(txHash: string, origChainId: string): PromiEvent<InnerTransactionStatus[]> {
    const promi = new PromiEvent<InnerTransactionStatus[]>(
      (resolve) =>
        (async () => {
          async function getInputTransactions(node: pTokensNode) {
            const resp = await node.getTransactionStatus(txHash, origChainId)
            return resp.inputs
          }
          let resp: InnerTransactionStatus[]
          // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return
          await polling(async () => {
            try {
              resp = await getInputTransactions(this.node)
              if (resp.length) {
                promi.emit('inputTxDetected', resp)
                return true
              }
            } catch (err) {
              return false
            }
          }, 1000)
          resolve(resp)
        })() as unknown
    )
    return promi
  }
 
  private monitorOutputTransactions(txHash: string, origChainId: string): PromiEvent<InnerTransactionStatus[]> {
    const promi = new PromiEvent<InnerTransactionStatus[]>(
      (resolve) =>
        (async () => {
          async function getOutputTransactions(node: pTokensNode) {
            const resp = await node.getTransactionStatus(txHash, origChainId)
            return resp.outputs
          }
          let notified = false
          let resp: InnerTransactionStatus[]
          // eslint-disable-next-line @typescript-eslint/no-unsafe-call, @typescript-eslint/no-unsafe-return
          await polling(async () => {
            try {
              resp = await getOutputTransactions(this.node)
              if (resp.length && !notified) {
                notified = true
                promi.emit('outputTxBroadcasted', resp)
              } else if (resp.length && resp.every((el) => el.status == Status.CONFIRMED)) {
                promi.emit('outputTxConfirmed', resp)
                return true
              }
            } catch (err) {
              return false
            }
          }, 1000)
          resolve(resp)
        })() as unknown
    )
    return promi
  }
 
  abort() {
    this.controller.abort()
  }
 
  execute() {
    const promi = new PromiEvent<InnerTransactionStatus[]>(
      (resolve, reject) =>
        (async () => {
          try {
            this.controller.signal.addEventListener('abort', () => reject(new Error('Swap aborted by user')))
            let swapPromiEvent: PromiEvent<string>
            if (this.sourceAsset.assetInfo.isNative) {
              swapPromiEvent = this.sourceAsset.nativeToInterim(
                this._amount,
                this._destinationAssets[0].destinationAddress,
                this._destinationAssets[0].asset.chainId,
                this._destinationAssets[0].userData
              )
            } else {
              swapPromiEvent = this.sourceAsset.hostToInterim(
                this._amount,
                this._destinationAssets[0].destinationAddress,
                this._destinationAssets[0].asset.chainId,
                this._destinationAssets[0].userData
              )
            }
            const txHash = await swapPromiEvent
              .on('depositAddress', (depositAddress) => {
                promi.emit('depositAddress', depositAddress)
              })
              .on('txBroadcasted', (txHash) => {
                promi.emit('inputTxBroadcasted', txHash)
              })
              .on('txConfirmed', (txHash) => {
                promi.emit('inputTxConfirmed', txHash)
              })
            await this.monitorInputTransactions(txHash, this.sourceAsset.chainId).on('inputTxDetected', (inputs) => {
              promi.emit('inputTxDetected', inputs)
            })
            const outputs = await this.monitorOutputTransactions(txHash, this.sourceAsset.chainId)
              .on('outputTxBroadcasted', (outputs) => {
                promi.emit('outputTxDetected', outputs)
              })
              .on('outputTxConfirmed', (outputs) => {
                promi.emit('outputTxProcessed', outputs)
              })
            return resolve(outputs)
          } catch (err) {
            return reject(err)
          }
        })() as unknown
    )
    return promi
  }
}