sdk.js 12 KB

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