Skip to content

Commit

Permalink
fix(bex): Fix issue with subgraph pull for price data and dump the di…
Browse files Browse the repository at this point in the history
…rect fetch from the codebase + Poll for bex api prices on a slow rate
  • Loading branch information
PaulMcInnis committed Dec 23, 2024
1 parent 3acb91c commit e2e2bbe
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 95 deletions.
2 changes: 1 addition & 1 deletion apps/hub/src/app/pools/create/CreatePageContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -649,7 +649,7 @@ export default function CreatePageContent() {
</Button>
<h2 className="self-start text-3xl font-semibold">Create a Pool</h2>
<div className="flex w-full flex-col justify-center xl:flex-row">
<div className="grid grid-cols-1 xl:grid-cols-12 gap-6">
<div className="grid grid-cols-1 gap-6 xl:grid-cols-12">
<ProcessSteps
titles={[
"Pool Type",
Expand Down
131 changes: 39 additions & 92 deletions packages/berajs/src/actions/shared/getTokenCurrentPrices.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
import { balancerApiChainName, balancerApiUrl } from "@bera/config";

// FIXME there is a serious issue with the apollo client and the way it's formatting the chain variable here. so I'm hardcoding this for now.
import { balancerApiChainName } from "@bera/config";
import { bexApiGraphqlClient } from "@bera/graphql";
import {
GetTokenCurrentPricesDocument,
GetTokenCurrentPricesQuery,
GetTokenCurrentPricesQueryVariables,
GqlChain,
} from "@bera/graphql/dex/api";
import { getAddress } from "viem";

import { getSafeNumber, handleNativeBera } from "~/utils";

interface TokenPriceInfo {
price: number;
Expand All @@ -13,101 +21,40 @@ export const getTokenCurrentPrices = async (): Promise<
TokenCurrentPriceMap | undefined
> => {
try {
const response = await fetch(balancerApiUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
const res = await bexApiGraphqlClient.query<
GetTokenCurrentPricesQuery,
GetTokenCurrentPricesQueryVariables
>({
query: GetTokenCurrentPricesDocument,
variables: {
chains: [balancerApiChainName as GqlChain],
},
body: JSON.stringify({
query:
"query GetTokenCurrentPrices($chains: [GqlChain!]!) {\n tokenGetCurrentPrices(chains: $chains) {\n address\n price\n chain\n updatedAt\n }\n}\n",
variables: {
chains: ["CARTIO"],
},
}),
});

if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}

const result = await response.json();
const tokenCurrentPriceMap: TokenCurrentPriceMap =
res.data?.tokenGetCurrentPrices.reduce<TokenCurrentPriceMap>(
(map, tokenInformation) => {
if (!tokenInformation.price || !tokenInformation.address) {
return map;
}

if (result.errors) {
console.error("GraphQL Errors:", result.errors);
throw new Error("GraphQL query failed.");
}
const formattedAddress = getAddress(
handleNativeBera(tokenInformation.address),
).toLowerCase();

const pricesArray = result.data.tokenGetCurrentPrices;
map[formattedAddress] = {
price: getSafeNumber(tokenInformation.price.toString()),
chain: tokenInformation.chain,
updatedAt: tokenInformation.updatedAt,
};

if (!pricesArray || !Array.isArray(pricesArray)) {
throw new Error("Unexpected response format.");
}

const tokenCurrentPriceMap: TokenCurrentPriceMap = pricesArray.reduce(
(map, { address, ...info }: { address: string } & TokenPriceInfo) => {
map[address] = info;
return map;
},
{} as TokenCurrentPriceMap,
);
return map;
},
{},
) || {};
return tokenCurrentPriceMap;
} catch (error) {
console.error("Failed to fetch token prices:", error);
} catch (e) {
console.error("Failed to fetch token prices:", e);
return undefined;
}
};

// import { gql } from "@apollo/client";
// import { bexSubgraphClient } from "@bera/graphql";
// import {
// GetTokenCurrentPrices,
// GetTokenCurrentPricesDocument,
// GetTokenCurrentPricesQuery,
// GetTokenCurrentPricesQueryVariables,
// GqlChain,
// } from "@bera/graphql/dex/api";
// import { getAddress } from "viem";

// import { getSafeNumber, handleNativeBera } from "~/utils";

// interface FetchCurrentTokenPricesArgs {
// chains: GqlChain | GqlChain[];
// }
// export interface CurrentTokenPrices {
// [key: string]: number; // aka Token.USDValue
// }
// export const getTokenCurrentPrices = async (): Promise<
// CurrentTokenPrices | undefined
// > => {
// try {
// const res = await bexSubgraphClient.query<
// GetTokenCurrentPricesQuery,
// GetTokenCurrentPricesQueryVariables
// >({
// query: GetTokenCurrentPricesDocument,
// variables: {
// chains: [balancerApiChainName as GqlChain],
// },
// });

// const results = res.data?.tokenGetCurrentPrices.reduce<CurrentTokenPrices>(
// (allPrices, tokenInformation) => {
// if (!tokenInformation.price) return allPrices; // Skip tokens without a price

// const formattedAddress = getAddress(
// handleNativeBera(tokenInformation.address).toLowerCase(),
// );

// return {
// ...allPrices,
// [formattedAddress]: getSafeNumber(tokenInformation.price.toString()),
// };
// },
// {},
// );
// console.log("Token Prices:", results);
// } catch (e) {
// console.error("$$$$$ Failed to fetch token prices:", e);
// return undefined;
// }
// };
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ export const useLiquidityMismatch = ({
const tokenPriceUSD =
tokenPrices[token.address.toLowerCase()]?.price ?? 0;
if (!tokenPriceUSD || tokenPriceUSD === 0) {
console.warn("Token BEX API price is missing for", token);
tokenUSDAmounts.push(0);
return null;
}
Expand Down
5 changes: 4 additions & 1 deletion packages/berajs/src/hooks/tokens/useTokenCurrentPrices.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
TokenCurrentPriceMap,
getTokenCurrentPrices,
} from "~/actions/shared/getTokenCurrentPrices";
import POLLING from "~/enum/polling";
import { DefaultHookReturnType } from "~/types/global";

export const useTokenCurrentPrices = (): DefaultHookReturnType<
Expand All @@ -16,11 +17,13 @@ export const useTokenCurrentPrices = (): DefaultHookReturnType<
async () => {
return await getTokenCurrentPrices();
},
{
refreshInterval: POLLING.SLOW,
},
);

return {
...swrResponse,
refresh: () => void swrResponse.mutate(),
// FIXME we should probably have a polling rate so this expires?
};
};

0 comments on commit e2e2bbe

Please sign in to comment.