sdk.js 17 KB

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