moralis_sdk.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  1. /* import moralis */
  2. const Moralis = require("moralis/node");
  3. var utils = require('./utils.js');
  4. // var config = require('../config/config.js')(db_config,
  5. // moralis_config)
  6. var { moralis_config, reids_token_config, account_config } = require('../config/config.js')
  7. const redis = require("./redis_db") //导入 db.js
  8. const mysql = require("./mysql_db")
  9. const logger = require('./logger')
  10. const BigNumber = require('bignumber.js')
  11. /* Moralis init code */
  12. var serverUrl = moralis_config.SERVER_URL;
  13. var appId = moralis_config.APP_ID;
  14. var masterKey = moralis_config.MASTER_KEY;
  15. var moralisSecret = moralis_config.MORALIS_SECRET;
  16. // 内部异常
  17. const ERROR_CODE_001 = -1;
  18. const SUCCEED_CODE = 0;
  19. /**
  20. * 初始化 moralis
  21. * https://st94nif1cq.feishu.cn/docs/doccnNxG2UwHPCdZXbywgbdy13f#
  22. */
  23. async function initMasterSDK() {
  24. await Moralis.start({ serverUrl, appId, masterKey });
  25. }
  26. async function initMoralisSecretSDK() {
  27. await Moralis.start({ serverUrl, appId, moralisSecret });
  28. }
  29. function toJson(code_, obj_, errMsg_) {
  30. return utils.toJson(code_, obj_, errMsg_);
  31. }
  32. /**
  33. * 获取转账的 gas 费
  34. * @param {*} type
  35. * @param {*} json
  36. * @returns
  37. */
  38. function getTransferGasFree(type, json) {
  39. var curGasPrice = account_config.BNB_GAS_PRICE
  40. var curGasLimit = account_config.TOKEN_GAS_LIMIT
  41. var nativeValue = 0;
  42. var tokenValue = 0;
  43. var code = -1;
  44. if (type == 'native') {
  45. curGasLimit = account_config.BNB_GAS_LIMIT
  46. }
  47. var totalGasFree = parseInt(curGasLimit) * parseInt(curGasPrice);
  48. logger.log('getTransferGasFree json=', json)
  49. if (json) {
  50. var obj = JSON.parse(json)
  51. code = obj.code;
  52. logger.log('getTransferGasFree obj=', obj)
  53. if (obj.data && obj.data.gasPrice && obj.data.gasLimit && obj.data.gasPrice.hex && obj.data.gasLimit.hex) {
  54. var curGasPrice = BigNumber(obj.data.gasPrice.hex).toNumber()
  55. var curGasLimit = BigNumber(obj.data.gasLimit.hex).toNumber()
  56. if (curGasPrice > 0 && curGasLimit > 0) {
  57. totalGasFree = curGasPrice * curGasLimit;
  58. }
  59. logger.log('getTransferGasFree totalGasFree=', curGasPrice, curGasLimit, totalGasFree)
  60. if (obj.data.value && obj.data.value.hex) {
  61. var value = BigNumber(obj.data.value.hex).toNumber()
  62. logger.log('getTransferGasFree native value=', value)
  63. if (value != 0) {
  64. nativeValue = value
  65. }
  66. }
  67. }
  68. }
  69. return {
  70. code: code,
  71. totalGasFree: totalGasFree,
  72. nativeValue: nativeValue,
  73. tokenValue: tokenValue,
  74. }
  75. }
  76. /**
  77. *
  78. * @param {转账是否成功} json
  79. */
  80. function isTransferSucceed(json) {
  81. if (json) {
  82. var obj = JSON.parse(json)
  83. return obj.code == 0
  84. }
  85. return false
  86. }
  87. const withdraw = async (obj) => {
  88. obj.withdraw = 1;
  89. return await transfer_handle(obj);
  90. }
  91. async function getAccountBalances(options) {
  92. await initMasterSDK();
  93. if (options.chain) {
  94. options.chain = utils.getChainName(options.chain)
  95. }
  96. logger.log('getAccountBalances :', options)
  97. try {
  98. if (options.type == 'native') {
  99. var opt_ret = await Moralis.Web3API.account.getNativeBalance(options);
  100. logger.log('getNativeBalance=', opt_ret);
  101. return opt_ret
  102. } else {
  103. var aar = await Moralis.Web3API.account.getTokenBalances(options);
  104. logger.log('getTokenBalances=', aar);
  105. return aar;
  106. }
  107. } catch (error) {
  108. logger.log('getAccountBalances error:', error)
  109. return null
  110. }
  111. }
  112. /**
  113. * 获取当前账户下所有不同种类的币 主流币 + 20币
  114. *
  115. * 必填项
  116. * obj.chain = ?
  117. * @param {*} obj
  118. */
  119. async function getAccountAllCoins(obj) {
  120. var temp_chain = obj.chain;
  121. //拿到我当前所有的币种
  122. obj.type = 'native'
  123. obj.chain = temp_chain
  124. var native_balance = await getAccountBalances(obj);
  125. //拿到我当前所有的 20 币
  126. obj.type = '20'
  127. obj.chain = temp_chain
  128. var others_balances = await getAccountBalances(obj);
  129. return {
  130. native: native_balance,
  131. other: others_balances,
  132. }
  133. }
  134. /**
  135. * 判断是否转 gas 费
  136. * @param {*} my_account_all_coins
  137. */
  138. async function computeTransferGasFree(obj, my_account_all_coins, tokenPrices) {
  139. var totalCount = 0;
  140. var tokenCount = 0;
  141. var tokenGasPrice = 0;
  142. var nativeGasPrice = 0;
  143. var ret_total_gas_price = 0;
  144. var ret_total_count = 0;
  145. var ret_a_gas = 0;
  146. //需要转账的数组对象
  147. var transfer_obj = [];
  148. var receiver_info = await queryCompanyInfoFromId(0);
  149. //得到 20 币 满足 1美刀的 count
  150. if (Array.isArray(my_account_all_coins.other) && my_account_all_coins.other.length > 0) {
  151. my_account_all_coins.other.forEach(element => {
  152. logger.debug('20 element=', element);
  153. var find_transfer_item = findTokenPriceItem(element.token_address, tokenPrices);
  154. if (find_transfer_item) {
  155. var total_all_usdprice = calculate_total_usdprice(element.balance, element.decimals, find_transfer_item.usdPrice);
  156. logger.debug('findTokenPriceItem ret=', element.token_address, find_transfer_item, total_all_usdprice);
  157. if (find_transfer_item && total_all_usdprice > 1.0) {
  158. tokenCount += 1;
  159. logger.debug('token > 1.0', tokenCount, element.token_address);
  160. var obj_20 = {
  161. chain: obj.chain,
  162. contractAddress: element.token_address,
  163. amount: element.balance,
  164. receiver: receiver_info.user_address,
  165. type: 'erc20',
  166. address: obj.address,
  167. }
  168. transfer_obj.push(obj_20)
  169. }
  170. } else {
  171. logger.log('findTokenPriceItem error=', element);
  172. }
  173. });
  174. logger.log('account_config.TOKEN_GAS_LIMIT=', account_config.TOKEN_GAS_LIMIT);
  175. var lastTokenFree = await redis.readRedis(reids_token_config.LAST_TOTAL_TOKEN_FREE)
  176. logger.log('LAST_TOTAL_TOKEN_FREE=', lastTokenFree);
  177. if (lastTokenFree && reids_token_config.LAST_TOTAL_TOKEN_FREE && parseInt(lastTokenFree) > 0) {
  178. tokenGasPrice = parseInt(tokenCount) * parseInt(lastTokenFree);
  179. } else {
  180. tokenGasPrice = parseInt(tokenCount) * parseInt(account_config.TOKEN_GAS_LIMIT) * parseInt(account_config.BNB_GAS_PRICE);
  181. }
  182. ret_a_gas = account_config.BNB_GAS_PRICE;
  183. logger.log('tokenGasPrice=', tokenGasPrice);
  184. }
  185. //计算 native 是否满足 1美刀
  186. logger.log('isTransferGasFree token count:', tokenCount);
  187. var nativeAllBalance = my_account_all_coins.native.balance;
  188. var nativeCount = 0
  189. var nativePriceItem = findTokenPriceItem('0x0000000000000000000000000000000000000000', tokenPrices);//todo 线上环境需要换
  190. logger.debug('native nativePriceItem=', nativePriceItem, nativeAllBalance);
  191. if (nativePriceItem) {
  192. var total_all_usdprice = calculate_total_usdprice(nativeAllBalance, '18', nativePriceItem.usdPrice);
  193. logger.debug('native total_all_usdprice=', total_all_usdprice);
  194. if (total_all_usdprice > 1.0) {
  195. nativeCount = 1;
  196. logger.debug('native > 1.0', tokenCount);
  197. var lastBnbFree = await redis.readRedis(reids_token_config.LAST_TOTAL_BNB_FREE)
  198. logger.log('LAST_TOTAL_BNB_FREE=', lastBnbFree);
  199. if (lastTokenFree && reids_token_config.LAST_TOTAL_TOKEN_FREE && parseInt(lastTokenFree) > 0) {
  200. nativeGasPrice = parseInt(nativeCount) * parseInt(lastBnbFree);
  201. } else {
  202. nativeGasPrice = parseInt(nativeCount) * parseInt(account_config.BNB_GAS_LIMIT) * parseInt(account_config.BNB_GAS_PRICE);
  203. }
  204. ret_a_gas = account_config.BNB_GAS_PRICE;
  205. var real_native_amount = BigInt(nativeAllBalance) - BigInt(nativeGasPrice) - BigInt(tokenGasPrice);
  206. var obj_native = {
  207. chain: obj.chain,
  208. amount: real_native_amount.toString(),
  209. receiver: receiver_info.user_address,
  210. type: 'native',
  211. address: obj.address,
  212. }
  213. transfer_obj.push(obj_native)
  214. }
  215. }
  216. logger.log('transfer obj=', transfer_obj)
  217. //计算所有币转账所需要的 gas
  218. totalCount = nativeCount + tokenCount;
  219. // var gasPrice = await redis.readRedis(reids_token_config.GASPRICE);
  220. logger.log('nativeAllBalance', nativeAllBalance);
  221. logger.log('totalCount', totalCount);
  222. var total2Gas = nativeGasPrice + tokenGasPrice;
  223. var service_charge = 0;
  224. logger.log('total2Gas', total2Gas);
  225. //需要转账的 obj
  226. my_account_all_coins.transfer_arrays = transfer_obj
  227. //如果当前的钱不够 gas
  228. if (nativeAllBalance < total2Gas) {
  229. if (tokenCount > 0) {//出现 token 需要转移手续费
  230. service_charge = 1;
  231. // total2Gas = (total2Gas - nativeAllBalance);//充手续费
  232. logger.log('需要转账=', total2Gas);
  233. }
  234. }
  235. ret_total_gas_price = total2Gas.toString();
  236. ret_total_count = totalCount;
  237. //返回结果
  238. return {
  239. gasPrice: ret_total_gas_price, //需要 归集到用户地址的 gas 费转移
  240. totalCount: ret_total_count, //一共归集次数
  241. aGasPrice: ret_a_gas, //单个 gas 费用
  242. get_service_charge: service_charge,//是否需要服务费
  243. };
  244. }
  245. function findTokenPriceItem(token_address, tokenPrices) {
  246. return tokenPrices.tokenPrice.find(element => {
  247. // logger.log('findTokenPriceItem find=', element.contract, token_address)
  248. return element.contract.toLowerCase() == token_address.toLowerCase();
  249. })
  250. }
  251. // function calculate_total_usdprice(amount, decimals, usdprice) {
  252. // return parseInt(amount) / (10**parseInt(decimals)) * parseInt(usdprice) ;
  253. function calculate_total_usdprice(amount, decimals, usdprice) {
  254. return parseInt(amount) / (10 ** parseInt(decimals)) * parseFloat(usdprice);
  255. }
  256. function addNativeValue(nativeValue, aValue) {
  257. return BigInt(nativeValue) + BigInt(aValue)
  258. }
  259. function reduceNativeValue(nativeValue, rValue) {
  260. return BigInt(nativeValue) - BigInt(rValue)
  261. }
  262. /**
  263. * todo --> 计算 gas
  264. * @param {*} nativeBalance
  265. * @param {*} obj
  266. * @returns
  267. */
  268. async function updateNativeBalance(nativeBalance, obj) {
  269. var temp = obj
  270. var retryCount = 30;
  271. do {
  272. //上面转账完 BNB 会减去,这里再获取一次
  273. var native_ret = await Moralis.Web3API.account.getNativeBalance(temp);
  274. logger.log('更新余额 :', native_ret, retryCount)
  275. if (nativeBalance != native_ret.balance) {
  276. return native_ret.balance;
  277. }
  278. await utils.sleep(3000);
  279. retryCount--;
  280. } while (native_ret.balance == nativeBalance && retryCount > 0);
  281. return null;
  282. }
  283. //20 and native 归集
  284. async function transfers(obj, my_account_all_coins) {
  285. // 优化后的归集
  286. if (my_account_all_coins && my_account_all_coins.transfer_arrays && Array.isArray(my_account_all_coins.transfer_arrays) && my_account_all_coins.transfer_arrays.length > 0) {
  287. var t_i = 0;
  288. for (let index = 0; index < my_account_all_coins.transfer_arrays.length; index++) {
  289. var ti = my_account_all_coins.transfer_arrays[index]
  290. logger.tlog('ti=', ti)
  291. var ret = await start_collectCoins(ti)
  292. //更新 native 金额
  293. if (isTransferSucceed(ret)) {
  294. logger.tlog('start_collectCoins respose...', ret);
  295. t_i += 1
  296. } else {
  297. logger.tlog('start_collectCoins error=', ret);
  298. t_err.push(ret)
  299. };
  300. }
  301. if(t_i == my_account_all_coins.transfer_arrays.length){
  302. return toJson(0, null, '所有币归集成功.');
  303. }else {
  304. return toJson(-1, null, '归集失败.');
  305. }
  306. } else {
  307. return toJson(-1, null, 'transfer conditions are not met.');
  308. }
  309. //v0.1 版本归集
  310. // var address = obj.address;
  311. // var chain = obj.chain;
  312. // var tokenPrices = obj.tokenPrices;
  313. // logger.log('tokenPrices=', tokenPrices, my_account_all_coins);
  314. // var nativeValue = my_account_all_coins.native.balance;
  315. // if (!my_account_all_coins || !tokenPrices) return 'error.'
  316. // logger.log(' my_account_all_coins.other.lenth=', my_account_all_coins.other.length);
  317. // var isUpdateNativeBalance = 0;
  318. // //token 归集
  319. // if (my_account_all_coins.other && Array.isArray(my_account_all_coins.other) && my_account_all_coins.other.length > 0) {
  320. // var available = Array.isArray(tokenPrices.tokenPrice) && tokenPrices.tokenPrice.length > 0
  321. // if (!available) return -1;
  322. // for (let i = 0; i < my_account_all_coins.other.length; ++i) {
  323. // var transfer_item = my_account_all_coins.other[i];
  324. // if (my_account_all_coins.other[i].token_address != null) {
  325. // var find_transfer_item = findTokenPriceItem(transfer_item.token_address, tokenPrices);
  326. // //todo 计算 token 币价格 * token美元单价
  327. // if (find_transfer_item && calculate_total_usdprice(transfer_item.balance, transfer_item.decimals, find_transfer_item.usdPrice) > 1.0) {
  328. // var info = await queryCompanyInfoFromId(0);
  329. // var obj_20 = {
  330. // chain: obj.chain,
  331. // contractAddress: transfer_item.token_address,
  332. // amount: transfer_item.balance,
  333. // receiver: info.user_address,
  334. // type: 'erc20',
  335. // address: address,
  336. // }
  337. // logger.log('start_collectCoins erc20:', obj_20);
  338. // logger.log('calculate_total_usdprice 20', calculate_total_usdprice(transfer_item.balance, transfer_item.decimals, '0.1'));
  339. // isUpdateNativeBalance = 1;
  340. // var ret = await start_collectCoins(obj_20)
  341. // logger.log('start_collectCoins erc20 respose...', ret);
  342. // //更新 native 金额
  343. // if (!isTransferSucceed(ret)) return ret;
  344. // var transfer = getTransferGasFree('token', ret)
  345. // if (transfer && transfer.totalGasFree > 0) {
  346. // logger.log('start_collectCoins 20 tempNativeValue=', my_account_all_coins.native.balance)
  347. // var tempNativeValue = reduceNativeValue(nativeValue, transfer.totalGasFree)
  348. // my_account_all_coins.native.balance = tempNativeValue.toString();
  349. // logger.log('start_collectCoins 20 udpateNativeValue=', tempNativeValue);
  350. // } else return "get native value error."
  351. // } else {
  352. // logger.error('find_transfer_item error.', transfer_item);
  353. // }
  354. // } else {
  355. // logger.error('token Must be greater than a dollar.', transfer_item.balance, transfer_item.decimals);
  356. // // return toJson(-1, null, 'token Must be greater than a dollar.');
  357. // }
  358. // }
  359. // }
  360. // //native 归集
  361. // if (my_account_all_coins.native) {
  362. // logger.log('查询本地余额参数=', obj)
  363. // if (obj.chain) {
  364. // obj.chain = utils.getChainName(obj.chain)
  365. // }
  366. // obj.chain = chain;
  367. // logger.log('查询本地余额 after', my_account_all_coins.native)
  368. // var find_native_item = findTokenPriceItem('0x0000000000000000000000000000000000000000', tokenPrices);
  369. // //todo 计算 token 币价格 * token美元单价
  370. // if (find_native_item) {
  371. // var nativeCoins = calculate_total_usdprice(my_account_all_coins.native.balance, '18', find_native_item.usdPrice);
  372. // logger.log('start_collectCoins nativeCoins:', nativeCoins, obj);
  373. // logger.log('start_collectCoins obj:', obj);
  374. // logger.log('start_collectCoins native.balance:', my_account_all_coins.native.balance);
  375. // if (nativeCoins > 1.0) {
  376. // logger.log('native.balance', my_account_all_coins.native.balance)
  377. // logger.log('aGasPrice', obj.transFerGasFree.aGasPrice)
  378. // logger.log('gasLimint', account_config.BNB_GAS_LIMIT)
  379. // // var gasPrice = BigInt(obj.transFerGasFree.aGasPrice);
  380. // var gasPrice = BigInt(account_config.BNB_GAS_PRICE);
  381. // var gasLimit = BigInt(account_config.BNB_GAS_LIMIT);
  382. // var nativeBalance = BigInt(my_account_all_coins.native.balance);
  383. // logger.log('native.balance>>>', nativeBalance)
  384. // logger.log('aGasPrice>>>', gasPrice)
  385. // logger.log('gasLimint>>>', gasLimit)
  386. // var real_native_amount = nativeBalance - gasPrice * gasLimit;
  387. // logger.log('start_collectCoins native amount:', real_native_amount.toString());
  388. // var info = await queryCompanyInfoFromId(0);
  389. // obj = {
  390. // chain: chain,
  391. // amount: real_native_amount.toString(),
  392. // receiver: info.user_address,
  393. // type: 'native',
  394. // address: address,
  395. // }
  396. // logger.log('start_collectCoins native:', obj);
  397. // logger.log('calculate_total_usdprice native', nativeCoins, find_native_item);
  398. // return await start_collectCoins(obj)
  399. // } else {
  400. // logger.error('native Must be greater than a dollar.', obj);
  401. // return toJson(-1, null, 'native Must be greater than a dollar.');
  402. // }
  403. // } else {
  404. // logger.error('native Must be greater than a dollar.', obj);
  405. // return toJson(-1, null, 'native Must be greater than a dollar.');
  406. // }
  407. // }
  408. }
  409. const start_collectCoins = async (obj) => {
  410. obj.withdraw = 0;
  411. return await transfer_handle(obj);
  412. }
  413. const transfer_handle = async (obj) => {
  414. //提币
  415. if (obj.withdraw) {
  416. var id = 0
  417. if (obj.privateKeyId)
  418. id = obj.privateKeyId
  419. //读取用户充币地址对应的私钥
  420. var info = await queryCompanyInfoFromId(id);
  421. logger.log('transfer_handle queryCompanyInfoFromId=', info);
  422. //提币公司
  423. obj.privateKey = info.user_private_key;
  424. // if (process.env.NODE_ENV != 'dev') {
  425. logger.debug('readCompanyPriveteKeyFromMysql=', obj.privateKey)
  426. // }
  427. } else {
  428. //读取用户充币地址对应的私钥
  429. obj.privateKey = await readPriveteKeyFromMysql(obj.address);
  430. }
  431. if (obj.privateKey && obj.privateKey.results) {
  432. obj.privateKey = obj.privateKey.results;
  433. }
  434. if (!obj.privateKey) {
  435. return toJson(-1, null, "readPriveteKeyFromMysql error.");
  436. }
  437. try {
  438. //解密
  439. obj.privateKey = utils.decryptPrivityKey(obj.privateKey);
  440. if (!obj.privateKey) {
  441. return toJson(-1, null, "decryptPrivityKey error.");
  442. }
  443. } catch (error) {
  444. if (!obj.privateKey) {
  445. return toJson(-1, null, "decryptPrivityKey error.", error.toString());
  446. }
  447. }
  448. if (!obj.privateKey) {
  449. return toJson(-1, null, "decryptPrivityKey error.");
  450. }
  451. var ret = await transfer(obj);
  452. if (isTransferSucceed(ret)) {
  453. //缓存当前交易的 gas 费用
  454. if (ret && obj.contractAddress) {
  455. var tr = getTransferGasFree('token', ret)
  456. logger.debug('cache setkey token LAST_TOTAL_TOKEN_FREE getTransferGasFree', tr)
  457. redis.redis_set(reids_token_config.LAST_TOTAL_TOKEN_FREE, tr.totalGasFree);
  458. } else {
  459. var tr = getTransferGasFree('native', ret)
  460. logger.debug('cache setkey LAST_TOTAL_BNB_FREE getTransferGasFree', tr)
  461. redis.redis_set(reids_token_config.LAST_TOTAL_BNB_FREE, tr.totalGasFree);
  462. }
  463. }
  464. return ret;
  465. }
  466. /**
  467. * 用户充币地址的币转移到归集地址
  468. * 1、检查当前账户的 主流币或者 20 币,是否满足一美刀,并且查看是否满足转账费用 n 如果不满足,先从归集地址 -> 用户提币地址(0.*2 来回2次转移)
  469. * 2、发起归集 用户账户 -> 从 mysql 拿到私钥进行解密 -> 转移到归集地址
  470. *
  471. *
  472. * @param {*} obj
  473. */
  474. const collectCoins = async (obj) => {
  475. var chain = obj.chain;
  476. //1、拿到当前账户所有的币
  477. //2、是否满足交易费 如果不满足则 归集地址转移 币count * 手续费 到充币地址
  478. //3、遍历所有币,开始转移到归集地址
  479. var my_account_all_coins = await getAccountAllCoins(obj);
  480. //得到币价格
  481. obj.tokenPrices = await redis.readRedis(reids_token_config.TOKENPRICE)
  482. if (!obj.tokenPrices) return 'readRedis error'
  483. if (typeof obj.tokenPrices == 'string')
  484. obj.tokenPrices = JSON.parse(obj.tokenPrices);
  485. obj.chain = chain;
  486. //计算 gas 费用 是否需要归集
  487. var transFerGasFree = await computeTransferGasFree(obj, my_account_all_coins, obj.tokenPrices);
  488. logger.log('computeTransferGasFree=', transFerGasFree)
  489. if (transFerGasFree) {
  490. // return
  491. }
  492. //是否需要归集
  493. if (transFerGasFree.totalCount > 0) {
  494. //需要转移 gas 费
  495. //每次都需要充值 gas 费
  496. if (account_config.TRANSFER_GAS || (parseInt(transFerGasFree.gasPrice) > 0 && transFerGasFree.get_service_charge == 1)) {
  497. var info = await queryCompanyInfoFromId(0);
  498. var obj_wd = {
  499. chain: chain,
  500. amount: transFerGasFree.gasPrice,
  501. receiver: obj.address,
  502. type: 'native',
  503. // address: account_config.WELLET_PUBLIC_KEY, //todo 正式环境需要替换从 mysql read
  504. address: info.user_address, //todo 正式环境需要替换从 mysql read
  505. }
  506. logger.log('开始充值 gas ', obj_wd)
  507. var ret = await withdraw(obj_wd)
  508. logger.log('充值完成 gas ', ret)
  509. if (!isTransferSucceed(ret)) return ret;
  510. var transfer = getTransferGasFree('native', ret)
  511. logger.log('getTransferGasFree transfer =', transfer)
  512. if (transfer && transfer.nativeValue > 0) {
  513. logger.log('tempNativeValue=', my_account_all_coins.native.balance)
  514. var tempNativeValue = addNativeValue(my_account_all_coins.native.balance, transfer.nativeValue)
  515. my_account_all_coins.native.balance = tempNativeValue.toString();
  516. logger.log('udpateNativeValue=', tempNativeValue);
  517. } else return "get native value error."
  518. }
  519. obj.chain = chain;
  520. obj.transFerGasFree = transFerGasFree;
  521. logger.log('transfers--->', obj);
  522. var ret = await transfers(obj, my_account_all_coins);
  523. logger.log('归集结果=', ret);
  524. return ret;
  525. }
  526. return obj.address + ':不满足归集条件';
  527. }
  528. var collectCoinsArrays = [];
  529. var lastCollectCoinsAddress;
  530. var isExecCollect = false;
  531. async function execCollectCoinsTask() {
  532. if (isExecCollect) return
  533. isExecCollect = true;
  534. while (collectCoinsArrays.length > 0) {
  535. var obj = collectCoinsArrays.pop();
  536. //开始收集用户地址里面的币到归集地址
  537. var ret = await collectCoins(obj);
  538. // await utils.sleep(3000)
  539. logger.log('execCollectCoinsTask=', collectCoinsArrays.length, ret)
  540. }
  541. isExecCollect = false;
  542. lastCollectCoinsAddress = ''
  543. }
  544. function pushCollectConisObj(obj) {
  545. logger.debug('collectCoinsArrays length=', collectCoinsArrays.length, lastCollectCoinsAddress)
  546. if (collectCoinsArrays.length > 0) {
  547. var findItem = collectCoinsArrays.find(element => {
  548. return (obj.address == element.address) || (!lastCollectCoinsAddress && lastCollectCoinsAddress == element.address)
  549. })
  550. if (findItem) {
  551. logger.log('当前任务正在处理中...', obj.address)
  552. return;
  553. }
  554. }
  555. collectCoinsArrays.push(obj)
  556. execCollectCoinsTask();
  557. lastCollectCoinsAddress = obj.address;
  558. }
  559. async function readPriveteKeyFromMysql(address) {
  560. return new Promise(resolve => {
  561. mysql.queryUserPrivateKeyFromUserAddress(address).then(ret => {
  562. logger.log('readPriveteKeyFromMysql=', ret);
  563. resolve(ret);
  564. })
  565. })
  566. }
  567. async function queryCompanyInfoFromId(id) {
  568. return new Promise(resolve => {
  569. mysql.queryCompanyInfoFromId(id).then(ret => {
  570. logger.log('queryCompanyInfoFromId=', ret, ret.results, ret.results.user_address, ret.results.user_private_key);
  571. resolve(ret.results);
  572. })
  573. })
  574. }
  575. const transfer = async (obj) => {
  576. logger.debug("fun transfer serverUrl ", serverUrl);
  577. logger.debug("fun transfer appId ", serverUrl);
  578. logger.debug("fun transfer moralisSecret ", moralisSecret);
  579. await initMoralisSecretSDK();
  580. // initSDK(moralisSecret);
  581. logger.debug("fun transfer start ok ");
  582. const opts = {};
  583. opts.chainId = 'bsc_testnet';
  584. opts.privateKey = moralis_config.DEFAULT_PRIVATE_KEY;
  585. opts.type = "erc20"; //native erc20
  586. if (!obj.receiver || !obj.amount || parseInt(obj.amount) <= 0) {
  587. logger.error("transfer fun transfer parameter error.", obj.receiver, obj.amount, obj.amount);
  588. return toJson(ERROR_CODE_001, null, "please check receiver or amount parameter is ok ?");
  589. }
  590. if (obj.chain != null) {
  591. opts.chainId = utils.getChainId(obj.chain);
  592. console.log("chainId:", opts.chainId);
  593. }
  594. if (obj.type != null) {
  595. opts.type = obj.type;
  596. }
  597. if (obj.from_block != null) {
  598. opts.from_block = obj.from_block;
  599. }
  600. if (obj.to_block != null) {
  601. opts.to_block = obj.to_block;
  602. }
  603. opts.contractAddress = obj.contractAddress;
  604. opts.receiver = obj.receiver;
  605. //调用者传入
  606. // opts.amount = Moralis.Units.Token(obj.amount, 18);
  607. opts.amount = obj.amount;
  608. if (obj.privateKey != null) {
  609. opts.privateKey = obj.privateKey;
  610. }
  611. try {
  612. // sending 0.5 DAI tokens with 18 decimals on BSC testnet
  613. var options;
  614. if (opts.contractAddress) { //如果存在就是代币
  615. options = Moralis.TransferOptions = {
  616. type: opts.type,
  617. amount: opts.amount,
  618. receiver: opts.receiver, //接收钱包地址
  619. contractAddress: opts.contractAddress //用户合约地址
  620. };
  621. logger.tlog("options 20 =", options);
  622. } else { //ETH or BNB
  623. options = Moralis.TransferOptions = {
  624. type: opts.type,
  625. amount: opts.amount,
  626. receiver: opts.receiver, //接收钱包地址
  627. };
  628. logger.tlog("options native =", options, opts.chainId);
  629. }
  630. // Enable web3
  631. await Moralis.enableWeb3({
  632. //BSC mainnet = 0x38-56 testnet:0x61-97
  633. chainId: opts.chainId,
  634. privateKey: opts.privateKey,
  635. });
  636. logger.tlog("options id =", opts.chainId);
  637. var ret = await Moralis.transfer(options);
  638. logger.tlog("transfer 结果 =", ret);
  639. return toJson(SUCCEED_CODE, ret, "");
  640. } catch (error) {
  641. logger.tlog('transfer error:', error);
  642. if (error.reason != null) {
  643. return toJson(ERROR_CODE_001, null, error.toString());
  644. } else {
  645. return toJson(ERROR_CODE_001, null, error);;
  646. }
  647. }
  648. };
  649. const getAllTokenWithdrawInfoLists = async (obj) => {
  650. try {
  651. var key = reids_token_config.TOKENWITHDRAW;
  652. var ret = await redis.readRedis(key);
  653. return toJson(SUCCEED_CODE, ret, null);
  654. } catch (error) {
  655. console.error("getAllTokenWithdrawInfoLists=", error);
  656. return toJson(ERROR_CODE_001, null, error.toString());
  657. }
  658. }
  659. /**
  660. * 获取代币价格 -> usdPrice
  661. */
  662. const getAllTotkenPrice = async () => {
  663. try {
  664. logger.log('当前环境:', process.env.NODE_ENV);
  665. logger.log("getAllTotkenPrice in", reids_token_config); // Prints "value"
  666. var token_price_key = reids_token_config.TOKENPRICE;
  667. logger.log("getAllTotkenPrice token_price_key=", token_price_key);
  668. return await redis.readRedis(token_price_key)
  669. } catch (error) {
  670. logger.error("getTotkenPrice=", error);
  671. return toJson(ERROR_CODE_001, null, error.toString());
  672. }
  673. }
  674. function setTransfersDataType(type, ret) {
  675. if (ret && Array.isArray(ret) && ret.length > 0) {
  676. ret.forEach(element => {
  677. element.type = type;
  678. });
  679. }
  680. }
  681. //获取交易记录
  682. //hash 0xe09ba3a4c9f7a8902e01af68d0f1f91906f3f7db1195227e61c45c0e86b2630a
  683. async function getTokenTransfers(opt) {
  684. await initMasterSDK();
  685. logger.debug("fun getTokenTransfers in ", opt);
  686. const options = {};
  687. options.type = 'all';
  688. options.chain = 'bsc_mainnet';
  689. if (opt.chain != null) {
  690. options.chain = utils.getChainName(opt.chain);
  691. logger.log('getTokenTransfers=', options.chain);
  692. }
  693. if (opt.order != null) {
  694. options.order = opt.order;
  695. }
  696. if (opt.startTime != null) {
  697. options.from_date = opt.startTime;
  698. }
  699. if (opt.endTime != null) {
  700. options.to_date = opt.endTime;
  701. }
  702. if (opt.from_block != null) {
  703. options.from_block = opt.from_block;
  704. }
  705. if (opt.to_block != null) {
  706. options.to_block = opt.to_block;
  707. }
  708. if (opt.transaction_hash) {
  709. options.transaction_hash = opt.transaction_hash;
  710. options.type = 'transaction_hash';
  711. }
  712. logger.debug('getTokenTransfers-->>>', options);
  713. if (options.type == 'all') {//查询主流币和 20 币所有的交易
  714. try {
  715. if (opt.address != null) {
  716. options.address = opt.address;
  717. } else {
  718. return toJson(ERROR_CODE_001, null, "please check address parameter is ok ?");
  719. }
  720. //主流币
  721. var t_1 = await Moralis.Web3API.account.getTransactions(options);
  722. setTransfersDataType('native', t_1.result)
  723. //20币
  724. var t_2 = await Moralis.Web3API.account.getTokenTransfers(options);
  725. setTransfersDataType('token', t_2.result)
  726. let arr = t_1.result;
  727. let arr1 = t_2.result;
  728. if (Array.isArray(arr1) && Array.isArray(arr)) {
  729. let arr2 = arr.concat(arr1);
  730. t_1.result = arr2;
  731. }
  732. //将结果排序
  733. t_1.result.sort((a, b) => {
  734. let t1 = new Date(Date.parse(a.block_timestamp))
  735. let t2 = new Date(Date.parse(b.block_timestamp))
  736. return t2.getTime() - t1.getTime()
  737. })
  738. return toJson(SUCCEED_CODE, t_1, null);
  739. } catch (error) {
  740. logger.error("getTransactions error:", error)
  741. return toJson(ERROR_CODE_001, null, error);;
  742. }
  743. } else if (options.type == 'transaction_hash') {//根据哈希查询
  744. try {
  745. //native
  746. const transaction = await Moralis.Web3API.native.getTransaction(options);
  747. var arr = [];
  748. if (transaction)
  749. arr.push(transaction)
  750. var obj = { result: arr }
  751. return toJson(SUCCEED_CODE, obj, null);
  752. } catch (error) {
  753. logger.error("native getTransaction error:", error)
  754. return toJson(ERROR_CODE_001, null, error);
  755. }
  756. } else {
  757. return toJson(ERROR_CODE_001, null, "This type is not supported.");;
  758. }
  759. }
  760. module.exports = {
  761. transfer,
  762. getTokenTransfers,
  763. toJson,
  764. getAllTokenWithdrawInfoLists,
  765. getAllTotkenPrice,
  766. withdraw,
  767. collectCoins,
  768. pushCollectConisObj,
  769. }