server_data_statistics.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. const logger = require('../model/logger')
  2. var remote_config_db = require("../model/db/remote_config_db");
  3. var collect_coins_db = require("../model/db/collect_coins_db");
  4. var withdraw_db = require("../model/db/withdraw_db");
  5. var moralis = require("../model/moralis_sdk");
  6. var utils = require("../model/utils");
  7. const axios = require('axios');
  8. var { account_config } = require('../config/config.js');
  9. const { max } = require('moment');
  10. // 拿到飞书写入的 token
  11. const feishu_write_table_token_url = 'https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal'
  12. const feishu_write_table_data_url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg/values_batch_update'
  13. const feishu_insert_table_url = 'https://open.feishu.cn/open-apis/sheets/v2/spreadsheets/shtcnp6zbrsep1Sz3Cvk7NXRpDg/insert_dimension_range'
  14. const reportTime = '08:00:00'
  15. //########################################### 出入金数据统计 ########################################
  16. const http_request_get = async (data) => {
  17. var host = account_config.STATISTICS_URL
  18. var path = data
  19. var url = host + path
  20. logger.log('http_request_get', url)
  21. return new Promise(response => {
  22. axios.get(url)
  23. .then(res => {
  24. logger.log('res=>', res.status, res.data);
  25. if (res.data.code == 0) {
  26. response(res.data)
  27. } else {
  28. response({
  29. code: 0,
  30. msg: err.toString(),
  31. data: {
  32. canNotWithdrawUSD: '0',
  33. canWithdrawUSD: '0',
  34. incomeUSDTotal: '0',
  35. incomeUSDFee: '0'
  36. }
  37. })
  38. }
  39. }).catch(err => {
  40. logger.error('http_request_get', err.toString(), url.toString());
  41. response({
  42. code: -1,
  43. msg: err.toString(),
  44. data: {
  45. canNotWithdrawUSD: '0',
  46. canWithdrawUSD: '0',
  47. incomeUSDTotal: '0',
  48. incomeUSDFee: '0'
  49. }
  50. })
  51. });
  52. })
  53. }
  54. async function computeAddressPrice(total_in_coins) {
  55. //计算总的价格
  56. for (key of total_in_coins.keys()) {
  57. var item = total_in_coins.get(key)
  58. var amount = item.amount
  59. var usdPrice = item.usdPrice
  60. if (key == '0x0000000000000000000000000000000000000000') {
  61. item.totalUsdPrice = parseFloat(amount) / parseFloat(10 ** 18) * parseFloat(usdPrice)
  62. } else {
  63. var decimals = 18
  64. try {
  65. decimals = await redis.readAppendRedis('REDIS_ERC20_CONTRACT_DECIMALS', item.chain, key.toLowerCase())
  66. logger.info('REDIS_ERC20_CONTRACT_DECIMALS', key.toLowerCase(), decimals)
  67. } catch (error) {
  68. decimals = 18
  69. }
  70. item.totalUsdPrice = parseFloat(amount) / parseFloat(10 ** decimals) * parseFloat(usdPrice)
  71. }
  72. }
  73. }
  74. function getBscEnv() {
  75. var bsc_env
  76. switch (process.env.NODE_ENV) {
  77. case 'dev':
  78. case 'test':
  79. // bsc_env = 'bsc_testnet'
  80. bsc_env = 'bsc_mainnet'
  81. break
  82. case 'prd':
  83. bsc_env = 'bsc_mainnet'
  84. break
  85. default:
  86. bsc_env = 'bsc_mainnet'
  87. break
  88. }
  89. return bsc_env;
  90. }
  91. async function filterCollectCoinsLists(collect_ret, filterTypt) {
  92. const total_in_coins = new Map();
  93. var total_gas_fee = 0
  94. for (let index = 0; index < collect_ret.results.length; index++) {
  95. const element = collect_ret.results[index];
  96. if (element.chain == null || element.chain == filterTypt) {
  97. var before_gas_fee = element.before_gas_fee ? BigInt(element.before_gas_fee) : element.chain == 'czz' ? BigInt(21000 * 2000000000) : BigInt(21000 * 5000000000)
  98. total_gas_fee = BigInt(element.total_gas_fee) + BigInt(before_gas_fee) + BigInt(total_gas_fee)
  99. if (element.transfers) {
  100. var opts = JSON.parse(element.transfers)
  101. for (let index = 0; index < opts.length; index++) {
  102. const transfers = opts[index];
  103. if (transfers.chain == filterTypt) {
  104. var address = transfers.contractAddress ? transfers.contractAddress : '0x0000000000000000000000000000000000000000'
  105. if (total_in_coins.get(address) != null) {
  106. var ins = total_in_coins.get(address)
  107. ins.amount = BigInt(ins.amount) + BigInt(transfers.amount)
  108. total_in_coins.set(address, ins)
  109. } else {
  110. total_in_coins.set(address, {
  111. amount: BigInt(transfers.amount), //总入金
  112. usdPrice: transfers.usdPrice,
  113. chain: transfers.chain,
  114. })
  115. }
  116. }
  117. }
  118. }
  119. }
  120. }
  121. //计算总的价格
  122. await computeAddressPrice(total_in_coins)
  123. var bsc_env = getBscEnv()
  124. //获取 total gas
  125. try {
  126. if (total_in_coins.size > 0) {
  127. switch (filterTypt) {
  128. case 'bsc_testnet':
  129. case 'bsc_mainnet':
  130. var price = await moralis.getAllTotkenPrice({ chain: bsc_env })
  131. if (typeof price === 'string') {
  132. price = JSON.parse(price)
  133. }
  134. var bnbPriceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price)
  135. total_gas_fee = parseFloat(total_gas_fee) / parseFloat(10 ** 18) * parseFloat(bnbPriceItem.usdPrice)
  136. logger.info('new-total_gas_fee ', total_gas_fee, bnbPriceItem)
  137. break
  138. case 'czz':
  139. var price = await moralis.getAllTotkenPrice({ chain: 'czz' })
  140. if (typeof price === 'string') {
  141. price = JSON.parse(price)
  142. }
  143. var czzPriceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price)
  144. total_gas_fee = parseFloat(total_gas_fee) / parseFloat(10 ** 18) * parseFloat(czzPriceItem.usdPrice)
  145. logger.info('new-total_gas_fee czz', total_gas_fee, czzPriceItem)
  146. break
  147. }
  148. }
  149. } catch (error) {
  150. logger.error('total_gas_fee', error)
  151. }
  152. if (!total_in_coins.get('0x0000000000000000000000000000000000000000')) {
  153. total_in_coins.set('0x0000000000000000000000000000000000000000', {
  154. amount: 0,
  155. usdPrice: 0,
  156. chain: filterTypt,
  157. totalUsdPrice: 0
  158. })
  159. }
  160. return {
  161. map: total_in_coins,
  162. totalGasFee: total_gas_fee //总入金所消耗的 gas fee
  163. }
  164. }
  165. function sumBalance(map) {
  166. var balances = 0;
  167. for (key of map.keys()) {
  168. balances += map.get(key).totalUsdPrice
  169. }
  170. return balances
  171. }
  172. async function getSLGas() {
  173. var maps = new Map()
  174. var collect_ret = await collect_coins_db.query_collect_total_fee(null, null);
  175. for (let index = 0; index < collect_ret.results.length; index++) {
  176. var element = collect_ret.results[index]
  177. try {
  178. if (element.prestore_gas_fee && typeof element.prestore_gas_fee === 'string') {
  179. var pre_gas_obj = JSON.parse(element.prestore_gas_fee)
  180. var bgf = element.before_gas_fee
  181. if (!bgf && pre_gas_obj.amount) {
  182. bgf = pre_gas_obj.amount
  183. }
  184. // logger.info('getSLGas item', bgf, pre_gas_obj, element)
  185. if (maps.get(pre_gas_obj.chain)) {
  186. maps.get(pre_gas_obj.chain).sl_gas_fee = BigInt(maps.get(pre_gas_obj.chain).sl_gas_fee) + (BigInt(pre_gas_obj.amount) - BigInt(bgf))
  187. } else {
  188. maps.set(pre_gas_obj.chain, {
  189. sl_gas_fee: BigInt(pre_gas_obj.amount) - BigInt(bgf)
  190. })
  191. }
  192. }
  193. } catch (error) {
  194. logger.error('getSLGas error', error.toString())
  195. }
  196. }
  197. var bsc_env = getBscEnv()
  198. logger.info('getSLGas', maps)
  199. var bsc_sl
  200. var czz_sl
  201. for (key of maps.keys()) {
  202. var item = maps.get(key)
  203. switch (key) {
  204. case "bsc_mainnet":
  205. case "bsc_testnet":
  206. var price = await moralis.getAllTotkenPrice({ chain: bsc_env })
  207. if (typeof price === 'string') {
  208. price = JSON.parse(price)
  209. }
  210. var bnbPriceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price)
  211. bsc_sl = parseFloat(item.sl_gas_fee) / parseFloat(10 ** 18) * parseFloat(bnbPriceItem.usdPrice)
  212. break
  213. case "czz":
  214. var price = await moralis.getAllTotkenPrice({ chain: 'czz' })
  215. if (typeof price === 'string') {
  216. price = JSON.parse(price)
  217. }
  218. var czzPriceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price)
  219. czz_sl = parseFloat(item.sl_gas_fee) / parseFloat(10 ** 18) * parseFloat(czzPriceItem.usdPrice)
  220. break
  221. }
  222. }
  223. return {
  224. bsc: bsc_sl,
  225. czz: czz_sl,
  226. total: bsc_sl + czz_sl
  227. }
  228. }
  229. async function getCollectCoinsOutInfo(startTime, endTime) {
  230. var collect_ret = await collect_coins_db.query_collect_total_fee(startTime, endTime);
  231. logger.info('getCollectCoinsOutInfo query_collect_total_fee', startTime, endTime)
  232. var bsc_env = getBscEnv()
  233. var bsc_envnet = await filterCollectCoinsLists(collect_ret, bsc_env)
  234. logger.info('getCollectCoinsOutInfo bsc_env', bsc_env, bsc_envnet)
  235. var czz = await filterCollectCoinsLists(collect_ret, 'czz')
  236. logger.info('getCollectCoinsOutInfo czz', czz)
  237. logger.info('getCollectCoinsOutInfo total ', bsc_envnet.totalGasFee, czz.totalGasFee)
  238. return {
  239. bsc: bsc_envnet.map,
  240. czz: czz.map,
  241. totalGasFee: parseFloat(bsc_envnet.totalGasFee) + parseFloat(czz.totalGasFee), //总归集消耗的 gas fee
  242. totalInFee: sumBalance(bsc_envnet.map) + sumBalance(czz.map),//总入金美元
  243. }
  244. }
  245. async function filterWithdrawTotalOutFee(chain_id, filterItem) {
  246. const withdraw_out_map = new Map();
  247. var price = await moralis.getAllTotkenPrice({ chain: chain_id + "" })
  248. if (typeof price === 'string') {
  249. price = JSON.parse(price)
  250. }
  251. for (let index = 0; index < filterItem.length; index++) {
  252. const element = filterItem[index];
  253. if (element.chain_id == chain_id) {
  254. var address = element.type == 'native' ? '0x0000000000000000000000000000000000000000' : element.contract_address
  255. if (withdraw_out_map.get(address) != null) {
  256. var item = withdraw_out_map.get(address)
  257. item.totalAmount = BigInt(element.amount) + BigInt(item.totalAmount)
  258. } else {
  259. var priceItem = moralis.findTokenPriceItem(address, price)
  260. var decimals = 18
  261. if (key == '0x0000000000000000000000000000000000000000') {
  262. item.totalUsdPrice = parseFloat(amount) / parseFloat(10 ** 18) * parseFloat(usdPrice)
  263. } else {
  264. try {
  265. decimals = await redis.readAppendRedis('REDIS_ERC20_CONTRACT_DECIMALS', chain_id + "", address.toLowerCase())
  266. logger.info('REDIS_ERC20_CONTRACT_DECIMALS', key.toLowerCase(), decimals)
  267. } catch (error) {
  268. decimals = 18
  269. }
  270. }
  271. withdraw_out_map.set(address, {
  272. totalAmount: BigInt(element.amount), //出金数量
  273. usdPrice: priceItem.usdPrice,
  274. chain: element.chain_id,
  275. decimals: decimals,
  276. })
  277. }
  278. }
  279. }
  280. logger.info('filterWithdrawTotalOutFee', withdraw_out_map, chain_id)
  281. return withdraw_out_map
  282. }
  283. async function getWithdrawOutInfo(startTime, endTime) {
  284. if (startTime && endTime) {
  285. startTime = new Date(startTime).getTime()
  286. endTime = new Date(endTime).getTime()
  287. }
  288. var withdraw_ret = await withdraw_db.getWidthdrawTotalFee(startTime, endTime)
  289. const withdraw_gas_map = new Map();
  290. for (let index = 0; index < withdraw_ret.length; index++) {
  291. const element = withdraw_ret[index];
  292. if (element.gas_price && element.gas_limit)
  293. var total_gas_fee2 = (BigInt(element.gas_price) * BigInt(element.gas_limit))
  294. if (withdraw_gas_map.get(element.chain_id) != null) {
  295. withdraw_gas_map.get(element.chain_id).total_gas_fee = BigInt(withdraw_gas_map.get(element.chain_id).total_gas_fee) + BigInt(total_gas_fee2)
  296. } else {
  297. withdraw_gas_map.set(element.chain_id,
  298. {
  299. total_gas_fee: BigInt(total_gas_fee2),
  300. total_withdraw: null
  301. }
  302. )
  303. }
  304. }
  305. var bsc_env = getBscEnv()
  306. //计算总消耗的 gas
  307. var keys = withdraw_gas_map.keys();
  308. var total_gas_fee = 0
  309. for (key of keys) {
  310. // console.log(key, withdraw_gas_map.get(key)); // map.get(key)可得value值。
  311. var value = withdraw_gas_map.get(key).total_gas_fee
  312. //获取币价
  313. try {
  314. if (key == 2019) {
  315. var price = await moralis.getAllTotkenPrice({ chain: 'czz' })
  316. if (typeof price === 'string') {
  317. price = JSON.parse(price)
  318. }
  319. var czzPriceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price)
  320. total_gas_fee += parseFloat(value) / parseFloat(10 ** 18) * parseFloat(czzPriceItem.usdPrice)
  321. logger.info('new-total_gas_fee czz', total_gas_fee, czzPriceItem)
  322. } else {
  323. var price = await moralis.getAllTotkenPrice({ chain: bsc_env })
  324. if (typeof price === 'string') {
  325. price = JSON.parse(price)
  326. }
  327. var bnbPriceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price)
  328. total_gas_fee += parseFloat(value) / parseFloat(10 ** 18) * parseFloat(bnbPriceItem.usdPrice)
  329. logger.info('new-total_gas_fee bsc', total_gas_fee, bnbPriceItem)
  330. }
  331. } catch (error) {
  332. logger.error('total_gas_fee', error)
  333. }
  334. }
  335. var withdrawout = 0
  336. if (!startTime && !endTime) {
  337. for (key of withdraw_gas_map.keys()) {
  338. try {
  339. var outs = await filterWithdrawTotalOutFee(key, withdraw_ret)
  340. withdraw_gas_map.get(key).total_withdraw = outs
  341. // logger.error('withdraw_gas_map.get(key).total_withdraw outs', outs)
  342. if (outs) {
  343. for (ckey of outs.keys()) {
  344. var item = outs.get(ckey);
  345. withdrawout = parseFloat(withdrawout) + (parseFloat(item.totalAmount) / parseFloat(10 ** item.decimals) * parseFloat(item.usdPrice))
  346. }
  347. }
  348. } catch (error) {
  349. logger.error('filterWithdrawTotalOutFee error', error.toString())
  350. }
  351. }
  352. }
  353. return {
  354. outmap: withdraw_gas_map,
  355. totalGasFee: total_gas_fee,
  356. totalWithdraw: withdrawout
  357. };
  358. }
  359. async function updateBalance(obj, type) {
  360. var price
  361. if (type == 'bsc') {
  362. var bsc_env = getBscEnv()
  363. price = await moralis.getAllTotkenPrice({ chain: bsc_env })
  364. } else if (type == 'czz') {
  365. price = await moralis.getAllTotkenPrice({ chain: 'czz' })
  366. }
  367. if (typeof price === 'string') {
  368. price = JSON.parse(price)
  369. }
  370. var priceItem = moralis.findTokenPriceItem('0x0000000000000000000000000000000000000000', price, price)
  371. if (!obj.native.balance) {
  372. obj.native.balance = '0'
  373. }
  374. if (obj.native) {
  375. obj.native.usdPrice = parseFloat(obj.native.balance) / parseFloat(10 ** 18) * priceItem.usdPrice
  376. logger.info('findTokenPriceItem 0x0000000000000000000000000000000000000000 ', obj, priceItem, type)
  377. }
  378. var tokenTotal = 0
  379. if (obj.other && Array.isArray(obj.other)) {
  380. for (let index = 0; index < obj.other.length; index++) {
  381. const element = obj.other[index];
  382. priceItem = moralis.findTokenPriceItem(element.token_address, price)
  383. logger.info('findTokenPriceItem element ', priceItem, element.token_address)
  384. if (priceItem) {
  385. if (!element.decimals || element.decimals == 0)
  386. element.decimals = 18
  387. element.usdPrice = parseFloat(element.balance) / parseFloat(10 ** element.decimals) * priceItem.usdPrice
  388. tokenTotal += element.usdPrice
  389. }
  390. }
  391. }
  392. return {
  393. nativeTotal: obj.native.usdPrice,
  394. tokenTotal: tokenTotal,
  395. total: parseFloat(obj.native.usdPrice) + parseFloat(tokenTotal)
  396. }
  397. }
  398. async function getAllBalance() {
  399. var bsc_env = getBscEnv()
  400. var company = await moralis.queryCompanyInfoFromId(0)
  401. logger.info('getAllBalance company', company)
  402. var bsc_balance = await moralis.getAccountAllCoins({
  403. chain: bsc_env,
  404. address: company.user_address
  405. })
  406. logger.info('getAccountAllCoins bsc_balance', bsc_balance)
  407. var bscb = await updateBalance(bsc_balance, 'bsc')
  408. logger.info('getAccountAllCoins updateBalance bscb', bscb)
  409. var czz_balance = await moralis.getAccountAllCoins({
  410. chain: 'czz',
  411. address: company.user_address
  412. })
  413. logger.info('getAccountAllCoins czz_balance', czz_balance)
  414. var czzb = await updateBalance(czz_balance, 'czz')
  415. logger.info('getAccountAllCoins updateBalance czzb', czzb)
  416. return {
  417. bsc: bscb,
  418. czz: czzb,
  419. totalBalance: bscb.total + czzb.total
  420. }
  421. }
  422. /**
  423. * 获取时间段总支出的 gas fee
  424. * @param {*} startTime
  425. * @param {*} endTime
  426. */
  427. async function getStatisticsInfo() {
  428. // //今日
  429. var startTime = utils.getLastDay('YYYY-MM-DD') + " 00:00:00"
  430. var endTime = utils.getLastDay('YYYY-MM-DD') + " 23:59:59"
  431. logger.info('getTotalOutGasFee', startTime, endTime)
  432. //归集
  433. var collectCoinsOut = await getCollectCoinsOutInfo(startTime, endTime)
  434. logger.info('getCollectCoinsOutInfo collectCoinsOut', collectCoinsOut)
  435. //提币
  436. var withdrawOut = await getWithdrawOutInfo(startTime, endTime)
  437. logger.info('getWithdrawOutInfo withdrawOut ', withdrawOut)
  438. var data = await http_request_get(utils.getLastDay('YYYYMMDD'))
  439. //历史,总的
  440. //归集
  441. var totalCollectCoinsOut = await getCollectCoinsOutInfo(null, null)
  442. logger.info('totalCollectCoinsOut ', totalCollectCoinsOut)
  443. //提币
  444. var totalWithdrawOut = await getWithdrawOutInfo(null, null)
  445. logger.info('totalWithdrawOut ', totalWithdrawOut)
  446. //获取当前账户总余额
  447. var curBalances = await getAllBalance()
  448. logger.info('getAllBalance ', curBalances)
  449. //获取散落 gas
  450. var totalSLGas = await getSLGas()
  451. logger.info('getSLGas ret', totalSLGas)
  452. return {
  453. updateTime: utils.getLastDay('YYYY-MM-DD'),
  454. todayTotalProfit: parseFloat(data.data.incomeUSDTotal) - parseFloat(collectCoinsOut.totalGasFee + withdrawOut.totalGasFee),
  455. todayTotalOutGasFee: collectCoinsOut.totalGasFee + withdrawOut.totalGasFee, //今日总支出的 gas fee
  456. canNotWithdrawUSD: parseFloat(data.data.canNotWithdrawUSD), //不可提现余额
  457. canWithdrawUSD: parseFloat(data.data.canWithdrawUSD), //可提现余额
  458. todayIncomeUSDTotal: parseFloat(data.data.incomeUSDTotal), //今日总收入
  459. todayIncomeUSDFee: parseFloat(data.data.incomeUSDFee), //今日固定收入
  460. totalOutGasFee: totalCollectCoinsOut.totalGasFee + totalWithdrawOut.totalGasFee, //总支出 gas fee
  461. totalWithdrawGasFee: totalWithdrawOut.totalGasFee, //总提币 gas fee
  462. totalCollectCoinsGasFee: totalCollectCoinsOut.totalGasFee, //总归集 gas fee
  463. totalInFee: totalCollectCoinsOut.totalInFee, //总入金
  464. totalNativeInFee: {
  465. bsc: totalCollectCoinsOut.bsc.get('0x0000000000000000000000000000000000000000').totalUsdPrice,
  466. czz: totalCollectCoinsOut.czz.get('0x0000000000000000000000000000000000000000').totalUsdPrice
  467. }, //总 native 入金
  468. totalOutFee: totalWithdrawOut.totalWithdraw, //总出金
  469. totalBalances: curBalances.totalBalance, //总余额
  470. ylGasBalance: { //预留 gas 费余额 native 总余额 - 总入金
  471. bsc: curBalances.bsc.nativeTotal - totalCollectCoinsOut.bsc.get('0x0000000000000000000000000000000000000000').totalUsdPrice,
  472. czz: curBalances.czz.nativeTotal - totalCollectCoinsOut.czz.get('0x0000000000000000000000000000000000000000').totalUsdPrice,
  473. total: (curBalances.bsc.nativeTotal - totalCollectCoinsOut.bsc.get('0x0000000000000000000000000000000000000000').totalUsdPrice) + (curBalances.czz.nativeTotal - totalCollectCoinsOut.czz.get('0x0000000000000000000000000000000000000000').totalUsdPrice)
  474. },
  475. slGasBalance: totalSLGas, //散落 gas 费余额 充值 0.5 gas - 使用 0.3 gas= 散落 0.2gas
  476. }
  477. }
  478. function timeoutFunc(config, func) {
  479. config.runNow && func()
  480. let nowTime = new Date().getTime()
  481. let timePoints = config.time.split(':').map(i => parseInt(i))
  482. let recent = new Date().setHours(...timePoints)
  483. recent >= nowTime || (recent += 24 * 3600000)
  484. setTimeout(() => {
  485. func()
  486. setInterval(func, config.interval * 3600000)
  487. }, recent - nowTime)
  488. }
  489. const getFeishuToken = async (params) => {
  490. return new Promise(resolve => {
  491. axios.post(feishu_write_table_token_url,
  492. {
  493. app_id: "cli_a223f015abbad00e",
  494. app_secret: "DMCF6tBwIpeOQPnWrFUMYd6tmjb53C4n"
  495. },
  496. {
  497. timeout: 1 * 60 * 1000,
  498. headers: {
  499. 'Content-Type': "application/json; charset=utf-8"
  500. }
  501. })
  502. .then(res => {
  503. logger.log('getFeishuToken res=>', res.status, res.data);
  504. resolve(res.data)
  505. }).catch(err => {
  506. logger.error('getFeishuToken error ', JSON.stringify(err));
  507. resolve(JSON.stringify(err))
  508. });
  509. })
  510. }
  511. function writeTable(app_token, data) {
  512. logger.info('writeTable', data)
  513. var body = {
  514. 'valueRanges': [
  515. {
  516. 'range': '0pRQpu!A2:C2',
  517. 'values': [
  518. [data.totalCollectCoinsGasFee, //归集总 gas
  519. data.totalWithdrawGasFee, //提币总 gas
  520. data.totalOutGasFee], //总支出 gas
  521. ]
  522. },
  523. {
  524. 'range': '1ygrMB!A2:B2',
  525. 'values': [
  526. [
  527. data.totalInFee, //总入金
  528. data.totalOutFee,//总出金
  529. ],
  530. ]
  531. },
  532. {
  533. 'range': 'BMjMDr!A3:J3',
  534. 'values': [
  535. [
  536. data.updateTime, //更新时间
  537. data.todayTotalProfit,//今日总利润
  538. data.todayIncomeUSDTotal,//今日总收入
  539. data.todayIncomeUSDFee,//今日固定手续费收入
  540. data.todayTotalOutGasFee,//今日总 gas 支出
  541. data.totalBalances, //总余额
  542. data.canNotWithdrawUSD, //不可提现余额
  543. data.canWithdrawUSD,//可提现余额
  544. data.ylGasBalance.total,//预留 gas
  545. data.slGasBalance.total,//散落 gas
  546. ],
  547. ]
  548. }
  549. ]
  550. }
  551. return new Promise(resolve => {
  552. axios.post(feishu_write_table_data_url,
  553. body,
  554. {
  555. timeout: 1 * 60 * 1000,
  556. headers: {
  557. 'Content-Type': "application/json; charset=utf-8",
  558. 'Authorization': 'Bearer ' + app_token
  559. }
  560. })
  561. .then(res => {
  562. logger.log('writeTable res=>', res.status, res.data);
  563. resolve(res.data)
  564. }).catch(err => {
  565. logger.error('writeTable error ', JSON.stringify(err));
  566. resolve(JSON.stringify(err))
  567. });
  568. })
  569. }
  570. async function insertTableRows(app_token) {
  571. var body = {
  572. dimension: {
  573. sheetId: 'BMjMDr',
  574. majorDimension: 'ROWS',
  575. startIndex: 2,
  576. endIndex: 3,
  577. },
  578. inheritStyle: 'AFTER'
  579. }
  580. return new Promise(resolve => {
  581. axios.post(feishu_insert_table_url,
  582. JSON.stringify(body),
  583. {
  584. timeout: 1 * 60 * 1000,
  585. headers: {
  586. 'Content-Type': "application/json; charset=utf-8",
  587. 'Authorization': 'Bearer ' + app_token
  588. }
  589. })
  590. .then(res => {
  591. console.log('res=>', res.status, res.data);
  592. resolve(res.data)
  593. }).catch(err => {
  594. logger.error('error ', JSON.stringify(err));
  595. resolve(JSON.stringify(err))
  596. });
  597. })
  598. }
  599. async function exec(data) {
  600. var app = await getFeishuToken()
  601. await insertTableRows(app.app_access_token)
  602. await writeTable(app.app_access_token, data)
  603. }
  604. async function report2FeishuTable() {
  605. try {
  606. logger.info('report2FeishuTable')
  607. var data = await getStatisticsInfo();
  608. logger.info('getStatisticsInfo', data)
  609. await exec(data)
  610. } catch (error) {
  611. logger.error('report2FeishuTable', error.toString())
  612. }
  613. }
  614. timeoutFunc({
  615. interval: 1, //间隔天数,间隔为整数
  616. runNow: false, //是否立即运行
  617. time: reportTime //执行的时间点 时在0~23之间
  618. }, func => {
  619. if (process.env.NODE_ENV == 'prd') {
  620. report2FeishuTable()
  621. }
  622. })
  623. module.exports = {
  624. getStatisticsInfo
  625. }