moralis_sdk.js 28 KB

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