sdk.js 18 KB

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