All files orderbook.ts

96.67% Statements 29/30
91.67% Branches 11/12
100% Functions 4/4
100% Lines 28/28

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      1x 1x                               8x 8x 8x 8x 8x 12x 4x 4x 2x 2x   2x   8x 2x 2x 1x 1x   1x     8x         2x 1x 1x                   1x 1x 1x 1x           1x  
/**
 * Created by Administrator on 2016/11/22.
 */
import { EventEmitter } from "events"
import { utils } from "@swtc/utils"
 
/**
 * order book stub for all order book
 * key: currency/issuer:currency/issuer
 *  if swt, currency/issuer=SWT
 *  TODO keep every order book up state, and return state when needed
 *  not need to query jingtumd again
 * @param remote
 * @constructor
 */
class OrderBook extends EventEmitter {
  public _books
  protected _token
  private _remote
  constructor(remote: any) {
    super()
    this._remote = remote
    this._books = {}
    this._token = remote._token || "swt"
    this.on("newListener", function(key, listener) {
      if (key === "removeListener") return
      const pair = utils.parseKey(key)
      if (!pair) {
        this.pair = new Error("invalid key")
        return this
      }
      this._books[key] = listener
    })
    this.on("removeListener", function(key) {
      const pair = utils.parseKey(key)
      if (!pair) {
        this.pair = new Error("invalid key")
        return this
      }
      delete this._books[key]
    })
    // same implement as account stub, subscribe all and dispatch
    this._remote.on("transactions", this.__updateBooks.bind(this))
  }
 
  private __updateBooks(data) {
    // dispatch
    if (data.meta) {
      const books = utils.affectedBooks(data)
      const _data = {
        tx: data.transaction,
        meta: data.meta,
        engine_result: data.engine_result,
        engine_result_code: data.engine_result_code,
        engine_result_message: data.engine_result_message,
        ledger_hash: data.ledger_hash,
        ledger_index: data.ledger_index,
        validated: data.validated
      }
      const _tx = utils.processTx(_data, data.transaction.Account)
      for (const book of books) {
        const callback = this._books[books[book]]
        Iif (callback) callback(_tx)
      }
    }
  }
}
 
export { OrderBook }