sdk.js 31 KB

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