sdk.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858
  1. var router = require('koa-router')();
  2. var moralis = require('../model/moralis_sdk.js')
  3. var utils = require('../model/utils.js');
  4. var { reids_token_config, account_config } = require('../config/config.js');
  5. const logger = require('../model/logger.js');
  6. router.prefix('/sdk');
  7. const redis = require("../model/db/redis_db") //导入 db.js
  8. const withdraw_db = require("../model/db/withdraw_db") //导入 db.js
  9. const report = require("../model/report") //导入 db.js
  10. const BigNumber = require('bignumber.js')
  11. const czz = require('../model/czz')
  12. var remote_config_db = require("../model/db/remote_config_db");
  13. const account_mysql = require("../model/db/account_info_db") //导入 db.js
  14. var collect_coins_db = require("../model/db/collect_coins_db");
  15. var stat = require('../model/server_data_statistics')
  16. var stat2 = require('../model/server_data_statisticsv2')
  17. /**
  18. * 获取代币价格
  19. * @param {*} ctx
  20. */
  21. async function getAllTotkenPrice(ctx) {
  22. console.log('getTotkenPrice in:')
  23. var ret = await moralis.getAllTotkenPrice(ctx.request.body)
  24. console.log('getTotkenPrice result:', ret)
  25. if (ret)
  26. ctx.body = utils.toJson(0, ret, null);
  27. else ctx.body = utils.toJson(-1, null, "redis read error.");
  28. }
  29. async function getAllTokenPrice(ctx) {
  30. var ret = await moralis.getAllTotkenPrice(ctx.request.body)
  31. console.log('getTotkenPrice result:', ret)
  32. if (ret)
  33. ctx.body = utils.toJson(0, ret, null);
  34. else ctx.body = utils.toJson(-1, null, "redis read error.");
  35. }
  36. /**
  37. * 获取交易记录
  38. * @param {*} ctx
  39. */
  40. async function getTransfers(ctx) {
  41. const obj = ctx.request.body;
  42. console.log("getTransfers body", obj);
  43. if (!obj.chain)//默认 bsc 币安链
  44. obj.chain = 'bsc_mainnet'
  45. var temp_obj = { ...obj }
  46. var index = 0
  47. await moralis.getTokenTransfers(obj).then((result) => {
  48. logger.log('getTransfers response', 'index=' + index, result)
  49. ctx.body = result;
  50. if (result) {
  51. //提交归集任务 native 能获取到 gas 、token 无法获取到 gas 费
  52. try {
  53. if (temp_obj.address && moralis.isTransferSucceed(result)) {
  54. var log_obj = { ...obj }
  55. log_obj.results = result
  56. log_obj.type = report.REPORT_TYPE.transfer_record
  57. //埋点日志上报-入金检查
  58. report.logReport(log_obj)
  59. var json_obj = JSON.parse(result);
  60. //缓存当前交易的 gas 费用
  61. var tr = moralis.getTransferRecordGasFree('native', json_obj, temp_obj.address)
  62. logger.log('getTransferRecordGasFree:', tr, temp_obj.address)
  63. if (tr && tr.totalGasFree > 0) {
  64. logger.log('getTransferRecordGasFree redis_set LAST_PRICE:', tr)
  65. // redis.redis_set(reids_token_config.LAST_BNB_PRICE, tr.gas_price.toString());
  66. // redis.redis_set(reids_token_config.LAST_TOKEN_PRICE, tr.gas_price.toString());
  67. redis.writeAppendRedis(reids_token_config.LAST_BNB_PRICE, temp_obj.chain, '', tr.gas_price.toString());
  68. redis.writeAppendRedis(reids_token_config.LAST_TOKEN_PRICE, temp_obj.chain, '', tr.gas_price.toString());
  69. }
  70. if (json_obj.data.total > 0) {
  71. //提交归集任务
  72. if (temp_obj.address) {
  73. logger.log('pushCollectConisObj>>>', temp_obj.address)
  74. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  75. }
  76. }
  77. if (json_obj.data.total > 0) {
  78. //提交归集任务
  79. if (temp_obj.address) {
  80. logger.log('pushCollectConisObj>>>', temp_obj.address)
  81. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  82. }
  83. }
  84. }
  85. } catch (error) {
  86. console.error('pushCollectConisObj error=', error)
  87. }
  88. }
  89. })
  90. }
  91. async function getCollectCoinsHash(trx_hash) {
  92. var ret = await collect_coins_db.query_collect_hash(trx_hash);
  93. if (ret && Array.isArray(ret) && ret.length > 0) {
  94. return trx_hash
  95. }
  96. return ' '
  97. }
  98. async function filterTransfers(result) {
  99. try {
  100. if (typeof result === 'string') {
  101. var ret = JSON.parse(result)
  102. if (ret.code == 0 && ret.data.total > 0) {
  103. var new_ret = []
  104. for (let index = 0; index < ret.data.results.length; index++) {
  105. const element = ret.data.results[index];
  106. if (element.trx_hash == await getCollectCoinsHash(element.trx_hash)) {
  107. logger.debug('element.trx_hash == await getCollectCoinsHash(element.trx_hash)', element)
  108. } else {
  109. new_ret.push(element)
  110. }
  111. }
  112. return {
  113. code: ret.code,
  114. data: {
  115. total: new_ret.length,
  116. results: new_ret,
  117. errMsg: ''
  118. }
  119. }
  120. } else {
  121. return result
  122. }
  123. }
  124. } catch (error) {
  125. logger.error('filterTransfers', JSON.parse(error))
  126. return result
  127. }
  128. }
  129. /**
  130. * 获取交易记录
  131. * @param {*} ctx
  132. */
  133. async function getTransfersV2(ctx) {
  134. const obj = ctx.request.body;
  135. console.log("getTransfers body", obj);
  136. if (!obj.chain)//默认 bsc 币安链
  137. obj.chain = 'bsc_mainnet'
  138. var temp_obj = { ...obj }
  139. var index = 0
  140. var result = await moralis.getTokenTransfersV2(obj)
  141. // await moralis.getTokenTransfersV2(obj).then((result) => {
  142. logger.log('getTokenTransfersV2 response', 'index=' + index, result)
  143. ctx.body = await filterTransfers(result);
  144. if (result) {
  145. //提交归集任务 native 能获取到 gas 、token 无法获取到 gas 费
  146. try {
  147. if (temp_obj.address && moralis.isTransferSucceed(result)) {
  148. var log_obj = { ...obj }
  149. log_obj.results = result
  150. log_obj.type = report.REPORT_TYPE.transfer_record
  151. //埋点日志上报-入金检查
  152. report.logReport(log_obj)
  153. var json_obj = JSON.parse(result);
  154. //缓存当前交易的 gas 费用
  155. var tr = moralis.getTransferRecordGasFree('native', json_obj, temp_obj.address)
  156. logger.log('getTransferRecordGasFree:', tr, temp_obj.address)
  157. if (tr && tr.totalGasFree > 0) {
  158. logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_BNB_FREE:', tr)
  159. // redis.redis_set(reids_token_config.LAST_BNB_PRICE, tr.gas_price.toString());
  160. // redis.redis_set(reids_token_config.LAST_TOKEN_PRICE, tr.gas_price.toString().toString());
  161. redis.writeAppendRedis(reids_token_config.LAST_BNB_PRICE, temp_obj.chain, '', tr.gas_price.toString());
  162. redis.writeAppendRedis(reids_token_config.LAST_TOKEN_PRICE, temp_obj.chain, '', tr.gas_price.toString());
  163. }
  164. if (json_obj.data.total > 0) {
  165. //提交归集任务
  166. if (temp_obj.address) {
  167. logger.log('pushCollectConisObj>>>', temp_obj.address)
  168. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  169. }
  170. }
  171. }
  172. } catch (error) {
  173. console.error('pushCollectConisObj error=', error)
  174. }
  175. }
  176. // })
  177. }
  178. async function getAllTokenWithdrawInfoLists(ctx) {
  179. if (ctx.request == null || ctx.request.body == null) {
  180. ctx.body = utils.toJson(-1, null, "request error. ");
  181. return
  182. }
  183. ctx.body = await moralis.getAllTokenWithdrawInfoLists(ctx);
  184. }
  185. async function check_czz_withdraw_task() {
  186. while (true) {
  187. var exec_obj;
  188. try {
  189. exec_obj = await redis.redis_pop(reids_token_config.CHECK_CZZ_WITHDRAW_STATUS_QUEUE)
  190. logger.log("check_czz_withdraw_task redis_pop", exec_obj)
  191. if (!exec_obj) {
  192. logger.log("没有 czz hash check")
  193. await utils.sleep(2 * 60 * 1000)
  194. continue
  195. }
  196. exec_obj = JSON.parse(exec_obj)
  197. if (utils.getTimestamp() - exec_obj.create_time > exec_obj.lifecycle) {
  198. logger.error('已过期 check_czz_withdraw_task :', JSON.stringify(exec_obj))
  199. var update_obj = {}
  200. update_obj.withdraw_status = 3
  201. update_obj.withdraw_hash = ''
  202. update_obj.nonce = -1
  203. update_obj.gas_price = ''
  204. update_obj.gas_limit = ''
  205. update_obj.value = '0'
  206. update_obj.errorMsg = 'czz timeout'
  207. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  208. continue
  209. }
  210. var obj = await czz.check_withdraw_status(exec_obj)
  211. if (obj.code == 0) {
  212. var nonce = obj.data.nonce
  213. var curGasPrice = obj.data.gasPrice.toString()
  214. var curGasLimit = obj.data.gasLimit.toString()
  215. var hash = obj.data.hash
  216. var update_obj = {}
  217. update_obj.withdraw_status = 2
  218. update_obj.withdraw_hash = hash
  219. update_obj.nonce = nonce
  220. update_obj.gas_price = curGasPrice.toString()
  221. update_obj.gas_limit = curGasLimit.toString()
  222. update_obj.value = utils.scientificNotationToString(obj.data.value).toString()
  223. update_obj.errorMsg = ''
  224. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  225. } else {
  226. redis.redis_push(reids_token_config.CHECK_CZZ_WITHDRAW_STATUS_QUEUE, JSON.stringify(exec_obj))
  227. }
  228. await utils.sleep(2 * 60 * 1000)
  229. } catch (error) {
  230. logger.error('check_czz_withdraw_task error', error.toString(), JSON.stringify(exec_obj))
  231. }
  232. }
  233. }
  234. async function collect_conis_task() {
  235. logger.log("collect_conis_task start")
  236. var last_address = ' ';
  237. var last_time = utils.getTimestamp();
  238. while (true) {
  239. var isPause = 0
  240. try {
  241. isPause = await remote_config_db.isPause('collect_coins')
  242. if (isPause) {
  243. logger.error("collect_conis_task pause")
  244. await utils.sleep(60000)
  245. continue
  246. }
  247. } catch (error) {
  248. logger.error("collect_conis_task isPause error", error.toString())
  249. }
  250. var start_time = utils.getTimestamp()
  251. var exec_obj = await redis.redis_pop(reids_token_config.COLLECT_CONIS_QUEUE_KEY)
  252. if (!exec_obj) {
  253. logger.log("没有归集任务")
  254. await utils.sleep(30000)
  255. continue
  256. }
  257. try {
  258. exec_obj = JSON.parse(exec_obj)
  259. logger.log('collect_conis_task exec item>>>>', exec_obj);
  260. try {
  261. //是否是黑名单
  262. var isBlackList = await remote_config_db.isBlackList('collect_coins', exec_obj.chain, exec_obj.address)
  263. if (isBlackList) {
  264. logger.error('collect_conis_task isBlackList', JSON.stringify(exec_obj));
  265. continue
  266. }
  267. } catch (error) {
  268. logger.error('collect_conis_task isBlackList error', JSON.stringify(exec_obj));
  269. }
  270. if (last_address && exec_obj.address && last_address == exec_obj.address && utils.getTimestamp() - last_time < 2 * 60 * 1000) {
  271. logger.info('collect coins wait...');
  272. await utils.sleep(60000)
  273. }
  274. //开始收集用户地址里面的币到归集地址
  275. var ret = await moralis.collectCoins(exec_obj)
  276. logger.log('collect_conis_task ret =', exec_obj, ret)
  277. try {
  278. var ret_obj = JSON.parse(ret)
  279. if (ret_obj.code == 0) {
  280. logger.log('触发归集 delay collect_conis_task ret =', exec_obj, ret)
  281. last_address = exec_obj.address
  282. }
  283. } catch (error) { }
  284. } catch (error) {
  285. logger.error('collect_conis_task error', error.toString());
  286. }
  287. logger.log("collect_conis_task cost-time", utils.getTimestamp() - start_time, exec_obj)
  288. last_time = utils.getTimestamp()
  289. }
  290. }
  291. async function withdraw_task() {
  292. logger.log("withdraw_task start")
  293. let last_time = 0
  294. let last_hash = ''
  295. let last_chain = ''
  296. while (true) {
  297. var isPause = 0
  298. try {
  299. isPause = await remote_config_db.isPause('withdraw')
  300. logger.info("withdraw_task pause", isPause)
  301. if (isPause) {
  302. logger.error("withdraw_task pause")
  303. await utils.sleep(60000)
  304. continue
  305. }
  306. } catch (error) {
  307. logger.error("withdraw_task isPause error", error.toString())
  308. }
  309. var exec_obj = await redis.redis_pop(reids_token_config.WITHDRAW_QUEUE_KEY)
  310. if (!exec_obj) {
  311. await utils.sleep(10000)
  312. logger.log("没有出金任务")
  313. continue
  314. }
  315. try {
  316. exec_obj = JSON.parse(exec_obj)
  317. } catch (error) {
  318. logger.error('withdraw_task item parse error', error);
  319. continue
  320. }
  321. try {
  322. logger.info('withdraw exec obj', exec_obj)
  323. //是否是黑名单
  324. var isBlackList = await remote_config_db.isBlackList('withdraw', exec_obj.chain, exec_obj.receiver)
  325. if (isBlackList) {
  326. var update_obj = {}
  327. update_obj.withdraw_status = 3
  328. update_obj.errorMsg = 'blackList'
  329. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  330. logger.error('withdraw_task isBlackList', JSON.stringify(exec_obj));
  331. continue
  332. }
  333. } catch (error) {
  334. logger.error('withdraw_task isBlackList error', JSON.stringify(exec_obj));
  335. }
  336. var temp_obj = { ...exec_obj }
  337. if (utils.getTimestamp() - last_time < 60000) {
  338. //有可能上一个区块还未更新,这里做一个尝试限制
  339. //Error: Failed to make "eth_sendRawTransaction" request with networkConnector: "already known"
  340. //通过 交易 hash 获取块。last_hash
  341. if (last_hash && last_chain) {
  342. var options = {
  343. transaction_hash: last_hash,
  344. chain: last_chain,
  345. endTime: '2099-01-01'
  346. }
  347. var tryCount = 3;
  348. do {
  349. try {
  350. //通过获取上一个交易记录来进行确认
  351. var transaction = await moralis.getTokenTransfersV2(options);
  352. logger.log('withdraw_task exectransaction', transaction, options, tryCount);
  353. if (typeof transaction === 'string')
  354. transaction = JSON.parse(transaction)
  355. if (transaction.code == 0) {
  356. if (transaction.data.results.length <= 0) {
  357. logger.log('等待10s');
  358. await utils.sleep(10000)
  359. } else {
  360. logger.log('等待5s');
  361. await utils.sleep(5000)
  362. break
  363. }
  364. } else {
  365. break
  366. }
  367. tryCount -= 1
  368. } catch (error) {
  369. logger.error('withdraw_task exectransaction err', error.toString());
  370. }
  371. if (tryCount < 0) {
  372. logger.error('withdraw_task getTokenTransfersV2 警告交易未更新:', JSON.stringify(options));
  373. }
  374. } while (tryCount >= 0);
  375. }
  376. }
  377. //如果失败重试一次
  378. var tryCount = 1;
  379. for (let index = 0; index < 1 + tryCount; index++) {
  380. var result;
  381. var obj;
  382. var curGasPrice = 0;
  383. var curGasLimit = 0;
  384. var value = 0
  385. var nonce = -1
  386. try {
  387. result = await withdraw_({ ...temp_obj })
  388. last_time = utils.getTimestamp()
  389. logger.log('withdraw_task withdraw_ =', result, last_time)
  390. if (result && moralis.getTransferCode(result) == 0) {
  391. if (typeof result === 'string') {
  392. obj = JSON.parse(result)
  393. }
  394. nonce = obj.data.nonce
  395. try {
  396. curGasPrice = BigNumber(obj.data.gasPrice.hex).toNumber()
  397. curGasLimit = BigNumber(obj.data.gasLimit.hex).toNumber()
  398. //不是 czz chain
  399. if (obj.data.chainId != 2019) {
  400. value = BigNumber(obj.data.value.hex).toNumber()
  401. } else {
  402. value = obj.data.value.number
  403. }
  404. } catch (error) {
  405. logger.error('BigNumber toNumber error')
  406. }
  407. var hash = obj.data.hash
  408. last_hash = hash
  409. last_chain = temp_obj.chain
  410. var update_obj = {}
  411. update_obj.withdraw_status = 2
  412. update_obj.withdraw_hash = hash
  413. update_obj.nonce = nonce
  414. update_obj.gas_price = curGasPrice.toString()
  415. update_obj.gas_limit = curGasLimit.toString()
  416. try {
  417. update_obj.value = utils.scientificNotationToString(value).toString()
  418. } catch (error) {
  419. logger.error('scientificNotationToString error')
  420. }
  421. update_obj.errorMsg = ''
  422. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  423. break
  424. } else if (result && moralis.getTransferCode(result) == 1) {
  425. moralis.pushChainDetailTOQueue(1, exec_obj, result);
  426. break
  427. } else {
  428. logger.error('withdraw_task withdraw_ error=', result, JSON.stringify(temp_obj))
  429. if (index < 1 + tryCount && result.includes('eth_sendRawTransaction')) {
  430. logger.error('try withdraw_:', JSON.stringify(temp_obj), index)
  431. await utils.sleep(3000)
  432. continue
  433. }
  434. var update_obj = {}
  435. update_obj.withdraw_status = 3
  436. if (typeof result === 'string') {
  437. try {
  438. result = JSON.parse(result)
  439. update_obj.errorMsg = result.errMsg
  440. } catch (error) {
  441. logger.error('withdraw_task=', result)
  442. }
  443. }
  444. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  445. break
  446. }
  447. } catch (error) {
  448. var update_obj = {}
  449. update_obj.withdraw_status = 3
  450. update_obj.errorMsg = error.toString()
  451. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  452. if (result)
  453. logger.error('withdraw_task error=', error.toString(), JSON.stringify(temp_obj), JSON.stringify(result))
  454. else {
  455. logger.error('withdraw_task error=', error.toString(), JSON.stringify(temp_obj))
  456. }
  457. break
  458. }
  459. }
  460. }
  461. logger.log("withdraw_task end")
  462. }
  463. /**
  464. * 队列版本
  465. * @param {*} ctx
  466. * @returns
  467. */
  468. async function withdrawV3(ctx) {
  469. logger.log('withdrawV3')
  470. if (ctx.request == null || ctx.request.body == null) {
  471. ctx.body = utils.toJson(-1, null, "request error. ");
  472. return
  473. }
  474. const obj = ctx.request.body;
  475. var log_obj = { ...obj }
  476. logger.log('withdrawV3', log_obj)
  477. var obj_ = decrypt_withdraw_content(log_obj.content)
  478. obj_.withdraw_id = obj_.withdrawId;
  479. // obj_.withdraw_id = utils.getTimestamp().toString();
  480. // var obj_ = log_obj
  481. if (obj_.withdraw_id) {
  482. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  483. if (isExist) {
  484. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  485. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  486. return
  487. }
  488. var info = await moralis.queryCompanyInfoFromId(0);
  489. obj_.user_address = info.user_address
  490. await withdraw_db.create_withdraw_task(obj_)
  491. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  492. // withdraw_task()
  493. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  494. } else {
  495. return utils.toJson(-2, null, ' withdraw_id not empty.')
  496. }
  497. }
  498. async function withdrawV3Test(ctx) {
  499. logger.log('withdrawV3Test')
  500. if (ctx.request == null || ctx.request.body == null) {
  501. ctx.body = utils.toJson(-1, null, "request error. ");
  502. return
  503. }
  504. const obj = ctx.request.body;
  505. // for (let index = 0; index < 10; index++) {
  506. var log_obj = { ...obj }
  507. logger.log('withdrawV3', log_obj)
  508. var obj_ = decrypt_withdraw_content(log_obj.content)
  509. obj_.withdraw_id = utils.getCurrentDateFormat('YYYY-MM-DD-HH:mm:ss:SSS').toString()
  510. // var obj_ = log_obj
  511. if (obj_.withdraw_id) {
  512. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  513. if (isExist) {
  514. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  515. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  516. return
  517. }
  518. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  519. var info = await moralis.queryCompanyInfoFromId(0);
  520. obj_.user_address = info.user_address
  521. await withdraw_db.create_withdraw_task(obj_)
  522. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  523. } else {
  524. return utils.toJson(-2, null, ' withdraw_id not empty.')
  525. }
  526. // }
  527. }
  528. function decrypt_withdraw_content(content) {
  529. // const encryptText = utils.encrypt(log_obj);
  530. const encryptText = content;
  531. logger.log("加密", encryptText);
  532. let decryptObj = utils.decrypt(encryptText);
  533. try {
  534. logger.log("解密 before", decryptObj);
  535. decryptObj = JSON.parse(decryptObj);
  536. console.log("解密 json parse", decryptObj);
  537. } catch (error) {
  538. logger.error("json error:", error);
  539. decryptObj = null;
  540. }
  541. return decryptObj;
  542. }
  543. /**
  544. *
  545. * @param {鉴权版本} ctx
  546. */
  547. async function withdrawV2(ctx) {
  548. if (ctx.request == null || ctx.request.body == null) {
  549. ctx.body = utils.toJson(-1, null, "request error. ");
  550. return
  551. }
  552. const obj = ctx.request.body;
  553. var log_obj = { ...obj }
  554. // const encryptText = utils.encrypt(log_obj);
  555. const encryptText = log_obj.content;
  556. logger.log("加密", encryptText);
  557. let decryptObj = utils.decrypt(encryptText);
  558. try {
  559. logger.log("解密 before", decryptObj);
  560. decryptObj = JSON.parse(decryptObj);
  561. // console.log("解密 json parse", decryptObj);
  562. await withdraw_(decryptObj).then(result => {
  563. ctx.body = result;
  564. })
  565. } catch (error) {
  566. logger.error("json error:", error);
  567. ctx.body = utils.toJson(-1, null, error.toString());
  568. }
  569. }
  570. async function withdraw_(obj) {
  571. console.log("withdraw_", obj);
  572. var log_obj = { ...obj }
  573. var info = await moralis.queryCompanyInfoFromId(0);
  574. // log_obj.company_address_total_balance_before = await moralis.queryCollectBalance(info.user_address, obj.chain)
  575. log_obj.company_public_key = info.user_address
  576. logger.log('withdraw log', log_obj);
  577. return new Promise((resolve) => {
  578. moralis.withdraw(obj).then((result) => {
  579. if (moralis.getTransferCode(result) == 0) {
  580. //提币日志上报
  581. log_obj.results = result
  582. log_obj.type = report.REPORT_TYPE.withdraw
  583. //缓存当前交易的 gas 费用
  584. if (result && log_obj.contractAddress) {
  585. var tr = moralis.getTransferGasFree('token', result)
  586. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  587. } else {
  588. var tr = moralis.getTransferGasFree('native', result)
  589. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  590. }
  591. //日志上报
  592. report.logReport(log_obj)
  593. }
  594. resolve(result)
  595. });
  596. })
  597. }
  598. //出金
  599. async function withdraw(ctx) {
  600. if (ctx.request == null || ctx.request.body == null) {
  601. ctx.body = utils.toJson(-1, null, "request error. ");
  602. return
  603. }
  604. const obj = ctx.request.body;
  605. await withdraw_(obj).then(result => {
  606. ctx.body = result;
  607. })
  608. }
  609. /**
  610. * 查询出金状态
  611. * @param {*} ctx
  612. */
  613. async function getWithdrawStatus(ctx) {
  614. if (ctx.request == null || ctx.request.body == null) {
  615. ctx.body = utils.toJson(-1, null, "request error. ");
  616. return
  617. }
  618. const obj = ctx.request.body;
  619. var info = await withdraw_db.queryWithdrawInfoFromWithdrawId(obj.withdrawId)
  620. logger.log('getWithdrawStatus info', JSON.stringify(info))
  621. if (info) {
  622. if (info.withdraw_status != 3) {
  623. ctx.body = utils.toJson(0, {
  624. withdrawId: info.withdraw_id,
  625. withdrawStatus: info.withdraw_status,
  626. withdrawHash: info.withdraw_hash,
  627. chainId: info.chain_id,
  628. transferTimestamp: info.update_time,
  629. }, null)
  630. } else {
  631. ctx.body = utils.toJson(0, {
  632. withdrawId: info.withdraw_id,
  633. withdrawStatus: info.withdraw_status,
  634. withdrawHash: info.withdraw_hash,
  635. chainId: info.chain_id,
  636. transferTimestamp: info.update_time,
  637. errorMsg: info.errorMsg
  638. }, info.errorMsg)
  639. }
  640. } else {
  641. ctx.body = utils.toJson(-1, null, obj.withdraw_id + ' id does not exist.')
  642. }
  643. }
  644. async function timer_collect_conis_bsc_task() {
  645. var index = 0
  646. var delay = 60 * 1000 * 60
  647. while (1) {
  648. var temp_obj = {
  649. "chain": "bsc_testnet",
  650. "address": "0x3B525c35DdC323B08241493f148340D89e3A73a7"
  651. }
  652. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  653. await utils.sleep(delay)
  654. index += 1
  655. }
  656. }
  657. async function timer_collect_conis_czz_task() {
  658. var index = 0
  659. var delay = 60 * 1000 * 60
  660. while (1) {
  661. var temp_obj = {
  662. "chain": "czz",
  663. "address": "0x39ACD9CC975D792D8160215Dc84fa00E4934F076",
  664. }
  665. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  666. await utils.sleep(delay)
  667. index += 1
  668. }
  669. }
  670. async function timer_transfer_bsc_task() {
  671. var index = 0
  672. var delay = 60 * 1000 * 60
  673. while (1) {
  674. var obj_ = {
  675. "type": "erc20",
  676. "contractAddress": "0xFF94950Ee8A79c52cC4B0Aa5178C8cEa48A3F3A6",
  677. "amount": "123000000000000000000",
  678. "chain": "bsc_testnet",
  679. "receiver": "0x3B525c35DdC323B08241493f148340D89e3A73a7",
  680. "withdrawId": index.toString()
  681. }
  682. obj_.withdraw_id = utils.getCurrentDateFormat('YYYY-MM-DD-HH:mm:ss:SSS').toString()
  683. var info = await moralis.queryCompanyInfoFromId(0);
  684. obj_.user_address = info.user_address
  685. await withdraw_db.create_withdraw_task(obj_)
  686. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  687. await utils.sleep(delay)
  688. index += 1
  689. }
  690. }
  691. async function timer_transfer_czz_task() {
  692. var index = 0
  693. var delay = 60 * 1000 * 60
  694. while (1) {
  695. var obj_ = {
  696. "type": "erc20",
  697. "contractAddress": "0xfb16179d5e84b0e3e7524ed61a9cf7b98d039b20",
  698. "amount": "100000000000000000000",
  699. "chain": "czz",
  700. "receiver": "0x39ACD9CC975D792D8160215Dc84fa00E4934F076"
  701. }
  702. obj_.withdraw_id = utils.getCurrentDateFormat('YYYY-MM-DD-HH:mm:ss:SSS').toString()
  703. var info = await moralis.queryCompanyInfoFromId(0);
  704. obj_.user_address = info.user_address
  705. await withdraw_db.create_withdraw_task(obj_)
  706. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  707. await utils.sleep(delay)
  708. index += 1
  709. }
  710. }
  711. async function checkout_taxhash(exec_obj) {
  712. logger.info('bsc_log_monitoring exec start:', exec_obj)
  713. var delay = 60 * 1000
  714. try {
  715. if (typeof exec_obj === 'string')
  716. exec_obj = JSON.parse(exec_obj)
  717. } catch (error) {
  718. logger.error('bsc_log_monitoring:', error)
  719. }
  720. var tryCount = 5
  721. do {
  722. if (tryCount == 0) {
  723. logger.error('数据在5分钟未更新', JSON.stringify(exec_obj))
  724. break
  725. }
  726. if (exec_obj.transactionHash) {
  727. var ret = await account_mysql.getAccountTransactions({
  728. type: 'only_hash',
  729. transaction_hash: exec_obj.transactionHash
  730. })
  731. if (ret && ret.code == 0 && ret.data.total > 0) {
  732. break
  733. }
  734. }
  735. --tryCount
  736. logger.debug('getAccountTransactions', tryCount, exec_obj)
  737. await utils.sleep(delay)
  738. } while (tryCount >= 0);
  739. }
  740. async function bsc_log_monitoring() {
  741. while (1) {
  742. var exec_obj = await redis.redis_pop(reids_token_config.BSC_LOG_MONITORING_KEY)
  743. if (!exec_obj) {
  744. await utils.sleep(10000)
  745. logger.log("no new check tasks")
  746. continue
  747. }
  748. checkout_taxhash(exec_obj)
  749. }
  750. }
  751. //获取交易记录
  752. router.post('/getTransfers', getTransfers)
  753. router.post('/getTransfersV2', getTransfersV2)
  754. // 获取所有代币价格
  755. router.post('/getAllTotkenPrice', getAllTotkenPrice)
  756. router.post('/getAllTokenPrice', getAllTokenPrice)
  757. // router.post('/transfer', transfer)
  758. //提现
  759. router.post('/withdraw', withdraw);
  760. //提现鉴权-body 加密
  761. router.post('/withdrawV2', withdrawV2);
  762. //队列的形式
  763. router.post('/withdrawV3', withdrawV3);
  764. // if (process.env.NODE_ENV == 'dev' || process.env.NODE_ENV == 'test') {
  765. router.post('/withdrawV3Test', withdrawV3Test);
  766. // }
  767. //查询出金服务
  768. router.post('/getWithdrawStatus', getWithdrawStatus);
  769. //获取所有地址的所要消耗的最低提取费
  770. router.post('/getAllTokenWithdrawInfoLists', getAllTokenWithdrawInfoLists)
  771. router.get('/report2FeishuTable', async (ctx) => {
  772. stat2.report2FeishuTable(1)
  773. ctx.body = 'ok'
  774. })
  775. // 定时任务 提币+归集
  776. withdraw_task();
  777. collect_conis_task();
  778. //czz 504 检查
  779. check_czz_withdraw_task();
  780. // bsc 监控
  781. bsc_log_monitoring()
  782. if (process.env.NODE_ENV == 'dev' || process.env.NODE_ENV == 'test') {
  783. timer_transfer_bsc_task()
  784. timer_transfer_czz_task()
  785. timer_collect_conis_bsc_task()
  786. timer_collect_conis_czz_task()
  787. }
  788. module.exports = router