moralis_sdk.js 32 KB

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