All files ptokens-swap-builder.ts

100% Statements 31/31
100% Branches 6/6
100% Functions 11/11
100% Lines 26/26

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 651x     1x 1x   1x   6x         6x       3x       3x       1x       1x       5x 5x       5x 5x 4x 4x       4x 4x       5x 4x 3x 2x     2x     1x 1x 1x      
import { pTokensSwap, DestinationInfo } from './ptokens-swap'
import { pTokensAsset } from 'ptokens-entities'
import { pTokensNode } from 'ptokens-node'
import { validators } from 'ptokens-helpers'
import BigNumber from 'bignumber.js'
 
export class pTokensSwapBuilder {
  private _sourceAsset: pTokensAsset
  private _destinationAssets: Array<DestinationInfo> = []
  private _amount: BigNumber
  private _node: pTokensNode
 
  constructor(node: pTokensNode) {
    this._node = node
  }
 
  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
  }
 
  setSourceAsset(asset: pTokensAsset) {
    this._sourceAsset = asset
    return this
  }
 
  addDestinationAsset(asset: pTokensAsset, destinationAddress: string, userData: Uint8Array = undefined) {
    const isValidAddressFunction = validators.chainIdToAddressValidatorMap.get(asset.chainId)
    if (!isValidAddressFunction(destinationAddress)) throw new Error('Invalid destination address')
    this._destinationAssets.push({ asset, destinationAddress, userData })
    return this
  }
 
  setAmount(_amount: number | string) {
    this._amount = BigNumber(_amount)
    return this
  }
 
  build(): pTokensSwap {
    if (!this._amount) throw new Error('Missing amount')
    if (!this._sourceAsset) throw new Error('Missing source asset')
    if (this._destinationAssets.length === 0) throw new Error('Missing destination assets')
    if (
      !this.destinationAssets.every(
        (_asset) =>
          _asset.assetInfo.tokenReference.toLowerCase() === this.sourceAsset.assetInfo.tokenReference.toLowerCase()
      )
    )
      throw new Error('Invalid swap')
    const ret = new pTokensSwap(this._node, this.sourceAsset, this._destinationAssets, this._amount)
    return ret
  }
}