sdk.js 16 KB

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