From 5e45fff3611da24a7f5ea647fe3e514556af0e13 Mon Sep 17 00:00:00 2001 From: Bogdan Fazakas Date: Tue, 22 Jun 2021 08:52:49 +0300 Subject: [PATCH] wip replace apollo with urql --- package-lock.json | 54 +++++++++++++++++++ package.json | 1 + src/components/molecules/MarketStats.tsx | 8 ++- src/components/molecules/PoolTransactions.tsx | 23 ++++---- .../organisms/AssetActions/Consume.tsx | 10 ++-- .../organisms/AssetActions/Pool/Graph.tsx | 10 ++-- .../organisms/AssetActions/Pool/index.tsx | 11 ++-- .../organisms/AssetContent/EditHistory.tsx | 6 ++- .../pages/History/ComputeJobs/index.tsx | 6 ++- src/components/pages/History/Downloads.tsx | 6 ++- src/components/pages/History/PoolShares.tsx | 16 +++--- src/helpers/wrapRootElement.tsx | 6 +-- src/providers/UrqlProvider.tsx | 46 ++++++++++++++++ src/utils/subgraph.ts | 43 +++++++-------- 14 files changed, 183 insertions(+), 63 deletions(-) create mode 100644 src/providers/UrqlProvider.tsx diff --git a/package-lock.json b/package-lock.json index 744c08cc1..61e6e3ba3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -68,6 +68,7 @@ "shortid": "^2.2.16", "slugify": "^1.5.3", "swr": "^0.5.6", + "urql": "^2.0.3", "use-dark-mode": "^2.3.1", "web3": "^1.3.6", "web3modal": "^1.9.3", @@ -6154,6 +6155,18 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@urql/core": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@urql/core/-/core-2.1.3.tgz", + "integrity": "sha512-CzrTMhO5SG7qdAaS3B5/g1TPH5k7326GHIyta1owT2vzxX9ev8YytxOE5m73EuacxIfF7qVZFhCzY+rubOlI0w==", + "dependencies": { + "@graphql-typed-document-node/core": "^3.1.0", + "wonka": "^4.0.14" + }, + "peerDependencies": { + "graphql": "^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0" + } + }, "node_modules/@use-it/event-listener": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/@use-it/event-listener/-/event-listener-0.1.6.tgz", @@ -37261,6 +37274,19 @@ "node": ">=0.4.x" } }, + "node_modules/urql": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/urql/-/urql-2.0.3.tgz", + "integrity": "sha512-CEfCsODKbAloDuAaT3NeMvibKpWxfS86DucI/HGam9uuqiZLpunuKb4p9+SWwoWLRf6Q1kUeQKGZoI5GqudOCg==", + "dependencies": { + "@urql/core": "^2.1.0", + "wonka": "^4.0.14" + }, + "peerDependencies": { + "graphql": "^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0", + "react": ">= 16.8.0" + } + }, "node_modules/use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", @@ -39980,6 +40006,11 @@ "window-getters": "^1.0.0" } }, + "node_modules/wonka": { + "version": "4.0.15", + "resolved": "https://registry.npmjs.org/wonka/-/wonka-4.0.15.tgz", + "integrity": "sha512-U0IUQHKXXn6PFo9nqsHphVCE5m3IntqZNB9Jjn7EB1lrR7YTDY3YWgFvEvwniTzXSvOH/XMzAZaIfJF/LvHYXg==" + }, "node_modules/word-wrap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", @@ -45410,6 +45441,15 @@ "eslint-visitor-keys": "^2.0.0" } }, + "@urql/core": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@urql/core/-/core-2.1.3.tgz", + "integrity": "sha512-CzrTMhO5SG7qdAaS3B5/g1TPH5k7326GHIyta1owT2vzxX9ev8YytxOE5m73EuacxIfF7qVZFhCzY+rubOlI0w==", + "requires": { + "@graphql-typed-document-node/core": "^3.1.0", + "wonka": "^4.0.14" + } + }, "@use-it/event-listener": { "version": "0.1.6", "resolved": "https://registry.npmjs.org/@use-it/event-listener/-/event-listener-0.1.6.tgz", @@ -70039,6 +70079,15 @@ "resolved": "https://registry.npmjs.org/url-to-options/-/url-to-options-1.0.1.tgz", "integrity": "sha1-FQWgOiiaSMvXpDTvuu7FBV9WM6k=" }, + "urql": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/urql/-/urql-2.0.3.tgz", + "integrity": "sha512-CEfCsODKbAloDuAaT3NeMvibKpWxfS86DucI/HGam9uuqiZLpunuKb4p9+SWwoWLRf6Q1kUeQKGZoI5GqudOCg==", + "requires": { + "@urql/core": "^2.1.0", + "wonka": "^4.0.14" + } + }, "use": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/use/-/use-3.1.1.tgz", @@ -72270,6 +72319,11 @@ "window-getters": "^1.0.0" } }, + "wonka": { + "version": "4.0.15", + "resolved": "https://registry.npmjs.org/wonka/-/wonka-4.0.15.tgz", + "integrity": "sha512-U0IUQHKXXn6PFo9nqsHphVCE5m3IntqZNB9Jjn7EB1lrR7YTDY3YWgFvEvwniTzXSvOH/XMzAZaIfJF/LvHYXg==" + }, "word-wrap": { "version": "1.2.3", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.3.tgz", diff --git a/package.json b/package.json index 0805daab4..9c813e492 100644 --- a/package.json +++ b/package.json @@ -81,6 +81,7 @@ "shortid": "^2.2.16", "slugify": "^1.5.3", "swr": "^0.5.6", + "urql": "^2.0.3", "use-dark-mode": "^2.3.1", "web3": "^1.3.6", "web3modal": "^1.9.3", diff --git a/src/components/molecules/MarketStats.tsx b/src/components/molecules/MarketStats.tsx index b3584dca0..f6ba2cd75 100644 --- a/src/components/molecules/MarketStats.tsx +++ b/src/components/molecules/MarketStats.tsx @@ -1,6 +1,6 @@ import React, { ReactElement, useEffect, useState } from 'react' import styles from './MarketStats.module.css' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import Conversion from '../atoms/Price/Conversion' import PriceUnit from '../atoms/Price/PriceUnit' import Tooltip from '../atoms/Tooltip' @@ -19,7 +19,11 @@ export default function MarketStats(): ReactElement { const [totalValueLocked, setTotalValueLocked] = useState() const [totalOceanLiquidity, setTotalOceanLiquidity] = useState() const [poolCount, setPoolCount] = useState() - const { data } = useQuery(getTotalPoolsValues, { pollInterval: 20000 }) + const [result] = useQuery({ + query: getTotalPoolsValues + // pollInterval: 20000 + }) + const { data } = result useEffect(() => { if (!data || !data.poolFactories || data.poolFactories.length === 0) return diff --git a/src/components/molecules/PoolTransactions.tsx b/src/components/molecules/PoolTransactions.tsx index 9da914dc3..e6578f992 100644 --- a/src/components/molecules/PoolTransactions.tsx +++ b/src/components/molecules/PoolTransactions.tsx @@ -8,7 +8,7 @@ import styles from './PoolTransactions.module.css' import { useUserPreferences } from '../../providers/UserPreferences' import { Ocean } from '@oceanprotocol/lib' import { formatPrice } from '../atoms/Price/PriceUnit' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import { TransactionHistory, TransactionHistory_poolTransactions as TransactionHistoryPoolTransactions @@ -198,27 +198,26 @@ export default function PoolTransactions({ const { accountId } = useWeb3() const [logs, setLogs] = useState() - const { data, loading } = useQuery( - poolAddress ? txHistoryQueryByPool : txHistoryQuery, - { - variables: { - user: accountId?.toLowerCase(), - pool: poolAddress?.toLowerCase() - }, - pollInterval: 20000 + const [result] = useQuery({ + query: poolAddress ? txHistoryQueryByPool : txHistoryQuery, + variables: { + user: accountId?.toLowerCase(), + pool: poolAddress?.toLowerCase() } - ) + // pollInterval: 20000 + }) + const { data, fetching } = result useEffect(() => { if (!data) return setLogs(data.poolTransactions) - }, [data, loading]) + }, [data, fetching]) return ( = 4 : logs?.length >= 9} diff --git a/src/components/organisms/AssetActions/Consume.tsx b/src/components/organisms/AssetActions/Consume.tsx index 27daeb031..f41b5ffc9 100644 --- a/src/components/organisms/AssetActions/Consume.tsx +++ b/src/components/organisms/AssetActions/Consume.tsx @@ -5,7 +5,7 @@ import File from '../../atoms/File' import Price from '../../atoms/Price' import { useSiteMetadata } from '../../../hooks/useSiteMetadata' import { useAsset } from '../../../providers/Asset' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import { OrdersData } from '../../../@types/apollo/OrdersData' import BigNumber from 'bignumber.js' import { useOcean } from '../../../providers/Ocean' @@ -56,13 +56,15 @@ export default function Consume({ const [hasDatatoken, setHasDatatoken] = useState(false) const [isConsumable, setIsConsumable] = useState(true) const [assetTimeout, setAssetTimeout] = useState('') - const { data } = useQuery(previousOrderQuery, { + const [result] = useQuery({ + query: previousOrderQuery, variables: { id: ddo.dataToken?.toLowerCase(), account: accountId?.toLowerCase() - }, - pollInterval: 5000 + } + // pollInterval: 5000 }) + const { data } = result useEffect(() => { if (!data || !assetTimeout || data.tokenOrders.length === 0) return diff --git a/src/components/organisms/AssetActions/Pool/Graph.tsx b/src/components/organisms/AssetActions/Pool/Graph.tsx index b13e1fc3d..f78dcb075 100644 --- a/src/components/organisms/AssetActions/Pool/Graph.tsx +++ b/src/components/organisms/AssetActions/Pool/Graph.tsx @@ -17,7 +17,7 @@ import { darkModeConfig } from '../../../../../app.config' import Button from '../../../atoms/Button' import { Logger } from '@oceanprotocol/lib' import { useAsset } from '../../../../providers/Asset' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import { PoolHistory } from '../../../../@types/apollo/PoolHistory' declare type GraphType = 'liquidity' | 'price' @@ -131,13 +131,15 @@ export default function Graph(): ReactElement { const [isLoading, setIsLoading] = useState(true) const [graphData, setGraphData] = useState() - const { data, refetch, error } = useQuery(poolHistory, { + const [result, refetch] = useQuery({ + query: poolHistory, variables: { id: price.address.toLowerCase(), block: lastBlock - }, - pollInterval: 20000 + } + // pollInterval: 20000 }) + const { data, error } = result useEffect(() => { Logger.log('Fired GraphOptions!') diff --git a/src/components/organisms/AssetActions/Pool/index.tsx b/src/components/organisms/AssetActions/Pool/index.tsx index ea13e9d87..2d1f0c558 100644 --- a/src/components/organisms/AssetActions/Pool/index.tsx +++ b/src/components/organisms/AssetActions/Pool/index.tsx @@ -15,7 +15,7 @@ import { PoolBalance } from '../../../../@types/TokenBalance' import Transactions from './Transactions' import Graph from './Graph' import { useAsset } from '../../../../providers/Asset' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import { PoolLiquidity } from '../../../../@types/apollo/PoolLiquidity' import { useOcean } from '../../../../providers/Ocean' import { useWeb3 } from '../../../../providers/Web3' @@ -91,14 +91,17 @@ export default function Pool(): ReactElement { // the purpose of the value is just to trigger the effect const [refreshPool, setRefreshPool] = useState(false) - const { data: dataLiquidity } = useQuery(poolLiquidityQuery, { + const [result] = useQuery({ + query: poolLiquidityQuery, variables: { id: price.address.toLowerCase(), shareId: `${price.address.toLowerCase()}-${ddo.publicKey[0].owner.toLowerCase()}` - }, - pollInterval: 5000 + } + // pollInterval: 5000 }) + const { data: dataLiquidity } = result + useEffect(() => { async function init() { if (!dataLiquidity || !dataLiquidity.pool) return diff --git a/src/components/organisms/AssetContent/EditHistory.tsx b/src/components/organisms/AssetContent/EditHistory.tsx index 6ef9b453c..89dac5705 100644 --- a/src/components/organisms/AssetContent/EditHistory.tsx +++ b/src/components/organisms/AssetContent/EditHistory.tsx @@ -3,7 +3,7 @@ import { useAsset } from '../../../providers/Asset' import ExplorerLink from '../../atoms/ExplorerLink' import Time from '../../atoms/Time' import styles from './EditHistory.module.css' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import { ReceiptData_datatokens_updates as ReceiptData } from '../../../@types/apollo/ReceiptData' import { useWeb3 } from '../../../providers/Web3' @@ -22,9 +22,11 @@ const getReceipts = gql` export default function EditHistory(): ReactElement { const { networkId } = useWeb3() const { ddo } = useAsset() - const { data } = useQuery(getReceipts, { + const [result] = useQuery({ + query: getReceipts, variables: { address: ddo?.dataToken.toLowerCase() } }) + const { data } = result const [receipts, setReceipts] = useState() const [creationTx, setCreationTx] = useState() diff --git a/src/components/pages/History/ComputeJobs/index.tsx b/src/components/pages/History/ComputeJobs/index.tsx index b4c49d171..37df6257b 100644 --- a/src/components/pages/History/ComputeJobs/index.tsx +++ b/src/components/pages/History/ComputeJobs/index.tsx @@ -8,7 +8,7 @@ import Dotdotdot from 'react-dotdotdot' import Table from '../../../atoms/Table' import Button from '../../../atoms/Button' import { useOcean } from '../../../../providers/Ocean' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import { useWeb3 } from '../../../../providers/Web3' import { queryMetadata } from '../../../../utils/aquarius' import axios, { CancelToken } from 'axios' @@ -105,11 +105,13 @@ export default function ComputeJobs(): ReactElement { const { accountId } = useWeb3() const [isLoading, setIsLoading] = useState(true) const [jobs, setJobs] = useState([]) - const { data } = useQuery(getComputeOrders, { + const [result] = useQuery({ + query: getComputeOrders, variables: { user: accountId?.toLowerCase() } }) + const { data } = result async function getJobs() { if (!ocean || !account) return diff --git a/src/components/pages/History/Downloads.tsx b/src/components/pages/History/Downloads.tsx index e956cd68a..eb5bd411b 100644 --- a/src/components/pages/History/Downloads.tsx +++ b/src/components/pages/History/Downloads.tsx @@ -1,6 +1,6 @@ import React, { ReactElement, useEffect, useState } from 'react' import Table from '../../atoms/Table' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import Time from '../../atoms/Time' import web3 from 'web3' import AssetTitle from '../../molecules/AssetListTitle' @@ -58,9 +58,11 @@ export default function ComputeDownloads(): ReactElement { const { accountId } = useWeb3() const [isLoading, setIsLoading] = useState(false) const [orders, setOrders] = useState() - const { data } = useQuery(getTokenOrders, { + const [result] = useQuery({ + query: getTokenOrders, variables: { user: accountId?.toLowerCase() } }) + const { data } = result const { appConfig } = useSiteMetadata() useEffect(() => { diff --git a/src/components/pages/History/PoolShares.tsx b/src/components/pages/History/PoolShares.tsx index f34f2ac27..33c290db4 100644 --- a/src/components/pages/History/PoolShares.tsx +++ b/src/components/pages/History/PoolShares.tsx @@ -3,7 +3,7 @@ import Table from '../../atoms/Table' import Conversion from '../../atoms/Price/Conversion' import styles from './PoolShares.module.css' import AssetTitle from '../../molecules/AssetListTitle' -import { gql, useQuery } from '@apollo/client' +import { gql, useQuery } from 'urql' import { PoolShares as PoolSharesList, PoolShares_poolShares as PoolShare, @@ -141,13 +141,15 @@ const columns = [ export default function PoolShares(): ReactElement { const { accountId } = useWeb3() const [assets, setAssets] = useState() - const { data, loading } = useQuery(poolSharesQuery, { + + const [result] = useQuery({ + query: poolSharesQuery, variables: { user: accountId?.toLowerCase() - }, - pollInterval: 20000 + } + // pollInterval: 20000 }) - + const { data, fetching } = result useEffect(() => { if (!data) return const assetList: Asset[] = [] @@ -159,7 +161,7 @@ export default function PoolShares(): ReactElement { }) }) setAssets(assetList) - }, [data, loading]) + }, [data, fetching]) return (
diff --git a/src/helpers/wrapRootElement.tsx b/src/helpers/wrapRootElement.tsx index 46e44b98e..6fe5c5774 100644 --- a/src/helpers/wrapRootElement.tsx +++ b/src/helpers/wrapRootElement.tsx @@ -2,7 +2,7 @@ import React, { ReactElement } from 'react' import Web3Provider from '../providers/Web3' import { UserPreferencesProvider } from '../providers/UserPreferences' import PricesProvider from '../providers/Prices' -import ApolloClientProvider from '../providers/ApolloClientProvider' +import UrqlProvider from '../providers/UrqlProvider' export default function wrapRootElement({ element @@ -11,11 +11,11 @@ export default function wrapRootElement({ }): ReactElement { return ( - + {element} - + ) } diff --git a/src/providers/UrqlProvider.tsx b/src/providers/UrqlProvider.tsx new file mode 100644 index 000000000..e7e1b5049 --- /dev/null +++ b/src/providers/UrqlProvider.tsx @@ -0,0 +1,46 @@ +import { createClient, Provider, Client } from 'urql' +import { Logger } from '@oceanprotocol/lib' +import React, { useState, useEffect, ReactNode, ReactElement } from 'react' +import { useWeb3 } from './Web3' +import { getOceanConfig } from '../utils/ocean' + +let urqlClient: Client + +function createUrqlClient(subgraphUri: string) { + const client = createClient({ + url: `${subgraphUri}/subgraphs/name/oceanprotocol/ocean-subgraph` + }) + return client +} + +export function getUrqlClientInstance(): Client { + return urqlClient +} + +export default function UrqlClientProvider({ + children +}: { + children: ReactNode +}): ReactElement { + const { networkId } = useWeb3() + const [client, setClient] = useState() + + useEffect(() => { + const oceanConfig = getOceanConfig(networkId || 1) + + if (!oceanConfig?.subgraphUri) { + Logger.error( + 'No subgraphUri defined, preventing UrqlProvider from initialization.' + ) + return + } + + const newClient = createUrqlClient(oceanConfig.subgraphUri) + urqlClient = newClient + setClient(newClient) + Logger.log(`[apollo] Client connected to ${oceanConfig.subgraphUri}`) + }, [networkId]) + + return client ? {children} : <> +} +export { UrqlClientProvider } diff --git a/src/utils/subgraph.ts b/src/utils/subgraph.ts index c5408ee53..cdf3752e6 100644 --- a/src/utils/subgraph.ts +++ b/src/utils/subgraph.ts @@ -1,6 +1,6 @@ -import { gql, DocumentNode, ApolloQueryResult } from '@apollo/client' +import { gql, OperationResult, TypedDocumentNode } from 'urql' import { DDO, BestPrice } from '@oceanprotocol/lib' -import { getApolloClientInstance } from '../providers/ApolloClientProvider' +import { getUrqlClientInstance } from '../providers/UrqlProvider' import { AssetsPoolPrice, AssetsPoolPrice_pools as AssetsPoolPricePools @@ -102,16 +102,13 @@ const HighestLiquidityAssets = gql` ` async function fetchData( - query: DocumentNode, + query: TypedDocumentNode, variables: any -): Promise> { +): Promise { try { - const client = getApolloClientInstance() - const response = await client.query({ - query: query, - variables: variables, - fetchPolicy: 'no-cache' - }) + const client = getUrqlClientInstance() + const response = await client.query(query, variables).toPromise() + console.log('resp == ', response) return response } catch (error) { console.error('Error fetchData: ', error.message) @@ -127,7 +124,7 @@ export async function getPreviousOrders( id: id, account: account } - const fetchedPreviousOrders: ApolloQueryResult = + const fetchedPreviousOrders: OperationResult = await fetchData(PreviousOrderQuery, variables) if (fetchedPreviousOrders.data?.tokenOrders?.length === 0) return null if (assetTimeout === '0') { @@ -195,8 +192,8 @@ async function getAssetsPoolsExchangesAndDatatokenMap( assets: DDO[] ): Promise< [ - ApolloQueryResult, - ApolloQueryResult, + OperationResult, + OperationResult, DidAndDatatokenMap ] > { @@ -214,11 +211,11 @@ async function getAssetsPoolsExchangesAndDatatokenMap( datatokenAddress_in: dataTokenList } - const poolPriceResponse: ApolloQueryResult = await fetchData( + const poolPriceResponse: OperationResult = await fetchData( PoolQuery, poolVariables ) - const frePriceResponse: ApolloQueryResult = await fetchData( + const frePriceResponse: OperationResult = await fetchData( FreQuery, freVariables ) @@ -230,14 +227,15 @@ export async function getAssetsPriceList(assets: DDO[]): Promise { const priceList: PriceList = {} const values: [ - ApolloQueryResult, - ApolloQueryResult, + OperationResult, + OperationResult, DidAndDatatokenMap ] = await getAssetsPoolsExchangesAndDatatokenMap(assets) const poolPriceResponse = values[0] const frePriceResponse = values[1] const didDTMap: DidAndDatatokenMap = values[2] + console.log('poolPriceResponse ++ ', poolPriceResponse) for (const poolPrice of poolPriceResponse.data?.pools) { priceList[didDTMap[poolPrice.datatokenAddress]] = poolPrice.consumePrice === '-1' @@ -259,15 +257,16 @@ export async function getPrice(asset: DDO): Promise { datatokenAddress: asset?.dataToken.toLowerCase() } - const poolPriceResponse: ApolloQueryResult = await fetchData( + const poolPriceResponse: OperationResult = await fetchData( AssetPoolPriceQuerry, poolVariables ) - const frePriceResponse: ApolloQueryResult = await fetchData( + const frePriceResponse: OperationResult = await fetchData( AssetFreQuery, freVariables ) + console.log('poolPriceResponse 2 -- ', poolPriceResponse) const bestPrice: BestPrice = transformPriceToBestPrice( frePriceResponse.data.fixedRateExchanges, poolPriceResponse.data.pools @@ -282,13 +281,15 @@ export async function getAssetsBestPrices( const assetsWithPrice: AssetListPrices[] = [] const values: [ - ApolloQueryResult, - ApolloQueryResult, + OperationResult, + OperationResult, DidAndDatatokenMap ] = await getAssetsPoolsExchangesAndDatatokenMap(assets) const poolPriceResponse = values[0] const frePriceResponse = values[1] + console.log('poolPriceResponse 3 || ', poolPriceResponse) + for (const ddo of assets) { const dataToken = ddo.dataToken.toLowerCase() const poolPrice: AssetsPoolPricePools[] = []