sdk.js 17 KB

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