sdk.js 32 KB

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