moralis_sdk.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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 real_native_amount = BigInt(nativeAllBalance);
  207. var obj_native = {
  208. chain: obj.chain,
  209. amount: real_native_amount.toString(),
  210. receiver: receiver_info.user_address,
  211. type: 'native',
  212. address: obj.address,
  213. }
  214. transfer_obj.push(obj_native)
  215. }
  216. }
  217. logger.log('transfer obj=', transfer_obj)
  218. //计算所有币转账所需要的 gas
  219. totalCount = nativeCount + tokenCount;
  220. // var gasPrice = await redis.readRedis(reids_token_config.GASPRICE);
  221. logger.log('nativeAllBalance', nativeAllBalance);
  222. logger.log('totalCount', totalCount);
  223. var total2Gas = nativeGasPrice + tokenGasPrice;
  224. var service_charge = 0;
  225. logger.log('total2Gas', total2Gas);
  226. //需要转账的 obj
  227. my_account_all_coins.transfer_arrays = transfer_obj
  228. //如果当前的钱不够 gas
  229. if (nativeAllBalance < total2Gas) {
  230. if (tokenCount > 0) {//出现 token 需要转移手续费
  231. service_charge = 1;
  232. // total2Gas = (total2Gas - nativeAllBalance);//充手续费
  233. logger.log('需要转账=', total2Gas);
  234. }
  235. }
  236. ret_total_gas_price = total2Gas.toString();
  237. ret_total_count = totalCount;
  238. //返回结果
  239. return {
  240. gasPrice: ret_total_gas_price, //需要 归集到用户地址的 gas 费转移
  241. totalCount: ret_total_count, //一共归集次数
  242. aGasPrice: ret_a_gas, //单个 gas 费用
  243. get_service_charge: service_charge,//是否需要服务费
  244. };
  245. }
  246. function findTokenPriceItem(token_address, tokenPrices) {
  247. return tokenPrices.tokenPrice.find(element => {
  248. // logger.log('findTokenPriceItem find=', element.contract, token_address)
  249. return element.contract.toLowerCase() == token_address.toLowerCase();
  250. })
  251. }
  252. // function calculate_total_usdprice(amount, decimals, usdprice) {
  253. // return parseInt(amount) / (10**parseInt(decimals)) * parseInt(usdprice) ;
  254. function calculate_total_usdprice(amount, decimals, usdprice) {
  255. return parseInt(amount) / (10 ** parseInt(decimals)) * parseFloat(usdprice);
  256. }
  257. function addNativeValue(nativeValue, aValue) {
  258. return BigInt(nativeValue) + BigInt(aValue)
  259. }
  260. function reduceNativeValue(nativeValue, rValue) {
  261. return BigInt(nativeValue) - BigInt(rValue)
  262. }
  263. /**
  264. * todo --> 计算 gas
  265. * @param {*} nativeBalance
  266. * @param {*} obj
  267. * @returns
  268. */
  269. async function updateNativeBalance(nativeBalance, obj) {
  270. var temp = obj
  271. var retryCount = 30;
  272. do {
  273. //上面转账完 BNB 会减去,这里再获取一次
  274. var native_ret = await Moralis.Web3API.account.getNativeBalance(temp);
  275. logger.log('更新余额 :', native_ret, retryCount)
  276. if (nativeBalance != native_ret.balance) {
  277. return native_ret.balance;
  278. }
  279. await utils.sleep(3000);
  280. retryCount--;
  281. } while (native_ret.balance == nativeBalance && retryCount > 0);
  282. return null;
  283. }
  284. //20 and native 归集
  285. async function transfers(obj, my_account_all_coins) {
  286. // 优化后的归集
  287. 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) {
  288. var t_i = 0;
  289. for (let index = 0; index < my_account_all_coins.transfer_arrays.length; index++) {
  290. var ti = my_account_all_coins.transfer_arrays[index]
  291. logger.tlog('ti=', ti)
  292. var ret = await start_collectCoins(ti)
  293. //更新 native 金额
  294. if (isTransferSucceed(ret)) {
  295. logger.tlog('start_collectCoins respose...', ret);
  296. t_i += 1
  297. } else {
  298. logger.tlog('start_collectCoins error=', 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. if (process.env.NODE_ENV == 'dev') {
  482. var test_json = '{"tokenPrice": [{"contract": "0x0000000000000000000000000000000000000000", "usdPrice": 400}, {"contract": "0x03716F32f72c692a0B355fa04639669E3341B94e", "usdPrice": 0.1}]}'
  483. obj.tokenPrices = JSON.parse(test_json);
  484. logger.log('dev tokenPrices=', obj.tokenPrices)
  485. } else {
  486. obj.tokenPrices = await redis.readRedis(reids_token_config.TOKENPRICE)
  487. if (!obj.tokenPrices) return 'readRedis error'
  488. if (typeof obj.tokenPrices == 'string')
  489. obj.tokenPrices = JSON.parse(obj.tokenPrices);
  490. }
  491. obj.chain = chain;
  492. //计算 gas 费用 是否需要归集
  493. var transFerGasFree = await computeTransferGasFree(obj, my_account_all_coins, obj.tokenPrices);
  494. logger.log('computeTransferGasFree=', transFerGasFree)
  495. if (transFerGasFree) {
  496. // return
  497. }
  498. //是否需要归集
  499. if (transFerGasFree.totalCount > 0) {
  500. //需要转移 gas 费
  501. //每次都需要充值 gas 费
  502. if (account_config.TRANSFER_GAS || (parseInt(transFerGasFree.gasPrice) > 0 && transFerGasFree.get_service_charge == 1)) {
  503. var info = await queryCompanyInfoFromId(0);
  504. var obj_wd = {
  505. chain: chain,
  506. amount: transFerGasFree.gasPrice,
  507. receiver: obj.address,
  508. type: 'native',
  509. // address: account_config.WELLET_PUBLIC_KEY, //todo 正式环境需要替换从 mysql read
  510. address: info.user_address, //todo 正式环境需要替换从 mysql read
  511. }
  512. logger.log('开始充值 gas ', obj_wd)
  513. var ret = await withdraw(obj_wd)
  514. logger.log('充值完成 gas ', ret)
  515. if (!isTransferSucceed(ret)) return ret;
  516. var transfer = getTransferGasFree('native', ret)
  517. logger.log('getTransferGasFree transfer =', transfer)
  518. if (transfer && transfer.nativeValue > 0) {
  519. logger.log('tempNativeValue=', my_account_all_coins.native.balance)
  520. var tempNativeValue = addNativeValue(my_account_all_coins.native.balance, transfer.nativeValue)
  521. my_account_all_coins.native.balance = tempNativeValue.toString();
  522. logger.log('udpateNativeValue=', tempNativeValue);
  523. } else return "get native value error."
  524. }
  525. obj.chain = chain;
  526. obj.transFerGasFree = transFerGasFree;
  527. logger.log('transfers--->', obj);
  528. var ret = await transfers(obj, my_account_all_coins);
  529. logger.log('归集结果=', ret);
  530. return ret;
  531. }
  532. return obj.address + ':不满足归集条件';
  533. }
  534. var collectCoinsArrays = [];
  535. var lastCollectCoinsAddress;
  536. var isExecCollect = false;
  537. async function execCollectCoinsTask() {
  538. if (isExecCollect) return
  539. isExecCollect = true;
  540. while (collectCoinsArrays.length > 0) {
  541. var obj = collectCoinsArrays.pop();
  542. //开始收集用户地址里面的币到归集地址
  543. var ret = await collectCoins(obj);
  544. // await utils.sleep(3000)
  545. logger.log('execCollectCoinsTask=', collectCoinsArrays.length, ret)
  546. }
  547. isExecCollect = false;
  548. lastCollectCoinsAddress = ''
  549. }
  550. function pushCollectConisObj(obj) {
  551. logger.debug('collectCoinsArrays length=', collectCoinsArrays.length, lastCollectCoinsAddress)
  552. if (collectCoinsArrays.length > 0) {
  553. var findItem = collectCoinsArrays.find(element => {
  554. return (obj.address == element.address) || (!lastCollectCoinsAddress && lastCollectCoinsAddress == element.address)
  555. })
  556. if (findItem) {
  557. logger.log('当前任务正在处理中...', obj.address)
  558. return;
  559. }
  560. }
  561. collectCoinsArrays.push(obj)
  562. execCollectCoinsTask();
  563. lastCollectCoinsAddress = obj.address;
  564. }
  565. async function readPriveteKeyFromMysql(address) {
  566. return new Promise(resolve => {
  567. mysql.queryUserPrivateKeyFromUserAddress(address).then(ret => {
  568. logger.log('readPriveteKeyFromMysql=', ret);
  569. resolve(ret);
  570. })
  571. })
  572. }
  573. async function queryCompanyInfoFromId(id) {
  574. return new Promise(resolve => {
  575. mysql.queryCompanyInfoFromId(id).then(ret => {
  576. logger.log('queryCompanyInfoFromId=', ret, ret.results, ret.results.user_address, ret.results.user_private_key);
  577. resolve(ret.results);
  578. })
  579. })
  580. }
  581. const transfer = async (obj) => {
  582. logger.debug("fun transfer serverUrl ", serverUrl);
  583. logger.debug("fun transfer appId ", serverUrl);
  584. logger.debug("fun transfer moralisSecret ", moralisSecret);
  585. await initMoralisSecretSDK();
  586. // initSDK(moralisSecret);
  587. logger.debug("fun transfer start ok ");
  588. const opts = {};
  589. opts.chainId = 'bsc_testnet';
  590. opts.privateKey = moralis_config.DEFAULT_PRIVATE_KEY;
  591. opts.type = "erc20"; //native erc20
  592. if (!obj.receiver || !obj.amount || parseInt(obj.amount) <= 0) {
  593. logger.error("transfer fun transfer parameter error.", obj.receiver, obj.amount, obj.amount);
  594. return toJson(ERROR_CODE_001, null, "please check receiver or amount parameter is ok ?");
  595. }
  596. if (obj.chain != null) {
  597. opts.chainId = utils.getChainId(obj.chain);
  598. console.log("chainId:", opts.chainId);
  599. }
  600. if (obj.type != null) {
  601. opts.type = obj.type;
  602. }
  603. if (obj.from_block != null) {
  604. opts.from_block = obj.from_block;
  605. }
  606. if (obj.to_block != null) {
  607. opts.to_block = obj.to_block;
  608. }
  609. opts.contractAddress = obj.contractAddress;
  610. opts.receiver = obj.receiver;
  611. //调用者传入
  612. // opts.amount = Moralis.Units.Token(obj.amount, 18);
  613. opts.amount = obj.amount;
  614. if (obj.privateKey != null) {
  615. opts.privateKey = obj.privateKey;
  616. }
  617. try {
  618. // sending 0.5 DAI tokens with 18 decimals on BSC testnet
  619. var options;
  620. if (opts.contractAddress) { //如果存在就是代币
  621. options = Moralis.TransferOptions = {
  622. type: opts.type,
  623. amount: opts.amount,
  624. receiver: opts.receiver, //接收钱包地址
  625. contractAddress: opts.contractAddress //用户合约地址
  626. };
  627. logger.tlog("options 20 =", options);
  628. } else { //ETH or BNB
  629. options = Moralis.TransferOptions = {
  630. type: opts.type,
  631. amount: opts.amount,
  632. receiver: opts.receiver, //接收钱包地址
  633. };
  634. logger.tlog("options native =", options, opts.chainId);
  635. }
  636. // Enable web3
  637. await Moralis.enableWeb3({
  638. //BSC mainnet = 0x38-56 testnet:0x61-97
  639. chainId: opts.chainId,
  640. privateKey: opts.privateKey,
  641. });
  642. logger.tlog("options id =", opts.chainId);
  643. var ret = await Moralis.transfer(options);
  644. logger.tlog("transfer 结果 =", ret);
  645. return toJson(SUCCEED_CODE, ret, "");
  646. } catch (error) {
  647. logger.tlog('transfer error:', error);
  648. if (error.reason != null) {
  649. return toJson(ERROR_CODE_001, null, error.toString());
  650. } else {
  651. return toJson(ERROR_CODE_001, null, error);;
  652. }
  653. }
  654. };
  655. const getAllTokenWithdrawInfoLists = async (obj) => {
  656. try {
  657. var key = reids_token_config.TOKENWITHDRAW;
  658. var ret = await redis.readRedis(key);
  659. return toJson(SUCCEED_CODE, ret, null);
  660. } catch (error) {
  661. console.error("getAllTokenWithdrawInfoLists=", error);
  662. return toJson(ERROR_CODE_001, null, error.toString());
  663. }
  664. }
  665. /**
  666. * 获取代币价格 -> usdPrice
  667. */
  668. const getAllTotkenPrice = async () => {
  669. try {
  670. logger.log('当前环境:', process.env.NODE_ENV);
  671. logger.log("getAllTotkenPrice in", reids_token_config); // Prints "value"
  672. var token_price_key = reids_token_config.TOKENPRICE;
  673. logger.log("getAllTotkenPrice token_price_key=", token_price_key);
  674. return await redis.readRedis(token_price_key)
  675. } catch (error) {
  676. logger.error("getTotkenPrice=", error);
  677. return toJson(ERROR_CODE_001, null, error.toString());
  678. }
  679. }
  680. function setTransfersDataType(type, ret) {
  681. if (ret && Array.isArray(ret) && ret.length > 0) {
  682. ret.forEach(element => {
  683. element.type = type;
  684. });
  685. }
  686. }
  687. //获取交易记录
  688. //hash 0xe09ba3a4c9f7a8902e01af68d0f1f91906f3f7db1195227e61c45c0e86b2630a
  689. async function getTokenTransfers(opt) {
  690. await initMasterSDK();
  691. logger.debug("fun getTokenTransfers in ", opt);
  692. const options = {};
  693. options.type = 'all';
  694. options.chain = 'bsc_mainnet';
  695. if (opt.chain != null) {
  696. options.chain = utils.getChainName(opt.chain);
  697. logger.log('getTokenTransfers=', options.chain);
  698. }
  699. if (opt.order != null) {
  700. options.order = opt.order;
  701. }
  702. if (opt.startTime != null) {
  703. options.from_date = opt.startTime;
  704. }
  705. if (opt.endTime != null) {
  706. options.to_date = opt.endTime;
  707. }
  708. if (opt.from_block != null) {
  709. options.from_block = opt.from_block;
  710. }
  711. if (opt.to_block != null) {
  712. options.to_block = opt.to_block;
  713. }
  714. if (opt.transaction_hash) {
  715. options.transaction_hash = opt.transaction_hash;
  716. options.type = 'transaction_hash';
  717. }
  718. logger.debug('getTokenTransfers-->>>', options);
  719. if (options.type == 'all') {//查询主流币和 20 币所有的交易
  720. try {
  721. if (opt.address != null) {
  722. options.address = opt.address;
  723. } else {
  724. return toJson(ERROR_CODE_001, null, "please check address parameter is ok ?");
  725. }
  726. //主流币
  727. var t_1 = await Moralis.Web3API.account.getTransactions(options);
  728. setTransfersDataType('native', t_1.result)
  729. //20币
  730. var t_2 = await Moralis.Web3API.account.getTokenTransfers(options);
  731. setTransfersDataType('token', t_2.result)
  732. let arr = t_1.result;
  733. let arr1 = t_2.result;
  734. if (Array.isArray(arr1) && Array.isArray(arr)) {
  735. let arr2 = arr.concat(arr1);
  736. t_1.result = arr2;
  737. }
  738. //将结果排序
  739. t_1.result.sort((a, b) => {
  740. let t1 = new Date(Date.parse(a.block_timestamp))
  741. let t2 = new Date(Date.parse(b.block_timestamp))
  742. return t2.getTime() - t1.getTime()
  743. })
  744. return toJson(SUCCEED_CODE, t_1, null);
  745. } catch (error) {
  746. logger.error("getTransactions error:", error)
  747. return toJson(ERROR_CODE_001, null, error);;
  748. }
  749. } else if (options.type == 'transaction_hash') {//根据哈希查询
  750. try {
  751. //native
  752. const transaction = await Moralis.Web3API.native.getTransaction(options);
  753. var arr = [];
  754. if (transaction)
  755. arr.push(transaction)
  756. var obj = { result: arr }
  757. return toJson(SUCCEED_CODE, obj, null);
  758. } catch (error) {
  759. logger.error("native getTransaction error:", error)
  760. return toJson(ERROR_CODE_001, null, error);
  761. }
  762. } else {
  763. return toJson(ERROR_CODE_001, null, "This type is not supported.");;
  764. }
  765. }
  766. module.exports = {
  767. transfer,
  768. getTokenTransfers,
  769. toJson,
  770. getAllTokenWithdrawInfoLists,
  771. getAllTotkenPrice,
  772. withdraw,
  773. collectCoins,
  774. pushCollectConisObj,
  775. }