sdk.js 30 KB

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