diff --git a/src/constants/graphEndpoints.ts b/src/constants/graphEndpoints.ts deleted file mode 100644 index 6685623b..00000000 --- a/src/constants/graphEndpoints.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { arbitrum, base, mainnet, polygon } from "viem/chains"; - -export const getGraphEndpointWithKey = (apiKey: string, chainId: number) => { - const GRAPH_ENDPOINTS: { [chainId: number]: string | undefined } = { - [mainnet.id]: `https://gateway-arbitrum.network.thegraph.com/api/${apiKey}/subgraphs/id/B6FW3z7yLTJKVuqz6kLDJAwJru1T89j4ww5JfY3GYX8F`, - [polygon.id]: `https://gateway-arbitrum.network.thegraph.com/api/${apiKey}/subgraphs/id/8bjHtQZ9PZUMQAbCGJw5Zx2SbZZY2LQz8WH3rURzN5do`, - [arbitrum.id]: `https://gateway.thegraph.com/api/${apiKey}/subgraphs/id/F2Cgx4q4ATiopuZ13nr1EMKmZXwfAdevF3EujqfayK7a`, - [base.id]: `https://gateway.thegraph.com/api/${apiKey}/subgraphs/id/8nZqHepMdWCy6CMV9gd4wBTawtxfku4kT8X4pBpa5r75`, - }; - - return GRAPH_ENDPOINTS[chainId]; -}; - -export const getUniswapV3GraphEndpointWithKey = ( - apiKey: string, - chainId: number -) => { - const GRAPH_ENDPOINTS: { [chainId: number]: string | undefined } = { - [mainnet.id]: `https://gateway.thegraph.com/api/${apiKey}/subgraphs/id/5zvR82QoaXYFyDEKLZ9t6v9adgnptxYpKpSbxtgVENFV`, - [polygon.id]: `https://gateway.thegraph.com/api/${apiKey}/subgraphs/id/3hCPRGf4z88VC5rsBKU5AA9FBBq5nF3jbKJG7VZCbhjm`, - [arbitrum.id]: `https://gateway.thegraph.com/api/${apiKey}/subgraphs/id/FbCGRftH4a3yZugY7TnbYgPJVEv2LvMT6oF1fxPe9aJM`, - [base.id]: `https://gateway.thegraph.com/api/${apiKey}/subgraphs/id/43Hwfi3dJSoGpyas9VwNoDAv55yjgGrPpNSmbQZArzMG -`, - }; - - return GRAPH_ENDPOINTS[chainId]; -}; diff --git a/src/hooks/queries/useGetActiveLoansForUser.ts b/src/hooks/queries/useGetActiveLoansForUser.ts index d381a596..24af4956 100644 --- a/src/hooks/queries/useGetActiveLoansForUser.ts +++ b/src/hooks/queries/useGetActiveLoansForUser.ts @@ -1,8 +1,8 @@ -import { useQuery } from "@tanstack/react-query"; -import request, { gql } from "graphql-request"; -import { useAccount } from "wagmi"; -import { useGraphURL } from "../useGraphURL"; -import { Address } from "viem"; +import { useQuery } from '@tanstack/react-query'; +import request, { gql } from 'graphql-request'; +import { useAccount, useChainId } from 'wagmi'; +import { Address } from 'viem'; +import { useGetGraphEndpoint } from '../useGetGraphEndpoint'; type CollateralToken = { name: string; @@ -52,10 +52,10 @@ export type Loan = { }; export enum LoanStatus { - DEFAULTED = "defaulted", - ACCEPTED = "accepted", - DUE_SOON = "dueSoon", - LATE = "late", + DEFAULTED = 'defaulted', + ACCEPTED = 'accepted', + DUE_SOON = 'dueSoon', + LATE = 'late', } export const activeStatuses = [ @@ -66,7 +66,11 @@ export const activeStatuses = [ ]; export const useGetActiveLoansForUser = () => { - const graphURL = useGraphURL(); + const chainId = useChainId(); + const { endpoint: endpointOG, isFetched: isFetchedOG } = useGetGraphEndpoint( + chainId, + 'og', + ); const { address } = useAccount(); const activeLoanForUser = gql` @@ -241,9 +245,22 @@ export const useGetActiveLoansForUser = () => { `; const { data, isLoading } = useQuery({ - queryKey: ["teller-widget", "getActiveLoansForUser", address], - queryFn: () => request(graphURL, activeLoanForUser), - enabled: !!address, + queryKey: ['teller-widget', 'getActiveLoansForUser', address], + queryFn: async () => { + let response = { user: { borrowers: [] } }; + try { + if (endpointOG) { + response = await request(endpointOG, activeLoanForUser); + } + + return response; + } catch (err) { + console.log(err); + } finally { + return response; + } + }, + enabled: !!address && isFetchedOG && !!endpointOG, }) as { data: { user: { diff --git a/src/hooks/queries/useGetCommitmentsForCollateralToken.ts b/src/hooks/queries/useGetCommitmentsForCollateralToken.ts index d8821ae8..3f4d5b4a 100644 --- a/src/hooks/queries/useGetCommitmentsForCollateralToken.ts +++ b/src/hooks/queries/useGetCommitmentsForCollateralToken.ts @@ -1,11 +1,11 @@ -import request, { gql } from "graphql-request"; -import { useMemo } from "react"; -import { useGraphURL } from "../useGraphURL"; -import { useQuery } from "@tanstack/react-query"; -import { useForwarderAddresses } from "../useForwarderAddresses"; -import { Address } from "viem"; -import { useChainId } from "wagmi"; -import { useGetGlobalPropsContext } from "../../contexts/GlobalPropsContext"; +import request, { gql } from 'graphql-request'; +import { useMemo } from 'react'; +import { useQuery } from '@tanstack/react-query'; +import { useForwarderAddresses } from '../useForwarderAddresses'; +import { Address } from 'viem'; +import { useChainId } from 'wagmi'; +import { useGetGlobalPropsContext } from '../../contexts/GlobalPropsContext'; +import { useGetGraphEndpoint } from '../useGetGraphEndpoint'; export type SubgraphTokenType = { imageUri?: string | undefined; @@ -50,10 +50,14 @@ export type CommitmentType = { export const useGetCommitmentsForCollateralToken = ( collateralTokenAddress?: string, - userAddress?: Address + userAddress?: Address, ) => { - const graphURL = useGraphURL(); const chainId = useChainId(); + const { endpoint: endpointOG, isFetched: isFetchedOG } = useGetGraphEndpoint( + chainId, + 'og', + ); + const { principalTokenForPair } = useGetGlobalPropsContext(); const { lcfAlphaAddress, lcfAddress } = useForwarderAddresses(); @@ -73,7 +77,7 @@ export const useGetCommitmentsForCollateralToken = ( ? `principalToken_: { address: "${principalTokenForPair.toLowerCase()}" },` - : "" + : '' } status: "Active", expirationTimestamp_gt: "${Math.floor(Date.now() / 1000)}", @@ -139,25 +143,38 @@ export const useGetCommitmentsForCollateralToken = ( } } `, - [collateralTokenAddress, lcfAddress, lcfAlphaAddress, userAddress] + [collateralTokenAddress, lcfAddress, lcfAlphaAddress, userAddress], ); const { data, isLoading, error } = useQuery({ queryKey: [ - "teller-widget", - "commitmentsForCollateralToken-", + 'teller-widget', + 'commitmentsForCollateralToken-', collateralTokenAddress, chainId, ], - queryFn: async () => request(graphURL, collateralTokenCommitments), - enabled: !!collateralTokenAddress, + queryFn: async () => { + let response = { commitments: [] }; + try { + if (endpointOG) { + response = await request(endpointOG, collateralTokenCommitments); + } + + return response; + } catch (err) { + console.log(err); + } finally { + return response; + } + }, + enabled: !!collateralTokenAddress && isFetchedOG && !!endpointOG, }) as { data: { commitments: CommitmentType[] }; isLoading: boolean; error: string; }; - if (error) console.error("commitmentsForCollateralToken Query error", error); + if (error) console.error('commitmentsForCollateralToken Query error', error); return { data, isLoading }; }; diff --git a/src/hooks/queries/useGetCommitmentsForUserTokens.ts b/src/hooks/queries/useGetCommitmentsForUserTokens.ts index 30247b54..6f735aac 100644 --- a/src/hooks/queries/useGetCommitmentsForUserTokens.ts +++ b/src/hooks/queries/useGetCommitmentsForUserTokens.ts @@ -8,7 +8,6 @@ import { createFingerprintHash } from "../../helpers/localStorageCache"; import type { LenderGroupsPoolMetrics } from "../../types/lenderGroupsPoolMetrics"; import { useGetGraphEndpoint } from "../useGetGraphEndpoint"; import type { UserToken } from "../useGetUserTokens"; -import { useGraphURL } from "../useGraphURL"; interface Commitment { collateralToken: { @@ -34,7 +33,10 @@ const CACHE_TIME = 15 * 60 * 1000; // 15 minutes export const useGetCommitmentsForUserTokens = () => { const chainId = useChainId(); - const graphURL = useGraphURL(); + const { endpoint: endpointOG, isFetched: isFetchedOG } = useGetGraphEndpoint( + chainId, + "og" + ); const { endpoint: endpointV1, isFetched: isFetchedV1 } = useGetGraphEndpoint( chainId, "v1" @@ -125,8 +127,21 @@ export const useGetCommitmentsForUserTokens = () => { address, userTokensFingerprint, ], - queryFn: async () => request(graphURL, userTokenCommitments), - enabled: userTokens.length > 0 && !!address && !!userTokensFingerprint, + queryFn: async () => { + let response = { commitments: [] }; + try { + if (endpointOG) { + response = await request(endpointOG, userTokenCommitments); + } + + return response; + } catch (err) { + console.log(err); + } finally { + return response; + } + }, + enabled: userTokens.length > 0 && !!address && !!userTokensFingerprint && isFetchedOG && !!endpointOG, }) as { data: { commitments: Commitment[] }; isLoading: boolean; diff --git a/src/hooks/queries/useGetRolloverableCommitments.ts b/src/hooks/queries/useGetRolloverableCommitments.ts index c9d78f2b..7cd9ee04 100644 --- a/src/hooks/queries/useGetRolloverableCommitments.ts +++ b/src/hooks/queries/useGetRolloverableCommitments.ts @@ -2,15 +2,16 @@ /* eslint-disable @typescript-eslint/no-unsafe-assignment */ import { useQuery } from "@tanstack/react-query"; import request, { gql } from "graphql-request"; +import { useChainId } from "wagmi"; import { useEffect, useMemo, useState } from "react"; import { Address } from "viem"; import { useCalculateMaxCollateralFromCommitment } from "../useCalculateMaxCollateralFromCommitment"; import { useConvertLenderGroupCommitmentToCommitment } from "../useConvertLenderGroupCommitmentToCommitment"; import { useForwarderAddresses } from "../useForwarderAddresses"; import { useGetMinimumBetweenLenderAndCommitment } from "../useGetMinimumBetweenLenderAndCommitment"; -import { useGraphURL } from "../useGraphURL"; import { Loan } from "./useGetActiveLoansForUser"; import { useGetRolloverableCommitmentsFromLiquidityPools } from "./useGetRolloverableCommitmentsFromLiquidityPools"; +import { useGetGraphEndpoint } from "../useGetGraphEndpoint"; export type CommitmentMapArray = Map; @@ -98,8 +99,11 @@ export const useGetRolloverableCommitments = ( principalTokenAddress?: string, loan?: Loan ) => { - const graphURL = useGraphURL(); - + const chainId = useChainId(); + const { endpoint: endpointOG, isFetched: isFetchedOG } = useGetGraphEndpoint( + chainId, + "og" + ); const { lcfAlphaAddress } = useForwarderAddresses(); const [filteredCommitments, setFilteredCommitments] = useState( @@ -191,8 +195,21 @@ export const useGetRolloverableCommitments = ( "rolloverableCommitmentsForCollateralToken-", collateralTokenAddress, ], - queryFn: async () => request(graphURL, collateralTokenCommitments), - enabled: !!collateralTokenAddress, + queryFn: async () => { + let response = { commitments: [] }; + try { + if (endpointOG) { + response = await request(endpointOG, collateralTokenCommitments); + } + + return response; + } catch (err) { + console.log(err); + } finally { + return response; + } + }, + enabled: !!collateralTokenAddress && !!endpointOG && isFetchedOG, }) as { data: { commitments: CommitmentType[] }; isLoading: boolean }; const { diff --git a/src/hooks/queries/useGetUniswapPools.ts b/src/hooks/queries/useGetUniswapPools.ts index c66102c0..e6df2903 100644 --- a/src/hooks/queries/useGetUniswapPools.ts +++ b/src/hooks/queries/useGetUniswapPools.ts @@ -1,10 +1,8 @@ -import { QueryClient, useQueryClient } from "@tanstack/react-query"; -import { getUniswapV3GraphEndpointWithKey } from "../../constants/graphEndpoints"; +import { useQueryClient } from "@tanstack/react-query"; import request, { gql } from "graphql-request"; import { useCallback, useState } from "react"; import { useChainId } from "wagmi"; import { UniswapV3Pool } from "../../constants/uniswapV3Pool.type"; -import { useGetGlobalPropsContext } from "../../contexts/GlobalPropsContext"; export interface UseGetUniswapV3LiquidityPoolsParams { /** The token address to search pools for */ @@ -85,16 +83,15 @@ const POOL_DAY_DATAS_QUERY = gql` */ export const useGetUniswapPools = () => { const chainId = useChainId(); - const { subgraphApiKey } = useGetGlobalPropsContext(); const queryClient = useQueryClient(); - const graphURL = getUniswapV3GraphEndpointWithKey(subgraphApiKey, chainId); const [isLoading, setIsLoading] = useState(false); const fetchPoolData = useCallback( - async ({ + async (endpoint: string, { tokenAddress, days = 30, }: UseGetUniswapV3LiquidityPoolsParams) => { + setIsLoading(true); try { const result = await queryClient.fetchQuery({ @@ -108,7 +105,7 @@ export const useGetUniswapPools = () => { queryFn: async () => { // Step 1: Get the best pool const poolsResponse = await request( - graphURL || "", + endpoint, UNISWAP_V3_POOLS_QUERY, { tokenAddress } ); @@ -129,7 +126,7 @@ export const useGetUniswapPools = () => { const daysAgoTimestamp = Math.floor(Date.now() / 1000) - secondsAgo; const dayDataResponse = await request( - graphURL || "", + endpoint, POOL_DAY_DATAS_QUERY, { poolId: bestPool.id, @@ -163,8 +160,8 @@ export const useGetUniswapPools = () => { setIsLoading(false); } }, - [chainId, graphURL, queryClient] + [chainId, queryClient] ); - return { fetchPoolData, isLoading }; + return { fetchPoolData, isLoading: isLoading }; }; diff --git a/src/hooks/queries/useGetUniswapRoutes.ts b/src/hooks/queries/useGetUniswapRoutes.ts index f5f24549..a8af750a 100644 --- a/src/hooks/queries/useGetUniswapRoutes.ts +++ b/src/hooks/queries/useGetUniswapRoutes.ts @@ -1,10 +1,9 @@ import request, { gql } from "graphql-request"; import { useEffect, useState } from "react"; import { useChainId } from "wagmi"; -import { getUniswapV3GraphEndpointWithKey } from "../../constants/graphEndpoints"; import { WETH_ADDRESSES } from "../../constants/tokens"; import { UniswapV3Pool } from "../../constants/uniswapV3Pool.type"; -import { useGetGlobalPropsContext } from "../../contexts/GlobalPropsContext"; +import { useGetGraphEndpoint } from "../../hooks/useGetGraphEndpoint"; interface PoolsResponse { pools: UniswapV3Pool[]; @@ -77,8 +76,10 @@ export const useBestUniswapV3Route = ( const isFinalTokenWETH = WETH_ADDRESSES.includes( finalTokenAddress?.toLowerCase() ?? "" ); - const { subgraphApiKey } = useGetGlobalPropsContext(); - const graphURL = getUniswapV3GraphEndpointWithKey(subgraphApiKey, chainId); + const { endpoint: endpointUniswap } = useGetGraphEndpoint( + chainId, + "uniswap" + ); const [route, setRoute] = useState<{ pools: any[]; @@ -90,7 +91,7 @@ export const useBestUniswapV3Route = ( useEffect(() => { const getRoute = async () => { - if (!principalTokenAddress || !finalTokenAddress || !graphURL || !chainId) + if (!principalTokenAddress || !finalTokenAddress || !endpointUniswap || !chainId) return; const cacheKey = `${chainId}-${principalTokenAddress.toLowerCase()}-${finalTokenAddress.toLowerCase()}`; @@ -104,7 +105,7 @@ export const useBestUniswapV3Route = ( try { // Step 1: Get pools involving the collateral token const { pools: collateralPools } = await request( - graphURL, + endpointUniswap, UNISWAP_V3_POOLS_BY_TOKEN_QUERY, { token: finalTokenAddress.toLowerCase() } ); @@ -153,7 +154,7 @@ export const useBestUniswapV3Route = ( : firstCollateralPool.token0.id; const { pools: principalPools } = await request( - graphURL, + endpointUniswap, UNISWAP_V3_POOLS_BY_PAIR_QUERY, { token0: principalTokenAddress.toLowerCase(), @@ -200,7 +201,7 @@ export const useBestUniswapV3Route = ( principalTokenAddress, finalTokenAddress, chainId, - graphURL, + endpointUniswap, isFinalTokenWETH, ]); diff --git a/src/hooks/queries/useIsNewBorrower.ts b/src/hooks/queries/useIsNewBorrower.ts index ebbfe5b4..f8962f85 100644 --- a/src/hooks/queries/useIsNewBorrower.ts +++ b/src/hooks/queries/useIsNewBorrower.ts @@ -1,15 +1,19 @@ import { useQuery } from "@tanstack/react-query"; import request, { gql } from "graphql-request"; import { useEffect, useMemo, useState } from "react"; -import { useAccount } from "wagmi"; +import { useAccount, useChainId } from "wagmi"; import { getItemFromLocalStorage } from "../../helpers/localStorageUtils"; -import { useGraphURL } from "../useGraphURL"; +import { useGetGraphEndpoint } from "../useGetGraphEndpoint"; export const useIsNewBorrower = () => { - const graphURL = useGraphURL(); + const chainId = useChainId(); const [showTerms, setShowTerms] = useState(false); + const { endpoint: endpointOG, isFetched: isFetchedOG } = useGetGraphEndpoint( + chainId, + "og" + ); useEffect(() => { const borrowTermsAccepted = JSON.parse( getItemFromLocalStorage("borrowTermsAccepted") || "false" @@ -35,8 +39,21 @@ export const useIsNewBorrower = () => { const { data, isLoading } = useQuery({ queryKey: ["teller-widget", "isNewBorrower", address], - queryFn: () => request(graphURL, isNewBorrower), - enabled: !!address, + queryFn: async () => { + let response = { borrowers: [] }; + try { + if (endpointOG) { + response = await request(endpointOG, isNewBorrower); + } + + return response; + } catch (err) { + console.log(err); + } finally { + return response; + } + }, + enabled: !!address && isFetchedOG && !!endpointOG, }) as { data: { borrowers: { id: string }[] }; isLoading: boolean }; return { diff --git a/src/hooks/queries/useUniswapV3PoolUSDValue.ts b/src/hooks/queries/useUniswapV3PoolUSDValue.ts index 9a89077e..808cb9eb 100644 --- a/src/hooks/queries/useUniswapV3PoolUSDValue.ts +++ b/src/hooks/queries/useUniswapV3PoolUSDValue.ts @@ -2,7 +2,6 @@ import { Address, erc20Abi } from "viem"; import { readContract } from "wagmi/actions"; import request, { gql } from "graphql-request"; import { config } from "../../helpers/createWagmiConfig"; -import { getUniswapV3GraphEndpointWithKey } from "../../constants/graphEndpoints"; import uniswapV3PoolAbi from "../../contracts/UNISWAP_V3_POOL_ABI.json"; import { useChainId } from "wagmi"; import { useGetGlobalPropsContext } from "../../contexts/GlobalPropsContext"; @@ -73,7 +72,7 @@ export const useUniswapV3PoolUSDValue = () => { const [isLoading, setIsLoading] = useState(false); const getPoolUSDValue = useCallback( - async ({ poolAddress }: GetUniswapV3PoolUSDValueParams) => { + async (endpoint: string, { poolAddress }: GetUniswapV3PoolUSDValueParams) => { if (!chainId) { throw new Error("Chain ID is undefined"); } @@ -117,18 +116,13 @@ export const useUniswapV3PoolUSDValue = () => { }); // 3. Setup subgraph queries - const UNISWAP_V3_SUBGRAPH_URL = getUniswapV3GraphEndpointWithKey( - subgraphApiKey, - chainId - ); - - if (!UNISWAP_V3_SUBGRAPH_URL) { + if (!endpoint) { throw new Error("Subgraph URL is undefined"); } // Fetch token0's derivedETH const token0DerivedETHResponse = await request( - UNISWAP_V3_SUBGRAPH_URL, + endpoint, GET_TOKEN_DERIVED_ETH, { tokenId: token0AddressLower, @@ -139,7 +133,7 @@ export const useUniswapV3PoolUSDValue = () => { // Fetch token1's derivedETH const token1DerivedETHResponse = await request( - UNISWAP_V3_SUBGRAPH_URL, + endpoint, GET_TOKEN_DERIVED_ETH, { tokenId: token1AddressLower, @@ -150,7 +144,7 @@ export const useUniswapV3PoolUSDValue = () => { // 4. Fetch the current ETH price in USD const ethPriceResponse = await request( - UNISWAP_V3_SUBGRAPH_URL, + endpoint, GET_ETH_PRICE_USD ); const ethPrice = parseFloat( diff --git a/src/hooks/useGetTokenPriceFromDerivedETH.ts b/src/hooks/useGetTokenPriceFromDerivedETH.ts index 86014e6f..9c9fd225 100644 --- a/src/hooks/useGetTokenPriceFromDerivedETH.ts +++ b/src/hooks/useGetTokenPriceFromDerivedETH.ts @@ -1,29 +1,26 @@ -import { useCallback, useMemo } from "react"; -import { useChainId } from "wagmi"; -import { AddressStringType } from "../types/addressStringType"; -import { useGetGlobalPropsContext } from "../contexts/GlobalPropsContext"; +import { useCallback, useMemo } from 'react'; +import { useChainId } from 'wagmi'; +import { AddressStringType } from '../types/addressStringType'; import { useTokenDerivedETH, useEthPriceUSD, fetchTokenDerivedETH, fetchEthPriceUSD, -} from "../services/uniswapV3Api"; +} from '../services/uniswapV3Api'; export const useGetTokenPriceFromDerivedETH = ( token?: AddressStringType, - tokenAmount?: number + tokenAmount?: number, ) => { const chainId = useChainId(); - const { subgraphApiKey } = useGetGlobalPropsContext(); const { data: derivedETHData, isLoading: derivedETHLoading, error: derivedETHError, } = useTokenDerivedETH({ - tokenId: token?.toLowerCase() ?? "0x", + tokenId: token?.toLowerCase() ?? '0x', chainId: chainId ?? 0, - subgraphApiKey, }); const { @@ -32,7 +29,6 @@ export const useGetTokenPriceFromDerivedETH = ( error: ethPriceUSDError, } = useEthPriceUSD({ chainId: 1, - subgraphApiKey, }); const tokenPriceInUSD = useMemo(() => { @@ -47,12 +43,10 @@ export const useGetTokenPriceFromDerivedETH = ( const tokenDerived = await fetchTokenDerivedETH({ tokenId: tokenAddress.toLowerCase(), chainId: chainId ?? 0, - subgraphApiKey, }); const ethPrice = await fetchEthPriceUSD({ chainId: 1, - subgraphApiKey, }); const derived = Number(tokenDerived?.derivedETH ?? 0); @@ -62,11 +56,11 @@ export const useGetTokenPriceFromDerivedETH = ( return tokenAmount * derived * ethPriceNum; } catch (err) { - console.error("Error fetching token price:", err); + console.error('Error fetching token price:', err); return null; } }, - [chainId, subgraphApiKey] + [chainId], ); return { diff --git a/src/hooks/useGraphURL.ts b/src/hooks/useGraphURL.ts deleted file mode 100644 index e20d49a9..00000000 --- a/src/hooks/useGraphURL.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { useChainId } from "wagmi"; - -import { getGraphEndpointWithKey } from "../constants/graphEndpoints"; -import { useGetGlobalPropsContext } from "../contexts/GlobalPropsContext"; - -export const useGraphURL = () => { - const chainId = useChainId(); - const { subgraphApiKey } = useGetGlobalPropsContext(); - return getGraphEndpointWithKey(subgraphApiKey, chainId) ?? ""; -}; diff --git a/src/pages/BorrowSection/BorrowSectionContext.tsx b/src/pages/BorrowSection/BorrowSectionContext.tsx index 6885d58a..99f9b39a 100644 --- a/src/pages/BorrowSection/BorrowSectionContext.tsx +++ b/src/pages/BorrowSection/BorrowSectionContext.tsx @@ -8,7 +8,7 @@ import { useState, } from "react"; import type { Address } from "viem"; -import { useAccount } from "wagmi"; +import { useAccount, useChainId } from "wagmi"; import type { TokenInputType } from "../../components/TokenInput/TokenInput"; import { @@ -24,6 +24,7 @@ import { useUniswapV3PoolUSDValue } from "../../hooks/queries/useUniswapV3PoolUS import { useGetCommitmentsForErc20Tokens } from "../../hooks/useGetCommitmentsForErc20Tokens"; import type { UserToken } from "../../hooks/useGetUserTokens"; import { getLoanRewards } from "../../services/borrowRewardsApi"; +import { useGetGraphEndpoint } from "../../hooks/useGetGraphEndpoint"; export type UniswapData = { bestPool: any; // Replace with your actual pool type if available. @@ -85,7 +86,12 @@ export const BorrowSectionContextProvider: FC = ({ }) => { const { singleWhitelistedToken, strategyToken, strategyAction } = useGetGlobalPropsContext(); + const chainId = useChainId(); + const { endpoint: endpointUniswap } = useGetGraphEndpoint( + chainId, + "uniswap" + ); const { address } = useAccount(); const [currentStep, setCurrentStep] = useState( @@ -136,15 +142,17 @@ export const BorrowSectionContextProvider: FC = ({ }, []); useEffect(() => { + if (!endpointUniswap) return; + (async () => { await Promise.all( principalErc20Tokens.map(async (token) => { - const data = await fetchUniswapPoolData({ + const data = await fetchUniswapPoolData(endpointUniswap, { tokenAddress: token.address, days: 30, }); const bestPool = data.bestPool; - const poolUSDValue = await getPoolUSDValue({ + const poolUSDValue = await getPoolUSDValue(endpointUniswap, { poolAddress: bestPool?.id as Address, }); @@ -170,7 +178,7 @@ export const BorrowSectionContextProvider: FC = ({ }) ); })().catch(console.error); - }, [fetchUniswapPoolData, getPoolUSDValue, principalErc20Tokens]); + }, [fetchUniswapPoolData, endpointUniswap, getPoolUSDValue, principalErc20Tokens]); const [selectedOpportunity, setSelectedOpportunity] = useState({} as CommitmentType); diff --git a/src/services/uniswapV3Api/index.ts b/src/services/uniswapV3Api/index.ts index 1b72704c..d1e090e4 100644 --- a/src/services/uniswapV3Api/index.ts +++ b/src/services/uniswapV3Api/index.ts @@ -1,163 +1,78 @@ -import { useQuery } from "@tanstack/react-query"; -import { GraphQLClient } from "graphql-request"; +import { useQuery } from '@tanstack/react-query'; +import { GraphQLClient } from 'graphql-request'; -import { UniswapV3Pool } from "../../constants/uniswapV3Pool.type"; +import { getEthPriceUSD, getTokenDerivedETH } from './uniswapV3ApiQueries'; -import { - getEthPriceUSD, - getTokenDerivedETH, - getUniswapV3PoolsByToken, - getUniswapV3PoolsByTokensPair, -} from "./uniswapV3ApiQueries"; -import { getSubgraphURL } from "./uniswapV3Config"; - -export const getUniswapV3Client = (subgraphApiKey: string, chainId: number) => { - const url = getSubgraphURL(subgraphApiKey, chainId); - return new GraphQLClient(url); -}; - -export const fetchUniswapV3PoolsByToken = async ({ - subgraphApiKey, - token0, - chainId, -}: { - subgraphApiKey: string; - token0: string; - chainId: number; -}): Promise => { - const client = getUniswapV3Client(subgraphApiKey, chainId); - const res: { pools: UniswapV3Pool[] } = await client.request( - getUniswapV3PoolsByToken, - { token0: token0.toLowerCase() } +export const getUniswapV3Client = async (chainId: number) => { + const res = await fetch( + `https://subgraph-endpoints-middleware-production.up.railway.app/endpoint?type=uniswap`, ); - return res?.pools ?? []; -}; + const json = (await res.json()) as Record; + if (!json) return null; -export const fetchUniswapV3PoolsByTokensPair = async ({ - subgraphApiKey, - token0, - token1, - chainId, -}: { - subgraphApiKey: string; - token0: string; - token1: string; - chainId: number; -}): Promise => { - const client = getUniswapV3Client(subgraphApiKey, chainId); - const res: { pools: UniswapV3Pool[] } = await client.request( - getUniswapV3PoolsByTokensPair, - { - token0: token0.toLowerCase(), - token1: token1.toLowerCase(), - } - ); - return res?.pools ?? []; + const url = json[chainId]; + + return new GraphQLClient(url); }; export const fetchTokenDerivedETH = async ({ - subgraphApiKey, tokenId, chainId, }: { - subgraphApiKey: string; tokenId: string; chainId: number; }): Promise<{ derivedETH: string }> => { - const client = getUniswapV3Client(subgraphApiKey, chainId); + const client = await getUniswapV3Client(chainId); + if (!client) { + return { derivedETH: '0' }; + } + const res: { token: { derivedETH: string } } = await client.request( getTokenDerivedETH, - { tokenId } + { tokenId }, ); return res.token; }; export const fetchEthPriceUSD = async ({ - subgraphApiKey, chainId, }: { - subgraphApiKey: string; chainId: number; }): Promise<{ ethPriceUSD: string }> => { - const client = getUniswapV3Client(subgraphApiKey, chainId); + const client = await getUniswapV3Client(chainId); + if (!client) { + return { ethPriceUSD: '0' }; + } + const res: { bundle: { ethPriceUSD: string } } = await client.request( getEthPriceUSD, - {} + {}, ); return res.bundle; }; -export const useUniswapV3PoolsByToken = ({ - subgraphApiKey, - token0, - chainId, -}: { - subgraphApiKey: string; - token0: string; - chainId: number; -}) => { - return useQuery({ - queryKey: ["uniswapV3PoolsByToken", chainId, token0], - queryFn: () => - fetchUniswapV3PoolsByToken({ subgraphApiKey, token0, chainId }), - }); -}; - -export const useUniswapV3PoolsByTokensPair = ({ - subgraphApiKey, - token0, - token1, - chainId, -}: { - subgraphApiKey: string; - token0: string; - token1: string; - chainId: number; -}) => { - return useQuery({ - queryKey: ["uniswapV3PoolsByTokensPair", chainId, token0, token1], - queryFn: () => - fetchUniswapV3PoolsByTokensPair({ - subgraphApiKey, - token0, - token1, - chainId, - }), - }); -}; - export const useTokenDerivedETH = ({ - subgraphApiKey, tokenId, chainId, }: { - subgraphApiKey: string; tokenId: string; chainId: number; }) => { return useQuery({ - queryKey: ["tokenDerivedETH", chainId, tokenId], + queryKey: ['tokenDerivedETH', chainId, tokenId], queryFn: () => fetchTokenDerivedETH({ - subgraphApiKey, tokenId, chainId, }), }); }; -export const useEthPriceUSD = ({ - subgraphApiKey, - chainId, -}: { - subgraphApiKey: string; - chainId: number; -}) => { +export const useEthPriceUSD = ({ chainId }: { chainId: number }) => { return useQuery({ - queryKey: ["ethPriceUSD", chainId], + queryKey: ['ethPriceUSD', chainId], queryFn: () => fetchEthPriceUSD({ - subgraphApiKey, chainId, }), }); diff --git a/src/services/uniswapV3Api/uniswapV3Config.ts b/src/services/uniswapV3Api/uniswapV3Config.ts deleted file mode 100644 index c7d7ae0f..00000000 --- a/src/services/uniswapV3Api/uniswapV3Config.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { DEFAULT_CHAIN_ID, isSupportedChain } from "../../constants/chains"; -import { getUniswapV3GraphEndpointWithKey } from "../../constants/graphEndpoints"; - -export const getSubgraphURL: ( - subgraphApiKey: string, - chainId?: number -) => string = (subgraphApiKey, chainId = DEFAULT_CHAIN_ID) => { - if (!isSupportedChain(chainId)) - return ( - getUniswapV3GraphEndpointWithKey(subgraphApiKey, DEFAULT_CHAIN_ID) || "" - ); - return getUniswapV3GraphEndpointWithKey(subgraphApiKey, chainId) || ""; -};