sdk.js 11 KB

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