moralis_sdk.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789
  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. logger.log('transfer_handle queryCompanyInfoFromId=',info);
  359. //提币公司
  360. obj.privateKey = info.user_private_key;
  361. // if (process.env.NODE_ENV != 'dev') {
  362. logger.debug('readCompanyPriveteKeyFromMysql=', obj.privateKey)
  363. // }
  364. } else {
  365. //读取用户充币地址对应的私钥
  366. obj.privateKey = await readPriveteKeyFromMysql(obj.address);
  367. }
  368. if (obj.privateKey && obj.privateKey.results) {
  369. obj.privateKey = obj.privateKey.results;
  370. }
  371. if (!obj.privateKey) {
  372. return toJson(-1, null, "readPriveteKeyFromMysql error.");
  373. }
  374. //解密
  375. obj.privateKey = utils.decryptPrivityKey(obj.privateKey);
  376. if (!obj.privateKey) {
  377. return toJson(-1, null, "decryptPrivityKey error.");
  378. }
  379. var ret = await transfer(obj);
  380. if (isTransferSucceed(ret)) {
  381. //缓存当前交易的 gas 费用
  382. if (ret && obj.contractAddress) {
  383. var tr = getTransferGasFree('token', ret)
  384. logger.debug('cache key token LAST_TOTAL_TOKEN_FREE getTransferGasFree', tr)
  385. redis.redis_set(reids_token_config.LAST_TOTAL_TOKEN_FREE, tr.totalGasFree);
  386. } else {
  387. var tr = getTransferGasFree('native', ret)
  388. logger.debug('cache key LAST_TOTAL_BNB_FREE getTransferGasFree', tr)
  389. redis.redis_set(reids_token_config.LAST_TOTAL_BNB_FREE, tr.totalGasFree);
  390. }
  391. }
  392. return ret;
  393. }
  394. /**
  395. * 用户充币地址的币转移到归集地址
  396. * 1、检查当前账户的 主流币或者 20 币,是否满足一美刀,并且查看是否满足转账费用 n 如果不满足,先从归集地址 -> 用户提币地址(0.*2 来回2次转移)
  397. * 2、发起归集 用户账户 -> 从 mysql 拿到私钥进行解密 -> 转移到归集地址
  398. *
  399. *
  400. * @param {*} obj
  401. */
  402. const collectCoins = async (obj) => {
  403. var chain = obj.chain;
  404. //1、拿到当前账户所有的币
  405. //2、是否满足交易费 如果不满足则 归集地址转移 币count * 手续费 到充币地址
  406. //3、遍历所有币,开始转移到归集地址
  407. var my_account_all_coins = await getAccountAllCoins(obj);
  408. //得到币价格
  409. obj.tokenPrices = await redis.readRedis(reids_token_config.TOKENPRICE)
  410. if (!obj.tokenPrices) return 'readRedis error'
  411. if (typeof obj.tokenPrices == 'string')
  412. obj.tokenPrices = JSON.parse(obj.tokenPrices);
  413. //计算 gas 费用 是否需要归集
  414. var transFerGasFree = await computeTransferGasFree(my_account_all_coins, obj.tokenPrices);
  415. logger.log('computeTransferGasFree=', transFerGasFree)
  416. //是否需要归集
  417. if (transFerGasFree.totalCount > 0) {
  418. //需要转移 gas 费
  419. //每次都需要充值 gas 费
  420. if (account_config.TRANSFER_GAS || (parseInt(transFerGasFree.gasPrice) > 0 && transFerGasFree.get_service_charge == 1)) {
  421. var info =await queryCompanyInfoFromId(0);
  422. var obj_wd = {
  423. chain: chain,
  424. amount: transFerGasFree.gasPrice,
  425. receiver: obj.address,
  426. type: 'native',
  427. // address: account_config.WELLET_PUBLIC_KEY, //todo 正式环境需要替换从 mysql read
  428. address: info.user_address, //todo 正式环境需要替换从 mysql read
  429. }
  430. logger.log('开始充值 gas ', obj_wd)
  431. var ret = await withdraw(obj_wd)
  432. logger.log('充值完成 gas ', ret)
  433. if (!isTransferSucceed(ret)) return ret;
  434. var transfer = getTransferGasFree('native', ret)
  435. logger.log('getTransferGasFree transfer =', transfer)
  436. if (transfer && transfer.nativeValue > 0) {
  437. logger.log('tempNativeValue=', my_account_all_coins.native.balance)
  438. var tempNativeValue = addNativeValue(my_account_all_coins.native.balance, transfer.nativeValue)
  439. my_account_all_coins.native.balance = tempNativeValue.toString();
  440. logger.log('udpateNativeValue=', tempNativeValue);
  441. } else return "get native value error."
  442. // //更新本地余额
  443. // var updateBalance = await updateNativeBalance(my_account_all_coins.native.balance, obj)
  444. // if (updateBalance)
  445. // my_account_all_coins.native.balance = updateBalance;
  446. // else return "error."
  447. }
  448. obj.chain = chain;
  449. obj.transFerGasFree = transFerGasFree;
  450. logger.log('transfers--->', obj);
  451. var ret = await transfers(obj, my_account_all_coins);
  452. logger.log('归集结果=', ret);
  453. return ret;
  454. }
  455. return obj.address + ':不满足归集条件';
  456. }
  457. var collectCoinsArrays = [];
  458. async function execCollectCoinsTask() {
  459. while (collectCoinsArrays.length > 0) {
  460. var obj = collectCoinsArrays.pop();
  461. //开始收集用户地址里面的币到归集地址
  462. var ret = await collectCoins(obj);
  463. logger.log('execCollectCoinsTask=', obj, ret)
  464. }
  465. }
  466. function pushCollectConisObj(obj) {
  467. collectCoinsArrays.push(obj)
  468. execCollectCoinsTask();
  469. }
  470. async function readPriveteKeyFromMysql(address) {
  471. return new Promise(resolve => {
  472. mysql.queryUserPrivateKeyFromUserAddress(address).then(ret => {
  473. logger.log('readPriveteKeyFromMysql=', ret);
  474. resolve(ret);
  475. })
  476. })
  477. }
  478. async function queryCompanyInfoFromId(id) {
  479. return new Promise(resolve => {
  480. mysql.queryCompanyInfoFromId(id).then(ret => {
  481. logger.log('queryCompanyInfoFromId=', ret,ret.results,ret.results.user_address,ret.results.user_private_key);
  482. resolve(ret.results);
  483. })
  484. })
  485. }
  486. const transfer = async (obj) => {
  487. logger.debug("fun transfer serverUrl ", serverUrl);
  488. logger.debug("fun transfer appId ", serverUrl);
  489. logger.debug("fun transfer moralisSecret ", moralisSecret);
  490. await initMoralisSecretSDK();
  491. // initSDK(moralisSecret);
  492. logger.debug("fun transfer start ok ");
  493. const opts = {};
  494. opts.chainId = 'bsc_testnet';
  495. opts.privateKey = moralis_config.DEFAULT_PRIVATE_KEY;
  496. opts.type = "erc20"; //native erc20
  497. if (!obj.receiver || !obj.amount || parseInt(obj.amount) <= 0) {
  498. logger.error("transfer fun transfer parameter error.", obj.receiver, obj.amount, obj.amount);
  499. return toJson(ERROR_CODE_001, null, "please check receiver or amount parameter is ok ?");
  500. }
  501. if (obj.chain != null) {
  502. opts.chainId = utils.getChainId(obj.chain);
  503. console.log("chainId:", opts.chainId);
  504. }
  505. if (obj.type != null) {
  506. opts.type = obj.type;
  507. }
  508. if (obj.from_block != null) {
  509. opts.from_block = obj.from_block;
  510. }
  511. if (obj.to_block != null) {
  512. opts.to_block = obj.to_block;
  513. }
  514. opts.contractAddress = obj.contractAddress;
  515. opts.receiver = obj.receiver;
  516. //调用者传入
  517. // opts.amount = Moralis.Units.Token(obj.amount, 18);
  518. opts.amount = obj.amount;
  519. if (obj.privateKey != null) {
  520. opts.privateKey = obj.privateKey;
  521. }
  522. try {
  523. // sending 0.5 DAI tokens with 18 decimals on BSC testnet
  524. var options;
  525. if (opts.contractAddress) { //如果存在就是代币
  526. options = Moralis.TransferOptions = {
  527. type: opts.type,
  528. amount: opts.amount,
  529. receiver: opts.receiver, //接收钱包地址
  530. contractAddress: opts.contractAddress //用户合约地址
  531. };
  532. logger.tlog("options 20 =", options);
  533. } else { //ETH or BNB
  534. options = Moralis.TransferOptions = {
  535. type: opts.type,
  536. amount: opts.amount,
  537. receiver: opts.receiver, //接收钱包地址
  538. };
  539. logger.tlog("options native =", options, opts.chainId);
  540. }
  541. // Enable web3
  542. await Moralis.enableWeb3({
  543. //BSC mainnet = 0x38-56 testnet:0x61-97
  544. chainId: opts.chainId,
  545. privateKey: opts.privateKey,
  546. });
  547. logger.tlog("options id =", opts.chainId);
  548. var ret = await Moralis.transfer(options);
  549. logger.tlog("transfer 结果 =", ret);
  550. return toJson(SUCCEED_CODE, ret, "");
  551. } catch (error) {
  552. logger.tlog('transfer error:', error);
  553. if (error.reason != null) {
  554. return toJson(ERROR_CODE_001, null, error.toString());
  555. } else {
  556. return toJson(ERROR_CODE_001, null, error);;
  557. }
  558. }
  559. };
  560. const getAllTokenWithdrawInfoLists = async (obj) => {
  561. try {
  562. var key = reids_token_config.TOKENWITHDRAW;
  563. var ret = await redis.readRedis(key);
  564. return toJson(SUCCEED_CODE, ret, null);
  565. } catch (error) {
  566. console.error("getAllTokenWithdrawInfoLists=", error);
  567. return toJson(ERROR_CODE_001, null, error.toString());
  568. }
  569. }
  570. /**
  571. * 获取代币价格 -> usdPrice
  572. */
  573. const getAllTotkenPrice = async () => {
  574. try {
  575. logger.log('当前环境:', process.env.NODE_ENV);
  576. logger.log("getAllTotkenPrice in", reids_token_config); // Prints "value"
  577. var token_price_key = reids_token_config.TOKENPRICE;
  578. logger.log("getAllTotkenPrice token_price_key=", token_price_key);
  579. return await redis.readRedis(token_price_key)
  580. } catch (error) {
  581. logger.error("getTotkenPrice=", error);
  582. return toJson(ERROR_CODE_001, null, error.toString());
  583. }
  584. }
  585. function setTransfersDataType(type, ret) {
  586. if (ret && Array.isArray(ret) && ret.length > 0) {
  587. ret.forEach(element => {
  588. element.type = type;
  589. });
  590. }
  591. }
  592. //获取交易记录
  593. //hash 0xe09ba3a4c9f7a8902e01af68d0f1f91906f3f7db1195227e61c45c0e86b2630a
  594. async function getTokenTransfers(opt) {
  595. await initMasterSDK();
  596. logger.debug("fun getTokenTransfers in ", opt);
  597. const options = {};
  598. options.type = 'all';
  599. options.chain = 'bsc_mainnet';
  600. if (opt.chain != null) {
  601. options.chain = utils.getChainName(opt.chain);
  602. logger.log('getTokenTransfers=', options.chain);
  603. }
  604. if (opt.order != null) {
  605. options.order = opt.order;
  606. }
  607. if (opt.startTime != null) {
  608. options.from_date = opt.startTime;
  609. }
  610. if (opt.endTime != null) {
  611. options.to_date = opt.endTime;
  612. }
  613. if (opt.from_block != null) {
  614. options.from_block = opt.from_block;
  615. }
  616. if (opt.to_block != null) {
  617. options.to_block = opt.to_block;
  618. }
  619. if (opt.transaction_hash) {
  620. options.transaction_hash = opt.transaction_hash;
  621. options.type = 'transaction_hash';
  622. }
  623. logger.debug('getTokenTransfers-->>>', options);
  624. if (options.type == 'all') {//查询主流币和 20 币所有的交易
  625. try {
  626. if (opt.address != null) {
  627. options.address = opt.address;
  628. } else {
  629. return toJson(ERROR_CODE_001, null, "please check address parameter is ok ?");
  630. }
  631. //主流币
  632. var t_1 = await Moralis.Web3API.account.getTransactions(options);
  633. setTransfersDataType('native', t_1.result)
  634. //20币
  635. var t_2 = await Moralis.Web3API.account.getTokenTransfers(options);
  636. setTransfersDataType('token', t_2.result)
  637. let arr = t_1.result;
  638. let arr1 = t_2.result;
  639. if (Array.isArray(arr1) && Array.isArray(arr)) {
  640. let arr2 = arr.concat(arr1);
  641. t_1.result = arr2;
  642. }
  643. //将结果排序
  644. t_1.result.sort((a, b) => {
  645. let t1 = new Date(Date.parse(a.block_timestamp))
  646. let t2 = new Date(Date.parse(b.block_timestamp))
  647. return t2.getTime() - t1.getTime()
  648. })
  649. return toJson(SUCCEED_CODE, t_1, null);
  650. } catch (error) {
  651. logger.error("getTransactions error:", error)
  652. return toJson(ERROR_CODE_001, null, error);;
  653. }
  654. } else if (options.type == 'transaction_hash') {//根据哈希查询
  655. try {
  656. //native
  657. const transaction = await Moralis.Web3API.native.getTransaction(options);
  658. var arr = [];
  659. if (transaction)
  660. arr.push(transaction)
  661. var obj = { result: arr }
  662. return toJson(SUCCEED_CODE, obj, null);
  663. } catch (error) {
  664. logger.error("native getTransaction error:", error)
  665. return toJson(ERROR_CODE_001, null, error);
  666. }
  667. } else {
  668. return toJson(ERROR_CODE_001, null, "This type is not supported.");;
  669. }
  670. }
  671. module.exports = {
  672. transfer,
  673. getTokenTransfers,
  674. toJson,
  675. getAllTokenWithdrawInfoLists,
  676. getAllTotkenPrice,
  677. withdraw,
  678. collectCoins,
  679. pushCollectConisObj,
  680. }