@clonegod/ttd-core 3.1.18 → 3.1.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/alert/reporter.js +12 -6
  2. package/dist/analyze/index.d.ts +5 -3
  3. package/dist/analyze/index.js +81 -19
  4. package/dist/analyze/ws_client.d.ts +15 -0
  5. package/dist/analyze/ws_client.js +88 -0
  6. package/dist/app_config/AppConfig.js +2 -4
  7. package/dist/app_config/EnvArgs.d.ts +22 -0
  8. package/dist/app_config/EnvArgs.js +45 -38
  9. package/dist/app_config/core_env.d.ts +3 -0
  10. package/dist/app_config/core_env.js +14 -0
  11. package/dist/app_config/env_loader.d.ts +3 -3
  12. package/dist/app_config/env_loader.js +8 -17
  13. package/dist/app_config/env_registry.js +25 -20
  14. package/dist/app_config/index.d.ts +1 -0
  15. package/dist/app_config/index.js +1 -0
  16. package/dist/cache/arb_cache.d.ts +1 -4
  17. package/dist/cache/arb_cache.js +10 -70
  18. package/dist/cache/arb_event_sub.js +2 -1
  19. package/dist/constants/service_ports.d.ts +0 -1
  20. package/dist/constants/service_ports.js +0 -1
  21. package/dist/index.d.ts +2 -4
  22. package/dist/index.js +17 -28
  23. package/dist/market_price/estimate_token_amount.js +14 -14
  24. package/dist/pool/cache_pool_config.js +4 -2
  25. package/dist/quote/on_quote_response.d.ts +0 -1
  26. package/dist/quote/on_quote_response.js +3 -16
  27. package/dist/quote/to_price_message.js +2 -1
  28. package/dist/redis/redis_client.d.ts +1 -0
  29. package/dist/redis/redis_client.js +8 -3
  30. package/dist/redis/redis_connection.js +4 -2
  31. package/dist/token/cache_token_config.js +3 -1
  32. package/dist/token/fixed_symbol_address.js +4 -3
  33. package/dist/token/price/get_bsc_token_price.js +1 -1
  34. package/dist/token/price/get_eth_token_price.d.ts +1 -1
  35. package/dist/token/price/get_eth_token_price.js +1 -1
  36. package/dist/token/price/get_solana_token_price.js +3 -3
  37. package/dist/token/zh_pinyin_map.js +4 -3
  38. package/dist/trade/abstract_tx_check.js +1 -1
  39. package/dist/trade/handle_order_message.js +1 -1
  40. package/dist/util/crypto.js +2 -2
  41. package/dist/util/ip_util.js +9 -3
  42. package/dist/ws/ws_client.js +14 -14
  43. package/package.json +1 -1
  44. package/types/index.d.ts +0 -40
  45. package/dist/cache/redis_client.d.ts +0 -3
  46. package/dist/cache/redis_client.js +0 -45
  47. package/dist/cache/redis_cmd.d.ts +0 -328
  48. package/dist/cache/redis_cmd.js +0 -285
  49. package/dist/chains/evm_gas_options.d.ts +0 -9
  50. package/dist/chains/evm_gas_options.js +0 -2
  51. package/dist/util/config_center_http.d.ts +0 -1
  52. package/dist/util/config_center_http.js +0 -14
  53. package/dist/ws/ws_client_example.d.ts +0 -5
  54. package/dist/ws/ws_client_example.js +0 -69
@@ -1,5 +1,5 @@
1
1
  import { EventEmitter } from 'events';
2
- import { CommonServiceType, LoadingCache, OrderMessageType, PriceMessageType, StandardDexPoolConfigType, StandardPairType, StandardPoolInfoType, StandardTokenInfoType, TradePairDexPoolsType, TradePairType, TradeResponseType, TradeRuntimeType, TradeServiceConfigType } from "../../types";
2
+ import { LoadingCache, OrderMessageType, PriceMessageType, StandardDexPoolConfigType, StandardPairType, StandardPoolInfoType, StandardTokenInfoType, TradePairDexPoolsType, TradePairType, TradeResponseType, TradeRuntimeType, TradeServiceConfigType } from "../../types";
3
3
  import { RedisClient } from "../redis";
4
4
  import { CHAIN_ID } from "../index";
5
5
  import { ArbEventPublisher } from './arb_event_pub';
@@ -23,7 +23,6 @@ export declare class ArbCache {
23
23
  init(): Promise<void>;
24
24
  init_configs(): Promise<void>;
25
25
  get_config_filepath(suffix: string): string;
26
- get_bak_config_filepath(suffix: string): string;
27
26
  refresh_local_cache_token_list(token_list: StandardTokenInfoType[]): void;
28
27
  refresh_local_cache_pool_list(pool_list: StandardPoolInfoType[]): void;
29
28
  refresh_local_cache_group_map(trade_config: TradeServiceConfigType): void;
@@ -44,8 +43,6 @@ export declare class ArbCache {
44
43
  publish_pool_change_event(): Promise<void>;
45
44
  get_one_pair(input_pair: string): Promise<StandardPairType>;
46
45
  get_pair_list(input_pair?: string): Promise<StandardPairType[]>;
47
- cache_common_service(): Promise<void>;
48
- get_common_service(): Promise<CommonServiceType>;
49
46
  cache_trade_group(update_group_id?: string): Promise<void>;
50
47
  update_trade_group(input_trade_config: TradeServiceConfigType): Promise<void>;
51
48
  get_trade_group_id_list(): Promise<string[]>;
@@ -13,6 +13,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.ArbCache = void 0;
16
+ const core_env_1 = require("../app_config/core_env");
16
17
  const fs_1 = __importDefault(require("fs"));
17
18
  const path_1 = __importDefault(require("path"));
18
19
  const index_1 = require("../index");
@@ -43,7 +44,7 @@ class ArbCache {
43
44
  this.get_token_list_no_cache(),
44
45
  this.get_pool_list_no_cache()
45
46
  ]);
46
- if ((_a = process.env.APP_NAME) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes('config-center')) {
47
+ if ((_a = (0, core_env_1.getCoreEnv)().app_name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes('config-center')) {
47
48
  yield this.init_configs();
48
49
  }
49
50
  }
@@ -56,18 +57,18 @@ class ArbCache {
56
57
  init_configs() {
57
58
  return __awaiter(this, void 0, void 0, function* () {
58
59
  var _a;
59
- let app_name = process.env.APP_NAME;
60
- if (!((_a = process.env.APP_NAME) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes('config-center'))) {
61
- (0, index_1.log_warn)(`Only ttd-config-center can initial config! process.env.APP_NAME=${app_name}, return`);
60
+ const coreEnv = (0, core_env_1.getCoreEnv)();
61
+ let app_name = coreEnv.app_name;
62
+ if (!((_a = coreEnv.app_name) === null || _a === void 0 ? void 0 : _a.toLowerCase().includes('config-center'))) {
63
+ (0, index_1.log_warn)(`Only ttd-config-center can initial config! APP_NAME=${app_name}, return`);
62
64
  return;
63
65
  }
64
- let enable_init_cache = process.env.ENABLE_INIT_CACHE;
66
+ let enable_init_cache = coreEnv.enable_init_cache;
65
67
  if (!(0, index_1.isTrue)(enable_init_cache)) {
66
- (0, index_1.log_warn)(`Skip initial config data! process.env.ENABLE_INIT_CACHE=${enable_init_cache}`);
68
+ (0, index_1.log_warn)(`Skip initial config data! ENABLE_INIT_CACHE=${enable_init_cache}`);
67
69
  return;
68
70
  }
69
71
  (0, index_1.log_trace)(`init cache start`);
70
- yield this.cache_common_service();
71
72
  yield this.cache_token_list();
72
73
  yield this.cache_pool_list();
73
74
  yield this.cache_trade_group();
@@ -79,13 +80,6 @@ class ArbCache {
79
80
  let file_name = `config-${chain_id}-${suffix}`;
80
81
  return path_1.default.join('config', chain_id, file_name);
81
82
  }
82
- get_bak_config_filepath(suffix) {
83
- let chain_id = this.chain_id.toLowerCase();
84
- let file_name = `config-${chain_id}-${suffix}`;
85
- let bak_dir = 'bak';
86
- (0, index_1.mkdirSync)(path_1.default.join('config', chain_id, bak_dir));
87
- return path_1.default.join('config', chain_id, 'bak', file_name);
88
- }
89
83
  refresh_local_cache_token_list(token_list) {
90
84
  this.token_list = token_list;
91
85
  this.token_symbol_map.clear();
@@ -115,7 +109,8 @@ class ArbCache {
115
109
  }
116
110
  refresh_local_cache_group_map(trade_config) {
117
111
  let group_id = trade_config.group.id;
118
- let group_id_set_in_env = process.env.GROUP_ID || process.env.TRADE_GROUP_ID;
112
+ const genv = (0, core_env_1.getCoreEnv)();
113
+ let group_id_set_in_env = genv.group_id || genv.trade_group_id;
119
114
  if (group_id_set_in_env && group_id !== group_id_set_in_env) {
120
115
  (0, index_1.log_warn)(`skip set trade group in local cache! group_id not match to current trader process:`, {
121
116
  group_id_set_in_env,
@@ -449,61 +444,6 @@ class ArbCache {
449
444
  return pair_list;
450
445
  });
451
446
  }
452
- cache_common_service() {
453
- return __awaiter(this, void 0, void 0, function* () {
454
- (0, index_1.log_trace)(`cache_common_service, start`);
455
- let filepath = this.get_config_filepath('common-service.json');
456
- if (!(0, index_1.file_exists)(filepath)) {
457
- throw new Error(`cache_common_service failed, config file not exist! filepath=${filepath}`);
458
- }
459
- let config = (0, index_1.readFile)(filepath);
460
- let service_list = [
461
- {
462
- name: 'config_center',
463
- service: config.config_center
464
- },
465
- {
466
- name: 'quote',
467
- service: config.quote || []
468
- },
469
- {
470
- name: 'orderbook',
471
- service: config.orderbook
472
- },
473
- {
474
- name: 'trade_proxy',
475
- service: config.trade_proxy
476
- },
477
- ];
478
- for (let { name, service } of service_list) {
479
- let field = name;
480
- let value = JSON.stringify(service);
481
- let result = yield this.loading_cache.hset(this.chain_id, index_1.CACHE_KEY_TYPE.CONFIG_COMMON_SERVICE, field, value);
482
- (0, index_1.log_trace)(`cache_common_service, field=${field}, result: ` + JSON.stringify(result));
483
- }
484
- (0, index_1.log_trace)(`cache_common_service, end`);
485
- });
486
- }
487
- get_common_service() {
488
- return __awaiter(this, void 0, void 0, function* () {
489
- try {
490
- let res = yield this.loading_cache.hget_all(this.chain_id, index_1.CACHE_KEY_TYPE.CONFIG_COMMON_SERVICE);
491
- let { key, value } = res;
492
- if (index_1.LOG.debug) {
493
- (0, index_1.log_trace)('get_common_service, res=', res);
494
- }
495
- let config = JSON.parse('{}');
496
- for (let name of Object.keys(value)) {
497
- config[name] = JSON.parse(value[name]);
498
- }
499
- return config;
500
- }
501
- catch (err) {
502
- (0, index_1.log_error)('get_common_service error!!!', err);
503
- throw new Error(`get_common_service error! err=${err.message}`);
504
- }
505
- });
506
- }
507
447
  cache_trade_group() {
508
448
  return __awaiter(this, arguments, void 0, function* (update_group_id = '') {
509
449
  (0, index_1.log_trace)(`cache_trade_service, start`);
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.ArbEventSubscriber = void 0;
13
+ const core_env_1 = require("../app_config/core_env");
13
14
  const index_1 = require("../index");
14
15
  class ArbEventSubscriber {
15
16
  constructor(arb_cache) {
@@ -103,7 +104,7 @@ class ArbEventSubscriber {
103
104
  }
104
105
  on_config_group_change_event(message) {
105
106
  return __awaiter(this, void 0, void 0, function* () {
106
- let group_id_set_in_env = process.env.GROUP_ID;
107
+ let group_id_set_in_env = (0, core_env_1.getCoreEnv)().group_id;
107
108
  let { group_id } = message;
108
109
  if (group_id_set_in_env && group_id_set_in_env != group_id) {
109
110
  (0, index_1.log_info)(`on_config_group_change_event, group_id not match, skip`, {
@@ -1,6 +1,5 @@
1
1
  export declare enum SERVICE_PORT {
2
2
  CONFIG_CENTER_HTTP = 4000,
3
- ORDERBOOK_HTTP = 7999,
4
3
  ORDERBOOK_WS = 8000,
5
4
  TRADE_PROXY_HTTP = 8001,
6
5
  TRADE_PROXY_WS = 8002,
@@ -4,7 +4,6 @@ exports.SERVICE_PORT = void 0;
4
4
  var SERVICE_PORT;
5
5
  (function (SERVICE_PORT) {
6
6
  SERVICE_PORT[SERVICE_PORT["CONFIG_CENTER_HTTP"] = 4000] = "CONFIG_CENTER_HTTP";
7
- SERVICE_PORT[SERVICE_PORT["ORDERBOOK_HTTP"] = 7999] = "ORDERBOOK_HTTP";
8
7
  SERVICE_PORT[SERVICE_PORT["ORDERBOOK_WS"] = 8000] = "ORDERBOOK_WS";
9
8
  SERVICE_PORT[SERVICE_PORT["TRADE_PROXY_HTTP"] = 8001] = "TRADE_PROXY_HTTP";
10
9
  SERVICE_PORT[SERVICE_PORT["TRADE_PROXY_WS"] = 8002] = "TRADE_PROXY_WS";
package/dist/index.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import BN from 'bn.js';
2
2
  import Decimal from 'decimal.js';
3
3
  import fs from "fs";
4
- import { ArbCache, StandardPoolInfoType, StandardTokenInfoType, TokenPriceWithAmountType, TradeCommandLineArgs, TradeResponseType, UniqueOrderbookIdType, WalletInfoType } from '../types';
4
+ import { ArbCache, StandardPoolInfoType, StandardTokenInfoType, TokenPriceWithAmountType, TradeResponseType, UniqueOrderbookIdType, WalletInfoType } from '../types';
5
5
  import * as redis from './redis';
6
6
  import * as cache from './cache';
7
7
  export * from './analyze';
@@ -19,7 +19,7 @@ export * from './alert';
19
19
  export * from './log_bus';
20
20
  export * from './ws';
21
21
  export * from './util';
22
- export type { CommonServiceType, ConfigCenterServiceType, QuoteServiceType, OrderbookServiceType, TradeProxyServiceType, StandardTokenConfigType, StandardTokenInfoType, StandardPoolConfigType, StandardDexPoolConfigType, StandardPoolInfoType, StandardPairType, TradeServiceConfigType, TradeGroupType, TradePairType, TradePairDexPoolsType, TradeSettingsType, RpcInfoType, TradeStrategyType, TradeCommandLineArgs, TradeRuntimeType, TradeProcessInstanceType, TokenPriceWithAmountType, QuoteResultType, PriceMessageType, QuoteSourceType, UniqueOrderbookIdType, PriceType, QuoteTimeInfoType, OrderbookPriceType, Ladder, OrderMessageType, OrderSubmitResultType, OrderSubmitResponseType, StandardSwapDetailType, TokenBalChangeType, TokenBalanceChangeType, TradeResponseType, TradeResultType, TradeResultBalanceChangeType, TradeExecutionInfoType, TradeTimeFlowType, TradeBroadcastType, TradeGasFeeType, ServerInfoType, SendTxLogType, WalletInfoType, WalletTokenBalanceInfoType, RedisConfigChangeEventMessageType, RedisOrderEventMessageType, RedisQuoteEventMessageType, PreTradeEventType, ProviderComparisonType, ProviderArrivalType, OnTradeType, OnTradePriceType, OnTradeDepthType, OnTradeExecutionType, OnTradeResultType, AnalyzeDepthLevelType, AnalyzeTokenAmountType, PostTradeType, AnalyzeQuoteSnapshotType, AnalyzePoolEventType, AnalyzeEventSummaryType, AnalyzeSameBlockType, } from '../types';
22
+ export type { StandardTokenConfigType, StandardTokenInfoType, StandardPoolConfigType, StandardDexPoolConfigType, StandardPoolInfoType, StandardPairType, TradeServiceConfigType, TradeGroupType, TradePairType, TradePairDexPoolsType, TradeSettingsType, RpcInfoType, TradeStrategyType, TradeCommandLineArgs, TradeRuntimeType, TradeProcessInstanceType, TokenPriceWithAmountType, QuoteResultType, PriceMessageType, QuoteSourceType, UniqueOrderbookIdType, PriceType, QuoteTimeInfoType, OrderbookPriceType, Ladder, OrderMessageType, OrderSubmitResultType, OrderSubmitResponseType, StandardSwapDetailType, TokenBalChangeType, TokenBalanceChangeType, TradeResponseType, TradeResultType, TradeResultBalanceChangeType, TradeExecutionInfoType, TradeTimeFlowType, TradeBroadcastType, TradeGasFeeType, ServerInfoType, SendTxLogType, WalletInfoType, WalletTokenBalanceInfoType, RedisConfigChangeEventMessageType, RedisOrderEventMessageType, RedisQuoteEventMessageType, PreTradeEventType, ProviderComparisonType, ProviderArrivalType, OnTradeType, OnTradePriceType, OnTradeDepthType, OnTradeExecutionType, OnTradeResultType, AnalyzeDepthLevelType, AnalyzeTokenAmountType, PostTradeType, AnalyzeQuoteSnapshotType, AnalyzePoolEventType, AnalyzeEventSummaryType, AnalyzeSameBlockType, } from '../types';
23
23
  export declare const FAILED = "FAILED";
24
24
  export declare const SUCCESS = "SUCCESS";
25
25
  export declare const NOT_FOUND = "NOT_FOUND";
@@ -119,7 +119,6 @@ export declare enum CACHE_KEY_TYPE {
119
119
  CONFIG_TOKEN_LIST = "c:token",
120
120
  CONFIG_POOL_LIST = "c:pool",
121
121
  CONFIG_PAIR_LIST = "c:pair",
122
- CONFIG_COMMON_SERVICE = "c:common",
123
122
  CONFIG_TRADE_SERVICE = "c:trade",
124
123
  QUOTE_PRICE = "q:price",
125
124
  ORDER_MESSAGE = "o:msg",
@@ -274,7 +273,6 @@ export declare const get_input_out_token_fix: (poolInfo: StandardPoolInfoType, a
274
273
  inputToken: StandardTokenInfoType;
275
274
  outputToken: StandardTokenInfoType;
276
275
  };
277
- export declare const parse_trade_cmdline_args: () => TradeCommandLineArgs;
278
276
  export declare const save_trade_execution_logs: (trade_response: TradeResponseType) => Promise<void>;
279
277
  export declare const inspect_arb_local_cache: (express: any, appConfig: any) => void;
280
278
  export declare const execute_bash: (command: string, parse_json?: boolean) => Promise<any>;
package/dist/index.js CHANGED
@@ -49,7 +49,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
49
49
  };
50
50
  Object.defineProperty(exports, "__esModule", { value: true });
51
51
  exports.DATE_TIME_FORMAT_NO_WHITESPACE = exports.DATE_TIME_FORMAT_DEFAULT = exports.to_json_str = exports.DecimalUtil = exports.generateRandomNumber = exports.LOG = exports._active_log_level = exports.LOG_LEVEL = exports.REDIS_EVENT_TYPE_TRADE_INSTANCE_CHANGE = exports.REDIS_EVENT_TYPE_ORDER = exports.REDIS_EVENT_TYPE_QUOTE = exports.REDIS_EVENT_TYPE_CONFIG_CHANGE = exports.REDIS_EVENT_CHANNEL = exports.get_new_block_channel_name = exports.get_tx_result_channel_name = exports.get_wallet_raw_tx_channel_name = exports.get_order_channel_name = exports.get_quote_channel_name = exports.get_config_channel_name = exports.get_cache_key = exports.getArbEventSubscriber = exports.getArbEventPublisher = exports.getArbCache = exports.getLoadingCache = exports.getRedisClient = exports.format_order_lock_key = exports.format_unique_order_msg_id = exports.parse_unique_orderbook_id = exports.format_unique_orderbook_id = exports.format_symbol_name = exports.LOCAL_EVENT_NAME = exports.CACHE_KEY_TYPE = exports.OnChainDataSubscribeType = exports.TradeErrorCodeType = exports.SystemErrorCodeType = exports.TRADE_TYPE = exports.GROUP_ID = exports.DEX_ID = exports.CHAIN_ID = exports.STREAMING_TRANSACTION_CONFIRMED = exports.TRANSACTION_STATE_FAILED = exports.TRANSACTION_STATE_SUCCESS = exports.TRANSACTION_STATE_PROCESSING = exports.QUOTE_AMOUNT_USD_MAX = exports.QUOTE_AMOUNT_USD_MIN = exports.REGEX_HEX_PREFIX = exports.PROCESSING = exports.NOT_FOUND = exports.SUCCESS = exports.FAILED = void 0;
52
- exports.execute_bash = exports.inspect_arb_local_cache = exports.save_trade_execution_logs = exports.parse_trade_cmdline_args = exports.get_input_out_token_fix = exports.get_input_out_token = exports.calc_amount_in_token = exports.estimate_amount_in_token = exports.failed = exports.success = exports.home_dir = exports.postJSON = exports.deep_merge_object = exports.isArray = exports.isTrue = exports.deep_clone = exports.uuid = void 0;
52
+ exports.execute_bash = exports.inspect_arb_local_cache = exports.save_trade_execution_logs = exports.get_input_out_token_fix = exports.get_input_out_token = exports.calc_amount_in_token = exports.estimate_amount_in_token = exports.failed = exports.success = exports.home_dir = exports.postJSON = exports.deep_merge_object = exports.isArray = exports.isTrue = exports.deep_clone = exports.uuid = void 0;
53
53
  exports._caller = _caller;
54
54
  exports.log_trace = log_trace;
55
55
  exports.log_debug = log_debug;
@@ -76,6 +76,7 @@ exports.load_wallet = load_wallet;
76
76
  exports.load_wallet_multi = load_wallet_multi;
77
77
  exports.chunkArray = chunkArray;
78
78
  require('dotenv').config();
79
+ const core_env_1 = require("./app_config/core_env");
79
80
  const log_bus_1 = require("./log_bus");
80
81
  const bn_js_1 = __importDefault(require("bn.js"));
81
82
  const decimal_js_1 = __importDefault(require("decimal.js"));
@@ -211,7 +212,6 @@ var CACHE_KEY_TYPE;
211
212
  CACHE_KEY_TYPE["CONFIG_TOKEN_LIST"] = "c:token";
212
213
  CACHE_KEY_TYPE["CONFIG_POOL_LIST"] = "c:pool";
213
214
  CACHE_KEY_TYPE["CONFIG_PAIR_LIST"] = "c:pair";
214
- CACHE_KEY_TYPE["CONFIG_COMMON_SERVICE"] = "c:common";
215
215
  CACHE_KEY_TYPE["CONFIG_TRADE_SERVICE"] = "c:trade";
216
216
  CACHE_KEY_TYPE["QUOTE_PRICE"] = "q:price";
217
217
  CACHE_KEY_TYPE["ORDER_MESSAGE"] = "o:msg";
@@ -369,7 +369,7 @@ var LOG_LEVEL;
369
369
  LOG_LEVEL[LOG_LEVEL["WARN"] = 4] = "WARN";
370
370
  LOG_LEVEL[LOG_LEVEL["ERROR"] = 5] = "ERROR";
371
371
  })(LOG_LEVEL || (exports.LOG_LEVEL = LOG_LEVEL = {}));
372
- let _log_level = LOG_LEVEL[process.env.LOG_LEVEL];
372
+ let _log_level = LOG_LEVEL[String(process.env.LOG_LEVEL || '').toUpperCase()];
373
373
  if (_log_level) {
374
374
  console.log(`Log level`, {
375
375
  'process.env.LOG_LEVEL': process.env.LOG_LEVEL,
@@ -410,6 +410,7 @@ function log_warn(msg, data = {}, traceId = '') {
410
410
  });
411
411
  }
412
412
  function log_info(msg, data = {}, traceId = '', caller = undefined, level = LOG_LEVEL.INFO) {
413
+ var _a;
413
414
  if (level < _log_level) {
414
415
  return;
415
416
  }
@@ -423,7 +424,7 @@ function log_info(msg, data = {}, traceId = '', caller = undefined, level = LOG_
423
424
  console.log(`${getCurDateTime()} - [${level}] - [${caller.module}] - ${msg}`);
424
425
  }
425
426
  if (!isEmpty(data)) {
426
- console.dir(data, { depth: parseInt(process.env.LOG_DEPTH || '4') });
427
+ console.dir(data, { depth: Number((_a = process.env.LOG_DEPTH) !== null && _a !== void 0 ? _a : 4) });
427
428
  }
428
429
  }
429
430
  function log_error(msg, err, traceId = '', caller = undefined) {
@@ -659,13 +660,15 @@ function mkdirSync(path, recursive = false) {
659
660
  fs_1.default.mkdirSync(path, { recursive });
660
661
  }
661
662
  function getServerInfo() {
663
+ var _a;
662
664
  let region = '';
663
665
  let ip = '';
664
666
  let name = '';
665
667
  try {
666
668
  ip = getIPAddress();
667
- name = process.env.SERVER_ID;
668
- region = (process.env.SERVER_ID || '').replace('lmm-', '').split('-')[0];
669
+ const se = (_a = (0, core_env_1.getCoreEnv)().server_id) !== null && _a !== void 0 ? _a : '';
670
+ name = se;
671
+ region = (se || '').replace('lmm-', '').split('-')[0];
669
672
  }
670
673
  catch (err) {
671
674
  log_error('getServerInfo error!', err);
@@ -697,12 +700,12 @@ function load_wallet(group_id, only_pubkey = true) {
697
700
  if (!group_id) {
698
701
  throw new Error('Invalid param: group_id is empty or null !');
699
702
  }
700
- let wallet_dir = process.env.WALLET_DIR;
703
+ let wallet_dir = (0, core_env_1.getCoreEnv)().wallet_dir;
701
704
  if (!wallet_dir) {
702
705
  wallet_dir = path_1.default.join((0, exports.home_dir)(), 'data', 'keypairs');
703
706
  }
704
707
  let file_path = path_1.default.join(wallet_dir, `${group_id}.json`);
705
- log_info(`Load wallet, group_id=${group_id}, file_path=${file_path}`);
708
+ log_debug(`Load wallet, group_id=${group_id}, file_path=${file_path}`);
706
709
  let wallet = readFile(file_path, true, false);
707
710
  if (wallet.type !== 1) {
708
711
  fs_1.default.writeFileSync(file_path, JSON.stringify({ public_key: wallet.public_key, private_key: (0, crypto_1.encrypt)(wallet.private_key), type: 1 }, null, 2));
@@ -722,14 +725,14 @@ function load_wallet_multi(group_ids, only_pubkey = true) {
722
725
  if (!group_ids || group_ids.length < 1) {
723
726
  throw new Error('Invalid param: group_ids is empty or null !');
724
727
  }
725
- let wallet_dir = process.env.WALLET_DIR;
728
+ let wallet_dir = (0, core_env_1.getCoreEnv)().wallet_dir;
726
729
  if (!wallet_dir) {
727
730
  wallet_dir = path_1.default.join((0, exports.home_dir)(), 'data', 'keypairs');
728
731
  }
729
732
  let wallets = [];
730
733
  for (let group_id of group_ids) {
731
734
  let file_path = path_1.default.join(wallet_dir, `${group_id}.json`);
732
- log_info(`Load wallet, group_id=${group_id}, file_path=${file_path}`);
735
+ log_debug(`Load wallet, group_id=${group_id}, file_path=${file_path}`);
733
736
  let wallet = readFile(file_path, true, false);
734
737
  if (wallet.type !== 1) {
735
738
  fs_1.default.writeFileSync(file_path, JSON.stringify({ public_key: wallet.public_key, private_key: (0, crypto_1.encrypt)(wallet.private_key), type: 1 }, null, 2));
@@ -830,21 +833,6 @@ const get_input_out_token_fix = (poolInfo, aToB) => {
830
833
  };
831
834
  };
832
835
  exports.get_input_out_token_fix = get_input_out_token_fix;
833
- const parse_trade_cmdline_args = () => {
834
- var _a;
835
- let chain_id = process.env.CHAIN_ID || '';
836
- let input_group_id = process.env.INPUT_GROUP_ID || '';
837
- let input_pair = process.env.INPUT_PAIR || '';
838
- let input_dex_id = ((_a = process.env.INPUT_DEX_ID) === null || _a === void 0 ? void 0 : _a.toUpperCase()) || '';
839
- let cmd_args = {
840
- chain_id,
841
- input_dex_id,
842
- input_pair,
843
- input_group_id
844
- };
845
- return cmd_args;
846
- };
847
- exports.parse_trade_cmdline_args = parse_trade_cmdline_args;
848
836
  const empty_broadcast = [
849
837
  {
850
838
  rpc: {
@@ -858,9 +846,10 @@ const empty_broadcast = [
858
846
  }
859
847
  }
860
848
  ];
861
- const log_url = process.env.TRADE_LOG_SEND_URL || '';
862
- const log_type = process.env.TRADE_LOG_DATA_TYPE || '';
863
849
  const save_trade_execution_logs = (trade_response) => __awaiter(void 0, void 0, void 0, function* () {
850
+ const coreEnv = (0, core_env_1.getCoreEnv)();
851
+ const log_url = (coreEnv === null || coreEnv === void 0 ? void 0 : coreEnv.trade_log_report_cex_url) || '';
852
+ const log_type = (coreEnv === null || coreEnv === void 0 ? void 0 : coreEnv.trade_log_report_cex_data_type) || '';
864
853
  if (LOG.debug) {
865
854
  log_debug(`save_trade_execution_logs, start`, {
866
855
  log_url,
@@ -908,7 +897,7 @@ const save_trade_execution_logs = (trade_response) => __awaiter(void 0, void 0,
908
897
  msgJson: JSON.stringify(trade_logs),
909
898
  };
910
899
  if (isEmpty(log_url) || isEmpty(log_type)) {
911
- log_warn(`save_trade_execution_logs, skip!!! TRADE_LOG_SEND_URL or TRADE_LOG_DATA_TYPE is empty`);
900
+ log_warn(`save_trade_execution_logs, skip!!! TRADE_LOG_REPORT_CEX_URL or TRADE_LOG_REPORT_CEX_DATA_TYPE is empty`);
912
901
  return;
913
902
  }
914
903
  if (LOG.debug) {
@@ -10,6 +10,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.EstimateAmountInToken = void 0;
13
+ const core_env_1 = require("../app_config/core_env");
13
14
  const index_1 = require("../index");
14
15
  var tmp_token_price_cache = new Map();
15
16
  const PRICE_CACHE_EXPIRE_MILLS = 3 * 60 * 1000;
@@ -75,20 +76,19 @@ class EstimateAmountInToken {
75
76
  }
76
77
  if (!amountInToken) {
77
78
  try {
78
- let token_price_url = query_token_market_price_url;
79
- if (!token_price_url) {
80
- query_token_market_price_url = process.env.TOKEN_MARKET_PRICE_URL;
81
- }
82
- let url = `${token_price_url}?symbol=${symbol}&amount_in_usd=${amount_in_usd}`;
83
- if (index_1.LOG.debug) {
84
- (0, index_1.log_debug)(`try get market price from config-center, symbol=${symbol}, start`, { url });
85
- }
86
- let res = yield (yield fetch(url)).json();
87
- let price_with_amount = res['data'];
88
- amountInToken = price_with_amount.amount_in_token;
89
- set_tmp_market_price(price_with_amount.token_info);
90
- if (index_1.LOG.debug) {
91
- (0, index_1.log_debug)(`try get market price from config-center, symbol=${symbol}, res=`, res);
79
+ const token_price_url = query_token_market_price_url || (0, core_env_1.getCoreEnv)().token_market_price_url || '';
80
+ if (token_price_url) {
81
+ let url = `${token_price_url}?symbol=${symbol}&amount_in_usd=${amount_in_usd}`;
82
+ if (index_1.LOG.debug) {
83
+ (0, index_1.log_debug)(`try get market price from config-center, symbol=${symbol}, start`, { url });
84
+ }
85
+ let res = yield (yield fetch(url)).json();
86
+ let price_with_amount = res['data'];
87
+ amountInToken = price_with_amount.amount_in_token;
88
+ set_tmp_market_price(price_with_amount.token_info);
89
+ if (index_1.LOG.debug) {
90
+ (0, index_1.log_debug)(`try get market price from config-center, symbol=${symbol}, res=`, res);
91
+ }
92
92
  }
93
93
  }
94
94
  catch (err) {
@@ -14,6 +14,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.cache_pool_config = void 0;
16
16
  const axios_1 = __importDefault(require("axios"));
17
+ const core_env_1 = require("../app_config/core_env");
17
18
  const index_1 = require("../index");
18
19
  const service_ports_1 = require("../constants/service_ports");
19
20
  const is_not_arb_token_1 = require("../token/is_not_arb_token");
@@ -21,7 +22,8 @@ const cache_pool_config = (chain_id, valid_tokens_map, sol_pools_cache) => __awa
21
22
  (0, index_1.log_info)(`cache_pool_config start`);
22
23
  let count = 0;
23
24
  let skip_pool_list = [];
24
- const ccBase = `http://${(process.env.CONFIG_CENTER_HOST || '127.0.0.1').trim()}:${service_ports_1.SERVICE_PORT.CONFIG_CENTER_HTTP}/${chain_id}/config`;
25
+ const genv = (0, core_env_1.getCoreEnv)();
26
+ const ccBase = `http://${(genv.config_center_host || '127.0.0.1').trim()}:${service_ports_1.SERVICE_PORT.CONFIG_CENTER_HTTP}/${chain_id}/config`;
25
27
  let config_pool_url = `${ccBase}/pools`;
26
28
  for (let [dex_id, pool_list] of sol_pools_cache) {
27
29
  let batch_pools = (0, index_1.chunkArray)(pool_list, 10);
@@ -50,7 +52,7 @@ const cache_pool_config = (chain_id, valid_tokens_map, sol_pools_cache) => __awa
50
52
  router_id: null,
51
53
  fee_rate: pool.fee_rate_bps,
52
54
  quote_token: pool.quote_token,
53
- quote_amount_usd: parseInt(process.env.QUOTE_AMOUNT_USD || '100'),
55
+ quote_amount_usd: genv.quote_amount_usd,
54
56
  quote_price_decimals: 18,
55
57
  is_reverse_token: null,
56
58
  cu_limit: get_cu_limit(dex_id),
@@ -28,7 +28,6 @@ export interface QuoteResponseOptions {
28
28
  pushPriceMessage?: boolean;
29
29
  source?: string;
30
30
  depth?: PoolDepthData;
31
- tickLiquidity?: any;
32
31
  }
33
32
  export declare function on_quote_response(opts: QuoteResponseOptions): void;
34
33
  export declare function on_quote_respose(appConfig: AppConfig, pool_info: StandardPoolInfoType, quote_amount_usd: number, _execution_price: number, stream_time: number, quote_start_time: number, slot_info: string, result: [QuoteResultType, QuoteResultType, number], txid: string, push_price_message?: boolean, source?: string, depth?: PoolDepthData): void;
@@ -6,10 +6,8 @@ const analyze_1 = require("../analyze");
6
6
  const log_quote_price_1 = require("./log_quote_price");
7
7
  const publish_quote_price_1 = require("./publish_quote_price");
8
8
  const to_price_message_1 = require("./to_price_message");
9
- const TICK_LIQUIDITY_INTERVAL_MS = parseInt(process.env.TICK_CACHE_FORCE_FULL_REFRESH_INTERVAL || '60000', 10);
10
- const _tickLiquidityLastPush = new Map();
11
9
  function on_quote_response(opts) {
12
- const { appConfig, poolInfo, quoteAmountUsd, streamTime, quoteStartTime, blockNumber, quotes, txid, pushPriceMessage = true, source = '', depth, tickLiquidity, } = opts;
10
+ const { appConfig, poolInfo, quoteAmountUsd, streamTime, quoteStartTime, blockNumber, quotes, txid, pushPriceMessage = true, source = '', depth, } = opts;
13
11
  const quoteEndTime = Date.now();
14
12
  const quoteAskPrice = Number(quotes[0].price);
15
13
  const quoteBidPrice = Number(quotes[1].price);
@@ -28,26 +26,15 @@ function on_quote_response(opts) {
28
26
  (0, publish_quote_price_1.publish_quote_price)(appConfig, price_msg);
29
27
  }
30
28
  (0, log_quote_price_1.log_quote_price)(String(blockNumber), price_msg, txid);
31
- (0, analyze_1.report_trade_analyze_data)('PriceMessageType', Object.assign(Object.assign({}, price_msg), { quote_source: { slot: String(blockNumber), block: null, txid } }));
29
+ (0, analyze_1.report_data_to_analyze)('PriceMessageType', Object.assign(Object.assign({}, price_msg), { quote_source: { slot: String(blockNumber), block: null, txid } }));
32
30
  if (depth) {
33
- (0, analyze_1.report_trade_analyze_data)('DepthLevels', {
31
+ (0, analyze_1.report_data_to_analyze)('DepthLevels', {
34
32
  price_id: price_msg.price_id,
35
33
  unique_orderbook_id: price_msg.unique_orderbook_id,
36
34
  pair: price_msg.pair,
37
35
  depth
38
36
  });
39
37
  }
40
- if (tickLiquidity) {
41
- const poolAddr = String(price_msg.pool_id || '').trim().toLowerCase();
42
- const now = Date.now();
43
- const lastPush = _tickLiquidityLastPush.get(poolAddr) || 0;
44
- if (now - lastPush >= TICK_LIQUIDITY_INTERVAL_MS) {
45
- _tickLiquidityLastPush.set(poolAddr, now);
46
- tickLiquidity.pair = price_msg.pair;
47
- tickLiquidity.protocolId = price_msg.dex_id;
48
- (0, analyze_1.report_trade_analyze_data)('TickLiquidity', tickLiquidity);
49
- }
50
- }
51
38
  })
52
39
  .catch(err => {
53
40
  console.error(`[on_quote_response] error: ${(err === null || err === void 0 ? void 0 : err.message) || err}`);
@@ -16,6 +16,7 @@ exports.get_quote_token_decimals = void 0;
16
16
  exports.to_price_message = to_price_message;
17
17
  exports.normalize_pair_name = normalize_pair_name;
18
18
  const decimal_js_1 = __importDefault(require("decimal.js"));
19
+ const core_env_1 = require("../app_config/core_env");
19
20
  const uuid_1 = require("uuid");
20
21
  const __1 = require("..");
21
22
  const get_quote_token_decimals = (pool_info) => {
@@ -51,7 +52,7 @@ function to_price_message(appConfig_1, quote_amount_usd_1, tx_price_1, quote_ask
51
52
  price: bid_price,
52
53
  quantity: quote_amount_usd
53
54
  };
54
- const cexBps = parseInt(process.env.DEPTH_CEX_BPS || '20');
55
+ const cexBps = (0, core_env_1.getCoreEnv)().depth_cex_bps;
55
56
  const askDepth = (_a = depth === null || depth === void 0 ? void 0 : depth.ask) === null || _a === void 0 ? void 0 : _a[cexBps];
56
57
  const bidDepth = (_b = depth === null || depth === void 0 ? void 0 : depth.bid) === null || _b === void 0 ? void 0 : _b[cexBps];
57
58
  askData.depth_bps = cexBps;
@@ -28,6 +28,7 @@ export declare class RedisClient {
28
28
  ltrim(key: string, start: number, stop: number): Promise<string>;
29
29
  ping(): Promise<string>;
30
30
  type(key: string): Promise<string>;
31
+ eval(script: string, keys: string[], args: string[]): Promise<any>;
31
32
  multi(): import("@redis/client/dist/lib/client/multi-command").RedisClientMultiCommandType<{
32
33
  graph: {
33
34
  CONFIG_GET: typeof import("@redis/graph/dist/commands/CONFIG_GET");
@@ -169,6 +169,12 @@ class RedisClient {
169
169
  return yield client.type(key);
170
170
  });
171
171
  }
172
+ eval(script, keys, args) {
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ const client = yield this.ensureClient();
175
+ return yield client.eval(script, { keys, arguments: args });
176
+ });
177
+ }
172
178
  multi() {
173
179
  return this.redis_client.multi();
174
180
  }
@@ -226,9 +232,8 @@ class RedisClient {
226
232
  }
227
233
  finally {
228
234
  if (acquired) {
229
- const releaseDelay = parseInt(process.env.NONCE_LOCK_RELEASE_DELAY_MS || String(release_lock_delay_ms));
230
- if (releaseDelay > 0) {
231
- yield (0, index_1.sleep)(releaseDelay);
235
+ if (release_lock_delay_ms > 0) {
236
+ yield (0, index_1.sleep)(release_lock_delay_ms);
232
237
  }
233
238
  this.releaseLock(lock_key, lock_value);
234
239
  (0, index_1.log_info)(`[Lock] withLock ok: key=${lock_key}, retries=${retries}, wait=${getLockTime - firstTryTime}ms, hold=${Date.now() - getLockTime}ms`);
@@ -10,12 +10,14 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.getRedisConnection = getRedisConnection;
13
+ const core_env_1 = require("../app_config/core_env");
13
14
  const redis_1 = require("redis");
14
15
  let redisClient = null;
15
16
  let connectPromise = null;
16
17
  function createConnection() {
17
- const host = process.env.REDIS_HOST || '127.0.0.1';
18
- const port = process.env.REDIS_PORT || '6379';
18
+ const coreEnv = (0, core_env_1.getCoreEnv)();
19
+ const host = coreEnv.redis_host || '127.0.0.1';
20
+ const port = String(coreEnv.redis_port || '6379');
19
21
  const url = `redis://${host}:${port}`;
20
22
  console.log(`[Redis] connecting to ${url}`);
21
23
  const client = (0, redis_1.createClient)({ url });
@@ -14,12 +14,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  exports.cache_token_config = void 0;
16
16
  const axios_1 = __importDefault(require("axios"));
17
+ const core_env_1 = require("../app_config/core_env");
17
18
  const index_1 = require("../index");
18
19
  const service_ports_1 = require("../constants/service_ports");
19
20
  const is_not_arb_token_1 = require("./is_not_arb_token");
20
21
  const cache_token_config = (chain_id, valid_tokens_map) => __awaiter(void 0, void 0, void 0, function* () {
21
22
  (0, index_1.log_info)(`cache_token_config start`);
22
- const ccBase = `http://${(process.env.CONFIG_CENTER_HOST || '127.0.0.1').trim()}:${service_ports_1.SERVICE_PORT.CONFIG_CENTER_HTTP}/${chain_id}/config`;
23
+ const genv = (0, core_env_1.getCoreEnv)();
24
+ const ccBase = `http://${(genv.config_center_host || '127.0.0.1').trim()}:${service_ports_1.SERVICE_PORT.CONFIG_CENTER_HTTP}/${chain_id}/config`;
23
25
  let config_token_url = `${ccBase}/tokens`;
24
26
  let count = 0;
25
27
  let batch_symbols = (0, index_1.chunkArray)(Array.from(valid_tokens_map.keys()), 20);
@@ -4,17 +4,18 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.get_fixed_symbol_address = void 0;
7
- require('dotenv').config();
8
7
  const os_1 = __importDefault(require("os"));
8
+ const core_env_1 = require("../app_config/core_env");
9
9
  const path_1 = __importDefault(require("path"));
10
10
  const index_1 = require("../index");
11
11
  let _first_load_logged = false;
12
12
  const get_fixed_symbol_address = () => {
13
- const chain_id = process.env.CHAIN_ID;
13
+ const coreEnv = (0, core_env_1.getCoreEnv)();
14
+ const chain_id = coreEnv.chain_id;
14
15
  if (!chain_id) {
15
16
  return [];
16
17
  }
17
- const filepath = process.env.BSC_FIXED_SYMBOL_ADDRESS_FILE ||
18
+ const filepath = coreEnv.fixed_symbol_address_file ||
18
19
  path_1.default.join(os_1.default.homedir(), 'data', 'onchain_data', chain_id.toLowerCase(), 'fixed_symbol_address.json');
19
20
  let list = [];
20
21
  try {
@@ -12,9 +12,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.get_bsc_token_price_info = get_bsc_token_price_info;
13
13
  require('dotenv').config();
14
14
  const index_1 = require("../../index");
15
+ const defi_llama_1 = require("./defi_llama");
15
16
  const gecko_terminal_1 = require("./gecko_terminal");
16
17
  const price_cache_1 = require("./price_cache");
17
- const defi_llama_1 = require("./defi_llama");
18
18
  function get_bsc_token_price_info(addresses) {
19
19
  return __awaiter(this, void 0, void 0, function* () {
20
20
  addresses = addresses.map(addr => addr.toLowerCase());
@@ -1,3 +1,3 @@
1
- import { FormattedTokenPrice } from "../types";
2
1
  import { EvmChainInfoType } from '../../chains';
2
+ import { FormattedTokenPrice } from "../types";
3
3
  export declare function get_eth_token_price_info(evm_chain_info: EvmChainInfoType, addresses: string[]): Promise<Map<string, FormattedTokenPrice>>;
@@ -16,9 +16,9 @@ exports.get_eth_token_price_info = get_eth_token_price_info;
16
16
  require('dotenv').config();
17
17
  const axios_1 = __importDefault(require("axios"));
18
18
  const index_1 = require("../../index");
19
+ const defi_llama_1 = require("./defi_llama");
19
20
  const gecko_terminal_1 = require("./gecko_terminal");
20
21
  const price_cache_1 = require("./price_cache");
21
- const defi_llama_1 = require("./defi_llama");
22
22
  function get_eth_token_price_info(evm_chain_info, addresses) {
23
23
  return __awaiter(this, void 0, void 0, function* () {
24
24
  addresses = addresses.map(addr => addr.toLowerCase());