sdk.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. 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_PRICE:', tr)
  52. redis.redis_set(reids_token_config.LAST_BNB_PRICE, tr.gas_price.toString());
  53. redis.redis_set(reids_token_config.LAST_TOKEN_PRICE, tr.gas_price.toString());
  54. }
  55. if (json_obj.data.total > 0) {
  56. //提交归集任务
  57. if (temp_obj.address) {
  58. logger.log('pushCollectConisObj>>>', temp_obj.address)
  59. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  60. }
  61. }
  62. if (json_obj.data.total > 0) {
  63. //提交归集任务
  64. if (temp_obj.address) {
  65. logger.log('pushCollectConisObj>>>', temp_obj.address)
  66. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  67. }
  68. }
  69. }
  70. } catch (error) {
  71. console.error('pushCollectConisObj error=', error)
  72. }
  73. }
  74. })
  75. }
  76. /**
  77. * 获取交易记录
  78. * @param {*} ctx
  79. */
  80. async function getTransfersV2(ctx) {
  81. const obj = ctx.request.body;
  82. console.log("getTransfers body", obj);
  83. if (!obj.chain)//默认 bsc 币安链
  84. obj.chain = 'bsc_mainnet'
  85. var temp_obj = { ...obj }
  86. var index = 0
  87. await moralis.getTokenTransfersV2(obj).then((result) => {
  88. logger.log('getTokenTransfersV2 response', 'index=' + index, result)
  89. ctx.body = result;
  90. if (result) {
  91. //提交归集任务 native 能获取到 gas 、token 无法获取到 gas 费
  92. try {
  93. if (temp_obj.address && moralis.isTransferSucceed(result)) {
  94. var log_obj = { ...obj }
  95. log_obj.results = result
  96. log_obj.type = report.REPORT_TYPE.transfer_record
  97. //埋点日志上报-入金检查
  98. report.logReport(log_obj)
  99. var json_obj = JSON.parse(result);
  100. //缓存当前交易的 gas 费用
  101. var tr = moralis.getTransferRecordGasFree('native', json_obj, temp_obj.address)
  102. logger.log('getTransferRecordGasFree:', tr, temp_obj.address)
  103. if (tr && tr.totalGasFree > 0) {
  104. logger.log('getTransferRecordGasFree redis_set LAST_TOTAL_BNB_FREE:', tr)
  105. redis.redis_set(reids_token_config.LAST_BNB_PRICE, tr.gas_price.toString());
  106. redis.redis_set(reids_token_config.LAST_TOKEN_PRICE, tr.gas_price.toString().toString());
  107. }
  108. if (json_obj.data.total > 0) {
  109. //提交归集任务
  110. if (temp_obj.address) {
  111. logger.log('pushCollectConisObj>>>', temp_obj.address)
  112. redis.redis_push(reids_token_config.COLLECT_CONIS_QUEUE_KEY, JSON.stringify(temp_obj))
  113. }
  114. }
  115. }
  116. } catch (error) {
  117. console.error('pushCollectConisObj error=', error)
  118. }
  119. }
  120. })
  121. }
  122. async function getAllTokenWithdrawInfoLists(ctx) {
  123. if (ctx.request == null || ctx.request.body == null) {
  124. ctx.body = utils.toJson(-1, null, "request error. ");
  125. return
  126. }
  127. ctx.body = await moralis.getAllTokenWithdrawInfoLists(ctx);
  128. }
  129. async function collect_conis_task() {
  130. logger.log("collect_conis_task start")
  131. while (true) {
  132. var start_time = utils.getTimestamp()
  133. var exec_obj = await redis.redis_pop(reids_token_config.COLLECT_CONIS_QUEUE_KEY)
  134. if (!exec_obj) {
  135. await utils.sleep(30000)
  136. logger.log("没有归集任务")
  137. continue
  138. }
  139. try {
  140. exec_obj = JSON.parse(exec_obj)
  141. logger.log('collect_conis_task exec item>>>>', exec_obj);
  142. //开始收集用户地址里面的币到归集地址
  143. var ret = await moralis.collectCoins(exec_obj)
  144. logger.log('collect_conis_task ret =', exec_obj, ret)
  145. try {
  146. var ret_obj = JSON.parse(ret)
  147. if (ret_obj.code == 0) {
  148. logger.log('触发归集 delay collect_conis_task ret =', exec_obj, ret)
  149. //间隔 10s 归集,避免提交任务过多
  150. await utils.sleep(10000)
  151. }
  152. } catch (error) { }
  153. } catch (error) {
  154. logger.error('collect_conis_task error', error.toString());
  155. }
  156. logger.log("collect_conis_task cost-time", utils.getTimestamp() - start_time, exec_obj)
  157. }
  158. }
  159. async function withdraw_task() {
  160. logger.log("withdraw_task start")
  161. let last_time = 0
  162. let last_hash = ''
  163. while (true) {
  164. var exec_obj = await redis.redis_pop(reids_token_config.WITHDRAW_QUEUE_KEY)
  165. if (!exec_obj) {
  166. await utils.sleep(60000)
  167. logger.log("没有出金任务")
  168. continue
  169. }
  170. try {
  171. exec_obj = JSON.parse(exec_obj)
  172. } catch (error) {
  173. logger.error('item parse error', error);
  174. break
  175. }
  176. var temp_obj = { ...exec_obj }
  177. if (utils.getTimestamp() - last_time < 60000) {
  178. //有可能上一个区块还未更新,这里做一个尝试限制
  179. //Error: Failed to make "eth_sendRawTransaction" request with networkConnector: "already known"
  180. //通过 交易 hash 获取块。last_hash
  181. if (last_hash) {
  182. var options = {
  183. transaction_hash: last_hash,
  184. chain: temp_obj.chain,
  185. endTime: '2099-01-01'
  186. }
  187. var tryCount = 10;
  188. do {
  189. try {
  190. //通过获取上一个交易记录来进行确认
  191. var transaction = await moralis.getTokenTransfers(options);
  192. logger.log('withdraw_task exectransaction', transaction, options, tryCount);
  193. transaction = JSON.parse(transaction)
  194. if (transaction.code == 0) {
  195. if (transaction.data.result.length <= 0) {
  196. logger.log('等待10s');
  197. await utils.sleep(10000)
  198. } else {
  199. logger.log('等待5s');
  200. await utils.sleep(5000)
  201. break
  202. }
  203. } else {
  204. break
  205. }
  206. tryCount -= 1
  207. } catch (error) {
  208. logger.error('withdraw_task exectransaction', error.toString());
  209. }
  210. } while (tryCount >= 0);
  211. }
  212. }
  213. //如果失败重试一次
  214. var tryCount = 1;
  215. for (let index = 0; index < 1 + tryCount; index++) {
  216. try {
  217. var result = await withdraw_({ ...temp_obj })
  218. last_time = utils.getTimestamp()
  219. logger.log('withdraw_task withdraw_ =', result, last_time)
  220. if (result && moralis.isTransferSucceed(result)) {
  221. var obj = JSON.parse(result)
  222. var nonce = obj.data.nonce
  223. var curGasPrice = BigNumber(obj.data.gasPrice.hex).toNumber()
  224. var curGasLimit = BigNumber(obj.data.gasLimit.hex).toNumber()
  225. var value = BigNumber(obj.data.value.hex).toNumber()
  226. var hash = obj.data.hash
  227. last_hash = hash
  228. var update_obj = {}
  229. update_obj.withdraw_status = 2
  230. update_obj.withdraw_hash = hash
  231. update_obj.nonce = nonce
  232. update_obj.gas_price = curGasPrice.toString()
  233. update_obj.gas_limit = curGasLimit.toString()
  234. update_obj.value = value.toString()
  235. update_obj.errorMsg = ''
  236. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  237. break
  238. } else {
  239. logger.error('withdraw_task withdraw_ error=', result, JSON.stringify(temp_obj))
  240. if (index < 1 + tryCount && result.includes('eth_sendRawTransaction')) {
  241. logger.error('try withdraw_:', JSON.stringify(temp_obj), index)
  242. await utils.sleep(3000)
  243. continue
  244. }
  245. var update_obj = {}
  246. update_obj.withdraw_status = 3
  247. if (typeof result === 'string') {
  248. try {
  249. result = JSON.parse(result)
  250. update_obj.errorMsg = result.errMsg
  251. } catch (error) {
  252. logger.error('withdraw_task=', result)
  253. }
  254. }
  255. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  256. break
  257. }
  258. } catch (error) {
  259. var update_obj = {}
  260. update_obj.withdraw_status = 3
  261. update_obj.errorMsg = error.toString()
  262. await withdraw_db.update_withdraw_task(exec_obj.withdraw_id, update_obj)
  263. logger.error('withdraw_task error=', error.toString())
  264. break
  265. }
  266. }
  267. }
  268. logger.log("withdraw_task end")
  269. }
  270. /**
  271. * 队列版本
  272. * @param {*} ctx
  273. * @returns
  274. */
  275. async function withdrawV3(ctx) {
  276. logger.log('withdrawV3')
  277. if (ctx.request == null || ctx.request.body == null) {
  278. ctx.body = utils.toJson(-1, null, "request error. ");
  279. return
  280. }
  281. const obj = ctx.request.body;
  282. // for (let index = 0; index < 10; index++) {
  283. var log_obj = { ...obj }
  284. logger.log('withdrawV3', log_obj)
  285. var obj_ = decrypt_withdraw_content(log_obj.content)
  286. obj_.withdraw_id = obj_.withdrawId;
  287. // obj_.withdraw_id = utils.getTimestamp().toString();
  288. // var obj_ = log_obj
  289. if (obj_.withdraw_id) {
  290. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  291. if (isExist) {
  292. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  293. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  294. return
  295. }
  296. var info = await moralis.queryCompanyInfoFromId(0);
  297. obj_.user_address = info.user_address
  298. await withdraw_db.create_withdraw_task(obj_)
  299. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  300. // withdraw_task()
  301. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  302. } else {
  303. return utils.toJson(-2, null, ' withdraw_id not empty.')
  304. }
  305. // }
  306. }
  307. async function withdrawV3Test(ctx) {
  308. logger.log('withdrawV3Test')
  309. if (ctx.request == null || ctx.request.body == null) {
  310. ctx.body = utils.toJson(-1, null, "request error. ");
  311. return
  312. }
  313. const obj = ctx.request.body;
  314. // for (let index = 0; index < 10; index++) {
  315. var log_obj = { ...obj }
  316. logger.log('withdrawV3', log_obj)
  317. var obj_ = decrypt_withdraw_content(log_obj.content)
  318. obj_.withdraw_id = obj_.withdrawId;
  319. obj_.withdraw_id = utils.getTimestamp().toString();
  320. // var obj_ = log_obj
  321. if (obj_.withdraw_id) {
  322. var isExist = await withdraw_db.withdraw_id_exist(obj_.withdraw_id)
  323. if (isExist) {
  324. logger.error('withdraw_id_exist', obj_.withdraw_id + ' is already in the queue.')
  325. ctx.body = utils.toJson(-2, null, obj_.withdraw_id + ' is already in the queue.')
  326. return
  327. }
  328. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  329. var info = await moralis.queryCompanyInfoFromId(0);
  330. obj_.user_address = info.user_address
  331. await withdraw_db.create_withdraw_task(obj_)
  332. ctx.body = utils.toJson(0, obj_.withdraw_id, null)
  333. } else {
  334. return utils.toJson(-2, null, ' withdraw_id not empty.')
  335. }
  336. // }
  337. }
  338. function decrypt_withdraw_content(content) {
  339. // const encryptText = utils.encrypt(log_obj);
  340. const encryptText = content;
  341. logger.log("加密", encryptText);
  342. let decryptObj = utils.decrypt(encryptText);
  343. try {
  344. logger.log("解密 before", decryptObj);
  345. decryptObj = JSON.parse(decryptObj);
  346. console.log("解密 json parse", decryptObj);
  347. } catch (error) {
  348. logger.error("json error:", error);
  349. decryptObj = null;
  350. }
  351. return decryptObj;
  352. }
  353. /**
  354. *
  355. * @param {鉴权版本} ctx
  356. */
  357. async function withdrawV2(ctx) {
  358. if (ctx.request == null || ctx.request.body == null) {
  359. ctx.body = utils.toJson(-1, null, "request error. ");
  360. return
  361. }
  362. const obj = ctx.request.body;
  363. var log_obj = { ...obj }
  364. // const encryptText = utils.encrypt(log_obj);
  365. const encryptText = log_obj.content;
  366. logger.log("加密", encryptText);
  367. let decryptObj = utils.decrypt(encryptText);
  368. try {
  369. logger.log("解密 before", decryptObj);
  370. decryptObj = JSON.parse(decryptObj);
  371. // console.log("解密 json parse", decryptObj);
  372. await withdraw_(decryptObj).then(result => {
  373. ctx.body = result;
  374. })
  375. } catch (error) {
  376. logger.error("json error:", error);
  377. ctx.body = utils.toJson(-1, null, error.toString());
  378. }
  379. }
  380. async function withdraw_(obj) {
  381. console.log("withdraw_", obj);
  382. var log_obj = { ...obj }
  383. var info = await moralis.queryCompanyInfoFromId(0);
  384. // log_obj.company_address_total_balance_before = await moralis.queryCollectBalance(info.user_address, obj.chain)
  385. log_obj.company_public_key = info.user_address
  386. logger.log('withdraw log', log_obj);
  387. return new Promise((resolve) => {
  388. moralis.withdraw(obj).then((result) => {
  389. if (moralis.isTransferSucceed(result)) {
  390. //提币日志上报
  391. log_obj.results = result
  392. log_obj.type = report.REPORT_TYPE.withdraw
  393. //缓存当前交易的 gas 费用
  394. if (result && log_obj.contractAddress) {
  395. var tr = moralis.getTransferGasFree('token', result)
  396. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  397. } else {
  398. var tr = moralis.getTransferGasFree('native', result)
  399. log_obj.withdrawTotalGasFee = tr.totalGasFree.toString()
  400. }
  401. // log_obj.receiver_address_total_balance_after = await queryCollectBalance(info.user_address, utils.getChainName(obj.chain))
  402. //日志上报
  403. report.logReport(log_obj)
  404. }
  405. resolve(result)
  406. });
  407. })
  408. }
  409. //出金
  410. async function withdraw(ctx) {
  411. if (ctx.request == null || ctx.request.body == null) {
  412. ctx.body = utils.toJson(-1, null, "request error. ");
  413. return
  414. }
  415. const obj = ctx.request.body;
  416. await withdraw_(obj).then(result => {
  417. ctx.body = result;
  418. })
  419. }
  420. /**
  421. * 查询出金状态
  422. * @param {*} ctx
  423. */
  424. async function getWithdrawStatus(ctx) {
  425. if (ctx.request == null || ctx.request.body == null) {
  426. ctx.body = utils.toJson(-1, null, "request error. ");
  427. return
  428. }
  429. const obj = ctx.request.body;
  430. var info = await withdraw_db.queryWithdrawInfoFromWithdrawId(obj.withdrawId)
  431. logger.log('getWithdrawStatus info', JSON.stringify(info))
  432. if (info) {
  433. if (info.withdraw_status != 3) {
  434. ctx.body = utils.toJson(0, {
  435. withdrawId: info.withdraw_id,
  436. withdrawStatus: info.withdraw_status,
  437. withdrawHash: info.withdraw_hash,
  438. chainId: info.chain_id,
  439. transferTimestamp: info.update_time,
  440. }, null)
  441. } else {
  442. ctx.body = utils.toJson(0, {
  443. withdrawId: info.withdraw_id,
  444. withdrawStatus: info.withdraw_status,
  445. withdrawHash: info.withdraw_hash,
  446. chainId: info.chain_id,
  447. transferTimestamp: info.update_time,
  448. errorMsg: info.errorMsg
  449. }, null)
  450. }
  451. } else {
  452. ctx.body = utils.toJson(-1, null, obj.withdraw_id + ' id does not exist.')
  453. }
  454. }
  455. async function timer_transfer_task() {
  456. var index = 0
  457. var delay = 60 * 1000 * 60
  458. while (1) {
  459. var obj_ = {
  460. "type": "erc20",
  461. "contractAddress": "0xFF94950Ee8A79c52cC4B0Aa5178C8cEa48A3F3A6",
  462. "amount": "111000000000000000000",
  463. "chain": "bsc_testnet",
  464. "receiver": "0x3B525c35DdC323B08241493f148340D89e3A73a7",
  465. "withdrawId": index.toString()
  466. }
  467. obj_.withdraw_id = utils.getTimestamp().toString();
  468. var info = await moralis.queryCompanyInfoFromId(0);
  469. obj_.user_address = info.user_address
  470. await withdraw_db.create_withdraw_task(obj_)
  471. redis.redis_push(reids_token_config.WITHDRAW_QUEUE_KEY, JSON.stringify(obj_))
  472. await utils.sleep(delay)
  473. index += 1
  474. }
  475. }
  476. //获取交易记录
  477. router.post('/getTransfers', getTransfers)
  478. router.post('/getTransfersV2', getTransfersV2)
  479. // 获取所有代币价格
  480. router.post('/getAllTotkenPrice', getAllTotkenPrice)
  481. // router.post('/transfer', transfer)
  482. //提现
  483. router.post('/withdraw', withdraw);
  484. //提现鉴权-body 加密
  485. router.post('/withdrawV2', withdrawV2);
  486. //队列的形式
  487. router.post('/withdrawV3', withdrawV3);
  488. if (process.env.NODE_ENV == 'dev')
  489. router.post('/withdrawV3Test', withdrawV3Test);
  490. //查询出金服务
  491. router.post('/getWithdrawStatus', getWithdrawStatus);
  492. //获取所有地址的所要消耗的最低提取费
  493. router.post('/getAllTokenWithdrawInfoLists', getAllTokenWithdrawInfoLists)
  494. // 定时任务 提币+归集
  495. withdraw_task();
  496. collect_conis_task();
  497. if (process.env.NODE_ENV == 'dev' || process.env.NODE_ENV == 'test')
  498. timer_transfer_task()
  499. module.exports = router