Skip to content

Commit

Permalink
Merge pull request #37 from MHaris-Ferrum/develop
Browse files Browse the repository at this point in the history
info api updated with coingecko api and token transfer api impl
  • Loading branch information
AbdulAhadArain authored Aug 29, 2024
2 parents b21d66a + a17aace commit cd46c57
Show file tree
Hide file tree
Showing 5 changed files with 121 additions and 92 deletions.
60 changes: 5 additions & 55 deletions src/controllers/info.controller.ts
Original file line number Diff line number Diff line change
@@ -1,72 +1,22 @@
import { Request, Response, NextFunction } from 'express';
import { transactionsService } from '../services';
import axios from 'axios';
import { COINGECKO_API } from '../utils/constants';

export const getInfoData = async (
req: Request,
res: Response,
next: NextFunction,
): Promise<void> => {
try {
// Fetch FRM data from CoinGecko API
const { data } = await axios.get(COINGECKO_API);

const frmPrice = data?.market_data.current_price.usd;
const frmPriceChangePercentage =
data?.market_data.price_change_percentage_24h;
const frmMarketCap = data?.market_data.market_cap.usd;
const frmMarketCapChangePercentage =
data?.market_data.market_cap_change_percentage_24h;
const frmVolume24h = data?.market_data.total_volume.usd;

// Fetch graph data for the last 24 hours
const now = new Date();
const oneDayAgo = new Date(now);
oneDayAgo.setDate(now.getDate() - 1);

const startTimeStamp = convertDateToTimestamp(oneDayAgo);
const endTimeStamp = convertDateToTimestamp(now);

const transactions = await transactionsService.getDataForChart(
startTimeStamp,
endTimeStamp,
);

// Fetch total transactions
const frmData = await transactionsService.fetchStateDataFromCoinGekoAPI();
const hourlyData = await transactionsService.getDataForChart();
const totalTransactions = await transactionsService.totalTransactions();
const generateLast24HourData = () => {
const data = [];

for (let i = 23; i >= 0; i--) {
const date = new Date();
date.setHours(date.getHours() - i);
const volume = Math.floor(Math.random() * (5000 - 1000 + 1)) + 1000;
data.push({
// date: date.toISOString(),
volume: volume,
});
}

return data;
};

// Example usage for graph data
const graphData =
transactions.length > 0 ? transactions : generateLast24HourData();
// Send data to the frontend
res.send({
frmData: {
price: frmPrice,
priceChangePercentage: frmPriceChangePercentage,
marketCap: frmMarketCap,
marketCapChangePercentage: frmMarketCapChangePercentage,
volume24h: frmVolume24h,
},
frmData,
totalTransactions,
graphData,
graphData: hourlyData,
});
} catch (error) {
console.error('Error fetching info data:', error);
next(error);
}
};
Expand Down
17 changes: 17 additions & 0 deletions src/controllers/transactions.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,23 @@ export const getTransactions = async (
next(error);
}
};
export const getTransferTokenTransactions = async (
req: Request,
res: Response,
next: NextFunction,
): Promise<void> => {
try {
const transactions = await transactionsService.getTransferTokensTxs(
'token_transfer',
req.query.address as any,
req.query.page as any,
req.query.limit as any,
);
res.send(transactions);
} catch (error) {
next(error);
}
};

export const getTransaction = async (
req: Request,
Expand Down
5 changes: 5 additions & 0 deletions src/routes/transactions.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,11 @@ router.get(
validate(transactionValidation.getTransactions),
transactionController.getTransactions,
);
router.get(
'/token-transfer/:address',
validate(transactionValidation.getTransferTokenTransactions),
transactionController.getTransferTokenTransactions,
);
router.get(
'/:txId',
validate(transactionValidation.getTransaction),
Expand Down
124 changes: 87 additions & 37 deletions src/services/transaction.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ import { chartData } from '../interfaces/QuantumPortalRemoteTransaction.interfac
import PocContractABI from '../utils/abi/poc.json';
import MGRContractABI from '../utils/abi/ledgerMgr.json';
import { ethers } from 'ethers';
import { ContractAddresses } from '../utils/constants';
import { COINGECKO_API, ContractAddresses } from '../utils/constants';
import axios from 'axios';

export const saveTransaction = async (tx: any) => {
const existedTx = await QuantumPortalTransactionModel.findOne({
Expand Down Expand Up @@ -105,6 +106,42 @@ export const getTxs = async (
return result;
};

export const getTransferTokensTxs = async (
type: string,
address: string,
page: number,
limit: number,
): Promise<any> => {
const query: any = {
method: 'finalize',
};
if (type) {
query.txType = type;
}
if (address) {
query.$or = [{ from: address }, { to: address }];
}
const docsPromise = QuantumPortalTransactionModel.find(query)
.sort({ timestamp: -1 })
.skip((page - 1) * limit)
.limit(limit);
const countPromise =
QuantumPortalTransactionModel.countDocuments(query).exec();
const [totalResults, results] = await Promise.all([
countPromise,
docsPromise,
]);
const totalPages = Math.ceil(totalResults / limit);
const result = {
results,
page,
limit,
totalPages,
totalResults,
};
return result;
};

export const getTransaction = async (txId: string): Promise<any> => {
let remoteContract: any = '';
let sourceMsgSender: any = '';
Expand Down Expand Up @@ -198,44 +235,41 @@ export const saveTransactions = async (txs: any[]) => {
return await QuantumPortalTransactionModel.insertMany(txs);
};

export const getDataForChart = async (
startDate: any,
endDate: any,
): Promise<chartData[]> => {
const result = QuantumPortalTransactionModel.aggregate([
{
$match: {
export const getDataForChart = async (): Promise<any> => {
try {
const newArray = [];
const horlyStartDate = new Date();

for (let i = 0; i < 24; i++) {
// Create a new date for the current hour
const currentDate = new Date(
horlyStartDate.getTime() - 40 * 60 * 60 * 1000,
);
currentDate.setHours(horlyStartDate.getHours() + i);

// Create a new date for the end of the hour
const endDate = new Date(currentDate);
endDate.setHours(currentDate.getHours() + 1);

// Query for records within the current hour
const hoursResult = await QuantumPortalTransactionModel.find({
timestamp: {
$gte: startDate,
$lte: endDate,
},
},
},
{
$group: {
_id: {
$dateToString: {
format: '%d/%m/%Y',
date: { $toDate: { $multiply: ['$timestamp', 1000] } }, // Convert timestamp to milliseconds
},
$gte: currentDate.toISOString(),
$lte: endDate.toISOString(),
},
count: { $sum: 1 },
},
},
{
$project: {
_id: 0,
date: '$_id',
count: 1,
},
},
{
$sort: {
date: 1,
},
},
]);
return result;
});

// Push the date and count to the array
newArray.push({
date: currentDate.toISOString(),
volume: hoursResult.length,
});
}
return newArray;
} catch (error) {
console.error('Error fetching data for chart:', error);
throw error;
}
};

export const getTransactionByQuery = async (query: Object): Promise<any> => {
Expand Down Expand Up @@ -507,3 +541,19 @@ export const fetchRemoteTransactionWithMinedAndFinalizedTx = async (
}
return responseObj;
};
export const fetchStateDataFromCoinGekoAPI = async () => {
try {
const { data } = await axios.get(COINGECKO_API);
return {
price: data?.market_data.current_price.usd,
priceChangePercentage: data?.market_data.price_change_percentage_24h,
marketCap: data?.market_data.market_cap.usd,
marketCapChangePercentage:
data?.market_data.market_cap_change_percentage_24h,
volume24h: data?.market_data.total_volume.usd,
};
} catch (error) {
console.error('Error fetching CoinGecko data:', error);
throw new Error('Failed to fetch CoinGecko data');
}
};
7 changes: 7 additions & 0 deletions src/validations/transaction.validation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,13 @@ export const getTransactions = {
limit: Joi.number().required().default(20),
}),
};
export const getTransferTokenTransactions = {
query: Joi.object().keys({
address: Joi.string().allow(''),
page: Joi.number().required().default(1),
limit: Joi.number().required().default(20),
}),
};

export const getTransaction = {
params: Joi.object().keys({
Expand Down

0 comments on commit cd46c57

Please sign in to comment.