moralis_sdk.js 29 KB

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