sdk.js 11 KB

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