token.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. nextHandleTime: this.nextHandleTime
  22. }
  23. await db.put(this.exchange.pair, JSON.stringify(localData))
  24. }
  25. async load() {
  26. try {
  27. const localDataJsonStr = await db.get(this.exchange.pair)
  28. const localData = JSON.parse(localDataJsonStr)
  29. this.orderAmount = localData.orderAmount
  30. this.orderPrice = localData.orderPrice
  31. this.nextHandleTime = localData.nextHandleTime
  32. } catch (e) {}
  33. }
  34. static async init(context, tokenHash, priceTickFilterMap, lotSizeFilterMap) {
  35. const config = context.config
  36. const logger = context.logger
  37. // token初始化
  38. const ierc20Decimals = parseInt(await IERC20.getDecimals(tokenHash))
  39. const exchangeSymbol = config.tokenMapping[tokenHash]
  40. const exchangePair = `${exchangeSymbol}${config.baseIerc20Token.symbol}`
  41. const exchangePriceTick = priceTickFilterMap[exchangePair]
  42. const exchangeLotSize = lotSizeFilterMap[exchangePair]
  43. const token = new Token(exchangeSymbol, exchangePriceTick, exchangeLotSize, exchangePair, ierc20Decimals)
  44. // 载入时持久化
  45. await token.load()
  46. context.tokenMap[tokenHash] = token
  47. logger.info(`${token.exchange.pair}初始化完毕,orderPrice:${token.orderPrice}, orderAmount:${token.orderAmount}.`)
  48. }
  49. static async batchInit(context, ierc20TokenAddressList, priceTickFilterMap, lotSizeFilterMap) {
  50. context.tokenMap = {}
  51. for (const tokenHash of ierc20TokenAddressList) {
  52. // 初始化token
  53. await Token.init(context, tokenHash, priceTickFilterMap, lotSizeFilterMap)
  54. }
  55. }
  56. }