Skip to content

Commit

Permalink
Merge pull request #74 from oraichain/fix/FOU-728
Browse files Browse the repository at this point in the history
Fix/fou 728
  • Loading branch information
trungbach authored Dec 5, 2023
2 parents 20b65a3 + 90eab07 commit f5cd4be
Show file tree
Hide file tree
Showing 8 changed files with 202 additions and 285 deletions.
2 changes: 1 addition & 1 deletion packages/oraidex-server/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@oraichain/oraidex-server",
"version": "1.0.29",
"version": "1.0.30",
"main": "dist/index.js",
"bin": "dist/index.js",
"license": "MIT",
Expand Down
2 changes: 1 addition & 1 deletion packages/oraidex-server/package.staging.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@oraichain/oraidex-server-staging",
"version": "1.0.39",
"version": "1.0.41",
"main": "dist/index.js",
"bin": "dist/index.js",
"license": "MIT",
Expand Down
126 changes: 54 additions & 72 deletions packages/oraidex-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,10 @@ import {
simulateSwapPrice,
toDisplay,
usdtInfo,
getMigrateStakingV3Client,
oraixCw20Address,
usdcCw20Address
usdcCw20Address,
getPoolLiquidities,
getPoolAmounts
} from "@oraichain/oraidex-sync";
import cors from "cors";
import "dotenv/config";
Expand Down Expand Up @@ -133,42 +134,36 @@ app.get("/tickers", async (req, res) => {
return pair;
});

const data: TickerInfo[] = (
await Promise.allSettled(
arrangedPairs.map(async (pair) => {
const symbols = pair.symbols;
const pairAddr = findPairAddress(pairInfos, pair.asset_infos);
const tickerId = parseSymbolsToTickerId(symbols);
const baseIndex = 0;
const targetIndex = 1;
const baseInfo = parseAssetInfoOnlyDenom(pair.asset_infos[baseIndex]);
const targetInfo = parseAssetInfoOnlyDenom(pair.asset_infos[targetIndex]);
const volume = await duckDb.queryAllVolumeRange(baseInfo, targetInfo, then, latestTimestamp);
const tickerInfo: TickerInfo = {
ticker_id: tickerId,
base_currency: symbols[baseIndex],
target_currency: symbols[targetIndex],
last_price: "",
base_volume: toDisplay(BigInt(volume.volume[baseInfo])).toString(),
target_volume: toDisplay(BigInt(volume.volume[targetInfo])).toString(),
pool_id: pairAddr ?? "",
base: symbols[baseIndex],
target: symbols[targetIndex]
};
try {
// reverse because in pairs, we put base info as first index
const price = await simulateSwapPrice(pair.asset_infos, routerContract);
tickerInfo.last_price = price.toString();
} catch (error) {
tickerInfo.last_price = "0";
}
return tickerInfo;
})
)
).map((result) => {
if (result.status === "fulfilled") return result.value;
else console.log("result: ", result.reason);
});
const data: TickerInfo[] = [];
for (const pair of arrangedPairs) {
const symbols = pair.symbols;
const pairAddr = findPairAddress(pairInfos, pair.asset_infos);
const tickerId = parseSymbolsToTickerId(symbols);
const baseIndex = 0;
const targetIndex = 1;
const baseInfo = parseAssetInfoOnlyDenom(pair.asset_infos[baseIndex]);
const targetInfo = parseAssetInfoOnlyDenom(pair.asset_infos[targetIndex]);
const volume = await duckDb.queryAllVolumeRange(baseInfo, targetInfo, then, latestTimestamp);
const tickerInfo: TickerInfo = {
ticker_id: tickerId,
base_currency: symbols[baseIndex],
target_currency: symbols[targetIndex],
last_price: "",
base_volume: toDisplay(BigInt(volume.volume[baseInfo])).toString(),
target_volume: toDisplay(BigInt(volume.volume[targetInfo])).toString(),
pool_id: pairAddr ?? "",
base: symbols[baseIndex],
target: symbols[targetIndex]
};
try {
// reverse because in pairs, we put base info as first index
const price = await simulateSwapPrice(pair.asset_infos, routerContract);
tickerInfo.last_price = price.toString();
} catch (error) {
tickerInfo.last_price = "0";
}
data.push(tickerInfo);
}
res.status(200).send(data);
} catch (error) {
console.log("error: ", error);
Expand All @@ -184,12 +179,13 @@ app.get("/volume/v2/historical/chart", async (req, res) => {
const then = startTime
? parseInt(startTime as string)
: getSpecificDateBeforeNow(new Date(latestTimestamp * 1000), 259200).getTime() / 1000;
const volumeInfos = await Promise.all(
pairsOnlyDenom.map((pair) => {
return duckDb.getVolumeRange(timeFrame, then, latestTimestamp, pairToString(pair.asset_infos));
})
);
// console.log("volume infos: ", volumeInfos);

const volumeInfos = [];
for (const { asset_infos } of pairsOnlyDenom) {
const volume = await duckDb.getVolumeRange(timeFrame, then, latestTimestamp, pairToString(asset_infos));
volumeInfos.push(volume);
}

const volumeRanges: { [time: string]: VolumeRange[] } = {};
for (const volumePair of volumeInfos) {
for (const volume of volumePair) {
Expand Down Expand Up @@ -236,19 +232,12 @@ app.get("/v1/candles/", async (req: Request<{}, {}, {}, GetCandlesQuery>, res) =

app.get("/v1/pools/", async (_req, res) => {
try {
const [volumes, allFee7Days, pools, allPoolApr] = await Promise.all([
getAllVolume24h(),
getAllFees(),
duckDb.getPools(),
duckDb.getAllAprs()
]);
const liquidityPromises = pools.map((pair) => getPairLiquidity(pair));
const poolAmountPromises = pools.map((pair) => duckDb.getLatestLpPoolAmount(pair.pairAddr));

const [allLiquidities, allPoolAmounts] = await Promise.all([
Promise.all(liquidityPromises),
Promise.all(poolAmountPromises)
]);
const volumes = await getAllVolume24h();
const allFee7Days = await getAllFees();
const pools = await duckDb.getPools();
const allPoolApr = await duckDb.getAllAprs();
const allLiquidities = await getPoolLiquidities(pools);
const allPoolAmounts = await getPoolAmounts(pools);

const allPoolInfoResponse: PairInfoDataResponse[] = pools.map((pool, index) => {
const poolApr = allPoolApr.find((item) => item.pairAddr === pool.pairAddr);
Expand Down Expand Up @@ -309,11 +298,9 @@ app.get("/v1/pool-detail", async (req: Request<{}, {}, {}, GetPoolDetailQuery>,
const currentDate = new Date();
const oneDayBeforeNow = getSpecificDateBeforeNow(new Date(), tf);
const twoDayBeforeNow = getSpecificDateBeforeNow(new Date(), tf * 2);
const [poolVolume, poolVolumeOnedayBefore, pool] = await Promise.all([
getVolumePairByUsdt(pair.asset_infos, oneDayBeforeNow, currentDate),
getVolumePairByUsdt(pair.asset_infos, twoDayBeforeNow, oneDayBeforeNow),
duckDb.getPoolByAssetInfos(pair.asset_infos)
]);
const poolVolume = await getVolumePairByUsdt(pair.asset_infos, oneDayBeforeNow, currentDate);
const poolVolumeOnedayBefore = await getVolumePairByUsdt(pair.asset_infos, twoDayBeforeNow, oneDayBeforeNow);
const pool = await duckDb.getPoolByAssetInfos(pair.asset_infos);

let percentVolumeChange = 0;
if (poolVolumeOnedayBefore !== 0n) {
Expand Down Expand Up @@ -347,12 +334,9 @@ app.get("/orai-info", async (req, res) => {
const dateBeforeNow = getSpecificDateBeforeNow(new Date(), tf);
const oneDayBeforeNow = getSpecificDateBeforeNow(new Date(), SECONDS_PER_DAY);
const timestamp = Math.round(dateBeforeNow.getTime() / 1000);

const [volume24h, oraiPriceByTime, currenOraiPrice] = await Promise.all([
getVolumePairByUsdt([oraiInfo, usdtInfo], oneDayBeforeNow, currentDate),
getOraiPrice(timestamp),
getOraiPrice()
]);
const volume24h = await getVolumePairByUsdt([oraiInfo, usdtInfo], oneDayBeforeNow, currentDate);
const oraiPriceByTime = await getOraiPrice(timestamp);
const currenOraiPrice = await getOraiPrice();

let percentPriceChange = 0;
if (oraiPriceByTime !== 0) {
Expand Down Expand Up @@ -389,10 +373,8 @@ app.get("/price", async (req: Request<{}, {}, {}, GetPricePairQuery>, res) => {
if (!pair)
return res.status(400).send(`Not found pair with assets: ${req.query.base_denom}-${req.query.quote_denom}`);

const [baseAssetPriceByTime, currentBaseAssetPrice] = await Promise.all([
getPriceByAsset(pair.asset_infos, "base_in_quote", timestamp),
getPriceByAsset(pair.asset_infos, "base_in_quote")
]);
const baseAssetPriceByTime = await getPriceByAsset(pair.asset_infos, "base_in_quote", timestamp);
const currentBaseAssetPrice = await getPriceByAsset(pair.asset_infos, "base_in_quote");

let percentPriceChange = 0;
if (baseAssetPriceByTime !== 0) {
Expand Down
115 changes: 41 additions & 74 deletions packages/oraidex-sync/src/db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -168,36 +168,6 @@ export class DuckDb {
return volumeData;
}

async queryAllVolume(offerDenom: string, askDenom: string): Promise<TokenVolumeData> {
const modifiedOfferDenom = replaceAllNonAlphaBetChar(offerDenom);
const modifiedAskDenom = replaceAllNonAlphaBetChar(askDenom);
const volume = (
await Promise.all([
this.conn.all(
`SELECT sum(offerAmount) as ${modifiedOfferDenom}, sum(returnAmount) as ${modifiedAskDenom}
from swap_ops_data
where offerDenom = ?
and askDenom = ?`,
offerDenom,
askDenom
),
this.conn.all(
`SELECT sum(offerAmount) as ${modifiedAskDenom}, sum(returnAmount) as ${modifiedOfferDenom}
from swap_ops_data
where offerDenom = ?
and askDenom = ?`,
askDenom,
offerDenom
)
])
).flat();
return {
offerDenom,
askDenom,
volume: this.reduceVolume(volume, { offerDenom, modifiedOfferDenom, askDenom, modifiedAskDenom })
};
}

async queryAllVolumeRange(
offerDenom: string, // eg: orai
askDenom: string, // usdt
Expand All @@ -207,34 +177,32 @@ export class DuckDb {
// need to replace because the denom can contain numbers and other figures. We replace for temporary only, will be reverted once finish reducing
const modifiedOfferDenom = replaceAllNonAlphaBetChar(offerDenom);
const modifiedAskDenom = replaceAllNonAlphaBetChar(askDenom);
const volume = (
await Promise.all([
this.conn.all(
`SELECT sum(offerAmount) as ${modifiedOfferDenom}, sum(returnAmount) as ${modifiedAskDenom}
from swap_ops_data
where offerDenom = ?
and askDenom = ?
and timestamp >= ?
and timestamp <= ?`,
offerDenom,
askDenom,
startTime,
endTime
),
this.conn.all(
`SELECT sum(offerAmount) as ${modifiedAskDenom}, sum(returnAmount) as ${modifiedOfferDenom}
from swap_ops_data
where offerDenom = ?
and askDenom = ?
and timestamp >= ?
and timestamp <= ?`,
askDenom,
offerDenom,
startTime,
endTime
)
])
).flat();
const volumeByOfferDenom = await this.conn.all(
`SELECT sum(offerAmount) as ${modifiedOfferDenom}, sum(returnAmount) as ${modifiedAskDenom}
from swap_ops_data
where offerDenom = ?
and askDenom = ?
and timestamp >= ?
and timestamp <= ?`,
offerDenom,
askDenom,
startTime,
endTime
);
const volumeByAskDenom = await this.conn.all(
`SELECT sum(offerAmount) as ${modifiedAskDenom}, sum(returnAmount) as ${modifiedOfferDenom}
from swap_ops_data
where offerDenom = ?
and askDenom = ?
and timestamp >= ?
and timestamp <= ?`,
askDenom,
offerDenom,
startTime,
endTime
);
const volume = [volumeByOfferDenom, volumeByAskDenom].flat();

return {
offerDenom,
askDenom,
Expand Down Expand Up @@ -394,9 +362,8 @@ export class DuckDb {

async getFeeSwap(payload: GetFeeSwap): Promise<[number, number]> {
const { offerDenom, askDenom, startTime, endTime } = payload;
const [feeRightDirection, feeReverseDirection] = await Promise.all([
this.conn.all(
`
const feeRightDirection = await this.conn.all(
`
SELECT
sum(commissionAmount + taxAmount) as totalFee,
FROM swap_ops_data
Expand All @@ -405,13 +372,14 @@ export class DuckDb {
AND offerDenom = ?
AND askDenom = ?
`,
startTime,
endTime,
offerDenom,
askDenom
),
this.conn.all(
`
startTime,
endTime,
offerDenom,
askDenom
);

const feeReverseDirection = await this.conn.all(
`
SELECT
sum(commissionAmount + taxAmount) as totalFee,
FROM swap_ops_data
Expand All @@ -420,12 +388,11 @@ export class DuckDb {
AND offerDenom = ?
AND askDenom = ?
`,
startTime,
endTime,
askDenom,
offerDenom
)
]);
startTime,
endTime,
askDenom,
offerDenom
);

return [feeRightDirection[0]?.totalFee, feeReverseDirection[0]?.totalFee];
}
Expand Down
Loading

0 comments on commit f5cd4be

Please sign in to comment.