sdk.js 32 KB

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