sdk.js 31 KB

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