sdk.js 11 KB

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