Skip to content

Commit

Permalink
Merge branch 'staging' into tr-cms-news
Browse files Browse the repository at this point in the history
  • Loading branch information
yornaath committed Jan 12, 2024
2 parents 1bcff7a + eb1a097 commit cd6216b
Show file tree
Hide file tree
Showing 16 changed files with 91 additions and 186 deletions.
4 changes: 1 addition & 3 deletions components/markets/MarketHeader.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -345,9 +345,7 @@ const MarketHeader: FC<{
const [showMarketHistory, setShowMarketHistory] = useState(false);
const starts = Number(period.start);
const ends = Number(period.end);
const volume = new Decimal(pool?.volume ?? neoPool?.volume ?? 0)
.div(ZTG)
.toNumber();
const volume = new Decimal(market.volume).div(ZTG).toNumber();

const { outcome, by } = getMarketStatusDetails(
marketType,
Expand Down
2 changes: 1 addition & 1 deletion components/markets/MarketsList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ const MarketsList = ({ className = "" }: MarketsListProps) => {
/>
<div className="grid grid-cols-1 gap-7 md:grid-cols-2 lg:grid-cols-3">
{markets?.map((market) => {
const volume = market.pool?.volume ?? market.neoPool?.volume ?? 0;
const volume = market.volume;
const scalarType = market.scalarType as ScalarRangeType;
const stat = stats?.find((s) => s.marketId === market.marketId);
const question = market.question ?? "";
Expand Down
4 changes: 1 addition & 3 deletions components/markets/SimilarMarketsSection.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,7 @@ export const SimilarMarketsSection = ({
neoPool={market?.neoPool}
status={market.status}
baseAsset={market.baseAsset}
volume={new Decimal(market.pool?.volume ?? 0)
.div(ZTG)
.toNumber()}
volume={new Decimal(market.volume ?? 0).div(ZTG).toNumber()}
tags={
market.tags?.filter((tag): tag is string => tag !== null) ??
[]
Expand Down
2 changes: 1 addition & 1 deletion components/markets/market-card/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export interface IndexedMarketCardData {
scalarType: ScalarRangeType | null;
prediction: { name: string; price: number };
volume: number;
pool?: { poolId?: number; volume: string } | null;
pool?: { poolId?: number } | null;
neoPool?: FullMarketFragment["neoPool"] | null;
baseAsset: string;
tags?: string[];
Expand Down
2 changes: 1 addition & 1 deletion lib/gql/featured-markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const getFeaturedMarkets = async (
creator: market.creator,
img: market.img ?? "",
prediction: prediction,
volume: new Decimal(market.pool?.volume ?? 0).div(ZTG).toNumber(),
volume: new Decimal(market.volume ?? 0).div(ZTG).toNumber(),
baseAsset: market.baseAsset,
outcomes: marketCategories,
pool: market.pool,
Expand Down
45 changes: 11 additions & 34 deletions lib/gql/get-network-stats.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,30 +5,24 @@ import { parseAssetIdString } from "lib/util/parse-asset-id";
import { getBaseAssetHistoricalPrices, lookupPrice } from "./historical-prices";
import {
PoolOrderByInput,
MarketOrderByInput,
NeoPoolOrderByInput,
HistoricalSwapOrderByInput,
} from "@zeitgeistpm/indexer";
import { MarketsOrderBy } from "lib/types/market-filter";

export const getNetworkStats = async (sdk: Sdk<FullContext>) => {
const [marketCountBN, basePrices, pools, neoPools, historicalSwaps] =
const [marketCountBN, basePrices, markets, historicalSwaps] =
await Promise.all([
sdk.api.query.marketCommons.marketCounter(),
getBaseAssetHistoricalPrices(),
fetchAllPages(async (pageNumber, limit) => {
const { pools } = await sdk.indexer.pools({
const { markets } = await sdk.indexer.markets({
limit: limit,
offset: pageNumber * limit,
order: PoolOrderByInput.IdAsc,
order: MarketOrderByInput.IdAsc,
});
return pools;
}),
fetchAllPages(async (pageNumber, limit) => {
const { neoPools } = await sdk.indexer.neoPools({
limit: limit,
offset: pageNumber * limit,
order: NeoPoolOrderByInput.IdAsc,
});
return neoPools;
return markets;
}),
fetchAllPages(async (pageNumber, limit) => {
const { historicalSwaps } = await sdk.indexer.historicalSwaps({
Expand All @@ -40,28 +34,14 @@ export const getNetworkStats = async (sdk: Sdk<FullContext>) => {
}),
]);

const totalPoolVolumeUsd = pools.reduce<Decimal>((total, pool) => {
const poolCreationBaseAssetPrice = lookupPrice(
basePrices,
parseAssetIdString(pool.baseAsset) as BaseAssetId,
new Date(pool.createdAt).getTime(),
);

const volumeUsd = new Decimal(pool.volume).mul(
poolCreationBaseAssetPrice ?? 0,
);

return total.plus(volumeUsd);
}, new Decimal(0));

const totalNeopoolVolumeUsd = pools.reduce<Decimal>((total, pool) => {
const totalMarketVolumeUsd = markets.reduce<Decimal>((total, market) => {
const poolCreationBaseAssetPrice = lookupPrice(
basePrices,
parseAssetIdString(pool.baseAsset) as BaseAssetId,
new Date(pool.createdAt).getTime(),
parseAssetIdString(market.baseAsset) as BaseAssetId,
new Date(market.pool?.createdAt ?? market.neoPool?.createdAt).getTime(),
);

const volumeUsd = new Decimal(pool.volume).mul(
const volumeUsd = new Decimal(market.volume).mul(
poolCreationBaseAssetPrice ?? 0,
);

Expand All @@ -76,9 +56,6 @@ export const getNetworkStats = async (sdk: Sdk<FullContext>) => {
return {
marketCount: marketCountBN.toNumber(),
tradersCount,
volumeUsd: totalNeopoolVolumeUsd
.plus(totalPoolVolumeUsd)
.div(ZTG)
.toNumber(),
volumeUsd: totalMarketVolumeUsd.div(ZTG).toNumber(),
};
};
6 changes: 2 additions & 4 deletions lib/gql/markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,15 @@ const marketQuery = gql`
marketId
description
baseAsset
volume
pool {
poolId
createdAt
volume
baseAsset
}
neoPool {
createdAt
collateral
volume
}
question
slug
Expand Down Expand Up @@ -90,6 +89,7 @@ export interface MarketPageIndexedData {
question: string;
description: string | PortableTextBlock[];
status: MarketStatus;
volume: string;
period: {
block: string[];
start: string;
Expand All @@ -105,14 +105,12 @@ export interface MarketPageIndexedData {
resolvedOutcome: string;
pool?: {
poolId: number;
volume: string;
createdAt: string;
baseAsset: string;
};
neoPool?: {
collateral: string;
createdAt: string;
volume: string;
};
scalarType: ScalarRangeType;
marketType: {
Expand Down
93 changes: 22 additions & 71 deletions lib/gql/trending-markets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import Decimal from "decimal.js";
import { GraphQLClient, gql } from "graphql-request";
import { DAY_SECONDS, ZTG } from "lib/constants";
import { hiddenMarketIds } from "lib/constants/markets";
import { marketMetaFilter } from "lib/hooks/queries/constants";
import {
ForeignAssetPrices,
getBaseAssetPrices,
Expand All @@ -23,68 +24,17 @@ import { MarketOutcome, MarketOutcomes } from "lib/types/markets";
import { getCurrentPrediction } from "lib/util/assets";
import { fetchAllPages } from "lib/util/fetch-all-pages";
import { parseAssetIdString } from "lib/util/parse-asset-id";
import { marketMetaFilter } from "./constants";

const poolChangesQuery = gql`
query PoolChanges($start: DateTime, $end: DateTime) {
historicalPools(
const marketChangesQuery = gql`
query MarketChanges($start: DateTime, $end: DateTime) {
historicalMarkets(
where: { timestamp_gt: $start, volume_gt: "0", timestamp_lt: $end }
orderBy: id_DESC
) {
poolId
dVolume
}
}
`;

const marketQuery = gql`
query Market($poolId: Int) {
markets(
where: {
pool: { poolId_eq: $poolId }
marketId_not_in: ${hiddenMarketIds}
hasValidMetaCategories_eq: true
categories_isNull: false
${marketMetaFilter}
}
) {
marketId
outcomeAssets
question
creation
img
baseAsset
creator
marketType {
categorical
scalar
}
categories {
color
name
market {
marketId
}
pool {
volume
}
outcomeAssets
tags
period {
end
}
status
scalarType
}
}
`;

const assetsQuery = gql`
query Assets($poolId: Int) {
assets(where: { pool: { poolId_eq: $poolId } }) {
pool {
poolId
}
price
assetId
}
}
`;
Expand All @@ -98,12 +48,14 @@ const getTrendingMarkets = async (
new Date().getTime() - DAY_SECONDS * 7 * 1000,
).toISOString();

const { historicalPools } = await client.request<{
historicalPools: {
const { historicalMarkets } = await client.request<{
historicalMarkets: {
dVolume: string;
poolId: number;
market: {
marketId: number;
};
}[];
}>(poolChangesQuery, {
}>(marketChangesQuery, {
start: dateOneWeekAgo,
end: now,
});
Expand All @@ -116,6 +68,7 @@ const getTrendingMarkets = async (
where: {
status_eq: MarketStatus.Active,
scoringRule_eq: ScoringRule.Lmsr,
...marketMetaFilter,
},
});
return markets;
Expand All @@ -124,7 +77,7 @@ const getTrendingMarkets = async (
const basePrices = await getBaseAssetPrices(sdk);

const trendingMarketIds = calcTrendingMarkets(
historicalPools,
historicalMarkets,
basePrices,
markets,
);
Expand Down Expand Up @@ -158,9 +111,7 @@ const getTrendingMarkets = async (
img: market.img ?? "",
prediction: prediction,
creator: market.creator,
volume: Number(
new Decimal(market.neoPool?.volume ?? 0).div(ZTG).toFixed(0),
),
volume: Number(new Decimal(market?.volume ?? 0).div(ZTG).toFixed(0)),
baseAsset: market.baseAsset,
outcomes: marketCategories,
pool: market.pool ?? null,
Expand Down Expand Up @@ -189,7 +140,9 @@ const lookupPrice = (

const calcTrendingMarkets = (
transactions: {
poolId: number;
market: {
marketId: number;
};
dVolume: string;
}[],
basePrices: ForeignAssetPrices,
Expand All @@ -200,16 +153,14 @@ const calcTrendingMarkets = (

// find total volume for each market
transactions.forEach((transaction) => {
//for lsmr poolId === marketId
const marketId = transaction.poolId;
const marketId = transaction.market.marketId;

if (markets.some((market) => market.marketId === marketId)) {
const volume = marketVolumes[transaction.poolId];
const volume = marketVolumes[marketId];
if (volume) {
// for amm2 marketId === poolId
marketVolumes[transaction.poolId] = volume.plus(transaction.dVolume);
marketVolumes[marketId] = volume.plus(transaction.dVolume);
} else {
marketVolumes[transaction.poolId] = new Decimal(transaction.dVolume);
marketVolumes[marketId] = new Decimal(transaction.dVolume);
}
}
});
Expand Down
6 changes: 3 additions & 3 deletions lib/hooks/queries/useInfiniteMarkets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ export const rootKey = "markets-filtered";
const orderByMap = {
[MarketsOrderBy.Newest]: MarketOrderByInput.MarketIdDesc,
[MarketsOrderBy.Oldest]: MarketOrderByInput.MarketIdAsc,
[MarketsOrderBy.MostVolume]: MarketOrderByInput.PoolVolumeDesc,
[MarketsOrderBy.LeastVolume]: MarketOrderByInput.PoolVolumeAsc,
[MarketsOrderBy.MostVolume]: MarketOrderByInput.VolumeDesc,
[MarketsOrderBy.LeastVolume]: MarketOrderByInput.VolumeAsc,
};

const validMarketWhereInput: MarketWhereInput = {
Expand Down Expand Up @@ -98,7 +98,7 @@ export const useInfiniteMarkets = (
},
offset: !pageParam ? 0 : limit * pageParam,
limit: limit,
order: orderByMap[orderBy],
order: orderByMap[orderBy] as MarketOrderByInput, //todo: fix this type once sdk updated,
});

const resMarkets: Array<QueryMarketData> = markets.map((market) => {
Expand Down
4 changes: 2 additions & 2 deletions lib/hooks/queries/useMarketSpotPrices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,11 +99,11 @@ const calcMarketPrices = (
const outcomeWeights = market.pool.weights.filter(
(weight) =>
weight.assetId.toLocaleLowerCase() !==
market.pool?.baseAsset.toLocaleLowerCase(),
market.baseAsset.toLocaleLowerCase(),
);

//base weight is equal to the sum of all other assets
const baseWeight = new Decimal(market.pool.totalWeight).div(2);
const baseWeight = new Decimal(market?.pool.totalWeight ?? 0).div(2);

outcomeWeights.forEach((weight, index) => {
const spotPrice = calcSpotPrice(
Expand Down
2 changes: 1 addition & 1 deletion lib/hooks/queries/usePortfolioPositions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,7 @@ export const usePortfolioPositions = (
): null | Decimal => {
const poolZtgBalance = poolsZtgBalances[pool.poolId]?.toNumber();

const ztgWeight = new Decimal(pool.totalWeight).div(2);
const ztgWeight = new Decimal(pool.totalWeight ?? 0).div(2);
const assetWeight = getAssetWeight(pool, assetId).unwrap();

const poolAssetBalance = poolAssetBalances?.get(
Expand Down
Loading

0 comments on commit cd6216b

Please sign in to comment.