sdk.js 18 KB

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