sdk.js 30 KB

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