sdk.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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. while (true) {
  80. var exec_obj = await redis.redis_pop(reids_token_config.COLLECT_CONIS_QUEUE_KEY)
  81. if (!exec_obj) {
  82. await utils.sleep(10000)
  83. logger.log("没有归集任务")
  84. continue
  85. }
  86. try {
  87. exec_obj = JSON.parse(exec_obj)
  88. } catch (error) {
  89. logger.error('item parse error', error);
  90. break
  91. }
  92. logger.log('collect_conis_task exec item>>>>', exec_obj);
  93. //开始收集用户地址里面的币到归集地址
  94. var ret = await moralis.collectCoins(exec_obj)
  95. logger.log('collect_conis_task ret =', exec_obj, ret)
  96. }
  97. }
  98. async function withdraw_task() {
  99. // var status = await redis.readRedis(reids_token_config.WITHDRAW_QUEUE_STATUS)
  100. // if (status && status == 1) {
  101. // logger.log('running...')
  102. // return
  103. // }
  104. // redis.redis_set(reids_token_config.WITHDRAW_QUEUE_STATUS, 1)
  105. while (true) {
  106. var exec_obj = await redis.redis_pop(reids_token_config.WITHDRAW_QUEUE_KEY)
  107. if (!exec_obj) {
  108. await utils.sleep(10000)
  109. logger.log("没有出金任务")
  110. continue
  111. }
  112. try {
  113. exec_obj = JSON.parse(exec_obj)
  114. } catch (error) {
  115. logger.error('item parse error', error);
  116. break
  117. }
  118. logger.log('withdraw_task exec item>>>>', exec_obj);
  119. try {
  120. var result = await withdraw_(exec_obj)
  121. logger.log('withdraw_task=', result)
  122. if (result && moralis.isTransferSucceed(result)) {
  123. var obj = JSON.parse(result)
  124. var nonce = obj.data.nonce
  125. var curGasPrice = BigNumber(obj.data.gasPrice.hex).toNumber()
  126. var curGasLimit = BigNumber(obj.data.gasLimit.hex).toNumber()
  127. var value = BigNumber(obj.data.value.hex).toNumber()
  128. var hash = obj.data.hash
  129. var update_obj = {}
  130. update_obj.withdraw_status = 2
  131. update_obj.withdraw_hash = hash
  132. update_obj.nonce = nonce
  133. update_obj.gas_price = curGasPrice.toString()
  134. update_obj.gas_limit = curGasLimit.toString()
  135. update_obj.value = value.toString()
  136. update_obj.errorMsg = ''
  137. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  138. } else {
  139. var update_obj = {}
  140. update_obj.withdraw_status = 3
  141. if (typeof result === 'string') {
  142. try {
  143. result = JSON.parse(result)
  144. update_obj.errorMsg = result.errMsg
  145. } catch (error) {
  146. logger.error('withdraw_task=', result)
  147. }
  148. }
  149. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  150. }
  151. } catch (error) {
  152. logger.error('withdraw_task error=', error)
  153. }
  154. }
  155. // redis.redis_set(reids_token_config.WITHDRAW_QUEUE_STATUS, 0)
  156. }
  157. /**
  158. * 队列版本
  159. * @param {*} ctx
  160. * @returns
  161. */
  162. async function withdrawV3(ctx) {
  163. logger.log('withdrawV3')
  164. if (ctx.request == null || ctx.request.body == null) {
  165. ctx.body = utils.toJson(-1, null, "request error. ");
  166. return
  167. }
  168. const obj = ctx.request.body;
  169. var log_obj = { ...obj }
  170. logger.log('withdrawV3', log_obj)
  171. var obj_ = decrypt_withdraw_content(log_obj.content)
  172. obj_.withdraw_id = obj_.withdrawId;
  173. // var obj_ = log_obj
  174. if (obj_.withdraw_id) {
  175. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  176. if (isExist) {
  177. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  178. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  179. return
  180. }
  181. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  182. var info = await moralis.queryCompanyInfoFromId(0);
  183. obj_.user_address = info.user_address
  184. await withdraw_db.create_withdraw_task(obj_)
  185. // withdraw_task()
  186. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  187. } else {
  188. return utils.toJson(-2, null, ' withdraw_id not empty.')
  189. }
  190. }
  191. function decrypt_withdraw_content(content) {
  192. // const encryptText = utils.encrypt(log_obj);
  193. const encryptText = content;
  194. logger.log("加密", encryptText);
  195. let decryptObj = utils.decrypt(encryptText);
  196. try {
  197. logger.log("解密 before", decryptObj);
  198. decryptObj = JSON.parse(decryptObj);
  199. console.log("解密 json parse", decryptObj);
  200. } catch (error) {
  201. logger.error("json error:", error);
  202. decryptObj = null;
  203. }
  204. return decryptObj;
  205. }
  206. /**
  207. *
  208. * @param {鉴权版本} ctx
  209. */
  210. async function withdrawV2(ctx) {
  211. if (ctx.request == null || ctx.request.body == null) {
  212. ctx.body = utils.toJson(-1, null, "request error. ");
  213. return
  214. }
  215. const obj = ctx.request.body;
  216. var log_obj = { ...obj }
  217. // const encryptText = utils.encrypt(log_obj);
  218. const encryptText = log_obj.content;
  219. logger.log("加密", encryptText);
  220. let decryptObj = utils.decrypt(encryptText);
  221. try {
  222. logger.log("解密 before", decryptObj);
  223. decryptObj = JSON.parse(decryptObj);
  224. // console.log("解密 json parse", decryptObj);
  225. await withdraw_(decryptObj).then(result => {
  226. ctx.body = result;
  227. })
  228. } catch (error) {
  229. logger.error("json error:", error);
  230. ctx.body = utils.toJson(-1, null, error.toString());
  231. }
  232. }
  233. async function withdraw_(obj) {
  234. console.log("withdraw_", obj);
  235. var log_obj = { ...obj }
  236. var info = await moralis.queryCompanyInfoFromId(0);
  237. log_obj.company_address_total_balance_before = await moralis.queryCollectBalance(info.user_address, obj.chain)
  238. log_obj.company_public_key = info.user_address
  239. logger.log('withdraw log', log_obj);
  240. return new Promise((resolve) => {
  241. moralis.withdraw(obj).then((result) => {
  242. if (moralis.isTransferSucceed(result)) {
  243. //提币日志上报
  244. log_obj.results = result
  245. log_obj.type = report.REPORT_TYPE.withdraw
  246. //缓存当前交易的 gas 费用
  247. if (result && log_obj.contractAddress) {
  248. var tr = moralis.getTransferGasFree('token', result)
  249. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  250. } else {
  251. var tr = moralis.getTransferGasFree('native', result)
  252. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  253. }
  254. // log_obj.receiver_address_total_balance_after = await queryCollectBalance(info.user_address, utils.getChainName(obj.chain))
  255. //日志上报
  256. report.logReport(log_obj)
  257. }
  258. resolve(result)
  259. });
  260. })
  261. }
  262. //出金
  263. async function withdraw(ctx) {
  264. if (ctx.request == null || ctx.request.body == null) {
  265. ctx.body = utils.toJson(-1, null, "request error. ");
  266. return
  267. }
  268. const obj = ctx.request.body;
  269. await withdraw_(obj).then(result => {
  270. ctx.body = result;
  271. })
  272. }
  273. /**
  274. * 查询出金状态
  275. * @param {*} ctx
  276. */
  277. async function getWithdrawStatus(ctx) {
  278. if (ctx.request == null || ctx.request.body == null) {
  279. ctx.body = utils.toJson(-1, null, "request error. ");
  280. return
  281. }
  282. const obj = ctx.request.body;
  283. var info = await withdraw_db.queryWithdrawInfoFromWithdrawId(obj.withdrawId)
  284. logger.log('getWithdrawStatus info', JSON.stringify(info))
  285. if (info) {
  286. if (info.withdraw_status != 3) {
  287. ctx.body = utils.toJson(0, {
  288. withdrawId: info.withdraw_id,
  289. withdrawStatus: info.withdraw_status,
  290. withdrawHash: info.withdraw_hash,
  291. chainId: info.chain_id,
  292. transferTimestamp: info.update_time,
  293. }, null)
  294. } else {
  295. ctx.body = utils.toJson(0, {
  296. withdrawId: info.withdraw_id,
  297. withdrawStatus: info.withdraw_status,
  298. withdrawHash: info.withdraw_hash,
  299. chainId: info.chain_id,
  300. transferTimestamp: info.update_time,
  301. errorMsg: info.errorMsg
  302. }, null)
  303. }
  304. } else {
  305. ctx.body = utils.toJson(-1, null, obj.withdraw_id + ' id does not exist.')
  306. }
  307. }
  308. //获取交易记录
  309. router.post('/getTransfers', getTransfers)
  310. // 获取所有代币价格
  311. router.post('/getAllTotkenPrice', getAllTotkenPrice)
  312. // router.post('/transfer', transfer)
  313. //提现
  314. router.post('/withdraw', withdraw);
  315. //提现鉴权-body 加密
  316. router.post('/withdrawV2', withdrawV2);
  317. //队列的形式
  318. router.post('/withdrawV3', withdrawV3);
  319. //查询出金服务
  320. router.post('/getWithdrawStatus', getWithdrawStatus);
  321. //获取所有地址的所要消耗的最低提取费
  322. router.post('/getAllTokenWithdrawInfoLists', getAllTokenWithdrawInfoLists)
  323. // 定时任务 提币+归集
  324. withdraw_task();
  325. collect_conis_task();
  326. module.exports = router