moralis_sdk.js 28 KB

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