sdk.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  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. update_obj.errorMsg = result
  116. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  117. }
  118. } catch (error) {
  119. logger.log('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.log("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.log("json error:", error);
  196. ctx.body = utils.toJson(-1, null, error.toString());
  197. }
  198. }
  199. function loop_test() {
  200. var obj = {
  201. type: "erc20",
  202. contractAddress: "0x03716F32f72c692a0B355fa04639669E3341B94e",
  203. amount: "112000000000000000000",
  204. chain: "bsc_testnet",
  205. receiver: "0x7C7401fcc82D1e53C4090561c3e6fde80d74e317"
  206. }
  207. var obj2 = {
  208. type: "erc20",
  209. contractAddress: "0x03716F32f72c692a0B355fa04639669E3341B94e",
  210. amount: "113000000000000000000",
  211. chain: "bsc_testnet",
  212. receiver: "0x741050F44196Ad4b427AC5E97beB7715FD0127E7"
  213. }
  214. withdraw_(obj)
  215. withdraw_(obj2)
  216. }
  217. async function withdraw_(obj) {
  218. console.log("withdraw_", obj);
  219. var log_obj = { ...obj }
  220. var info = await moralis.queryCompanyInfoFromId(0);
  221. log_obj.company_address_total_balance_before = await moralis.queryCollectBalance(info.user_address, obj.chain)
  222. log_obj.company_public_key = info.user_address
  223. logger.log('withdraw log', log_obj);
  224. return new Promise((resolve) => {
  225. moralis.withdraw(obj).then((result) => {
  226. if (moralis.isTransferSucceed(result)) {
  227. //提币日志上报
  228. log_obj.results = result
  229. log_obj.type = report.REPORT_TYPE.withdraw
  230. //缓存当前交易的 gas 费用
  231. if (result && log_obj.contractAddress) {
  232. var tr = moralis.getTransferGasFree('token', result)
  233. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  234. } else {
  235. var tr = moralis.getTransferGasFree('native', result)
  236. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  237. }
  238. // log_obj.receiver_address_total_balance_after = await queryCollectBalance(info.user_address, utils.getChainName(obj.chain))
  239. //日志上报
  240. report.logReport(log_obj)
  241. }
  242. resolve(result)
  243. });
  244. })
  245. }
  246. //出金
  247. async function withdraw(ctx) {
  248. if (ctx.request == null || ctx.request.body == null) {
  249. ctx.body = utils.toJson(-1, null, "request error. ");
  250. return
  251. }
  252. const obj = ctx.request.body;
  253. await withdraw_(obj).then(result => {
  254. ctx.body = result;
  255. })
  256. }
  257. /**
  258. * 查询出金状态
  259. * @param {*} ctx
  260. */
  261. async function getWithdrawStatus(ctx) {
  262. if (ctx.request == null || ctx.request.body == null) {
  263. ctx.body = utils.toJson(-1, null, "request error. ");
  264. return
  265. }
  266. const obj = ctx.request.body;
  267. var info = await withdraw_db.queryWithdrawInfoFromWithdrawId(obj.withdraw_id)
  268. logger.log('getWithdrawStatus info', JSON.stringify(info))
  269. if (info) {
  270. // try {
  271. // var ret = await moralis.getTokenTransfers({
  272. // transaction_hash: info.withdraw_hash,
  273. // chain: utils.getChainIdToName(info.chain_id)
  274. // })
  275. // logger.log('getWithdrawStatus getTokenTransfers', ret)
  276. // info.block_timestamp = ''
  277. // if (ret) {
  278. // if (typeof ret === 'string') {
  279. // ret = JSON.parse(ret)
  280. // info.block_timestamp = ret.data.result[0].block_timestamp
  281. // }
  282. // }
  283. // } catch (error) {
  284. // logger.error('getWithdrawStatus getTokenTransfers error', error)
  285. // }
  286. ctx.body = utils.toJson(0, {
  287. withdrawId: info.withdraw_id,
  288. withdrawStatus: info.withdraw_status,
  289. withdrawHash: info.withdraw_hash,
  290. chainId: info.chain_id,
  291. transferTimestamp: info.update_time,
  292. }, null)
  293. } else {
  294. ctx.body = utils.toJson(-1, null, obj.withdraw_id + ' id does not exist.')
  295. }
  296. }
  297. //获取交易记录
  298. router.post('/getTransfers', getTransfers)
  299. // 获取所有代币价格
  300. router.post('/getAllTotkenPrice', getAllTotkenPrice)
  301. // router.post('/transfer', transfer)
  302. //提现
  303. router.post('/withdraw', withdraw);
  304. //提现鉴权-body 加密
  305. router.post('/withdrawV2', withdrawV2);
  306. //队列的形式
  307. router.post('/withdrawV3', withdrawV3);
  308. //查询出金服务
  309. router.post('/getWithdrawStatus', getWithdrawStatus);
  310. //获取所有地址的所要消耗的最低提取费
  311. router.post('/getAllTokenWithdrawInfoLists', getAllTokenWithdrawInfoLists)
  312. module.exports = router;