index.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. const ChainLib = require("../lib/chain-lib");
  2. const Web3Utils = require("../../utils/web3-utils");
  3. const logger = require("../../utils/logger");
  4. const Time = require("../../utils/time");
  5. const LpLib = require("../lib/lp-lib");
  6. class LpMaintenance {
  7. constructor(web3, chain) {
  8. this.web3 = web3
  9. this.chain = chain
  10. // 初始化依赖库
  11. this.lpLib = new LpLib(this.web3, this.chain)
  12. }
  13. async tick() {
  14. const v2LpList = await this.lpLib.getLpList(LpLib.VERSION.UNIV2)
  15. const v3LpList = await this.lpLib.getLpList(LpLib.VERSION.UNIV3)
  16. const lpList = v2LpList.concat(v3LpList)
  17. // 完善lp信息
  18. // 1. 更新所有lp的r0,r1
  19. await this.lpLib.putR0AndR1(lpList)
  20. // 2. 获取每种交易对的最佳兑换池子(最佳:池子价值最高)
  21. // 按相同交易对分组的对象,通过token0+token1的字符串串联方式索引
  22. const maxValueLpMap = this.lpLib.getMaxValueLpMap(lpList)
  23. // 3. 计算token0与token1的相对价格(需要decimals0,decimals1)
  24. this.lpLib.putSwapPrice(lpList)
  25. // 4. 获取基本币对baseToken的价值
  26. const baseTokenConvertEthValueMap = this.lpLib.getBaseTokenCovertEthValue(maxValueLpMap)
  27. // 5. 获取各池子价值
  28. for (const lp of lpList) {
  29. lp.valueStr = this.lpLib.getLpEthValue(lp, baseTokenConvertEthValueMap, maxValueLpMap)
  30. // if (lp.valueStr > 0) logger.info(`lp: ${lp.hash}, value: ${lp.valueStr}.`)
  31. }
  32. // 6. 更新池子到数据库
  33. for (const v2Lp of v2LpList) {
  34. const rst = await this.lpLib.v2LpModel.appendOrUpdate(v2Lp)
  35. if (!rst.state) logger.info(rst)
  36. }
  37. for (const v3Lp of v3LpList) {
  38. const rst = await this.lpLib.v3LpModel.appendOrUpdate(v3Lp)
  39. if (!rst.state) logger.info(rst)
  40. }
  41. }
  42. async run() {
  43. logger.debug(`${this.chain.networkName} liquidity pool maintenance is start.`)
  44. logger.debug(`web3 is connected, block number: ${await this.web3.eth.getBlockNumber()}.`)
  45. // 3. 开始处理
  46. while (true) {
  47. try {
  48. await this.tick()
  49. } catch (e) {
  50. logger.error(e)
  51. }
  52. await Time.delay(1000)
  53. }
  54. }
  55. }
  56. async function main() {
  57. const chain = await ChainLib.getChainFromCommand()
  58. const web3 = Web3Utils.autoCreate(chain)
  59. const generator = new LpMaintenance(web3, chain)
  60. await generator.run()
  61. }
  62. main().catch((error) => {
  63. console.error(error);
  64. process.exitCode = 1;
  65. })