@/utils/utils#totalInUSD JavaScript Examples

The following examples show how to use @/utils/utils#totalInUSD. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: marketData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
function parseMarketData (data){
    let tvlArr = [];
    let volArr = []
    var d = new Date();
    d.setDate(d.getDate()-49);
    for (let i=0;i<50;i++){
        tvlArr.push([d.toISOString().substring(0, 10),0]);
        volArr.push([d.toISOString().substring(0, 10),0]);
        d.setDate(d.getDate()+1);
    }
    data.forEach(element => {
        //let _token0 = findTokenWithAddress(element.token0).symbol;
        //let _token1 = findTokenWithAddress(element.token1).symbol;

        let _token0 = findTokenWithAddress_market(element.token0).symbol;
        let _token1 = findTokenWithAddress_market(element.token1).symbol;

        element.historicalData.forEach(item => {
            let at = tvlArr.findIndex(index => index[0] == item.date);
            let currTVL = totalInUSD([
                {
                    token : _token0,
                    amount : item.reserves.token0
                },
                {
                    token : _token1,
                    amount : item.reserves.token1
                }
            ], tokensPriceUSD);
            let currVolume = totalInUSD([
                {
                    token : _token0,
                    amount : item.volume24h.token0
                },
                {
                    token : _token1,
                    amount : item.volume24h.token1
                }
            ], tokensPriceUSD);

            if(at>=0){
                tvlArr[at][1] += currTVL;
                volArr[at][1] += currVolume;
            }
        })
    });

    let output = {
        tvl : tvlArr,
        volume24h : volArr,
    }

    return output;
}
Example #2
Source File: poolData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
// fetch general pool info
// top 10, etc
// FOLLOWING 2 FUNCTIONS GET DATA FROM API
/*
data is an array of items with following format : 
{
  token0 : String,
  token1 : string,
  lastReserves : formatted number,
  lastVolumes : formatted number
}

we want : 
  address: "0x21b8065d10f73ee2e260e5b47d3344d3ced7596e"
  coin1: "WISE"
  coin2: "WETH"
  percent: 0
  price: 0
  tvl: 396257257.00010574
  volume7d: 940097.9591566627
  volume24h: 86149.02125578691
*/

function parsePoolData (data){

  let _data = data.map((item)=>{

    // console.log("mapping....",item.token0,item.token1);
    let _token0 = findTokenWithAddress_market(item.token0);
    let _token1 = findTokenWithAddress_market(item.token1);

    let _logoURL1 = _token0.logoURI;
    let _logoURL2 = _token1.logoURI;

    _token0 = _token0.symbol;
    _token1 = _token1.symbol;


    let _tvl = totalInUSD ( [
      {
        token : _token0,
        amount : item.lastReserves.token0
      },
      {
        token : _token1,
        amount : item.lastReserves.token1
      }
    ],tokensPriceUSD);

    let _volume24h = totalInUSD ( [
      {
        token : _token0,
        amount : item.lastVolume.token0
      },
      {
        token : _token1,
        amount : item.lastVolume.token1
      }
    ],tokensPriceUSD);

    return {
      pairAddr : item.pairAddr,
      coin1 : _token0,
      coin2 : _token1,
      logoURL1 : _logoURL1,
      logoURL2 : _logoURL2,
      tvl : _tvl ,
      volume24h : _volume24h,
      volume7d : 0
    }
  });
  let allsums = 0;
  let allvolumes = 0;
  _data.forEach(element => {
    allsums += element.tvl;
    allvolumes += element.volume24h;
  });

  return sortTable(_data,'volume24h',true);
}
Example #3
Source File: poolData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
function parsePoolDayInfoData(data){

  let _data = [];
  let _token0 = findTokenWithAddress_market(data.token0).symbol;
  let _token1 = findTokenWithAddress_market(data.token1).symbol;

  data.historicalData.forEach(element => {

    let currTVL = totalInUSD([
      {
          token : _token0,
          amount : element.reserves.token0
      },
      {
          token : _token1,
          amount : element.reserves.token1
      }
    ], tokensPriceUSD);

    let currVolume = totalInUSD([
      {
          token : _token0,
          amount : element.volume24h.token0
      },
      {
          token : _token1,
          amount : element.volume24h.token1
      }
    ], tokensPriceUSD);
      
    let myDate = element.date;
    myDate = myDate.split("-");
    var newDate = new Date( myDate[0], myDate[1]-1, myDate[2]);
    console.log(newDate);

    _data.push({
      dailyVolumeUSD : currVolume.toString(),
      date : newDate.getTime()/1000,
      reserveUSD: currTVL.toString(),
      token0 : {
        symbol : _token0
      },
      token1 : {
        symbol : _token1
      }
    })
  });

 _data.reverse();
 return _data;
}
Example #4
Source File: poolData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
function parseSearchPoolReturns(data, key){

  let _data = data.map((item)=>{

    console.log("mapping....",item.token0,item.token1);
    let _token0 = findTokenWithAddress_market(item.token0);
    let _token1 = findTokenWithAddress_market(item.token1);

    let _logoURL1 = _token0.logoURI;
    let _logoURL2 = _token1.logoURI;

    _token0 = _token0.symbol;
    _token1 = _token1.symbol;


    let _tvl = totalInUSD ( [
      {
        token : _token0,
        amount : item.lastReserves.token0
      },
      {
        token : _token1,
        amount : item.lastReserves.token1
      }
    ],tokensPriceUSD);

    let _volume24h = totalInUSD ( [
      {
        token : _token0,
        amount : item.lastVolume.token0
      },
      {
        token : _token1,
        amount : item.lastVolume.token1
      }
    ], tokensPriceUSD);
    
    // Find pair addr
    let pairAddr = getPairAddress(item.token0, item.token1);
  
    return {
      coin1 : _token0,
      coin2: _token1,
      pairAddr: pairAddr,
      logoURL1 : _logoURL1,
      logoURL2 : _logoURL2,
      tvl : _tvl ,
      volume24h : _volume24h,
      volume7d : 0
    }
  });
  let allsums = 0;
  let allvolumes = 0;
  _data.forEach(element => {
    allsums += element.tvl;
    allvolumes += element.volume24h;
  });

  return sortTable(_data, key ,true);
}
Example #5
Source File: tokenData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
function parseTokenData (data){

  //INIT TOKEN LIST;
  let newData = [];

  MARKET_TOKEN_LIST().forEach(element => {
    newData.push({
      address : element.address,
      name : element.name,
      price : tokensPriceUSD[element.symbol] ? tokensPriceUSD[element.symbol] : 1,
      priceChange : -0,
      short : element.symbol,
      logoURL : element.logoURI,
      tvl : 0,
      volume24h : 0

    })
  });

  data.forEach(element => {
      let index0 = newData.findIndex(item => item.address.toLowerCase() == element.token0.toLowerCase() );
      let index1 = newData.findIndex(item => item.address.toLowerCase() == element.token1.toLowerCase() );

      if(index0>=0 && index0<newData.length){

          newData[index0].tvl += totalInUSD([
            {
              token : newData[index0].short,
              amount : element.lastReserves.token0
            }
          ],tokensPriceUSD);
    
          newData[index0].volume24h += totalInUSD([
            {
              token : newData[index0].short,
              amount : element.lastVolume.token0
            }
          ],tokensPriceUSD);

      }

      if(index1>=0 && index1<newData.length){
          newData[index1].tvl += totalInUSD([
            {
              token : newData[index1].short,
              amount : element.lastReserves.token1
            }
          ],tokensPriceUSD);
    
          newData[index1].volume24h += totalInUSD([
            {
              token : newData[index1].short,
              amount : element.lastVolume.token1
            }
          ],tokensPriceUSD);
      }


  });

  console.log("token data",newData);

  return sortTable(newData,'volume24h',true);
  
}
Example #6
Source File: tokenData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
function parseSearchCoinReturns (data, key){
  //INIT TOKEN LIST;
  let newData = [];
  const uniqueTokens = MARKET_TOKEN_LIST();
  uniqueTokens.forEach(element => {
    newData.push({
      address : element.address,
      name : element.name,
      price : tokensPriceUSD[element.symbol] ? tokensPriceUSD[element.symbol] : 1,
      priceChange : -0,
      short : element.symbol,
      logoURL : element.logoURI,
      tvl : 0,
      volume24h : 0

    })
  });

  data.forEach(element => {
      let index0 = newData.findIndex(item => item.address.toLowerCase() == element.token0.toLowerCase() );
      let index1 = newData.findIndex(item => item.address.toLowerCase() == element.token1.toLowerCase() );
      newData[index0].tvl += totalInUSD([
        {
          token : newData[index0].short,
          amount : element.lastReserves.token0
        }
      ],tokensPriceUSD);

      newData[index0].volume24h += totalInUSD([
        {
          token : newData[index0].short,
          amount : element.lastVolume.token0
        }
      ],tokensPriceUSD);

      newData[index1].tvl += totalInUSD([
        {
          token : newData[index1].short,
          amount : element.lastReserves.token1
        }
      ],tokensPriceUSD);

      newData[index1].volume24h += totalInUSD([
        {
          token : newData[index1].short,
          amount : element.lastVolume.token1
        }
      ],tokensPriceUSD);

  });

  return sortTable(newData, key, true);
  
}
Example #7
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
//function to parse tx list to fit in datasource
async function parseTransactionList(data){


  const tokensPriceUSD = await getAllSupportedTokensPrice_forMarket();

  let _txList = data.filter(item=>item.token1Number!=null);

  console.log("pringting filtered tx",_txList);
    
  _txList = _txList.map((item) => {
    let totalValue;
    item.action == 'Swap' ? 
    
    totalValue = totalInUSD([{
      token : item.token1Symbol,
      amount : item.token1Number
    }],tokensPriceUSD) 
    
    : totalValue = totalInUSD([{
      token : item.token1Symbol,
      amount : item.token1Number}
      ,

      {token : item.token2Symbol,
      amount : item.token2Number
    }],tokensPriceUSD);

    return {
      account: item.address,
      coin1: item.token1Symbol,
      coin1Amount: item.token1Number,
      coin2: item.token2Symbol,
      coin2Amount: item.token2Number,
      time: item.transactionTime,
      totalValue: totalValue,
      transactionID: item.hash,
      type: item.action
    }
  })

  return _txList.filter(item => item.coin1Amount !=0 );
}
Example #8
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
function saveTxInDB(data){


    let valueSwapped = totalInUSD([
        {
            token : data.inputTokenSymbol,
            amount : parseFloat(data.inputTokenNum)
        }
    ],tokenPriceUSD);


    let feesPaid = totalInUSD([
        {
            token : constantInstance.gasTokenSymbol,
            amount : data.gasFee
        }
    ],tokenPriceUSD);

    try{
        axios
        .post(
            `${API_URL()}/users/swap?address=${data.address}&hash=${data.hash}&valueSwapped=${valueSwapped}&feesPaid=${feesPaid}`
        )
        .then(response => {
          console.log(response.response);
        });
    }catch(e){
        console.log("service not working...")
    }
    // TODO (Gary): Bonus here
    try{
        axios
        .get(
            `${API_URL()}/launch/allocation/bonus?walletId=${data.address}&T=${valueSwapped}&bonusName=swap`
        )
        .then(response => {
          console.log(response.response);
        });
    } catch(e) {
        console.log("failed to allocate bonus, catching error: ", e)
    }
    if (data.outTokenSymbol == 'ACY') {
        try{
            axios
            .get(
                `${API_URL()}/launch/allocation/bonus?walletId=${data.address}&T=${valueSwapped}&bonusName=acy`
            )
            .then(response => {
              console.log(response.response);
            });
        } catch(e) {
            console.log("failed to allocate bonus, catching error: ", e)
        }
    }

}
Example #9
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
async function fetchUniqueETHToToken (account, hash, timestamp, FROM_HASH, library, gasPrice){
    console.log("fetchUniqueETHToToken",hash);

    const actionList = ACTION_LIST();

    try{

        let response = await library.getTransactionReceipt(hash);
        
        if(!response.status) return {};
        FROM_HASH = response.from.toLowerCase().slice(2);
        let TO_HASH = response.to.toLowerCase().slice(2);
        let inLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[1].includes(TO_HASH));
        let outLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[2].includes(FROM_HASH));
        // console.log("pringting data of tx::::::",response,inLogs,outLogs);
        let inToken = findTokenInList(inLogs[0]);
        let outToken =  findTokenInList(outLogs[0]);

        inLogs = inLogs.filter(log => log.address.toLowerCase() == inToken.address.toLowerCase());
        outLogs = outLogs.filter(log => log.address.toLowerCase() == outToken.address.toLowerCase());

        
        // console.log(inToken,outToken);
        // console.log("debug finished");

        let inTokenNumber = 0;
        let outTokenNumber = 0;

        for(let log of inLogs){inTokenNumber = inTokenNumber + (log.data / Math.pow(10, inToken.decimals))};
        // inTokenNumber = inTokenNumber.toString();
        for(let log of outLogs){outTokenNumber += (log.data / Math.pow(10, outToken.decimals))};
        // outTokenNumber = outTokenNumber.toString();         

        let now = Date.now();
        let transactionTime ;
        if(timestamp) transactionTime = moment(parseInt(timestamp * 1000)).format('YYYY-MM-DD HH:mm:ss');
        else transactionTime = moment(now).format('YYYY-MM-DD HH:mm:ss');

        let gasFee = (gasPrice / (Math.pow(10,18)) )* response.gasUsed.toNumber();

        let totalAmount = totalInUSD([
            {
                token : inToken.symbol,
                amount : parseFloat(inTokenNumber)
            },
        ],tokenPriceUSD);

        // console.log(response);

        return {
            "address" : response.from,
            "hash": hash,
            "action" : 'Swap',
            "totalToken": totalAmount,
            "inputTokenNum": inTokenNumber,
            "inputTokenSymbol": inToken.symbol,
            "outTokenNum": outTokenNumber,
            "outTokenSymbol": outToken.symbol,
            "transactionTime": transactionTime,
            "gasFee" : gasFee
        };

    }catch(e){
        return null;
    }

        
}
Example #10
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
async function fetchUniqueTokenToETH(account, hash, timestamp, FROM_HASH, library, gasPrice){

    console.log("fetchUniqueTokenToETH",hash);

    const actionList = ACTION_LIST();

    try {

        let response = await library.getTransactionReceipt(hash);
        
        if(!response.status) return {};
        FROM_HASH = response.from.toLowerCase().slice(2);
        let TO_HASH = response.to.toLowerCase().slice(2);
        let inLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[1].includes(FROM_HASH));
        let outLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[2].includes(TO_HASH));
        let inToken = findTokenInList(inLogs[0]);
        let outToken =  findTokenInList(outLogs[0]);
        let inTokenNumber = 0;
        let outTokenNumber = 0;

        inLogs = inLogs.filter(log => log.address.toLowerCase() == inToken.address.toLowerCase());
        outLogs = outLogs.filter(log => log.address.toLowerCase() == outToken.address.toLowerCase());

        for(let log of inLogs){inTokenNumber = inTokenNumber + (log.data / Math.pow(10, inToken.decimals))};
        // inTokenNumber = inTokenNumber.toString();
        for(let log of outLogs){outTokenNumber += (log.data / Math.pow(10, outToken.decimals))};
        // outTokenNumber = outTokenNumber.toString();
        let now = Date.now();
        let transactionTime ;
        if(timestamp) transactionTime = moment(parseInt(timestamp * 1000)).format('YYYY-MM-DD HH:mm:ss');
        else transactionTime = moment(now).format('YYYY-MM-DD HH:mm:ss');

        let gasFee = (gasPrice / (Math.pow(10,18)) )* response.gasUsed.toNumber();

        let totalAmount = totalInUSD([
            {
                token : inToken.symbol,
                amount : parseFloat(inTokenNumber)
            },
        ],tokenPriceUSD);

        return  {
            "address" : response.from,
            "action" : 'Swap',
            "hash": hash,
            "totalToken": totalAmount,
            "inputTokenNum": inTokenNumber,
            "inputTokenSymbol": inToken.symbol,
            "outTokenNum": outTokenNumber,
            "outTokenSymbol": outToken.symbol,
            "transactionTime": transactionTime,
            "gasFee" : gasFee
        };

    }catch(e){
        return null;

    }

    
}
Example #11
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
async function fetchUniqueTokenToToken(account, hash, timestamp, FROM_HASH, library, gasPrice){

    console.log("fetchUniqueTokenToToken",hash);

    const actionList = ACTION_LIST();

    try{
    
        let response = await library.getTransactionReceipt(hash);
        FROM_HASH = response.from.toLowerCase().slice(2);
        if(!response.status) return {};
        let inLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]==actionList.transfer.hash && log.topics[1].includes(FROM_HASH));
        let outLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]==actionList.transfer.hash && log.topics[2].includes(FROM_HASH));
    
        let inToken = findTokenInList(inLogs[0]);
        let outToken =  findTokenInList(outLogs[0]);
    
        let inTokenNumber = 0;
        let outTokenNumber = 0;

        inLogs = inLogs.filter(log => log.address.toLowerCase() == inToken.address.toLowerCase());
        outLogs = outLogs.filter(log => log.address.toLowerCase() == outToken.address.toLowerCase());
    
        for(let log of inLogs){inTokenNumber = inTokenNumber + (log.data / Math.pow(10, inToken.decimals))};
        // inTokenNumber = inTokenNumber.toString();
        for(let log of outLogs){outTokenNumber += (log.data / Math.pow(10, outToken.decimals))};
        // outTokenNumber = outTokenNumber.toString();
    
        let now = Date.now();
        let transactionTime ;
        if(timestamp) transactionTime = moment(parseInt(timestamp * 1000)).format('YYYY-MM-DD HH:mm:ss');
        else transactionTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
    
        let gasFee = (gasPrice / (Math.pow(10,18)) )* response.gasUsed.toNumber();
    
        let totalAmount = totalInUSD([
            {
                token : inToken.symbol,
                amount : parseFloat(inTokenNumber)
            },
        ],tokenPriceUSD);
    
        return {
            "address" : response.from,
            "hash": hash,
            "action" : 'Swap',
            "totalToken": totalAmount,
            "inputTokenNum": inTokenNumber,
            "inputTokenSymbol": inToken.symbol,
            "outTokenNum": outTokenNumber,
            "outTokenSymbol": outToken.symbol,
            "transactionTime": transactionTime,
            "gasFee" : gasFee
        }

    }catch(e){
        return null;
    }
    
}
Example #12
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
async function fetchUniqueAddLiquidity(account, hash, timestamp, FROM_HASH, library){

    console.log("fetchUniqueAddLiquidity",hash);

    const actionList = ACTION_LIST();

    try {

        let response = await library.getTransactionReceipt(hash);
        FROM_HASH = response.from.toLowerCase().slice(2);
        let outLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[1].includes(FROM_HASH));
        let tokensOut = new Set();
        for(let log of outLogs){
            tokensOut.add(log.address);
        }
         
        tokensOut = Array.from(tokensOut);

        let logsToken1 = outLogs.filter(log => log.address==tokensOut[0]);
        let logsToken2 = outLogs.filter(log => log.address==tokensOut[1]);

        let token1 = findTokenInList(logsToken1[0]);
        let token2 =  findTokenInList(logsToken2[0]);

        let token1Number = 0;
        for(let log of logsToken1){
            if(log.address.toLowerCase() == token1.address.toLowerCase()) token1Number = token1Number + (log.data / Math.pow(10, token1.decimals))
        };
        // console.log(token1Number);
        // token1Number = token1Number.toString();
        let token2Number = 0;
        for(let log of logsToken2){
            if(log.address.toLowerCase() == token2.address.toLowerCase()) token2Number += (log.data / Math.pow(10, token2.decimals))
        };
        // token2Number = token2Number.toString();
        let now = Date.now();
        let transactionTime ;
        if(timestamp) transactionTime = moment(parseInt(timestamp * 1000)).format('YYYY-MM-DD HH:mm:ss');
        else transactionTime = moment(now).format('YYYY-MM-DD HH:mm:ss');

        let totalAmount = totalInUSD([
            {
                token : token1.symbol,
                amount : parseFloat(token1Number)
            },
            {
                token : token2.symbol,
                amount : parseFloat(token2Number)
            }
        ],tokenPriceUSD);

        return ({
        "address" : response.from,
        "hash": hash,
        "action":'Add',
        "totalToken": totalAmount,
        "token1Number": token1Number,
        "token1Symbol": token1.symbol,
        "token2Number": token2Number,
        "token2Symbol": token2.symbol,
        "transactionTime": transactionTime
        })

    }catch (e){
        console.log(e);
        return null;
    }
    

            
}
Example #13
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export async function fetchUniqueRemoveLiquidity(account, hash, timestamp, FROM_HASH, library){

    console.log("fetchUniqueRemoveLiquidity",hash);

    const actionList = ACTION_LIST();

    try {

        let response = await library.getTransactionReceipt(hash);
        FROM_HASH = response.from.toLowerCase().slice(2);
        // console.log('filtered data',response);
        let inLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[2].includes(FROM_HASH));
        // console.log('filtered logs',outLogs);
        let tokensIn = new Set();
        for(let log of inLogs){
            tokensIn.add(log.address);
        }
        // console.log(tokensIn);
        tokensIn = Array.from(tokensIn);
        // console.log('set',tokensIn);

        let logsToken1 = inLogs.filter(log => log.address==tokensIn[0]);
        let logsToken2 = inLogs.filter(log => log.address==tokensIn[1]);

        let token1 = findTokenInList(logsToken1[0]);
        let token2 =  findTokenInList(logsToken2[0]);

        let token1Number = 0;
        for(let log of logsToken1){token1Number = token1Number + (log.data / Math.pow(10, token1.decimals))};
        // token1Number = token1Number.toString();
        let token2Number = 0;
        for(let log of logsToken2){token2Number += (log.data / Math.pow(10, token2.decimals))};
        // token2Number = token2Number.toString();

        let now = Date.now();
        let transactionTime ;
        if(timestamp) transactionTime = moment(parseInt(timestamp * 1000)).format('YYYY-MM-DD HH:mm:ss');
        else transactionTime = moment(now).format('YYYY-MM-DD HH:mm:ss');

        let totalAmount = totalInUSD([
            {
                token : token1.symbol,
                amount : parseFloat(token1Number)
            },
            {
                token : token2.symbol,
                amount : parseFloat(token2Number)
            }
        ],tokenPriceUSD);

        return ({
        "address" : response.from,
        "hash": hash,
        "action":'Remove',
        "totalToken": totalAmount,
        "token1Number": token1Number,
        "token1Symbol": token1.symbol,
        "token2Number": token2Number,
        "token2Symbol": token2.symbol,
        "transactionTime": transactionTime
        })
    }catch (e){
        console.log(e)
        return null;
    }
    
}
Example #14
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export async function fetchUniqueAddLiquidityEth(account, hash, timestamp, FROM_HASH, library){
    console.log("fetchUniqueAddLiquidityEth",hash);

    const actionList = ACTION_LIST();

    try{

        let response = await library.getTransactionReceipt(hash);
        let TO_HASH = response.to.toLowerCase().slice(2);
        FROM_HASH = response.from.toLowerCase().slice(2);
        let logsToken1 = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[1].includes(FROM_HASH));
        let logsToken2 = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[1].includes(TO_HASH));
    
        let token1 = findTokenInList(logsToken1[0]);
        let token2 =  findTokenInList(logsToken2[0]);
    
        let token1Number = 0;
        for(let log of logsToken1){token1Number = token1Number + (log.data / Math.pow(10, token1.decimals))};
        // token1Number = token1Number.toString();
        let token2Number = 0;
        for(let log of logsToken2){token2Number += (log.data / Math.pow(10, token2.decimals))};
        // token2Number = token2Number.toString();
    
        let now = Date.now();
        let transactionTime ;
        if(timestamp) transactionTime = moment(parseInt(timestamp * 1000)).format('YYYY-MM-DD HH:mm:ss');
        else transactionTime = moment(now).format('YYYY-MM-DD HH:mm:ss');
    
        let totalAmount = totalInUSD([
            {
                token : token1.symbol,
                amount : parseFloat(token1Number)
            },
            {
                token : token2.symbol,
                amount : parseFloat(token2Number)
            }
        ],tokenPriceUSD);
    
        return ({
        "address" : response.from,
        "hash": hash,
        "action":'Add',
        "totalToken": totalAmount,
        "token1Number": token1Number,
        "token1Symbol": token1.symbol,
        "token2Number": token2Number,
        "token2Symbol": token2.symbol,
        "transactionTime": transactionTime
        })

    }catch (e){
        console.log(e);
        return null;
    }

}
Example #15
Source File: txData.js    From acy-dex-interface with MIT License 5 votes vote down vote up
export async function fetchUniqueRemoveLiquidityEth(account, hash, timestamp, FROM_HASH, library){

    console.log("fetchUniqueRemoveLiquidityEth",hash);

    const actionList = ACTION_LIST();

    try {

        let response = await library.getTransactionReceipt(hash);
        let TO_HASH = response.to.toLowerCase().slice(2);
        FROM_HASH = response.from.toLowerCase().slice(2);
        let logsToken1 = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[2].includes(FROM_HASH));
        let logsToken2 = response.logs.filter(log => log.topics.length > 2 && log.topics[0]===actionList.transfer.hash && log.topics[2].includes(TO_HASH));

        let token1 = findTokenInList(logsToken1[0]);
        let token2 =  findTokenWithSymbol(constantInstance.gasTokenSymbol);


        console.log(token1,token2,logsToken1,logsToken2);

        let token1Number = 0;
        for(let log of logsToken1){
            if(log.address.toLowerCase() == token1.address.toLowerCase()) token1Number = token1Number + (log.data / Math.pow(10, token1.decimals))
        };

        let token2Number = 0;
        for(let log of logsToken2){
            if(log.address.toLowerCase() == token2.address.toLowerCase()) token2Number += (log.data / Math.pow(10, token2.decimals))
        };

        let now = Date.now();
        let transactionTime ;
        if(timestamp) transactionTime = moment(parseInt(timestamp * 1000)).format('YYYY-MM-DD HH:mm:ss');
        else transactionTime = moment(now).format('YYYY-MM-DD HH:mm:ss');

        let totalAmount = totalInUSD([
            {
                token : token1.symbol,
                amount : parseFloat(token1Number)
            },
            {
                token : token2.symbol,
                amount : parseFloat(token2Number)
            }
        ],tokenPriceUSD);

        return ({
        "address" : response.from,
        "hash": hash,
        "action":'Remove',
        "totalToken": totalAmount,
        "token1Number": token1Number,
        "token1Symbol": token1.symbol,
        "token2Number": token2Number,
        "token2Symbol": token2.symbol,
        "transactionTime": transactionTime
        })        
    }catch(e){
        console.log(e);
        return null;
    }

}
Example #16
Source File: txData.js    From acy-dex-interface with MIT License 4 votes vote down vote up
//below code is used for transaction detail page

export async function fetchTransactionData(address,library){

    tokenPriceUSD = await getAllSupportedTokensPrice();
    const web3 = new Web3(RPC_URL());
    let SCAN_API = constantInstance.scanAPIPrefix.scanUrl;
    let GAS_TOKEN = constantInstance.gasTokenSymbol;
    const actionList = ACTION_LIST();
    const methodList = METHOD_LIST();

    const txReceipt = await library.getTransactionReceipt(address.toString());
    const transactionData = await library.getTransaction(address.toString());

    console.log(txReceipt);
    console.log(transactionData);

    const from = (transactionData.from).toLowerCase();
    const to = (transactionData.to).toLowerCase();

    //parse ROUTES  and AMM Output

    const [routes,amm_output,dist_output] = decodeFinalLog(
        txReceipt.logs[txReceipt.logs.length-1],
        from , 
        to, 
        txReceipt.logs.filter(item=>item.topics.length > 2 && item.topics[0].includes(actionList.transfer.hash)),
        transactionData.data);
    
    console.log("found routes", routes);
    //get GAS PRICE and symbol
    // let priceRequest = '';
    // let gasPrice;
    // if(GAS_TOKEN == 'BNB'){
    //     priceRequest = SCAN_API + '?module=stats&action=bnbprice';
    //     priceRequest = await fetch(priceRequest);
    //     gasPrice = await priceRequest.json();
    //     gasPrice = gasPrice.result.ethusd;
    // }else if( GAS_TOKEN == 'MATIC'){
    //     priceRequest = SCAN_API + '?module=stats&action=maticprice';
    //     priceRequest = await fetch(priceRequest);
    //     gasPrice = await priceRequest.json();
    //     gasPrice = gasPrice.result.maticusd;
    // }else {
    //     console.log("GAS NOT DEFINED YET");
    // }

    let gasUsed = txReceipt.gasUsed * transactionData.gasPrice.toNumber() / Math.pow(10, findTokenWithSymbol(GAS_TOKEN).decimals) ; //expressed in BNB
    console.log(gasUsed);

    // calculate total amounts of TX

    let totalIn = 0;
    routes.forEach(element => {
        totalIn += element.token1Num;
    });

    let totalOut = 0;
    routes.forEach(element => {
        totalOut += element.token3Num;
    });
    
    let inToken = findTokenWithSymbol(routes[0].token1);
    let outToken = findTokenWithSymbol(routes[0].token3);
    // calculate trading fee

    let trading_fee = totalInUSD([
        {
            token : inToken.symbol,
            amount : totalIn * FEE_PERCENT
        },
    ],tokenPriceUSD);

    // temporary fix for dist_output AKA trader output/treasury

    let new_dist = (totalOut - amm_output) * .5;

    return {
        'token1' : inToken,
        'token2' : outToken,
        'totalIn' : totalIn,
        'totalOut' : totalOut,
        'routes' : routes,
        'gasFee' : gasUsed,
        'gasFeeUSD' : totalInUSD([
            {
                token : GAS_TOKEN,
                amount : gasUsed
            },
        ],tokenPriceUSD),
        'amm_output': amm_output,
        'acy_treasury': totalOut - amm_output - new_dist,
        'trader_treasury': new_dist,
        'gas_symbol' : GAS_TOKEN,
        'trading_fee' : trading_fee,
        'trader_final' : new_dist + amm_output,
        'trader_finalUSD' : totalInUSD([
            {
                token : outToken.symbol,
                amount : new_dist + amm_output
            }
        ],tokenPriceUSD)

    }

    // try{
    //     const apikey = 'H2W1JHHRFB5H7V735N79N75UVG86E9HFH2';

    //     const transactionData = await library.getTransaction(address.toString());
    //     const sourceAddress = (transactionData.from).toLowerCase();
    //     const destAddress = (transactionData.to).toLowerCase();
    //     // console.log("transactionData", transactionData);
    //     // console.log(sourceAddress, destAddress);

    //     // this code is used to get METHOD ID
    //     // for (let i = 0; i < ACYV1ROUTER02_ABI.length; i ++) {
    //     //     console.log(ACYV1ROUTER02_ABI[i]["name"]);
    //     //     console.log(web3.eth.abi.encodeFunctionSignature(ACYV1ROUTER02_ABI[i]));
    //     // }

    //     const methodUsed = Object.keys(methodList).find(key => transactionData.data.startsWith(methodList[key].id));
    //     console.log("methodUsed", methodUsed);
        
    //     if (Object.keys(methodList).includes(methodUsed)) {
    //         const methodUsedABI = ACYV1ROUTER02_ABI.find(item => item.name == methodList[methodUsed].name)
    //         const parsedInputData = "0x" + transactionData.data.substring(10, transactionData.data.length);
    //         const txnDataDecoded = web3.eth.abi.decodeParameters(methodUsedABI.inputs, parsedInputData);
    //         console.log("txnDataDecoded", txnDataDecoded);
    //         const fromTokenAddress = txnDataDecoded.path[0];
    //         const toTokenAddress = txnDataDecoded.path[1];
            
    //         // parsing loggings
    //         const response = await library.getTransactionReceipt(address.toString());
    //         // console.log("Response: ",response);
    //         const gasFee = (transactionData.gasPrice.toNumber() / (Math.pow(10,18)) ) * response.gasUsed.toNumber()
    //         const FlashArbitrageResult_Log = response.logs[response.logs.length-1];
    //         const FlashArbitrageResultLogs_ABI = ACYV1ROUTER02_ABI.find(item => item.name == 'FlashArbitrageResultLogs');
    //         const txnReceiptDecoded = web3.eth.abi.decodeLog(
    //             FlashArbitrageResultLogs_ABI.inputs, 
    //             FlashArbitrageResult_Log.data, 
    //             FlashArbitrageResult_Log.topics
    //             )
    //         // console.log("txnReceiptDecoded", txnReceiptDecoded);
            
    //         /**
    //          * Parse transfer logs
    //          * 1. find all the routes from sourceAddress to destAddress
    //          * */
    //         const transferLogs = response.logs.filter(log => log.topics.length > 2 && log.topics[0] == actionList.transfer.hash);
    //         // console.log("transferLogs", transferLogs);
    //         const routes_loglists = [];
    //         if (methodList[methodUsed].name === methodList.tokenToTokenArb.name) {
    //             // console.log("method: swapExactTokensForTokensByArb")
    //             for (let i = 0; i < transferLogs.length; i ++) {
    //                 let transferFromAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[1])).toLowerCase();
    //                 let transferToAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[2])).toLowerCase();
    //                 if (transferFromAddress == sourceAddress) {
    //                     let pathList = [i];
    //                     let path = getTransferLogPath(transferLogs, pathList, transferToAddress, destAddress);
    //                     if (path != null) {
    //                         routes_loglists.push(path);
    //                     }
    //                 }
    //             } 
    //         } else if (methodList[methodUsed].name === methodList.ethToTokenArb.name) {
    //             // console.log("method: swapExactETHForTokensByArb")
    //             for (let i = 0; i < transferLogs.length; i++) {
    //                 let transferFromAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[1])).toLowerCase();
    //                 let transferToAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[2])).toLowerCase();
    //                 if (transferFromAddress == destAddress) {
    //                     let pathList = [i];
    //                     let path = getTransferLogPath(transferLogs, pathList, transferToAddress, destAddress);
    //                     if (path != null) {
    //                         routes_loglists.push(path);
    //                     }
    //                 }
    //             } 
    //         } else if (methodList[methodUsed].name === methodList.tokenToEthArb.name) {
    //             // console.log("method: swapExactTokensForETHByArb")
    //             for (let i = 0; i < transferLogs.length; i++) {
    //                 let transferFromAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[1])).toLowerCase();
    //                 let transferToAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[2])).toLowerCase();
    //                 if (transferFromAddress == sourceAddress) {
    //                     let pathList = [i];
    //                     let path = getTransferLogPath(transferLogs, pathList, transferToAddress, destAddress);
    //                     if (path != null) {
    //                         routes_loglists.push(path);
    //                     }
    //                 }
    //             }
    //         } else if (methodList[methodUsed].name === methodList.tokenToExactTokenArb.name) {
    //             // console.log("method: swapTokensForExactTokensByArb")
    //             for (let i = 0; i < transferLogs.length; i++) {
    //                 let transferFromAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[1])).toLowerCase();
    //                 let transferToAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[2])).toLowerCase();
    //                 if (transferFromAddress == sourceAddress) {
    //                     let pathList = [i];
    //                     let path = getTransferLogPath(transferLogs, pathList, transferToAddress, sourceAddress);
    //                     if (path != null) {
    //                         routes_loglists.push(path);
    //                     }
    //                 }
    //             }
    //         } else if (methodList[methodUsed].name === methodList.ethToExactTokenArb.name) {
    //             // console.log("method: swapETHForExactTokensByArb")
    //             for (let i = 0; i < transferLogs.length; i++) {
    //                 let transferFromAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[1])).toLowerCase();
    //                 let transferToAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[2])).toLowerCase();
    //                 if (transferFromAddress == destAddress) {
    //                     let pathList = [i];
    //                     let path = getTransferLogPath(transferLogs, pathList, transferToAddress, sourceAddress);
    //                     if (path != null) {
    //                         routes_loglists.push(path);
    //                     }
    //                 }
    //             }
    //         } else if (methodList[methodUsed].name === methodList.tokenToExactEthArb.name) {
    //             // console.log("method: swapTokensForExactETHByArb")
    //             for (let i = 0; i < transferLogs.length; i++) {
    //                 let transferFromAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[1])).toLowerCase();
    //                 let transferToAddress = (web3.eth.abi.decodeParameter("address", transferLogs[i].topics[2])).toLowerCase();
    //                 if (transferFromAddress == sourceAddress) {
    //                     let pathList = [i];
    //                     let path = getTransferLogPath(transferLogs, pathList, transferToAddress, destAddress);
    //                     if (path != null) {
    //                         routes_loglists.push(path);
    //                     }
    //                 }
    //             }
    //         } else {
    //             console.log("no method matched")
    //         }


    //         // console.log("routes_loglists", routes_loglists);

    //         /**
    //          * Parse the routes_loglists into frontend readable data
    //          */
    //         let routes = []
    //         let totalIn = 0;
    //         let totalOut = 0;
    //         let token1 = null;
    //         let token2 = null;
    //         let token3 = null;
    //         const INITIAL_TOKEN_LIST = TOKENLIST();
    //         for (const path of routes_loglists) {
    //             token1 = INITIAL_TOKEN_LIST.find(item => item.address.toLowerCase() == transferLogs[path[0]].address.toLowerCase());
    //             token2 = null;
    //             let amount1 = (transferLogs[path[0]].data / Math.pow(10, token1.decimals)); 
    //             let amount2 = null;
    //             let amount3 = null;
    //             // direct path
    //             if (path.length == 2) {
    //                 token3 = token3 == null ? INITIAL_TOKEN_LIST.find(item => item.address.toLowerCase() == transferLogs[path[1]].address.toLowerCase()) : token3;
    //                 amount3 = (transferLogs[path[1]].data / Math.pow(10, token3.decimals)); 
    //                 // console.log(token1, token3);
    //                 routes.push({
    //                     "token1": token1.symbol,
    //                     "token2": null,
    //                     "token3": token3.symbol,
    //                     "token1Num": amount1,
    //                     "token2Num": null,
    //                     "token3Num": amount3,
    //                     "logoURI": null
    //                 })
    //             } 
    //             // routed path
    //             else {
    //                 token2 = INITIAL_TOKEN_LIST.find(item => item.address.toLowerCase() == transferLogs[path[1]].address.toLowerCase());
    //                 token3 = token3 == null ? INITIAL_TOKEN_LIST.find(item => item.address.toLowerCase() == transferLogs[path[2]].address.toLowerCase()) : token3;
    //                 amount2 = (transferLogs[path[1]].data / Math.pow(10, token2.decimals)); 
    //                 amount3 = (transferLogs[path[2]].data / Math.pow(10, token3.decimals)); 
    //                 // console.log(token1, token2, token3);
    //                 routes.push({
    //                     "token1": token1.symbol,
    //                     "token2": token2.symbol,
    //                     "token3": token3.symbol,
    //                     "token1Num": amount1,
    //                     "token2Num": amount2,
    //                     "token3Num": amount3,
    //                     "logoURI": token2.logoURI
    //                 })
    //             }
    //             totalIn += amount3;
    //             totalOut += amount1;
    //         }

    //         // let requestPrice = API()+'?module=stats&action=bnbprice&apikey='+apikey;
    //         // let responsePrice = await fetch(requestPrice);
    //         // let ethPrice = await responsePrice.json();
    //         // ethPrice = parseFloat(ethPrice.result.ethusd);

    //         // console.log("fetching ethprice",ethPrice);
    //         // console.log("txnReceiptDecoded.AMMOutput", txnReceiptDecoded.AMMOutput);
    //         // console.log("txnReceiptDecoded.FAOutput", txnReceiptDecoded.FAOutput);
    //         // console.log("txnReceiptDecoded.userDistributionAmount", txnReceiptDecoded.userDistributionAmount);

    //         const newData = {
    //             "routes" : routes,
    //             "totalIn" : totalIn,
    //             "totalOut" : totalOut,
    //             "gasFee" : gasFee,
    //             "token1" : token1,
    //             "token2" : token3,
    //             "ethPrice" : 0,
    //             "AMMOutput": (Math.floor(txnReceiptDecoded.AMMOutput) / Math.pow(10, token3.decimals)), // this number is actually too large for integer, so it doesnt convert the string to int completely, but its enough for frontend showcase, wont be effecting the result.
    //             "FAOutput": (Math.floor(txnReceiptDecoded.FAOutput) / Math.pow(10, token3.decimals)),
    //             "userDistributionAmount": (Math.floor(txnReceiptDecoded.userDistributionAmount) / Math.pow(10, token3.decimals))
    //         }
    //         // console.log("newData", newData);

    //         let chartData = getChartData(newData);
    //         newData.chartData = chartData;
    //         return newData;
    //     } else if(transactionData.data.startsWith(methodList.addLiquidity.id)){

    //     } else if(transactionData.data.startsWith(methodList.addLiquidityEth.id)){

    //     } else if(transactionData.data.startsWith(methodList.removeLiquidity.id)){

    //     } else if(transactionData.data.startsWith(methodList.removeLiquidityETH.id)){

    //     } else {
    //         console.log("Transaction not parseable");
    //     }

    // } catch (e){
    //     console.log(e);
    // }
    // return {};
}
Example #17
Source File: poolData.js    From acy-dex-interface with MIT License 4 votes vote down vote up
// var ACY_API='http://localhost:3001/api/';

// export async function fetchPoolInfo(client, address, timestamp) {
//   const block = await getBlockFromTimestamp(timestamp);

//   const { loading, error, data } = await client.query({
//     query: GET_POOL_INFO,
//     variables: {
//       pairAddress: address,
//       block: parseInt(block.number),
//     },
//   });

//   if (loading) return null;
//   if (error) return `Error! ${error}`;

//   console.log(data);

//   return data.pairs[0];
// }

function parsePoolInfo(data){

    let _token0 = findTokenWithAddress_market(data.token0);
    let _token1 = findTokenWithAddress_market(data.token1);

    let _logoURL1 = _token0.logoURI;
    let _logoURL2 = _token1.logoURI;

    _token0 = _token0.symbol;
    _token1 = _token1.symbol;

    let _tvl = totalInUSD ( [
      {
        token : _token0,
        amount : data.lastReserves.token0
      },
      {
        token : _token1,
        amount : data.lastReserves.token1
      }
    ],tokensPriceUSD);

    let _volume24h = totalInUSD ( [
      {
        token : _token0,
        amount : data.lastVolume.token0
      },
      {
        token : _token1,
        amount : data.lastVolume.token1
      }
    ],tokensPriceUSD);

    let _token0USD = totalInUSD( [
      {
        token : _token0,
        amount : 1
      }
    ],tokensPriceUSD)

    let _token1USD = totalInUSD( [
      {
        token : _token1,
        amount : 1
      }
    ],tokensPriceUSD)

    const parsed = {
      reserve0: data.lastReserves.token0.toString(),
      reserve1: data.lastReserves.token1.toString(),
      reserveUSD: _tvl.toString(),
      token0: {
        symbol:  _token0 , logoURI : _logoURL1, id: data.token0
      },
      token0Price: _token0USD.toString(),
      token1: {
        symbol:  _token1 , logoURI : _logoURL2, id: data.token1
      },
      token1Price: _token1USD.toString(),
      untrackedVolumeUSD: "0",
      volumeUSD: _volume24h.toString()
    }
    return parsed
}