123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888 |
- /* import moralis */
- const Moralis = require("moralis/node");
- var utils = require('./utils.js');
- // var config = require('../config/config.js')(db_config,
- // moralis_config)
- var { moralis_config, reids_token_config, account_config } = require('../config/config.js')
- const redis = require("./redis_db") //导入 db.js
- const mysql = require("./mysql_db")
- const logger = require('./logger')
- const BigNumber = require('bignumber.js')
- /* Moralis init code */
- var serverUrl = moralis_config.SERVER_URL;
- var appId = moralis_config.APP_ID;
- var masterKey = moralis_config.MASTER_KEY;
- var moralisSecret = moralis_config.MORALIS_SECRET;
- // 内部异常
- const ERROR_CODE_001 = -1;
- const SUCCEED_CODE = 0;
- /**
- * 初始化 moralis
- * https://st94nif1cq.feishu.cn/docs/doccnNxG2UwHPCdZXbywgbdy13f#
- */
- async function initMasterSDK() {
- await Moralis.start({ serverUrl, appId, masterKey });
- }
- async function initMoralisSecretSDK() {
- await Moralis.start({ serverUrl, appId, moralisSecret });
- }
- function toJson(code_, obj_, errMsg_) {
- return utils.toJson(code_, obj_, errMsg_);
- }
- /**
- * 获取转账的 gas 费
- * @param {*} type
- * @param {*} json
- * @returns
- */
- function getTransferGasFree(type, json) {
- var curGasPrice = account_config.BNB_GAS_PRICE
- var curGasLimit = account_config.TOKEN_GAS_LIMIT
- var nativeValue = 0;
- var tokenValue = 0;
- var code = -1;
- if (type == 'native') {
- curGasLimit = account_config.BNB_GAS_LIMIT
- }
- var totalGasFree = parseInt(curGasLimit) * parseInt(curGasPrice);
- logger.log('getTransferGasFree json=', json)
- if (json) {
- var obj = JSON.parse(json)
- code = obj.code;
- logger.log('getTransferGasFree obj=', obj)
- if (obj.data && obj.data.gasPrice && obj.data.gasLimit && obj.data.gasPrice.hex && obj.data.gasLimit.hex) {
- var curGasPrice = BigNumber(obj.data.gasPrice.hex).toNumber()
- var curGasLimit = BigNumber(obj.data.gasLimit.hex).toNumber()
- if (curGasPrice > 0 && curGasLimit > 0) {
- totalGasFree = curGasPrice * curGasLimit;
- }
- logger.log('getTransferGasFree totalGasFree=', curGasPrice, curGasLimit, totalGasFree)
- if (obj.data.value && obj.data.value.hex) {
- var value = BigNumber(obj.data.value.hex).toNumber()
- logger.log('getTransferGasFree native value=', value)
- if (value != 0) {
- nativeValue = value
- }
- }
- }
- }
- return {
- code: code,
- totalGasFree: totalGasFree,
- nativeValue: nativeValue,
- tokenValue: tokenValue,
- }
- }
- /**
- *
- * @param {转账是否成功} json
- */
- function isTransferSucceed(json) {
- if (json) {
- var obj = JSON.parse(json)
- return obj.code == 0
- }
- return false
- }
- const withdraw = async (obj) => {
- obj.withdraw = 1;
- return await transfer_handle(obj);
- }
- async function getAccountBalances(options) {
- await initMasterSDK();
- if (options.chain) {
- options.chain = utils.getChainName(options.chain)
- }
- logger.log('getAccountBalances :', options)
- try {
- if (options.type == 'native') {
- var opt_ret = await Moralis.Web3API.account.getNativeBalance(options);
- logger.log('getNativeBalance=', opt_ret);
- return opt_ret
- } else {
- var aar = await Moralis.Web3API.account.getTokenBalances(options);
- logger.log('getTokenBalances=', aar);
- return aar;
- }
- } catch (error) {
- logger.log('getAccountBalances error:', error)
- return null
- }
- }
- /**
- * 获取当前账户下所有不同种类的币 主流币 + 20币
- *
- * 必填项
- * obj.chain = ?
- * @param {*} obj
- */
- async function getAccountAllCoins(obj) {
- var temp_chain = obj.chain;
- //拿到我当前所有的币种
- obj.type = 'native'
- obj.chain = temp_chain
- var native_balance = await getAccountBalances(obj);
- //拿到我当前所有的 20 币
- obj.type = '20'
- obj.chain = temp_chain
- var others_balances = await getAccountBalances(obj);
- return {
- native: native_balance,
- other: others_balances,
- }
- }
- /**
- * 判断是否转 gas 费
- * @param {*} my_account_all_coins
- */
- async function computeTransferGasFree(obj, my_account_all_coins, tokenPrices) {
- var totalCount = 0;
- var tokenCount = 0;
- var tokenGasPrice = 0;
- var nativeGasPrice = 0;
- var ret_total_gas_price = 0;
- var ret_total_count = 0;
- var ret_a_gas = 0;
- //需要转账的数组对象
- var transfer_obj = [];
- var receiver_info = await queryCompanyInfoFromId(0);
- //得到 20 币 满足 1美刀的 count
- if (Array.isArray(my_account_all_coins.other) && my_account_all_coins.other.length > 0) {
- my_account_all_coins.other.forEach(element => {
- logger.debug('20 element=', element);
- var find_transfer_item = findTokenPriceItem(element.token_address, tokenPrices);
- if (find_transfer_item) {
- var total_all_usdprice = calculate_total_usdprice(element.balance, element.decimals, find_transfer_item.usdPrice);
- logger.debug('findTokenPriceItem ret=', element.token_address, find_transfer_item, total_all_usdprice);
- if (find_transfer_item && total_all_usdprice > 1.0) {
- tokenCount += 1;
- logger.debug('token > 1.0', tokenCount, element.token_address);
- var obj_20 = {
- chain: obj.chain,
- contractAddress: element.token_address,
- amount: element.balance,
- receiver: receiver_info.user_address,
- type: 'erc20',
- address: obj.address,
- }
- transfer_obj.push(obj_20)
- }
- } else {
- logger.log('findTokenPriceItem error=', element);
- }
- });
- logger.log('account_config.TOKEN_GAS_LIMIT=', account_config.TOKEN_GAS_LIMIT);
- var lastTokenFree = await redis.readRedis(reids_token_config.LAST_TOTAL_TOKEN_FREE)
- logger.log('LAST_TOTAL_TOKEN_FREE=', lastTokenFree);
- if (lastTokenFree && reids_token_config.LAST_TOTAL_TOKEN_FREE && parseInt(lastTokenFree) > 0) {
- tokenGasPrice = parseInt(tokenCount) * parseInt(lastTokenFree);
- } else {
- tokenGasPrice = parseInt(tokenCount) * parseInt(account_config.TOKEN_GAS_LIMIT) * parseInt(account_config.BNB_GAS_PRICE);
- }
- ret_a_gas = account_config.BNB_GAS_PRICE;
- logger.log('tokenGasPrice=', tokenGasPrice);
- }
- //计算 native 是否满足 1美刀
- logger.log('isTransferGasFree token count:', tokenCount);
- var nativeAllBalance = my_account_all_coins.native.balance;
- var nativeCount = 0
- var nativePriceItem = findTokenPriceItem('0x0000000000000000000000000000000000000000', tokenPrices);//todo 线上环境需要换
- logger.debug('native nativePriceItem=', nativePriceItem, nativeAllBalance);
- if (nativePriceItem) {
- var total_all_usdprice = calculate_total_usdprice(nativeAllBalance, '18', nativePriceItem.usdPrice);
- logger.debug('native total_all_usdprice=', total_all_usdprice);
- if (total_all_usdprice > 1.0) {
- nativeCount = 1;
- logger.debug('native > 1.0', tokenCount);
- var lastBnbFree = await redis.readRedis(reids_token_config.LAST_TOTAL_BNB_FREE)
- logger.log('LAST_TOTAL_BNB_FREE=', lastBnbFree);
- if (lastTokenFree && reids_token_config.LAST_TOTAL_TOKEN_FREE && parseInt(lastTokenFree) > 0) {
- nativeGasPrice = parseInt(nativeCount) * parseInt(lastBnbFree);
- } else {
- nativeGasPrice = parseInt(nativeCount) * parseInt(account_config.BNB_GAS_LIMIT) * parseInt(account_config.BNB_GAS_PRICE);
- }
- ret_a_gas = account_config.BNB_GAS_PRICE;
- var real_native_amount = BigInt(nativeAllBalance) - BigInt(nativeGasPrice) - BigInt(tokenGasPrice);
- var obj_native = {
- chain: obj.chain,
- amount: real_native_amount.toString(),
- receiver: receiver_info.user_address,
- type: 'native',
- address: obj.address,
- }
- transfer_obj.push(obj_native)
- }
- }
- logger.log('transfer obj=', transfer_obj)
- //计算所有币转账所需要的 gas
- totalCount = nativeCount + tokenCount;
- // var gasPrice = await redis.readRedis(reids_token_config.GASPRICE);
- logger.log('nativeAllBalance', nativeAllBalance);
- logger.log('totalCount', totalCount);
- var total2Gas = nativeGasPrice + tokenGasPrice;
- var service_charge = 0;
- logger.log('total2Gas', total2Gas);
- //需要转账的 obj
- my_account_all_coins.transfer_arrays = transfer_obj
- //如果当前的钱不够 gas
- if (nativeAllBalance < total2Gas) {
- if (tokenCount > 0) {//出现 token 需要转移手续费
- service_charge = 1;
- // total2Gas = (total2Gas - nativeAllBalance);//充手续费
- logger.log('需要转账=', total2Gas);
- }
- }
- ret_total_gas_price = total2Gas.toString();
- ret_total_count = totalCount;
- //返回结果
- return {
- gasPrice: ret_total_gas_price, //需要 归集到用户地址的 gas 费转移
- totalCount: ret_total_count, //一共归集次数
- aGasPrice: ret_a_gas, //单个 gas 费用
- get_service_charge: service_charge,//是否需要服务费
- };
- }
- function findTokenPriceItem(token_address, tokenPrices) {
- return tokenPrices.tokenPrice.find(element => {
- // logger.log('findTokenPriceItem find=', element.contract, token_address)
- return element.contract.toLowerCase() == token_address.toLowerCase();
- })
- }
- // function calculate_total_usdprice(amount, decimals, usdprice) {
- // return parseInt(amount) / (10**parseInt(decimals)) * parseInt(usdprice) ;
- function calculate_total_usdprice(amount, decimals, usdprice) {
- return parseInt(amount) / (10 ** parseInt(decimals)) * parseFloat(usdprice);
- }
- function addNativeValue(nativeValue, aValue) {
- return BigInt(nativeValue) + BigInt(aValue)
- }
- function reduceNativeValue(nativeValue, rValue) {
- return BigInt(nativeValue) - BigInt(rValue)
- }
- /**
- * todo --> 计算 gas
- * @param {*} nativeBalance
- * @param {*} obj
- * @returns
- */
- async function updateNativeBalance(nativeBalance, obj) {
- var temp = obj
- var retryCount = 30;
- do {
- //上面转账完 BNB 会减去,这里再获取一次
- var native_ret = await Moralis.Web3API.account.getNativeBalance(temp);
- logger.log('更新余额 :', native_ret, retryCount)
- if (nativeBalance != native_ret.balance) {
- return native_ret.balance;
- }
- await utils.sleep(3000);
- retryCount--;
- } while (native_ret.balance == nativeBalance && retryCount > 0);
- return null;
- }
- //20 and native 归集
- async function transfers(obj, my_account_all_coins) {
- // 优化后的归集
- 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) {
- var t_i = 0;
- for (let index = 0; index < my_account_all_coins.transfer_arrays.length; index++) {
- var ti = my_account_all_coins.transfer_arrays[index]
- logger.tlog('ti=', ti)
- var ret = await start_collectCoins(ti)
- //更新 native 金额
- if (isTransferSucceed(ret)) {
- logger.tlog('start_collectCoins respose...', ret);
- t_i += 1
- } else {
- logger.tlog('start_collectCoins error=', ret);
- t_err.push(ret)
- };
- }
- if(t_i == my_account_all_coins.transfer_arrays.length){
- return toJson(0, null, '所有币归集成功.');
- }else {
- return toJson(-1, null, '归集失败.');
- }
- } else {
- return toJson(-1, null, 'transfer conditions are not met.');
- }
- //v0.1 版本归集
- // var address = obj.address;
- // var chain = obj.chain;
- // var tokenPrices = obj.tokenPrices;
- // logger.log('tokenPrices=', tokenPrices, my_account_all_coins);
- // var nativeValue = my_account_all_coins.native.balance;
- // if (!my_account_all_coins || !tokenPrices) return 'error.'
- // logger.log(' my_account_all_coins.other.lenth=', my_account_all_coins.other.length);
- // var isUpdateNativeBalance = 0;
- // //token 归集
- // if (my_account_all_coins.other && Array.isArray(my_account_all_coins.other) && my_account_all_coins.other.length > 0) {
- // var available = Array.isArray(tokenPrices.tokenPrice) && tokenPrices.tokenPrice.length > 0
- // if (!available) return -1;
- // for (let i = 0; i < my_account_all_coins.other.length; ++i) {
- // var transfer_item = my_account_all_coins.other[i];
- // if (my_account_all_coins.other[i].token_address != null) {
- // var find_transfer_item = findTokenPriceItem(transfer_item.token_address, tokenPrices);
- // //todo 计算 token 币价格 * token美元单价
- // if (find_transfer_item && calculate_total_usdprice(transfer_item.balance, transfer_item.decimals, find_transfer_item.usdPrice) > 1.0) {
- // var info = await queryCompanyInfoFromId(0);
- // var obj_20 = {
- // chain: obj.chain,
- // contractAddress: transfer_item.token_address,
- // amount: transfer_item.balance,
- // receiver: info.user_address,
- // type: 'erc20',
- // address: address,
- // }
- // logger.log('start_collectCoins erc20:', obj_20);
- // logger.log('calculate_total_usdprice 20', calculate_total_usdprice(transfer_item.balance, transfer_item.decimals, '0.1'));
- // isUpdateNativeBalance = 1;
- // var ret = await start_collectCoins(obj_20)
- // logger.log('start_collectCoins erc20 respose...', ret);
- // //更新 native 金额
- // if (!isTransferSucceed(ret)) return ret;
- // var transfer = getTransferGasFree('token', ret)
- // if (transfer && transfer.totalGasFree > 0) {
- // logger.log('start_collectCoins 20 tempNativeValue=', my_account_all_coins.native.balance)
- // var tempNativeValue = reduceNativeValue(nativeValue, transfer.totalGasFree)
- // my_account_all_coins.native.balance = tempNativeValue.toString();
- // logger.log('start_collectCoins 20 udpateNativeValue=', tempNativeValue);
- // } else return "get native value error."
- // } else {
- // logger.error('find_transfer_item error.', transfer_item);
- // }
- // } else {
- // logger.error('token Must be greater than a dollar.', transfer_item.balance, transfer_item.decimals);
- // // return toJson(-1, null, 'token Must be greater than a dollar.');
- // }
- // }
- // }
- // //native 归集
- // if (my_account_all_coins.native) {
- // logger.log('查询本地余额参数=', obj)
- // if (obj.chain) {
- // obj.chain = utils.getChainName(obj.chain)
- // }
- // obj.chain = chain;
- // logger.log('查询本地余额 after', my_account_all_coins.native)
- // var find_native_item = findTokenPriceItem('0x0000000000000000000000000000000000000000', tokenPrices);
- // //todo 计算 token 币价格 * token美元单价
- // if (find_native_item) {
- // var nativeCoins = calculate_total_usdprice(my_account_all_coins.native.balance, '18', find_native_item.usdPrice);
- // logger.log('start_collectCoins nativeCoins:', nativeCoins, obj);
- // logger.log('start_collectCoins obj:', obj);
- // logger.log('start_collectCoins native.balance:', my_account_all_coins.native.balance);
- // if (nativeCoins > 1.0) {
- // logger.log('native.balance', my_account_all_coins.native.balance)
- // logger.log('aGasPrice', obj.transFerGasFree.aGasPrice)
- // logger.log('gasLimint', account_config.BNB_GAS_LIMIT)
- // // var gasPrice = BigInt(obj.transFerGasFree.aGasPrice);
- // var gasPrice = BigInt(account_config.BNB_GAS_PRICE);
- // var gasLimit = BigInt(account_config.BNB_GAS_LIMIT);
- // var nativeBalance = BigInt(my_account_all_coins.native.balance);
- // logger.log('native.balance>>>', nativeBalance)
- // logger.log('aGasPrice>>>', gasPrice)
- // logger.log('gasLimint>>>', gasLimit)
- // var real_native_amount = nativeBalance - gasPrice * gasLimit;
- // logger.log('start_collectCoins native amount:', real_native_amount.toString());
- // var info = await queryCompanyInfoFromId(0);
- // obj = {
- // chain: chain,
- // amount: real_native_amount.toString(),
- // receiver: info.user_address,
- // type: 'native',
- // address: address,
- // }
- // logger.log('start_collectCoins native:', obj);
- // logger.log('calculate_total_usdprice native', nativeCoins, find_native_item);
- // return await start_collectCoins(obj)
- // } else {
- // logger.error('native Must be greater than a dollar.', obj);
- // return toJson(-1, null, 'native Must be greater than a dollar.');
- // }
- // } else {
- // logger.error('native Must be greater than a dollar.', obj);
- // return toJson(-1, null, 'native Must be greater than a dollar.');
- // }
- // }
- }
- const start_collectCoins = async (obj) => {
- obj.withdraw = 0;
- return await transfer_handle(obj);
- }
- const transfer_handle = async (obj) => {
- //提币
- if (obj.withdraw) {
- var id = 0
- if (obj.privateKeyId)
- id = obj.privateKeyId
- //读取用户充币地址对应的私钥
- var info = await queryCompanyInfoFromId(id);
- logger.log('transfer_handle queryCompanyInfoFromId=', info);
- //提币公司
- obj.privateKey = info.user_private_key;
- // if (process.env.NODE_ENV != 'dev') {
- logger.debug('readCompanyPriveteKeyFromMysql=', obj.privateKey)
- // }
- } else {
- //读取用户充币地址对应的私钥
- obj.privateKey = await readPriveteKeyFromMysql(obj.address);
- }
- if (obj.privateKey && obj.privateKey.results) {
- obj.privateKey = obj.privateKey.results;
- }
- if (!obj.privateKey) {
- return toJson(-1, null, "readPriveteKeyFromMysql error.");
- }
- try {
- //解密
- obj.privateKey = utils.decryptPrivityKey(obj.privateKey);
- if (!obj.privateKey) {
- return toJson(-1, null, "decryptPrivityKey error.");
- }
- } catch (error) {
- if (!obj.privateKey) {
- return toJson(-1, null, "decryptPrivityKey error.", error.toString());
- }
- }
- if (!obj.privateKey) {
- return toJson(-1, null, "decryptPrivityKey error.");
- }
- var ret = await transfer(obj);
- if (isTransferSucceed(ret)) {
- //缓存当前交易的 gas 费用
- if (ret && obj.contractAddress) {
- var tr = getTransferGasFree('token', ret)
- logger.debug('cache setkey token LAST_TOTAL_TOKEN_FREE getTransferGasFree', tr)
- redis.redis_set(reids_token_config.LAST_TOTAL_TOKEN_FREE, tr.totalGasFree);
- } else {
- var tr = getTransferGasFree('native', ret)
- logger.debug('cache setkey LAST_TOTAL_BNB_FREE getTransferGasFree', tr)
- redis.redis_set(reids_token_config.LAST_TOTAL_BNB_FREE, tr.totalGasFree);
- }
- }
- return ret;
- }
- /**
- * 用户充币地址的币转移到归集地址
- * 1、检查当前账户的 主流币或者 20 币,是否满足一美刀,并且查看是否满足转账费用 n 如果不满足,先从归集地址 -> 用户提币地址(0.*2 来回2次转移)
- * 2、发起归集 用户账户 -> 从 mysql 拿到私钥进行解密 -> 转移到归集地址
- *
- *
- * @param {*} obj
- */
- const collectCoins = async (obj) => {
- var chain = obj.chain;
- //1、拿到当前账户所有的币
- //2、是否满足交易费 如果不满足则 归集地址转移 币count * 手续费 到充币地址
- //3、遍历所有币,开始转移到归集地址
- var my_account_all_coins = await getAccountAllCoins(obj);
- //得到币价格
- obj.tokenPrices = await redis.readRedis(reids_token_config.TOKENPRICE)
- if (!obj.tokenPrices) return 'readRedis error'
- if (typeof obj.tokenPrices == 'string')
- obj.tokenPrices = JSON.parse(obj.tokenPrices);
- obj.chain = chain;
- //计算 gas 费用 是否需要归集
- var transFerGasFree = await computeTransferGasFree(obj, my_account_all_coins, obj.tokenPrices);
- logger.log('computeTransferGasFree=', transFerGasFree)
- if (transFerGasFree) {
- // return
- }
- //是否需要归集
- if (transFerGasFree.totalCount > 0) {
- //需要转移 gas 费
- //每次都需要充值 gas 费
- if (account_config.TRANSFER_GAS || (parseInt(transFerGasFree.gasPrice) > 0 && transFerGasFree.get_service_charge == 1)) {
- var info = await queryCompanyInfoFromId(0);
- var obj_wd = {
- chain: chain,
- amount: transFerGasFree.gasPrice,
- receiver: obj.address,
- type: 'native',
- // address: account_config.WELLET_PUBLIC_KEY, //todo 正式环境需要替换从 mysql read
- address: info.user_address, //todo 正式环境需要替换从 mysql read
- }
- logger.log('开始充值 gas ', obj_wd)
- var ret = await withdraw(obj_wd)
- logger.log('充值完成 gas ', ret)
- if (!isTransferSucceed(ret)) return ret;
- var transfer = getTransferGasFree('native', ret)
- logger.log('getTransferGasFree transfer =', transfer)
- if (transfer && transfer.nativeValue > 0) {
- logger.log('tempNativeValue=', my_account_all_coins.native.balance)
- var tempNativeValue = addNativeValue(my_account_all_coins.native.balance, transfer.nativeValue)
- my_account_all_coins.native.balance = tempNativeValue.toString();
- logger.log('udpateNativeValue=', tempNativeValue);
- } else return "get native value error."
- }
- obj.chain = chain;
- obj.transFerGasFree = transFerGasFree;
- logger.log('transfers--->', obj);
- var ret = await transfers(obj, my_account_all_coins);
- logger.log('归集结果=', ret);
- return ret;
- }
- return obj.address + ':不满足归集条件';
- }
- var collectCoinsArrays = [];
- var lastCollectCoinsAddress;
- var isExecCollect = false;
- async function execCollectCoinsTask() {
- if (isExecCollect) return
- isExecCollect = true;
- while (collectCoinsArrays.length > 0) {
- var obj = collectCoinsArrays.pop();
- //开始收集用户地址里面的币到归集地址
- var ret = await collectCoins(obj);
- // await utils.sleep(3000)
- logger.log('execCollectCoinsTask=', collectCoinsArrays.length, ret)
- }
- isExecCollect = false;
- lastCollectCoinsAddress = ''
- }
- function pushCollectConisObj(obj) {
- logger.debug('collectCoinsArrays length=', collectCoinsArrays.length, lastCollectCoinsAddress)
- if (collectCoinsArrays.length > 0) {
- var findItem = collectCoinsArrays.find(element => {
- return (obj.address == element.address) || (!lastCollectCoinsAddress && lastCollectCoinsAddress == element.address)
- })
- if (findItem) {
- logger.log('当前任务正在处理中...', obj.address)
- return;
- }
- }
- collectCoinsArrays.push(obj)
- execCollectCoinsTask();
- lastCollectCoinsAddress = obj.address;
- }
- async function readPriveteKeyFromMysql(address) {
- return new Promise(resolve => {
- mysql.queryUserPrivateKeyFromUserAddress(address).then(ret => {
- logger.log('readPriveteKeyFromMysql=', ret);
- resolve(ret);
- })
- })
- }
- async function queryCompanyInfoFromId(id) {
- return new Promise(resolve => {
- mysql.queryCompanyInfoFromId(id).then(ret => {
- logger.log('queryCompanyInfoFromId=', ret, ret.results, ret.results.user_address, ret.results.user_private_key);
- resolve(ret.results);
- })
- })
- }
- const transfer = async (obj) => {
- logger.debug("fun transfer serverUrl ", serverUrl);
- logger.debug("fun transfer appId ", serverUrl);
- logger.debug("fun transfer moralisSecret ", moralisSecret);
- await initMoralisSecretSDK();
- // initSDK(moralisSecret);
- logger.debug("fun transfer start ok ");
- const opts = {};
- opts.chainId = 'bsc_testnet';
- opts.privateKey = moralis_config.DEFAULT_PRIVATE_KEY;
- opts.type = "erc20"; //native erc20
- if (!obj.receiver || !obj.amount || parseInt(obj.amount) <= 0) {
- logger.error("transfer fun transfer parameter error.", obj.receiver, obj.amount, obj.amount);
- return toJson(ERROR_CODE_001, null, "please check receiver or amount parameter is ok ?");
- }
- if (obj.chain != null) {
- opts.chainId = utils.getChainId(obj.chain);
- console.log("chainId:", opts.chainId);
- }
- if (obj.type != null) {
- opts.type = obj.type;
- }
- if (obj.from_block != null) {
- opts.from_block = obj.from_block;
- }
- if (obj.to_block != null) {
- opts.to_block = obj.to_block;
- }
- opts.contractAddress = obj.contractAddress;
- opts.receiver = obj.receiver;
- //调用者传入
- // opts.amount = Moralis.Units.Token(obj.amount, 18);
- opts.amount = obj.amount;
- if (obj.privateKey != null) {
- opts.privateKey = obj.privateKey;
- }
- try {
- // sending 0.5 DAI tokens with 18 decimals on BSC testnet
- var options;
- if (opts.contractAddress) { //如果存在就是代币
- options = Moralis.TransferOptions = {
- type: opts.type,
- amount: opts.amount,
- receiver: opts.receiver, //接收钱包地址
- contractAddress: opts.contractAddress //用户合约地址
- };
- logger.tlog("options 20 =", options);
- } else { //ETH or BNB
- options = Moralis.TransferOptions = {
- type: opts.type,
- amount: opts.amount,
- receiver: opts.receiver, //接收钱包地址
- };
- logger.tlog("options native =", options, opts.chainId);
- }
- // Enable web3
- await Moralis.enableWeb3({
- //BSC mainnet = 0x38-56 testnet:0x61-97
- chainId: opts.chainId,
- privateKey: opts.privateKey,
- });
- logger.tlog("options id =", opts.chainId);
- var ret = await Moralis.transfer(options);
- logger.tlog("transfer 结果 =", ret);
- return toJson(SUCCEED_CODE, ret, "");
- } catch (error) {
- logger.tlog('transfer error:', error);
- if (error.reason != null) {
- return toJson(ERROR_CODE_001, null, error.toString());
- } else {
- return toJson(ERROR_CODE_001, null, error);;
- }
- }
- };
- const getAllTokenWithdrawInfoLists = async (obj) => {
- try {
- var key = reids_token_config.TOKENWITHDRAW;
- var ret = await redis.readRedis(key);
- return toJson(SUCCEED_CODE, ret, null);
- } catch (error) {
- console.error("getAllTokenWithdrawInfoLists=", error);
- return toJson(ERROR_CODE_001, null, error.toString());
- }
- }
- /**
- * 获取代币价格 -> usdPrice
- */
- const getAllTotkenPrice = async () => {
- try {
- logger.log('当前环境:', process.env.NODE_ENV);
- logger.log("getAllTotkenPrice in", reids_token_config); // Prints "value"
- var token_price_key = reids_token_config.TOKENPRICE;
- logger.log("getAllTotkenPrice token_price_key=", token_price_key);
- return await redis.readRedis(token_price_key)
- } catch (error) {
- logger.error("getTotkenPrice=", error);
- return toJson(ERROR_CODE_001, null, error.toString());
- }
- }
- function setTransfersDataType(type, ret) {
- if (ret && Array.isArray(ret) && ret.length > 0) {
- ret.forEach(element => {
- element.type = type;
- });
- }
- }
- //获取交易记录
- //hash 0xe09ba3a4c9f7a8902e01af68d0f1f91906f3f7db1195227e61c45c0e86b2630a
- async function getTokenTransfers(opt) {
- await initMasterSDK();
- logger.debug("fun getTokenTransfers in ", opt);
- const options = {};
- options.type = 'all';
- options.chain = 'bsc_mainnet';
- if (opt.chain != null) {
- options.chain = utils.getChainName(opt.chain);
- logger.log('getTokenTransfers=', options.chain);
- }
- if (opt.order != null) {
- options.order = opt.order;
- }
- if (opt.startTime != null) {
- options.from_date = opt.startTime;
- }
- if (opt.endTime != null) {
- options.to_date = opt.endTime;
- }
- if (opt.from_block != null) {
- options.from_block = opt.from_block;
- }
- if (opt.to_block != null) {
- options.to_block = opt.to_block;
- }
- if (opt.transaction_hash) {
- options.transaction_hash = opt.transaction_hash;
- options.type = 'transaction_hash';
- }
- logger.debug('getTokenTransfers-->>>', options);
- if (options.type == 'all') {//查询主流币和 20 币所有的交易
- try {
- if (opt.address != null) {
- options.address = opt.address;
- } else {
- return toJson(ERROR_CODE_001, null, "please check address parameter is ok ?");
- }
- //主流币
- var t_1 = await Moralis.Web3API.account.getTransactions(options);
- setTransfersDataType('native', t_1.result)
- //20币
- var t_2 = await Moralis.Web3API.account.getTokenTransfers(options);
- setTransfersDataType('token', t_2.result)
- let arr = t_1.result;
- let arr1 = t_2.result;
- if (Array.isArray(arr1) && Array.isArray(arr)) {
- let arr2 = arr.concat(arr1);
- t_1.result = arr2;
- }
- //将结果排序
- t_1.result.sort((a, b) => {
- let t1 = new Date(Date.parse(a.block_timestamp))
- let t2 = new Date(Date.parse(b.block_timestamp))
- return t2.getTime() - t1.getTime()
- })
- return toJson(SUCCEED_CODE, t_1, null);
- } catch (error) {
- logger.error("getTransactions error:", error)
- return toJson(ERROR_CODE_001, null, error);;
- }
- } else if (options.type == 'transaction_hash') {//根据哈希查询
- try {
- //native
- const transaction = await Moralis.Web3API.native.getTransaction(options);
- var arr = [];
- if (transaction)
- arr.push(transaction)
- var obj = { result: arr }
- return toJson(SUCCEED_CODE, obj, null);
- } catch (error) {
- logger.error("native getTransaction error:", error)
- return toJson(ERROR_CODE_001, null, error);
- }
- } else {
- return toJson(ERROR_CODE_001, null, "This type is not supported.");;
- }
- }
- module.exports = {
- transfer,
- getTokenTransfers,
- toJson,
- getAllTokenWithdrawInfoLists,
- getAllTotkenPrice,
- withdraw,
- collectCoins,
- pushCollectConisObj,
- }
|