sdk.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  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. /**
  12. * 获取代币价格
  13. * @param {*} ctx
  14. */
  15. async function getAllTotkenPrice(ctx) {
  16. console.log('getTotkenPrice in:')
  17. var ret = await moralis.getAllTotkenPrice()
  18. console.log('getTotkenPrice result:', ret)
  19. if (ret)
  20. ctx.body = utils.toJson(0, ret, null);
  21. else ctx.body = utils.toJson(-1, null, "redis read error.");
  22. }
  23. /**
  24. * 获取交易记录
  25. * @param {*} ctx
  26. */
  27. async function getTransfers(ctx) {
  28. const obj = ctx.request.body;
  29. console.log("getTransfers body", obj);
  30. if (!obj.chain)//默认 bsc 币安链
  31. obj.chain = 'bsc_mainnet'
  32. var temp_obj = { ...obj }
  33. var index = 0
  34. // for (let index = 0; index < 30; index++) {
  35. await moralis.getTokenTransfers(obj).then((result) => {
  36. logger.log('getTransfers response', 'index=' + index, result)
  37. ctx.body = result;
  38. if (result) {
  39. //提交归集任务 native 能获取到 gas 、token 无法获取到 gas 费
  40. try {
  41. if (temp_obj.address && moralis.isTransferSucceed(result)) {
  42. var log_obj = { ...obj }
  43. log_obj.results = result
  44. log_obj.type = report.REPORT_TYPE.transfer_record
  45. //埋点日志上报-入金检查
  46. report.logReport(log_obj)
  47. var json_obj = JSON.parse(result);
  48. //缓存当前交易的 gas 费用
  49. var tr = moralis.getTransferRecordGasFree('native', json_obj, temp_obj.address)
  50. logger.log('getTransferRecordGasFree:', tr, temp_obj.address)
  51. if (tr && tr.totalGasFree > 0) {
  52. logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_BNB_FREE:', tr.totalGasFree.toString())
  53. logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_TOKEN_FREE:', (parseInt(tr.totalGasFree) * parseInt(account_config.TOKEN_GAS_LIMIT)).toString())
  54. redis.redis_set(reids_token_config.LAST_TOTAL_BNB_FREE, tr.totalGasFree.toString());
  55. redis.redis_set(reids_token_config.LAST_TOTAL_TOKEN_FREE, (parseInt(tr.gas_price) * parseInt(account_config.TOKEN_GAS_LIMIT)).toString());
  56. }
  57. //提交归集任务
  58. if (temp_obj.address) {
  59. logger.log('pushCollectConisObj>>>', temp_obj.address)
  60. // moralis.pushCollectConisObj(temp_obj)
  61. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  62. }
  63. }
  64. } catch (error) {
  65. console.error('pushCollectConisObj error=', error)
  66. }
  67. }
  68. })
  69. // }
  70. }
  71. async function getAllTokenWithdrawInfoLists(ctx) {
  72. if (ctx.request == null || ctx.request.body == null) {
  73. ctx.body = utils.toJson(-1, null, "request error. ");
  74. return
  75. }
  76. ctx.body = await moralis.getAllTokenWithdrawInfoLists(ctx);
  77. }
  78. async function collect_conis_task() {
  79. logger.log("collect_conis_task start")
  80. while (true) {
  81. var exec_obj = await redis.redis_pop(reids_token_config.COLLECT_CONIS_QUEUE_KEY)
  82. if (!exec_obj) {
  83. await utils.sleep(10000)
  84. logger.log("没有归集任务")
  85. continue
  86. }
  87. try {
  88. exec_obj = JSON.parse(exec_obj)
  89. logger.log('collect_conis_task exec item>>>>', exec_obj);
  90. if (exec_obj.address == await redis.readRedis(reids_token_config.LAST_COLLECT_PUBLIC_KEY) && utils.getTimestamp() - await redis.readRedis(reids_token_config.LAST_COLLECT_TIME) < 60 * 2 * 1000) {
  91. logger.log('间隔不足 2 分钟', exec_obj);
  92. continue
  93. }
  94. redis.redis_set(reids_token_config.LAST_COLLECT_TIME, utils.getTimestamp())
  95. redis.redis_set(reids_token_config.LAST_COLLECT_PUBLIC_KEY, exec_obj.address)
  96. //开始收集用户地址里面的币到归集地址
  97. var ret = await moralis.collectCoins(exec_obj)
  98. logger.log('collect_conis_task ret =', exec_obj, ret)
  99. // var ret_obj = JSON.parse(ret)
  100. // if (ret_obj.code == 0) {
  101. // //间隔 10s 归集,避免提交任务过多
  102. // await utils.sleep(10000)
  103. // }
  104. } catch (error) {
  105. logger.error('collect_conis_task error', error.toString());
  106. redis.redis_set(reids_token_config.LAST_COLLECT_TIME, 0)
  107. redis.redis_set(reids_token_config.LAST_COLLECT_PUBLIC_KEY, 0)
  108. }
  109. await utils.sleep(10000)
  110. }
  111. logger.log("collect_conis_task end")
  112. }
  113. async function withdraw_task() {
  114. logger.log("withdraw_task start")
  115. let last_time = 0
  116. let last_hash = ''
  117. while (true) {
  118. var exec_obj = await redis.redis_pop(reids_token_config.WITHDRAW_QUEUE_KEY)
  119. if (!exec_obj) {
  120. await utils.sleep(60000)
  121. logger.log("没有出金任务")
  122. continue
  123. }
  124. try {
  125. exec_obj = JSON.parse(exec_obj)
  126. } catch (error) {
  127. logger.error('item parse error', error);
  128. break
  129. }
  130. var temp_obj = { ...exec_obj }
  131. if (utils.getTimestamp() - last_time < 60000) {
  132. //有可能上一个区块还未更新,这里做一个尝试限制
  133. //Error: Failed to make "eth_sendRawTransaction" request with networkConnector: "already known"
  134. //通过 交易 hash 获取块。last_hash
  135. if (last_hash) {
  136. var options = {
  137. transaction_hash: last_hash,
  138. chain: temp_obj.chain,
  139. endTime: '2099-01-01'
  140. }
  141. var tryCount = 10;
  142. do {
  143. try {
  144. //通过获取上一个交易记录来进行确认
  145. var transaction = await moralis.getTokenTransfers(options);
  146. logger.log('withdraw_task exectransaction', transaction, options, tryCount);
  147. transaction = JSON.parse(transaction)
  148. if (transaction.code == 0) {
  149. if (transaction.data.result.length <= 0) {
  150. logger.log('等待10s');
  151. await utils.sleep(10000)
  152. } else {
  153. logger.log('等待5s');
  154. await utils.sleep(5000)
  155. break
  156. }
  157. } else {
  158. break
  159. }
  160. tryCount -= 1
  161. } catch (error) {
  162. logger.error('withdraw_task exectransaction', error.toString());
  163. }
  164. } while (tryCount >= 0);
  165. }
  166. }
  167. //如果失败重试一次
  168. var tryCount = 1;
  169. for (let index = 0; index < 1 + tryCount; index++) {
  170. try {
  171. var result = await withdraw_({ ...temp_obj })
  172. last_time = utils.getTimestamp()
  173. logger.log('withdraw_task withdraw_ =', result, last_time)
  174. if (result && moralis.isTransferSucceed(result)) {
  175. var obj = JSON.parse(result)
  176. var nonce = obj.data.nonce
  177. var curGasPrice = BigNumber(obj.data.gasPrice.hex).toNumber()
  178. var curGasLimit = BigNumber(obj.data.gasLimit.hex).toNumber()
  179. var value = BigNumber(obj.data.value.hex).toNumber()
  180. var hash = obj.data.hash
  181. last_hash = hash
  182. var update_obj = {}
  183. update_obj.withdraw_status = 2
  184. update_obj.withdraw_hash = hash
  185. update_obj.nonce = nonce
  186. update_obj.gas_price = curGasPrice.toString()
  187. update_obj.gas_limit = curGasLimit.toString()
  188. update_obj.value = value.toString()
  189. update_obj.errorMsg = ''
  190. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  191. break
  192. } else {
  193. logger.error('withdraw_task withdraw_ error=', result, JSON.stringify(temp_obj))
  194. if (index < 1 + tryCount && result.includes('eth_sendRawTransaction')) {
  195. logger.error('try withdraw_:', JSON.stringify(temp_obj), index)
  196. await utils.sleep(3000)
  197. continue
  198. }
  199. var update_obj = {}
  200. update_obj.withdraw_status = 3
  201. if (typeof result === 'string') {
  202. try {
  203. result = JSON.parse(result)
  204. update_obj.errorMsg = result.errMsg
  205. } catch (error) {
  206. logger.error('withdraw_task=', result)
  207. }
  208. }
  209. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  210. break
  211. }
  212. } catch (error) {
  213. var update_obj = {}
  214. update_obj.withdraw_status = 3
  215. update_obj.errorMsg = error.toString()
  216. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  217. logger.error('withdraw_task error=', error.toString())
  218. break
  219. }
  220. }
  221. }
  222. logger.log("withdraw_task end")
  223. }
  224. /**
  225. * 队列版本
  226. * @param {*} ctx
  227. * @returns
  228. */
  229. async function withdrawV3(ctx) {
  230. logger.log('withdrawV3')
  231. if (ctx.request == null || ctx.request.body == null) {
  232. ctx.body = utils.toJson(-1, null, "request error. ");
  233. return
  234. }
  235. const obj = ctx.request.body;
  236. // for (let index = 0; index < 10; index++) {
  237. var log_obj = { ...obj }
  238. logger.log('withdrawV3', log_obj)
  239. var obj_ = decrypt_withdraw_content(log_obj.content)
  240. obj_.withdraw_id = obj_.withdrawId;
  241. // obj_.withdraw_id = utils.getTimestamp().toString();
  242. // var obj_ = log_obj
  243. if (obj_.withdraw_id) {
  244. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  245. if (isExist) {
  246. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  247. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  248. return
  249. }
  250. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  251. var info = await moralis.queryCompanyInfoFromId(0);
  252. obj_.user_address = info.user_address
  253. await withdraw_db.create_withdraw_task(obj_)
  254. // withdraw_task()
  255. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  256. } else {
  257. return utils.toJson(-2, null, ' withdraw_id not empty.')
  258. }
  259. // }
  260. }
  261. async function withdrawV3Test(ctx) {
  262. logger.log('withdrawV3Test')
  263. if (ctx.request == null || ctx.request.body == null) {
  264. ctx.body = utils.toJson(-1, null, "request error. ");
  265. return
  266. }
  267. const obj = ctx.request.body;
  268. // for (let index = 0; index < 10; index++) {
  269. var log_obj = { ...obj }
  270. logger.log('withdrawV3', log_obj)
  271. var obj_ = decrypt_withdraw_content(log_obj.content)
  272. obj_.withdraw_id = obj_.withdrawId;
  273. obj_.withdraw_id = utils.getTimestamp().toString();
  274. // var obj_ = log_obj
  275. if (obj_.withdraw_id) {
  276. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  277. if (isExist) {
  278. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  279. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  280. return
  281. }
  282. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  283. var info = await moralis.queryCompanyInfoFromId(0);
  284. obj_.user_address = info.user_address
  285. await withdraw_db.create_withdraw_task(obj_)
  286. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  287. } else {
  288. return utils.toJson(-2, null, ' withdraw_id not empty.')
  289. }
  290. // }
  291. }
  292. function decrypt_withdraw_content(content) {
  293. // const encryptText = utils.encrypt(log_obj);
  294. const encryptText = content;
  295. logger.log("加密", encryptText);
  296. let decryptObj = utils.decrypt(encryptText);
  297. try {
  298. logger.log("解密 before", decryptObj);
  299. decryptObj = JSON.parse(decryptObj);
  300. console.log("解密 json parse", decryptObj);
  301. } catch (error) {
  302. logger.error("json error:", error);
  303. decryptObj = null;
  304. }
  305. return decryptObj;
  306. }
  307. /**
  308. *
  309. * @param {鉴权版本} ctx
  310. */
  311. async function withdrawV2(ctx) {
  312. if (ctx.request == null || ctx.request.body == null) {
  313. ctx.body = utils.toJson(-1, null, "request error. ");
  314. return
  315. }
  316. const obj = ctx.request.body;
  317. var log_obj = { ...obj }
  318. // const encryptText = utils.encrypt(log_obj);
  319. const encryptText = log_obj.content;
  320. logger.log("加密", encryptText);
  321. let decryptObj = utils.decrypt(encryptText);
  322. try {
  323. logger.log("解密 before", decryptObj);
  324. decryptObj = JSON.parse(decryptObj);
  325. // console.log("解密 json parse", decryptObj);
  326. await withdraw_(decryptObj).then(result => {
  327. ctx.body = result;
  328. })
  329. } catch (error) {
  330. logger.error("json error:", error);
  331. ctx.body = utils.toJson(-1, null, error.toString());
  332. }
  333. }
  334. async function withdraw_(obj) {
  335. console.log("withdraw_", obj);
  336. var log_obj = { ...obj }
  337. var info = await moralis.queryCompanyInfoFromId(0);
  338. log_obj.company_address_total_balance_before = await moralis.queryCollectBalance(info.user_address, obj.chain)
  339. log_obj.company_public_key = info.user_address
  340. logger.log('withdraw log', log_obj);
  341. return new Promise((resolve) => {
  342. moralis.withdraw(obj).then((result) => {
  343. if (moralis.isTransferSucceed(result)) {
  344. //提币日志上报
  345. log_obj.results = result
  346. log_obj.type = report.REPORT_TYPE.withdraw
  347. //缓存当前交易的 gas 费用
  348. if (result && log_obj.contractAddress) {
  349. var tr = moralis.getTransferGasFree('token', result)
  350. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  351. } else {
  352. var tr = moralis.getTransferGasFree('native', result)
  353. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  354. }
  355. // log_obj.receiver_address_total_balance_after = await queryCollectBalance(info.user_address, utils.getChainName(obj.chain))
  356. //日志上报
  357. report.logReport(log_obj)
  358. }
  359. resolve(result)
  360. });
  361. })
  362. }
  363. //出金
  364. async function withdraw(ctx) {
  365. if (ctx.request == null || ctx.request.body == null) {
  366. ctx.body = utils.toJson(-1, null, "request error. ");
  367. return
  368. }
  369. const obj = ctx.request.body;
  370. await withdraw_(obj).then(result => {
  371. ctx.body = result;
  372. })
  373. }
  374. /**
  375. * 查询出金状态
  376. * @param {*} ctx
  377. */
  378. async function getWithdrawStatus(ctx) {
  379. if (ctx.request == null || ctx.request.body == null) {
  380. ctx.body = utils.toJson(-1, null, "request error. ");
  381. return
  382. }
  383. const obj = ctx.request.body;
  384. var info = await withdraw_db.queryWithdrawInfoFromWithdrawId(obj.withdrawId)
  385. logger.log('getWithdrawStatus info', JSON.stringify(info))
  386. if (info) {
  387. if (info.withdraw_status != 3) {
  388. ctx.body = utils.toJson(0, {
  389. withdrawId: info.withdraw_id,
  390. withdrawStatus: info.withdraw_status,
  391. withdrawHash: info.withdraw_hash,
  392. chainId: info.chain_id,
  393. transferTimestamp: info.update_time,
  394. }, null)
  395. } else {
  396. ctx.body = utils.toJson(0, {
  397. withdrawId: info.withdraw_id,
  398. withdrawStatus: info.withdraw_status,
  399. withdrawHash: info.withdraw_hash,
  400. chainId: info.chain_id,
  401. transferTimestamp: info.update_time,
  402. errorMsg: info.errorMsg
  403. }, null)
  404. }
  405. } else {
  406. ctx.body = utils.toJson(-1, null, obj.withdraw_id + ' id does not exist.')
  407. }
  408. }
  409. //获取交易记录
  410. router.post('/getTransfers', getTransfers)
  411. // 获取所有代币价格
  412. router.post('/getAllTotkenPrice', getAllTotkenPrice)
  413. // router.post('/transfer', transfer)
  414. //提现
  415. router.post('/withdraw', withdraw);
  416. //提现鉴权-body 加密
  417. router.post('/withdrawV2', withdrawV2);
  418. //队列的形式
  419. router.post('/withdrawV3', withdrawV3);
  420. if (process.env.NODE_ENV == 'dev')
  421. router.post('/withdrawV3Test', withdrawV3Test);
  422. //查询出金服务
  423. router.post('/getWithdrawStatus', getWithdrawStatus);
  424. //获取所有地址的所要消耗的最低提取费
  425. router.post('/getAllTokenWithdrawInfoLists', getAllTokenWithdrawInfoLists)
  426. // 定时任务 提币+归集
  427. withdraw_task();
  428. collect_conis_task();
  429. module.exports = router