sdk.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. console.log("body", ctx);
  29. const obj = ctx.request.body;
  30. console.log("obj", obj);
  31. if (!obj.chain)//默认 bsc 币安链
  32. obj.chain = 'bsc_mainnet'
  33. var temp_obj = { ...obj }
  34. await moralis.getTokenTransfers(obj).then((result) => {
  35. if (result) {
  36. //提交归集任务 native 能获取到 gas 、token 无法获取到 gas 费
  37. try {
  38. if (temp_obj.address && moralis.isTransferSucceed(result)) {
  39. var log_obj = { ...obj }
  40. log_obj.results = result
  41. log_obj.type = report.REPORT_TYPE.transfer_record
  42. //埋点日志上报-入金检查
  43. report.logReport(log_obj)
  44. var json_obj = JSON.parse(result);
  45. //缓存当前交易的 gas 费用
  46. var tr = moralis.getTransferRecordGasFree('native', json_obj, temp_obj.address)
  47. logger.log('getTransferRecordGasFree:', tr, temp_obj.address)
  48. if (tr && tr.totalGasFree > 0) {
  49. logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_BNB_FREE:', tr.totalGasFree.toString())
  50. logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_TOKEN_FREE:', (parseInt(tr.totalGasFree) * parseInt(account_config.TOKEN_GAS_LIMIT)).toString())
  51. redis.redis_set(reids_token_config.LAST_TOTAL_BNB_FREE, tr.totalGasFree.toString());
  52. redis.redis_set(reids_token_config.LAST_TOTAL_TOKEN_FREE, (parseInt(tr.gas_price) * parseInt(account_config.TOKEN_GAS_LIMIT)).toString());
  53. }
  54. //提交归集任务
  55. if (temp_obj.address) {
  56. logger.log('pushCollectConisObj>>>', temp_obj.address)
  57. moralis.pushCollectConisObj(temp_obj)
  58. }
  59. }
  60. } catch (error) {
  61. console.error('pushCollectConisObj error=', error)
  62. }
  63. }
  64. ctx.body = result;
  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.log('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. if (typeof result === 'string') {
  116. try {
  117. result = JSON.parse(result)
  118. update_obj.errorMsg = result.errMsg
  119. } catch (error) {
  120. logger.error('withdraw_task=', result)
  121. }
  122. }
  123. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  124. }
  125. } catch (error) {
  126. logger.log('withdraw_task error=', error)
  127. }
  128. }
  129. redis.redis_set(reids_token_config.WITHDRAW_QUEUE_STATUS, 0)
  130. }
  131. /**
  132. * 队列版本
  133. * @param {*} ctx
  134. * @returns
  135. */
  136. async function withdrawV3(ctx) {
  137. logger.log('withdrawV3')
  138. if (ctx.request == null || ctx.request.body == null) {
  139. ctx.body = utils.toJson(-1, null, "request error. ");
  140. return
  141. }
  142. const obj = ctx.request.body;
  143. var log_obj = { ...obj }
  144. logger.log('withdrawV3', log_obj)
  145. var obj_ = decrypt_withdraw_content(log_obj.content)
  146. obj_.withdraw_id = obj_.withdrawId;
  147. // var obj_ = log_obj
  148. if (obj_.withdraw_id) {
  149. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  150. if (isExist) {
  151. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  152. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  153. return
  154. }
  155. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  156. var info = await moralis.queryCompanyInfoFromId(0);
  157. obj_.user_address = info.user_address
  158. await withdraw_db.create_withdraw_task(obj_)
  159. withdraw_task()
  160. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  161. } else {
  162. return utils.toJson(-2, null, ' withdraw_id not empty.')
  163. }
  164. }
  165. function decrypt_withdraw_content(content) {
  166. // const encryptText = utils.encrypt(log_obj);
  167. const encryptText = content;
  168. logger.log("加密", encryptText);
  169. let decryptObj = utils.decrypt(encryptText);
  170. try {
  171. logger.log("解密 before", decryptObj);
  172. decryptObj = JSON.parse(decryptObj);
  173. console.log("解密 json parse", decryptObj);
  174. } catch (error) {
  175. logger.log("json error:", error);
  176. decryptObj = null;
  177. }
  178. return decryptObj;
  179. }
  180. /**
  181. *
  182. * @param {鉴权版本} ctx
  183. */
  184. async function withdrawV2(ctx) {
  185. if (ctx.request == null || ctx.request.body == null) {
  186. ctx.body = utils.toJson(-1, null, "request error. ");
  187. return
  188. }
  189. const obj = ctx.request.body;
  190. var log_obj = { ...obj }
  191. // const encryptText = utils.encrypt(log_obj);
  192. const encryptText = log_obj.content;
  193. logger.log("加密", encryptText);
  194. let decryptObj = utils.decrypt(encryptText);
  195. try {
  196. logger.log("解密 before", decryptObj);
  197. decryptObj = JSON.parse(decryptObj);
  198. console.log("解密 json parse", decryptObj);
  199. await withdraw_(decryptObj).then(result => {
  200. ctx.body = result;
  201. })
  202. } catch (error) {
  203. logger.log("json error:", error);
  204. ctx.body = utils.toJson(-1, null, error.toString());
  205. }
  206. }
  207. async function withdraw_(obj) {
  208. console.log("withdraw_", obj);
  209. var log_obj = { ...obj }
  210. var info = await moralis.queryCompanyInfoFromId(0);
  211. log_obj.company_address_total_balance_before = await moralis.queryCollectBalance(info.user_address, obj.chain)
  212. log_obj.company_public_key = info.user_address
  213. logger.log('withdraw log', log_obj);
  214. return new Promise((resolve) => {
  215. moralis.withdraw(obj).then((result) => {
  216. if (moralis.isTransferSucceed(result)) {
  217. //提币日志上报
  218. log_obj.results = result
  219. log_obj.type = report.REPORT_TYPE.withdraw
  220. //缓存当前交易的 gas 费用
  221. if (result && log_obj.contractAddress) {
  222. var tr = moralis.getTransferGasFree('token', result)
  223. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  224. } else {
  225. var tr = moralis.getTransferGasFree('native', result)
  226. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  227. }
  228. // log_obj.receiver_address_total_balance_after = await queryCollectBalance(info.user_address, utils.getChainName(obj.chain))
  229. //日志上报
  230. report.logReport(log_obj)
  231. }
  232. resolve(result)
  233. });
  234. })
  235. }
  236. //出金
  237. async function withdraw(ctx) {
  238. if (ctx.request == null || ctx.request.body == null) {
  239. ctx.body = utils.toJson(-1, null, "request error. ");
  240. return
  241. }
  242. const obj = ctx.request.body;
  243. await withdraw_(obj).then(result => {
  244. ctx.body = result;
  245. })
  246. }
  247. /**
  248. * 查询出金状态
  249. * @param {*} ctx
  250. */
  251. async function getWithdrawStatus(ctx) {
  252. if (ctx.request == null || ctx.request.body == null) {
  253. ctx.body = utils.toJson(-1, null, "request error. ");
  254. return
  255. }
  256. const obj = ctx.request.body;
  257. var info = await withdraw_db.queryWithdrawInfoFromWithdrawId(obj.withdrawId)
  258. logger.log('getWithdrawStatus info', JSON.stringify(info))
  259. if (info) {
  260. // try {
  261. // var ret = await moralis.getTokenTransfers({
  262. // transaction_hash: info.withdraw_hash,
  263. // chain: utils.getChainIdToName(info.chain_id)
  264. // })
  265. // logger.log('getWithdrawStatus getTokenTransfers', ret)
  266. // info.block_timestamp = ''
  267. // if (ret) {
  268. // if (typeof ret === 'string') {
  269. // ret = JSON.parse(ret)
  270. // info.block_timestamp = ret.data.result[0].block_timestamp
  271. // }
  272. // }
  273. // } catch (error) {
  274. // logger.error('getWithdrawStatus getTokenTransfers error', error)
  275. // }
  276. if (info.withdraw_status != 3) {
  277. ctx.body = utils.toJson(0, {
  278. withdrawId: info.withdraw_id,
  279. withdrawStatus: info.withdraw_status,
  280. withdrawHash: info.withdraw_hash,
  281. chainId: info.chain_id,
  282. transferTimestamp: info.update_time,
  283. }, null)
  284. } else {
  285. ctx.body = utils.toJson(-1, null, info.errorMsg)
  286. }
  287. } else {
  288. ctx.body = utils.toJson(-1, null, obj.withdraw_id + ' id does not exist.')
  289. }
  290. }
  291. //获取交易记录
  292. router.post('/getTransfers', getTransfers)
  293. // 获取所有代币价格
  294. router.post('/getAllTotkenPrice', getAllTotkenPrice)
  295. // router.post('/transfer', transfer)
  296. //提现
  297. router.post('/withdraw', withdraw);
  298. //提现鉴权-body 加密
  299. router.post('/withdrawV2', withdrawV2);
  300. //队列的形式
  301. router.post('/withdrawV3', withdrawV3);
  302. //查询出金服务
  303. router.post('/getWithdrawStatus', getWithdrawStatus);
  304. //获取所有地址的所要消耗的最低提取费
  305. router.post('/getAllTokenWithdrawInfoLists', getAllTokenWithdrawInfoLists)
  306. module.exports = router;