token.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. const IERC20 = require("./web3/ierc20-token");
  2. const { Level } = require("level");
  3. const db = new Level('app.db', { valueEncoding: 'json' })
  4. module.exports = class Token {
  5. exchange = {}
  6. ierc20 = {}
  7. orderPrice = 0
  8. orderAmount = 0
  9. nextHandleTime = 0
  10. constructor(exchangeSymbol, exchangePriceTick, exchangeLotSize, exchangePair, ierc20Decimals) {
  11. this.exchange.symbol = exchangeSymbol
  12. this.exchange.priceTick = exchangePriceTick
  13. this.exchange.lotSize = exchangeLotSize
  14. this.exchange.pair = exchangePair
  15. this.ierc20.decimals = ierc20Decimals
  16. }
  17. async save() {
  18. const localData = {
  19. orderPrice: this.orderPrice,
  20. orderAmount: this.orderAmount,
  21. orderTime: this.orderTime,
  22. nextHandleTime: this.nextHandleTime
  23. }
  24. await db.put(this.exchange.pair, JSON.stringify(localData))
  25. }
  26. async load() {
  27. try {
  28. const localDataJsonStr = await db.get(this.exchange.pair)
  29. const localData = JSON.parse(localDataJsonStr)
  30. this.orderAmount = localData.orderAmount
  31. this.orderPrice = localData.orderPrice
  32. this.orderTime = localData.orderTime ? localData.orderTime : 0
  33. this.nextHandleTime = localData.nextHandleTime
  34. } catch (e) {}
  35. }
  36. static async init(context, logger, tokenHash, priceTickFilterMap, lotSizeFilterMap) {
  37. const config = context.config
  38. // token初始化
  39. const ierc20Decimals = parseInt(await IERC20.getDecimals(tokenHash))
  40. const exchangeSymbol = config.tokenMapping[tokenHash]
  41. const exchangePair = `${exchangeSymbol}${config.baseIerc20Token.symbol}`
  42. const exchangePriceTick = priceTickFilterMap[exchangePair]
  43. const exchangeLotSize = lotSizeFilterMap[exchangePair]
  44. const token = new Token(exchangeSymbol, exchangePriceTick, exchangeLotSize, exchangePair, ierc20Decimals)
  45. // 载入时持久化
  46. await token.load()
  47. context.tokenMap[tokenHash] = token
  48. logger.info(`${token.exchange.pair}初始化完毕,orderPrice:${token.orderPrice}, orderAmount:${token.orderAmount}, orderTime:${token.orderTime}.`)
  49. }
  50. static async batchInit(context, logger, ierc20TokenAddressList, priceTickFilterMap, lotSizeFilterMap) {
  51. context.tokenMap = {}
  52. for (const tokenHash of ierc20TokenAddressList) {
  53. // 初始化token
  54. await Token.init(context, logger, tokenHash, priceTickFilterMap, lotSizeFilterMap)
  55. }
  56. }
  57. }