From 3332249928ed87d4e08f367cf47df2e9cd907aaa Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Fri, 28 May 2021 14:47:47 +0200 Subject: [PATCH] refactor and tinkering --- README.md | 12 +- app.config.js | 8 +- src/components/App.tsx | 6 +- src/components/molecules/AssetListTitle.tsx | 12 +- src/components/molecules/Bookmarks.tsx | 8 +- .../molecules/UserPreferences/Chain.tsx | 9 +- .../molecules/UserPreferences/index.tsx | 2 +- src/components/molecules/Wallet/Details.tsx | 12 +- src/components/molecules/Wallet/Network.tsx | 9 +- src/components/molecules/Web3Feedback.tsx | 30 ++-- .../organisms/AssetActions/Compute/index.tsx | 6 +- .../Edit/FormEditComputeDataset.tsx | 8 +- src/components/organisms/Footer.tsx | 4 +- .../pages/History/ComputeJobs/Details.tsx | 10 +- .../pages/History/ComputeJobs/index.tsx | 8 +- src/components/pages/History/Downloads.tsx | 12 +- .../pages/History/PublishedList.tsx | 6 +- src/components/pages/Home.tsx | 10 +- src/components/templates/PageAssetDetails.tsx | 12 +- src/components/templates/Search/index.tsx | 17 +- src/helpers/wrapRootElement.tsx | 14 +- src/hooks/useSiteMetadata.ts | 4 +- src/providers/Asset.tsx | 12 +- src/providers/Ocean.tsx | 156 +++++++++--------- src/providers/UserPreferences.tsx | 42 ++--- src/utils/ocean.ts | 10 +- 26 files changed, 199 insertions(+), 240 deletions(-) diff --git a/README.md b/README.md index c7b73fc41..03af3a048 100644 --- a/README.md +++ b/README.md @@ -132,19 +132,15 @@ const queryLatest = { } function Component() { - const { config } = useOcean() + const { metadataCacheUri } = useOcean() const [result, setResult] = useState() useEffect(() => { - if (!config?.metadataCacheUri) return + if (!metadataCacheUri) return const source = axios.CancelToken.source() async function init() { - const result = await queryMetadata( - query, - config.metadataCacheUri, - source.token - ) + const result = await queryMetadata(query, metadataCacheUri, source.token) setResult(result) } init() @@ -152,7 +148,7 @@ function Component() { return () => { source.cancel() } - }, [config?.metadataCacheUri, query]) + }, [metadataCacheUri, query]) return
{result}
} diff --git a/app.config.js b/app.config.js index 722d0239d..9226d2f28 100644 --- a/app.config.js +++ b/app.config.js @@ -1,9 +1,7 @@ module.exports = { - // The default network and its associated config the app should connect to - // on start. App will automatically switch network configs when user switches - // networks in their wallet. - // Ocean Protocol contracts are deployed for: 'mainnet', 'rinkeby', 'development' - network: process.env.GATSBY_NETWORK || 'mainnet', + // List of supported chainIds which metadata cache queries + // will return by default + chainIds: [1, 3, 4, 137, 1287], infuraProjectId: process.env.GATSBY_INFURA_PROJECT_ID || 'xxx', diff --git a/src/components/App.tsx b/src/components/App.tsx index 99ab88e0c..9fe4f0ae7 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -40,17 +40,17 @@ export default function App({ const { warning } = useSiteMetadata() const { accountId } = useWeb3() const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) - const { isGraphSynced, blockHead, blockGraph } = useGraphSyncStatus() + // const { isGraphSynced, blockHead, blockGraph } = useGraphSyncStatus() return (
- {!isGraphSynced && ( + {/* {!isGraphSynced && ( - )} + )} */}
{(props as PageProps).uri === '/' && ( diff --git a/src/components/molecules/AssetListTitle.tsx b/src/components/molecules/AssetListTitle.tsx index c62bd62f4..7b93b24fa 100644 --- a/src/components/molecules/AssetListTitle.tsx +++ b/src/components/molecules/AssetListTitle.tsx @@ -15,11 +15,11 @@ export default function AssetListTitle({ did?: string title?: string }): ReactElement { - const { config } = useOcean() + const { metadataCacheUri } = useOcean() const [assetTitle, setAssetTitle] = useState(title) useEffect(() => { - if (title || !config?.metadataCacheUri) return + if (title || !metadataCacheUri) return if (ddo) { const { attributes } = ddo.findServiceByType('metadata') setAssetTitle(attributes.main.name) @@ -29,11 +29,7 @@ export default function AssetListTitle({ const source = axios.CancelToken.source() async function getAssetName() { - const title = await getAssetsNames( - [did], - config.metadataCacheUri, - source.token - ) + const title = await getAssetsNames([did], metadataCacheUri, source.token) setAssetTitle(title[did]) } @@ -42,7 +38,7 @@ export default function AssetListTitle({ return () => { source.cancel() } - }, [assetTitle, config?.metadataCacheUri, ddo, did, title]) + }, [assetTitle, metadataCacheUri, ddo, did, title]) return (

diff --git a/src/components/molecules/Bookmarks.tsx b/src/components/molecules/Bookmarks.tsx index c05d9a5e8..9db952e0b 100644 --- a/src/components/molecules/Bookmarks.tsx +++ b/src/components/molecules/Bookmarks.tsx @@ -78,7 +78,7 @@ const columns = [ ] export default function Bookmarks(): ReactElement { - const { config } = useOcean() + const { metadataCacheUri } = useOcean() const { bookmarks } = useUserPreferences() const [pinned, setPinned] = useState() @@ -87,7 +87,7 @@ export default function Bookmarks(): ReactElement { const networkName = (config as ConfigHelperConfig)?.network useEffect(() => { - if (!config?.metadataCacheUri || !networkName || bookmarks === {}) return + if (!metadataCacheUri || !networkName || bookmarks === {}) return const source = axios.CancelToken.source() @@ -102,7 +102,7 @@ export default function Bookmarks(): ReactElement { try { const resultPinned = await getAssetsBookmarked( bookmarks[networkName], - config.metadataCacheUri, + metadataCacheUri, source.token ) setPinned(resultPinned?.results) @@ -117,7 +117,7 @@ export default function Bookmarks(): ReactElement { return () => { source.cancel() } - }, [bookmarks, config.metadataCacheUri, networkName]) + }, [bookmarks, metadataCacheUri, networkName]) return ( ) { @@ -48,10 +46,7 @@ export default function Chain(): ReactElement { } ] - // TODO: to fully solve https://github.com/oceanprotocol/market/issues/432 - // there are more considerations for users with a wallet connected (wallet network vs. setting network). - // For now, only show the setting for non-wallet users. - return !web3 ? ( + return (
  • Switch the data source for the interface.
  • - ) : null + ) } diff --git a/src/components/molecules/UserPreferences/index.tsx b/src/components/molecules/UserPreferences/index.tsx index 3c07f5326..1c5a1ae30 100644 --- a/src/components/molecules/UserPreferences/index.tsx +++ b/src/components/molecules/UserPreferences/index.tsx @@ -20,7 +20,7 @@ export default function UserPreferences(): ReactElement {
      - + {/* */}
    } diff --git a/src/components/molecules/Wallet/Details.tsx b/src/components/molecules/Wallet/Details.tsx index 32d8e4776..c1684e8a8 100644 --- a/src/components/molecules/Wallet/Details.tsx +++ b/src/components/molecules/Wallet/Details.tsx @@ -12,8 +12,8 @@ import styles from './Details.module.css' export default function Details(): ReactElement { const { web3Provider, web3ProviderInfo, connect, logout, networkData } = - useWeb3() - const { balance, config } = useOcean() + } = useWeb3() + // const { balance, config } = useOcean() const { locale } = useUserPreferences() const [mainCurrency, setMainCurrency] = useState() @@ -38,7 +38,7 @@ export default function Details(): ReactElement { return (
      - {Object.entries(balance).map(([key, value]) => ( + {/* {Object.entries(balance).map(([key, value]) => (
    • {key === 'eth' ? mainCurrency : config.oceanTokenSymbol} @@ -48,7 +48,7 @@ export default function Details(): ReactElement { })} {key === 'ocean' && }
    • - ))} + ))} */}
    • @@ -66,14 +66,14 @@ export default function Details(): ReactElement { onChange={handlePortisNetworkChange} /> )} */} - {web3ProviderInfo?.name === 'MetaMask' && ( + {/* {web3ProviderInfo?.name === 'MetaMask' && ( - )} + )} */}

      {web3ProviderInfo?.name === 'Portis' && ( diff --git a/src/components/molecules/Wallet/Network.tsx b/src/components/molecules/Wallet/Network.tsx index 8118a940f..b9eccd893 100644 --- a/src/components/molecules/Wallet/Network.tsx +++ b/src/components/molecules/Wallet/Network.tsx @@ -10,21 +10,18 @@ import styles from './Network.module.css' export default function Network(): ReactElement { const { networkId, isTestnet } = useWeb3() - const { config } = useOcean() - const networkIdConfig = (config as ConfigHelperConfig).networkId const [isSupportedNetwork, setIsSupportedNetwork] = useState() useEffect(() => { - // take network from user when present, - // otherwise use the default configured one of app - const network = networkId || networkIdConfig + // take network from user when present + const network = networkId || 1 // Check networkId against ocean.js ConfigHelper configs // to figure out if network is supported. const isSupportedNetwork = Boolean(new ConfigHelper().getConfig(network)) setIsSupportedNetwork(isSupportedNetwork) - }, [networkId, networkIdConfig]) + }, [networkId]) return networkId ? (

      diff --git a/src/components/molecules/Web3Feedback.tsx b/src/components/molecules/Web3Feedback.tsx index 17356e506..2f548b742 100644 --- a/src/components/molecules/Web3Feedback.tsx +++ b/src/components/molecules/Web3Feedback.tsx @@ -1,5 +1,5 @@ import React, { ReactElement } from 'react' -import { useOcean } from '../../providers/Ocean' +import { useWeb3 } from '../../providers/Web3' import Status from '../atoms/Status' import styles from './Web3Feedback.module.css' @@ -16,36 +16,36 @@ export default function Web3Feedback({ isBalanceSufficient?: boolean isAssetNetwork?: boolean }): ReactElement { - const { account, ocean } = useOcean() + const { accountId } = useWeb3() const showFeedback = - !account || - !ocean || + !accountId || + // !ocean || isBalanceSufficient === false || isAssetNetwork === false - const state = !account + const state = !accountId ? 'error' - : account && isBalanceSufficient && isAssetNetwork + : accountId && isBalanceSufficient && isAssetNetwork ? 'success' : 'warning' - const title = !account + const title = !accountId ? 'No account connected' - : !ocean - ? 'Error connecting to Ocean' - : account && isAssetNetwork === false + : // : !ocean + // ? 'Error connecting to Ocean' + accountId && isAssetNetwork === false ? 'Wrong network' - : account + : accountId ? isBalanceSufficient === false ? 'Insufficient balance' : 'Connected to Ocean' : 'Something went wrong' - const message = !account + const message = !accountId ? 'Please connect your Web3 wallet.' - : !ocean - ? 'Please try again.' - : isBalanceSufficient === false + : // : !ocean + // ? 'Please try again.' + isBalanceSufficient === false ? 'You do not have enough OCEAN in your wallet to purchase this asset.' : isAssetNetwork === false ? 'Connect to the asset network.' diff --git a/src/components/organisms/AssetActions/Compute/index.tsx b/src/components/organisms/AssetActions/Compute/index.tsx index 52d63a6d0..8cc9a4f74 100644 --- a/src/components/organisms/AssetActions/Compute/index.tsx +++ b/src/components/organisms/AssetActions/Compute/index.tsx @@ -55,7 +55,7 @@ export default function Compute({ }): ReactElement { const { appConfig } = useSiteMetadata() const { accountId } = useWeb3() - const { ocean, account, config } = useOcean() + const { ocean, account, metadataCacheUri } = useOcean() const { price, type, ddo, isAssetNetwork } = useAsset() const { buyDT, pricingError, pricingStepText } = usePricing() const [isJobStarting, setIsJobStarting] = useState(false) @@ -150,13 +150,13 @@ export default function Compute({ getQuerryString( computeService.attributes.main.privacy.publisherTrustedAlgorithms ), - config.metadataCacheUri, + metadataCacheUri, source.token ) setDdoAlgorithmList(gueryResults.results) algorithmSelectionList = await transformDDOToAssetSelection( gueryResults.results, - config.metadataCacheUri, + metadataCacheUri, [] ) } diff --git a/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx b/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx index b8a395ced..3b769b72a 100644 --- a/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx +++ b/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx @@ -27,7 +27,7 @@ export default function FormEditComputeDataset({ setShowEdit: (show: boolean) => void }): ReactElement { const { accountId } = useWeb3() - const { ocean, config } = useOcean() + const { ocean, metadataCacheUri } = useOcean() const { ddo } = useAsset() const { isValid, values }: FormikContextType = useFormikContext() @@ -51,12 +51,12 @@ export default function FormEditComputeDataset({ } const querryResult = await queryMetadata( query, - config.metadataCacheUri, + metadataCacheUri, source.token ) const algorithmSelectionList = await transformDDOToAssetSelection( querryResult.results, - config.metadataCacheUri, + metadataCacheUri, publisherTrustedAlgorithms ) return algorithmSelectionList @@ -66,7 +66,7 @@ export default function FormEditComputeDataset({ getAlgorithmList(publisherTrustedAlgorithms).then((algorithms) => { setAllAlgorithms(algorithms) }) - }, [config.metadataCacheUri, publisherTrustedAlgorithms]) + }, [metadataCacheUri, publisherTrustedAlgorithms]) return (
      diff --git a/src/components/organisms/Footer.tsx b/src/components/organisms/Footer.tsx index 075ac2dda..21b0d6699 100644 --- a/src/components/organisms/Footer.tsx +++ b/src/components/organisms/Footer.tsx @@ -14,8 +14,8 @@ export default function Footer(): ReactElement { return (
      - | - + {/* | + */}
      © {year} —{' '} Terms diff --git a/src/components/pages/History/ComputeJobs/Details.tsx b/src/components/pages/History/ComputeJobs/Details.tsx index c1bede935..88d1e19fa 100644 --- a/src/components/pages/History/ComputeJobs/Details.tsx +++ b/src/components/pages/History/ComputeJobs/Details.tsx @@ -41,7 +41,7 @@ function Asset({ } function DetailsAssets({ job }: { job: ComputeJobMetaData }) { - const { config } = useOcean() + const { metadataCacheUri } = useOcean() const [algoName, setAlgoName] = useState() const [algoDtSymbol, setAlgoDtSymbol] = useState() @@ -49,18 +49,14 @@ function DetailsAssets({ job }: { job: ComputeJobMetaData }) { async function getAlgoMetadata() { const source = axios.CancelToken.source() - const ddo = await retrieveDDO( - job.algoDID, - config.metadataCacheUri, - source.token - ) + const ddo = await retrieveDDO(job.algoDID, metadataCacheUri, source.token) setAlgoDtSymbol(ddo.dataTokenInfo.symbol) const { attributes } = ddo.findServiceByType('metadata') setAlgoName(attributes?.main.name) } getAlgoMetadata() - }, [config?.metadataCacheUri, job.algoDID]) + }, [metadataCacheUri, job.algoDID]) return ( <> diff --git a/src/components/pages/History/ComputeJobs/index.tsx b/src/components/pages/History/ComputeJobs/index.tsx index 765a48171..49fd6da26 100644 --- a/src/components/pages/History/ComputeJobs/index.tsx +++ b/src/components/pages/History/ComputeJobs/index.tsx @@ -99,7 +99,7 @@ async function getAssetMetadata( } export default function ComputeJobs(): ReactElement { - const { ocean, account, config } = useOcean() + const { ocean, account, metadataCacheUri, config } = useOcean() const { accountId } = useWeb3() const [isLoading, setIsLoading] = useState(true) const [jobs, setJobs] = useState([]) @@ -128,7 +128,7 @@ export default function ComputeJobs(): ReactElement { const source = axios.CancelToken.source() const assets = await getAssetMetadata( queryDtList, - config.metadataCacheUri, + metadataCacheUri, source.token ) const providers: Provider[] = [] @@ -232,12 +232,12 @@ export default function ComputeJobs(): ReactElement { } useEffect(() => { - if (data === undefined || !config?.metadataCacheUri) { + if (data === undefined || !metadataCacheUri) { setIsLoading(false) return } getJobs() - }, [ocean, account, data, config?.metadataCacheUri]) + }, [ocean, account, data, metadataCacheUri]) return ( <> diff --git a/src/components/pages/History/Downloads.tsx b/src/components/pages/History/Downloads.tsx index e96070551..80ff2eb22 100644 --- a/src/components/pages/History/Downloads.tsx +++ b/src/components/pages/History/Downloads.tsx @@ -61,10 +61,10 @@ export default function ComputeDownloads(): ReactElement { const { data } = useQuery(getTokenOrders, { variables: { user: accountId?.toLowerCase() } }) - const { config } = useOcean() + const { metadataCacheUri } = useOcean() useEffect(() => { - if (!config.metadataCacheUri || !data) return + if (!metadataCacheUri || !data) return async function filterAssets() { const filteredOrders: DownloadedAssets[] = [] @@ -76,11 +76,7 @@ export default function ComputeDownloads(): ReactElement { const did = web3.utils .toChecksumAddress(data.tokenOrders[i].datatokenId.address) .replace('0x', 'did:op:') - const ddo = await retrieveDDO( - did, - config?.metadataCacheUri, - source.token - ) + const ddo = await retrieveDDO(did, metadataCacheUri, source.token) if (ddo.service[1].type === 'access') { filteredOrders.push({ did: did, @@ -98,7 +94,7 @@ export default function ComputeDownloads(): ReactElement { } filterAssets() - }, [config?.metadataCacheUri, data]) + }, [metadataCacheUri, data]) return (
    () const [isLoading, setIsLoading] = useState(false) @@ -34,7 +34,7 @@ export default function PublishedList(): ReactElement { queryResult || setIsLoading(true) const result = await queryMetadata( queryPublishedAssets, - config.metadataCacheUri, + metadataCacheUri, source.token ) setQueryResult(result) @@ -45,7 +45,7 @@ export default function PublishedList(): ReactElement { } } getPublished() - }, [accountId, page, config.metadataCacheUri]) + }, [accountId, page, metadataCacheUri]) return accountId ? ( () const [loading, setLoading] = useState() useEffect(() => { - if (!config?.metadataCacheUri) return + if (!metadataCacheUri) return const source = axios.CancelToken.source() async function init() { @@ -58,7 +58,7 @@ function SectionQueryResult({ setLoading(true) const result = await queryMetadata( query, - config.metadataCacheUri, + metadataCacheUri, source.token ) if (result.totalResults <= 15) { @@ -83,7 +83,7 @@ function SectionQueryResult({ return () => { source.cancel() } - }, [query, config?.metadataCacheUri]) + }, [metadataCacheUri, query]) return (
    @@ -128,7 +128,7 @@ export default function HomePage(): ReactElement {

    Bookmarks

    - + {/* */}
    {queryAndDids && ( diff --git a/src/components/templates/PageAssetDetails.tsx b/src/components/templates/PageAssetDetails.tsx index 108ef97da..1420810a4 100644 --- a/src/components/templates/PageAssetDetails.tsx +++ b/src/components/templates/PageAssetDetails.tsx @@ -24,13 +24,11 @@ export default function PageTemplateAssetDetails({ }, [ddo, error, isInPurgatory, title]) return ddo && pageTitle ? ( - <> - - - - - - + + + + + ) : error ? ( diff --git a/src/components/templates/Search/index.tsx b/src/components/templates/Search/index.tsx index f83e6efc0..66a1c3437 100644 --- a/src/components/templates/Search/index.tsx +++ b/src/components/templates/Search/index.tsx @@ -19,7 +19,7 @@ export default function SearchPage({ location: Location setTotalResults: (totalResults: number) => void }): ReactElement { - const { config } = useOcean() + const { metadataCacheUri } = useOcean() const parsed = queryString.parse(location.search) const { text, owner, tags, page, sort, sortOrder, serviceType } = parsed const [queryResult, setQueryResult] = useState() @@ -31,27 +31,18 @@ export default function SearchPage({ ) useEffect(() => { - if (!config?.metadataCacheUri) return + if (!metadataCacheUri) return async function initSearch() { setLoading(true) setTotalResults(undefined) - const queryResult = await getResults(parsed, config.metadataCacheUri) + const queryResult = await getResults(parsed, metadataCacheUri) setQueryResult(queryResult) setTotalResults(queryResult.totalResults) setLoading(false) } initSearch() - }, [ - text, - owner, - tags, - sort, - page, - serviceType, - sortOrder, - config.metadataCacheUri - ]) + }, [text, owner, tags, sort, page, serviceType, sortOrder, metadataCacheUri]) function setPage(page: number) { const newUrl = updateQueryStringParameter( diff --git a/src/helpers/wrapRootElement.tsx b/src/helpers/wrapRootElement.tsx index 84e22110a..3ad24560f 100644 --- a/src/helpers/wrapRootElement.tsx +++ b/src/helpers/wrapRootElement.tsx @@ -1,30 +1,18 @@ import React, { ReactElement } from 'react' import Web3Provider from '../providers/Web3' -import appConfig from '../../app.config' import { UserPreferencesProvider } from '../providers/UserPreferences' import PricesProvider from '../providers/Prices' import ApolloClientProvider from '../providers/ApolloClientProvider' import OceanProvider from '../providers/Ocean' -import { getDevelopmentConfig, getOceanConfig } from '../utils/ocean' export default function wrapRootElement({ element }: { element: ReactElement }): ReactElement { - const { network } = appConfig - const oceanInitialConfig = { - ...getOceanConfig(network), - - // add local dev values - ...(network === 'development' && { - ...getDevelopmentConfig() - }) - } - return ( - + {element} diff --git a/src/hooks/useSiteMetadata.ts b/src/hooks/useSiteMetadata.ts index 0db181ea0..63cef169a 100644 --- a/src/hooks/useSiteMetadata.ts +++ b/src/hooks/useSiteMetadata.ts @@ -21,7 +21,7 @@ interface UseSiteMetadata { } appConfig: { infuraProjectId: string - network: string + chainIds: number[] marketFeeAddress: string currencies: string[] portisId: string @@ -53,7 +53,7 @@ const query = graphql` } appConfig { infuraProjectId - network + chainIds marketFeeAddress currencies portisId diff --git a/src/providers/Asset.tsx b/src/providers/Asset.tsx index b8bfc1ee7..9df9857c3 100644 --- a/src/providers/Asset.tsx +++ b/src/providers/Asset.tsx @@ -45,7 +45,7 @@ function AssetProvider({ children: ReactNode }): ReactElement { const { networkId } = useWeb3() - const { config } = useOcean() + const { metadataCacheUri } = useOcean() const [isInPurgatory, setIsInPurgatory] = useState(false) const [purgatoryData, setPurgatoryData] = useState() const [ddo, setDDO] = useState() @@ -60,11 +60,7 @@ function AssetProvider({ const fetchDdo = async (token?: CancelToken) => { Logger.log('[asset] Init asset, get DDO') - const ddo = await retrieveDDO( - asset as string, - config.metadataCacheUri, - token - ) + const ddo = await retrieveDDO(asset as string, metadataCacheUri, token) if (!ddo) { setError( @@ -86,7 +82,7 @@ function AssetProvider({ // Get and set DDO based on passed DDO or DID // useEffect(() => { - if (!asset || !config?.metadataCacheUri) return + if (!asset || !metadataCacheUri) return const source = axios.CancelToken.source() let isMounted = true @@ -103,7 +99,7 @@ function AssetProvider({ isMounted = false source.cancel() } - }, [asset, config?.metadataCacheUri]) + }, [asset, metadataCacheUri]) const setPurgatory = useCallback(async (did: string): Promise => { if (!did) return diff --git a/src/providers/Ocean.tsx b/src/providers/Ocean.tsx index 820b950db..93cfdc52c 100644 --- a/src/providers/Ocean.tsx +++ b/src/providers/Ocean.tsx @@ -22,10 +22,13 @@ import { getUserInfo } from '../utils/ocean' import { UserBalance } from '../@types/TokenBalance' +import { useSiteMetadata } from '../hooks/useSiteMetadata' const refreshInterval = 20000 // 20 sec. interface OceanProviderValue { + oceanConfigs: ConfigHelperConfig[] + metadataCacheUri: string ocean: Ocean config: ConfigHelperConfig account: Account @@ -37,128 +40,131 @@ interface OceanProviderValue { const OceanContext = createContext({} as OceanProviderValue) -function OceanProvider({ - initialConfig, - children -}: { - initialConfig: Config | ConfigHelperConfig - children: ReactNode -}): ReactElement { +function OceanProvider({ children }: { children: ReactNode }): ReactElement { + const { appConfig } = useSiteMetadata() const { web3, accountId, networkId } = useWeb3() + + const [oceanConfigs, setOceanConfigs] = useState() + const [metadataCacheUri, setMetadataCacheUri] = useState() const [ocean, setOcean] = useState() const [account, setAccount] = useState() const [balance, setBalance] = useState({ eth: undefined, ocean: undefined }) - const [config, setConfig] = - useState(initialConfig) - const [loading, setLoading] = useState() + const [config, setConfig] = useState() + + // ----------------------------------- + // Initially get all supported configs + // from ocean.js ConfigHelper + // ----------------------------------- + useEffect(() => { + const allConfigs = appConfig.chainIds.map((chainId: number) => + getOceanConfig(chainId) + ) + setOceanConfigs(allConfigs) + setMetadataCacheUri(allConfigs[0].metadataCacheUri) + }, []) + + // ----------------------------------- + // Set active config + // ----------------------------------- + // useEffect(() => { + // const config = { + // ...getOceanConfig(networkId || 'mainnet'), + + // // add local dev values + // ...(networkId === 8996 && { + // ...getDevelopmentConfig() + // }) + // } + // setConfig(config) + // // Sync config.metadataCacheUri with metadataCacheUri + // setMetadataCacheUri(config.metadataCacheUri) + // }, [networkId]) // ----------------------------------- // Create Ocean instance // ----------------------------------- const connect = useCallback( - async (newConfig?: ConfigHelperConfig | Config) => { - setLoading(true) + async (config: ConfigHelperConfig | Config) => { + if (!web3) return + try { - const usedConfig = newConfig || config - Logger.log('[ocean] Connecting Ocean...', usedConfig) - usedConfig.web3Provider = web3 || initialConfig.web3Provider + Logger.log('[ocean] Connecting Ocean...', config) - if (newConfig) { - await setConfig(usedConfig) - } + config.web3Provider = web3 + setConfig(config) - if (usedConfig.web3Provider) { - const newOcean = await Ocean.getInstance(usedConfig) - await setOcean(newOcean) - Logger.log('[ocean] Ocean instance created.', newOcean) - } - setLoading(false) + const newOcean = await Ocean.getInstance(config) + setOcean(newOcean) + Logger.log('[ocean] Ocean instance created.', newOcean) } catch (error) { Logger.error('[ocean] Error: ', error.message) } }, - [web3, config, initialConfig.web3Provider] + [web3] ) - async function refreshBalance() { - if (!ocean || !account || !web3) return + // async function refreshBalance() { + // if (!ocean || !account || !web3) return - const { balance } = await getUserInfo(ocean) - setBalance(balance) - } + // const { balance } = await getUserInfo(ocean) + // setBalance(balance) + // } // ----------------------------------- // Initial connection // ----------------------------------- useEffect(() => { + const config = { + ...getOceanConfig('mainnet'), + + // add local dev values + ...(networkId === 8996 && { + ...getDevelopmentConfig() + }) + } + async function init() { - await connect() + await connect(config) } init() // init periodic refresh of wallet balance - const balanceInterval = setInterval(() => refreshBalance(), refreshInterval) + // const balanceInterval = setInterval(() => refreshBalance(), refreshInterval) - return () => { - clearInterval(balanceInterval) - } - }, []) + // return () => { + // clearInterval(balanceInterval) + // } + }, [connect, networkId]) // ----------------------------------- // Get user info, handle account change from web3 // ----------------------------------- - useEffect(() => { - if (!ocean || !accountId || !web3) return + // useEffect(() => { + // if (!ocean || !accountId || !web3) return - async function getInfo() { - const { account, balance } = await getUserInfo(ocean) - setAccount(account) - setBalance(balance) - } - getInfo() - }, [ocean, accountId, web3]) - - // ----------------------------------- - // Handle network change from web3 - // ----------------------------------- - useEffect(() => { - if (!networkId) return - - async function reconnect() { - const newConfig = { - ...getOceanConfig(networkId), - - // add local dev values - ...(networkId === 8996 && { - ...getDevelopmentConfig() - }) - } - - try { - setLoading(true) - await connect(newConfig) - setLoading(false) - } catch (error) { - Logger.error('[ocean] Error: ', error.message) - } - } - reconnect() - }, [networkId]) + // async function getInfo() { + // const { account, balance } = await getUserInfo(ocean) + // setAccount(account) + // setBalance(balance) + // } + // getInfo() + // }, [ocean, accountId, web3]) return ( diff --git a/src/providers/UserPreferences.tsx b/src/providers/UserPreferences.tsx index 04ad39296..7e877df38 100644 --- a/src/providers/UserPreferences.tsx +++ b/src/providers/UserPreferences.tsx @@ -45,8 +45,8 @@ function UserPreferencesProvider({ }: { children: ReactNode }): ReactElement { - const { config } = useOcean() - const networkName = (config as ConfigHelperConfig).network + // const { config } = useOcean() + // const networkName = (config as ConfigHelperConfig).network const localStorage = getLocalStorage() // Set default values from localStorage @@ -75,23 +75,23 @@ function UserPreferencesProvider({ setLocale(window.navigator.language) }, []) - function addBookmark(didToAdd: string): void { - const newPinned = { - ...bookmarks, - [networkName]: [didToAdd].concat(bookmarks[networkName]) - } - setBookmarks(newPinned) - } + // function addBookmark(didToAdd: string): void { + // const newPinned = { + // ...bookmarks, + // [networkName]: [didToAdd].concat(bookmarks[networkName]) + // } + // setBookmarks(newPinned) + // } - function removeBookmark(didToAdd: string): void { - const newPinned = { - ...bookmarks, - [networkName]: bookmarks[networkName].filter( - (did: string) => did !== didToAdd - ) - } - setBookmarks(newPinned) - } + // function removeBookmark(didToAdd: string): void { + // const newPinned = { + // ...bookmarks, + // [networkName]: bookmarks[networkName].filter( + // (did: string) => did !== didToAdd + // ) + // } + // setBookmarks(newPinned) + // } // Bookmarks old data structure migration useEffect(() => { @@ -109,9 +109,9 @@ function UserPreferencesProvider({ locale, bookmarks, setDebug, - setCurrency, - addBookmark, - removeBookmark + setCurrency + // addBookmark, + // removeBookmark } as UserPreferencesValue } > diff --git a/src/utils/ocean.ts b/src/utils/ocean.ts index e6c80eb08..652f6e6da 100644 --- a/src/utils/ocean.ts +++ b/src/utils/ocean.ts @@ -14,7 +14,7 @@ import { UserBalance } from '../@types/TokenBalance' export function getOceanConfig( network: ConfigHelperNetworkName | ConfigHelperNetworkId ): ConfigHelperConfig { - return new ConfigHelper().getConfig( + const config = new ConfigHelper().getConfig( network, network === 'polygon' || network === 137 || @@ -22,7 +22,13 @@ export function getOceanConfig( network === 1287 ? undefined : process.env.GATSBY_INFURA_PROJECT_ID - ) as ConfigHelperConfig + ) + + return { + ...config, + // TODO: remove faking one Aquarius for all networks + metadataCacheUri: 'https://aquarius.mainnet.oceanprotocol.com' + } as ConfigHelperConfig } export function getDevelopmentConfig(): Partial {