1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-12-02 05:57:29 +01:00

refactor and tinkering

This commit is contained in:
Matthias Kretschmann 2021-05-28 14:47:47 +02:00
parent 6bc37b9b7b
commit 3332249928
Signed by: m
GPG Key ID: 606EEEF3C479A91F
26 changed files with 199 additions and 240 deletions

View File

@ -132,19 +132,15 @@ const queryLatest = {
} }
function Component() { function Component() {
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const [result, setResult] = useState<QueryResult>() const [result, setResult] = useState<QueryResult>()
useEffect(() => { useEffect(() => {
if (!config?.metadataCacheUri) return if (!metadataCacheUri) return
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
async function init() { async function init() {
const result = await queryMetadata( const result = await queryMetadata(query, metadataCacheUri, source.token)
query,
config.metadataCacheUri,
source.token
)
setResult(result) setResult(result)
} }
init() init()
@ -152,7 +148,7 @@ function Component() {
return () => { return () => {
source.cancel() source.cancel()
} }
}, [config?.metadataCacheUri, query]) }, [metadataCacheUri, query])
return <div>{result}</div> return <div>{result}</div>
} }

View File

@ -1,9 +1,7 @@
module.exports = { module.exports = {
// The default network and its associated config the app should connect to // List of supported chainIds which metadata cache queries
// on start. App will automatically switch network configs when user switches // will return by default
// networks in their wallet. chainIds: [1, 3, 4, 137, 1287],
// Ocean Protocol contracts are deployed for: 'mainnet', 'rinkeby', 'development'
network: process.env.GATSBY_NETWORK || 'mainnet',
infuraProjectId: process.env.GATSBY_INFURA_PROJECT_ID || 'xxx', infuraProjectId: process.env.GATSBY_INFURA_PROJECT_ID || 'xxx',

View File

@ -40,17 +40,17 @@ export default function App({
const { warning } = useSiteMetadata() const { warning } = useSiteMetadata()
const { accountId } = useWeb3() const { accountId } = useWeb3()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId)
const { isGraphSynced, blockHead, blockGraph } = useGraphSyncStatus() // const { isGraphSynced, blockHead, blockGraph } = useGraphSyncStatus()
return ( return (
<Styles> <Styles>
<div className={styles.app}> <div className={styles.app}>
{!isGraphSynced && ( {/* {!isGraphSynced && (
<AnnouncementBanner <AnnouncementBanner
text={`The data for this network has only synced to Ethereum block ${blockGraph} (out of ${blockHead}). Please check back soon.`} text={`The data for this network has only synced to Ethereum block ${blockGraph} (out of ${blockHead}). Please check back soon.`}
state="error" state="error"
/> />
)} )} */}
<Header /> <Header />
{(props as PageProps).uri === '/' && ( {(props as PageProps).uri === '/' && (

View File

@ -15,11 +15,11 @@ export default function AssetListTitle({
did?: string did?: string
title?: string title?: string
}): ReactElement { }): ReactElement {
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const [assetTitle, setAssetTitle] = useState<string>(title) const [assetTitle, setAssetTitle] = useState<string>(title)
useEffect(() => { useEffect(() => {
if (title || !config?.metadataCacheUri) return if (title || !metadataCacheUri) return
if (ddo) { if (ddo) {
const { attributes } = ddo.findServiceByType('metadata') const { attributes } = ddo.findServiceByType('metadata')
setAssetTitle(attributes.main.name) setAssetTitle(attributes.main.name)
@ -29,11 +29,7 @@ export default function AssetListTitle({
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
async function getAssetName() { async function getAssetName() {
const title = await getAssetsNames( const title = await getAssetsNames([did], metadataCacheUri, source.token)
[did],
config.metadataCacheUri,
source.token
)
setAssetTitle(title[did]) setAssetTitle(title[did])
} }
@ -42,7 +38,7 @@ export default function AssetListTitle({
return () => { return () => {
source.cancel() source.cancel()
} }
}, [assetTitle, config?.metadataCacheUri, ddo, did, title]) }, [assetTitle, metadataCacheUri, ddo, did, title])
return ( return (
<h3 className={styles.title}> <h3 className={styles.title}>

View File

@ -78,7 +78,7 @@ const columns = [
] ]
export default function Bookmarks(): ReactElement { export default function Bookmarks(): ReactElement {
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const { bookmarks } = useUserPreferences() const { bookmarks } = useUserPreferences()
const [pinned, setPinned] = useState<DDO[]>() const [pinned, setPinned] = useState<DDO[]>()
@ -87,7 +87,7 @@ export default function Bookmarks(): ReactElement {
const networkName = (config as ConfigHelperConfig)?.network const networkName = (config as ConfigHelperConfig)?.network
useEffect(() => { useEffect(() => {
if (!config?.metadataCacheUri || !networkName || bookmarks === {}) return if (!metadataCacheUri || !networkName || bookmarks === {}) return
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
@ -102,7 +102,7 @@ export default function Bookmarks(): ReactElement {
try { try {
const resultPinned = await getAssetsBookmarked( const resultPinned = await getAssetsBookmarked(
bookmarks[networkName], bookmarks[networkName],
config.metadataCacheUri, metadataCacheUri,
source.token source.token
) )
setPinned(resultPinned?.results) setPinned(resultPinned?.results)
@ -117,7 +117,7 @@ export default function Bookmarks(): ReactElement {
return () => { return () => {
source.cancel() source.cancel()
} }
}, [bookmarks, config.metadataCacheUri, networkName]) }, [bookmarks, metadataCacheUri, networkName])
return ( return (
<Table <Table

View File

@ -1,7 +1,6 @@
import { ConfigHelperConfig } from '@oceanprotocol/lib' import { ConfigHelperConfig } from '@oceanprotocol/lib'
import React, { ReactElement, ChangeEvent } from 'react' import React, { ReactElement, ChangeEvent } from 'react'
import { useOcean } from '../../../providers/Ocean' import { useOcean } from '../../../providers/Ocean'
import { useWeb3 } from '../../../providers/Web3'
import { getOceanConfig } from '../../../utils/ocean' import { getOceanConfig } from '../../../utils/ocean'
import FormHelp from '../../atoms/Input/Help' import FormHelp from '../../atoms/Input/Help'
import Label from '../../atoms/Input/Label' import Label from '../../atoms/Input/Label'
@ -12,7 +11,6 @@ import { ReactComponent as MoonbeamIcon } from '../../../images/moonbeam.svg'
import styles from './Chain.module.css' import styles from './Chain.module.css'
export default function Chain(): ReactElement { export default function Chain(): ReactElement {
const { web3 } = useWeb3()
const { config, connect } = useOcean() const { config, connect } = useOcean()
async function connectOcean(event: ChangeEvent<HTMLInputElement>) { async function connectOcean(event: ChangeEvent<HTMLInputElement>) {
@ -48,10 +46,7 @@ export default function Chain(): ReactElement {
} }
] ]
// TODO: to fully solve https://github.com/oceanprotocol/market/issues/432 return (
// 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 ? (
<li className={styles.chains}> <li className={styles.chains}>
<Label htmlFor="">Chain</Label> <Label htmlFor="">Chain</Label>
<BoxSelection <BoxSelection
@ -61,5 +56,5 @@ export default function Chain(): ReactElement {
/> />
<FormHelp>Switch the data source for the interface.</FormHelp> <FormHelp>Switch the data source for the interface.</FormHelp>
</li> </li>
) : null )
} }

View File

@ -20,7 +20,7 @@ export default function UserPreferences(): ReactElement {
<ul className={styles.preferencesDetails}> <ul className={styles.preferencesDetails}>
<Currency /> <Currency />
<Appearance darkMode={darkMode} /> <Appearance darkMode={darkMode} />
<Chain /> {/* <Chain /> */}
<Debug /> <Debug />
</ul> </ul>
} }

View File

@ -12,8 +12,8 @@ import styles from './Details.module.css'
export default function Details(): ReactElement { export default function Details(): ReactElement {
const { web3Provider, web3ProviderInfo, connect, logout, networkData } = const { web3Provider, web3ProviderInfo, connect, logout, networkData } =
useWeb3() } = useWeb3()
const { balance, config } = useOcean() // const { balance, config } = useOcean()
const { locale } = useUserPreferences() const { locale } = useUserPreferences()
const [mainCurrency, setMainCurrency] = useState<string>() const [mainCurrency, setMainCurrency] = useState<string>()
@ -38,7 +38,7 @@ export default function Details(): ReactElement {
return ( return (
<div className={styles.details}> <div className={styles.details}>
<ul> <ul>
{Object.entries(balance).map(([key, value]) => ( {/* {Object.entries(balance).map(([key, value]) => (
<li className={styles.balance} key={key}> <li className={styles.balance} key={key}>
<span className={styles.symbol}> <span className={styles.symbol}>
{key === 'eth' ? mainCurrency : config.oceanTokenSymbol} {key === 'eth' ? mainCurrency : config.oceanTokenSymbol}
@ -48,7 +48,7 @@ export default function Details(): ReactElement {
})} })}
{key === 'ocean' && <Conversion price={value} />} {key === 'ocean' && <Conversion price={value} />}
</li> </li>
))} ))} */}
<li className={styles.actions}> <li className={styles.actions}>
<div title="Connected provider" className={styles.walletInfo}> <div title="Connected provider" className={styles.walletInfo}>
@ -66,14 +66,14 @@ export default function Details(): ReactElement {
onChange={handlePortisNetworkChange} onChange={handlePortisNetworkChange}
/> />
)} */} )} */}
{web3ProviderInfo?.name === 'MetaMask' && ( {/* {web3ProviderInfo?.name === 'MetaMask' && (
<AddToken <AddToken
address={config.oceanTokenAddress} address={config.oceanTokenAddress}
symbol={config.oceanTokenSymbol} symbol={config.oceanTokenSymbol}
logo="https://raw.githubusercontent.com/oceanprotocol/art/main/logo/token.png" logo="https://raw.githubusercontent.com/oceanprotocol/art/main/logo/token.png"
className={styles.addToken} className={styles.addToken}
/> />
)} )} */}
</div> </div>
<p> <p>
{web3ProviderInfo?.name === 'Portis' && ( {web3ProviderInfo?.name === 'Portis' && (

View File

@ -10,21 +10,18 @@ import styles from './Network.module.css'
export default function Network(): ReactElement { export default function Network(): ReactElement {
const { networkId, isTestnet } = useWeb3() const { networkId, isTestnet } = useWeb3()
const { config } = useOcean()
const networkIdConfig = (config as ConfigHelperConfig).networkId
const [isSupportedNetwork, setIsSupportedNetwork] = useState<boolean>() const [isSupportedNetwork, setIsSupportedNetwork] = useState<boolean>()
useEffect(() => { useEffect(() => {
// take network from user when present, // take network from user when present
// otherwise use the default configured one of app const network = networkId || 1
const network = networkId || networkIdConfig
// Check networkId against ocean.js ConfigHelper configs // Check networkId against ocean.js ConfigHelper configs
// to figure out if network is supported. // to figure out if network is supported.
const isSupportedNetwork = Boolean(new ConfigHelper().getConfig(network)) const isSupportedNetwork = Boolean(new ConfigHelper().getConfig(network))
setIsSupportedNetwork(isSupportedNetwork) setIsSupportedNetwork(isSupportedNetwork)
}, [networkId, networkIdConfig]) }, [networkId])
return networkId ? ( return networkId ? (
<div className={styles.network}> <div className={styles.network}>

View File

@ -1,5 +1,5 @@
import React, { ReactElement } from 'react' import React, { ReactElement } from 'react'
import { useOcean } from '../../providers/Ocean' import { useWeb3 } from '../../providers/Web3'
import Status from '../atoms/Status' import Status from '../atoms/Status'
import styles from './Web3Feedback.module.css' import styles from './Web3Feedback.module.css'
@ -16,36 +16,36 @@ export default function Web3Feedback({
isBalanceSufficient?: boolean isBalanceSufficient?: boolean
isAssetNetwork?: boolean isAssetNetwork?: boolean
}): ReactElement { }): ReactElement {
const { account, ocean } = useOcean() const { accountId } = useWeb3()
const showFeedback = const showFeedback =
!account || !accountId ||
!ocean || // !ocean ||
isBalanceSufficient === false || isBalanceSufficient === false ||
isAssetNetwork === false isAssetNetwork === false
const state = !account const state = !accountId
? 'error' ? 'error'
: account && isBalanceSufficient && isAssetNetwork : accountId && isBalanceSufficient && isAssetNetwork
? 'success' ? 'success'
: 'warning' : 'warning'
const title = !account const title = !accountId
? 'No account connected' ? 'No account connected'
: !ocean : // : !ocean
? 'Error connecting to Ocean' // ? 'Error connecting to Ocean'
: account && isAssetNetwork === false accountId && isAssetNetwork === false
? 'Wrong network' ? 'Wrong network'
: account : accountId
? isBalanceSufficient === false ? isBalanceSufficient === false
? 'Insufficient balance' ? 'Insufficient balance'
: 'Connected to Ocean' : 'Connected to Ocean'
: 'Something went wrong' : 'Something went wrong'
const message = !account const message = !accountId
? 'Please connect your Web3 wallet.' ? 'Please connect your Web3 wallet.'
: !ocean : // : !ocean
? 'Please try again.' // ? 'Please try again.'
: isBalanceSufficient === false isBalanceSufficient === false
? 'You do not have enough OCEAN in your wallet to purchase this asset.' ? 'You do not have enough OCEAN in your wallet to purchase this asset.'
: isAssetNetwork === false : isAssetNetwork === false
? 'Connect to the asset network.' ? 'Connect to the asset network.'

View File

@ -55,7 +55,7 @@ export default function Compute({
}): ReactElement { }): ReactElement {
const { appConfig } = useSiteMetadata() const { appConfig } = useSiteMetadata()
const { accountId } = useWeb3() const { accountId } = useWeb3()
const { ocean, account, config } = useOcean() const { ocean, account, metadataCacheUri } = useOcean()
const { price, type, ddo, isAssetNetwork } = useAsset() const { price, type, ddo, isAssetNetwork } = useAsset()
const { buyDT, pricingError, pricingStepText } = usePricing() const { buyDT, pricingError, pricingStepText } = usePricing()
const [isJobStarting, setIsJobStarting] = useState(false) const [isJobStarting, setIsJobStarting] = useState(false)
@ -150,13 +150,13 @@ export default function Compute({
getQuerryString( getQuerryString(
computeService.attributes.main.privacy.publisherTrustedAlgorithms computeService.attributes.main.privacy.publisherTrustedAlgorithms
), ),
config.metadataCacheUri, metadataCacheUri,
source.token source.token
) )
setDdoAlgorithmList(gueryResults.results) setDdoAlgorithmList(gueryResults.results)
algorithmSelectionList = await transformDDOToAssetSelection( algorithmSelectionList = await transformDDOToAssetSelection(
gueryResults.results, gueryResults.results,
config.metadataCacheUri, metadataCacheUri,
[] []
) )
} }

View File

@ -27,7 +27,7 @@ export default function FormEditComputeDataset({
setShowEdit: (show: boolean) => void setShowEdit: (show: boolean) => void
}): ReactElement { }): ReactElement {
const { accountId } = useWeb3() const { accountId } = useWeb3()
const { ocean, config } = useOcean() const { ocean, metadataCacheUri } = useOcean()
const { ddo } = useAsset() const { ddo } = useAsset()
const { isValid, values }: FormikContextType<ComputePrivacyForm> = const { isValid, values }: FormikContextType<ComputePrivacyForm> =
useFormikContext() useFormikContext()
@ -51,12 +51,12 @@ export default function FormEditComputeDataset({
} }
const querryResult = await queryMetadata( const querryResult = await queryMetadata(
query, query,
config.metadataCacheUri, metadataCacheUri,
source.token source.token
) )
const algorithmSelectionList = await transformDDOToAssetSelection( const algorithmSelectionList = await transformDDOToAssetSelection(
querryResult.results, querryResult.results,
config.metadataCacheUri, metadataCacheUri,
publisherTrustedAlgorithms publisherTrustedAlgorithms
) )
return algorithmSelectionList return algorithmSelectionList
@ -66,7 +66,7 @@ export default function FormEditComputeDataset({
getAlgorithmList(publisherTrustedAlgorithms).then((algorithms) => { getAlgorithmList(publisherTrustedAlgorithms).then((algorithms) => {
setAllAlgorithms(algorithms) setAllAlgorithms(algorithms)
}) })
}, [config.metadataCacheUri, publisherTrustedAlgorithms]) }, [metadataCacheUri, publisherTrustedAlgorithms])
return ( return (
<Form className={styles.form}> <Form className={styles.form}>

View File

@ -14,8 +14,8 @@ export default function Footer(): ReactElement {
return ( return (
<footer className={styles.footer}> <footer className={styles.footer}>
<div className={styles.content}> <div className={styles.content}>
<SyncStatus /> | <BuildId /> {/* <SyncStatus /> | <BuildId />
<MarketStats /> <MarketStats /> */}
<div className={styles.copyright}> <div className={styles.copyright}>
© {year} <Markdown text={copyright} /> {' '} © {year} <Markdown text={copyright} /> {' '}
<Link to="/terms">Terms</Link> <Link to="/terms">Terms</Link>

View File

@ -41,7 +41,7 @@ function Asset({
} }
function DetailsAssets({ job }: { job: ComputeJobMetaData }) { function DetailsAssets({ job }: { job: ComputeJobMetaData }) {
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const [algoName, setAlgoName] = useState<string>() const [algoName, setAlgoName] = useState<string>()
const [algoDtSymbol, setAlgoDtSymbol] = useState<string>() const [algoDtSymbol, setAlgoDtSymbol] = useState<string>()
@ -49,18 +49,14 @@ function DetailsAssets({ job }: { job: ComputeJobMetaData }) {
async function getAlgoMetadata() { async function getAlgoMetadata() {
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
const ddo = await retrieveDDO( const ddo = await retrieveDDO(job.algoDID, metadataCacheUri, source.token)
job.algoDID,
config.metadataCacheUri,
source.token
)
setAlgoDtSymbol(ddo.dataTokenInfo.symbol) setAlgoDtSymbol(ddo.dataTokenInfo.symbol)
const { attributes } = ddo.findServiceByType('metadata') const { attributes } = ddo.findServiceByType('metadata')
setAlgoName(attributes?.main.name) setAlgoName(attributes?.main.name)
} }
getAlgoMetadata() getAlgoMetadata()
}, [config?.metadataCacheUri, job.algoDID]) }, [metadataCacheUri, job.algoDID])
return ( return (
<> <>

View File

@ -99,7 +99,7 @@ async function getAssetMetadata(
} }
export default function ComputeJobs(): ReactElement { export default function ComputeJobs(): ReactElement {
const { ocean, account, config } = useOcean() const { ocean, account, metadataCacheUri, config } = useOcean()
const { accountId } = useWeb3() const { accountId } = useWeb3()
const [isLoading, setIsLoading] = useState(true) const [isLoading, setIsLoading] = useState(true)
const [jobs, setJobs] = useState<ComputeJobMetaData[]>([]) const [jobs, setJobs] = useState<ComputeJobMetaData[]>([])
@ -128,7 +128,7 @@ export default function ComputeJobs(): ReactElement {
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
const assets = await getAssetMetadata( const assets = await getAssetMetadata(
queryDtList, queryDtList,
config.metadataCacheUri, metadataCacheUri,
source.token source.token
) )
const providers: Provider[] = [] const providers: Provider[] = []
@ -232,12 +232,12 @@ export default function ComputeJobs(): ReactElement {
} }
useEffect(() => { useEffect(() => {
if (data === undefined || !config?.metadataCacheUri) { if (data === undefined || !metadataCacheUri) {
setIsLoading(false) setIsLoading(false)
return return
} }
getJobs() getJobs()
}, [ocean, account, data, config?.metadataCacheUri]) }, [ocean, account, data, metadataCacheUri])
return ( return (
<> <>

View File

@ -61,10 +61,10 @@ export default function ComputeDownloads(): ReactElement {
const { data } = useQuery(getTokenOrders, { const { data } = useQuery(getTokenOrders, {
variables: { user: accountId?.toLowerCase() } variables: { user: accountId?.toLowerCase() }
}) })
const { config } = useOcean() const { metadataCacheUri } = useOcean()
useEffect(() => { useEffect(() => {
if (!config.metadataCacheUri || !data) return if (!metadataCacheUri || !data) return
async function filterAssets() { async function filterAssets() {
const filteredOrders: DownloadedAssets[] = [] const filteredOrders: DownloadedAssets[] = []
@ -76,11 +76,7 @@ export default function ComputeDownloads(): ReactElement {
const did = web3.utils const did = web3.utils
.toChecksumAddress(data.tokenOrders[i].datatokenId.address) .toChecksumAddress(data.tokenOrders[i].datatokenId.address)
.replace('0x', 'did:op:') .replace('0x', 'did:op:')
const ddo = await retrieveDDO( const ddo = await retrieveDDO(did, metadataCacheUri, source.token)
did,
config?.metadataCacheUri,
source.token
)
if (ddo.service[1].type === 'access') { if (ddo.service[1].type === 'access') {
filteredOrders.push({ filteredOrders.push({
did: did, did: did,
@ -98,7 +94,7 @@ export default function ComputeDownloads(): ReactElement {
} }
filterAssets() filterAssets()
}, [config?.metadataCacheUri, data]) }, [metadataCacheUri, data])
return ( return (
<Table <Table

View File

@ -9,7 +9,7 @@ import { useOcean } from '../../../providers/Ocean'
export default function PublishedList(): ReactElement { export default function PublishedList(): ReactElement {
const { accountId } = useWeb3() const { accountId } = useWeb3()
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const [queryResult, setQueryResult] = useState<QueryResult>() const [queryResult, setQueryResult] = useState<QueryResult>()
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
@ -34,7 +34,7 @@ export default function PublishedList(): ReactElement {
queryResult || setIsLoading(true) queryResult || setIsLoading(true)
const result = await queryMetadata( const result = await queryMetadata(
queryPublishedAssets, queryPublishedAssets,
config.metadataCacheUri, metadataCacheUri,
source.token source.token
) )
setQueryResult(result) setQueryResult(result)
@ -45,7 +45,7 @@ export default function PublishedList(): ReactElement {
} }
} }
getPublished() getPublished()
}, [accountId, page, config.metadataCacheUri]) }, [accountId, page, metadataCacheUri])
return accountId ? ( return accountId ? (
<AssetList <AssetList

View File

@ -45,12 +45,12 @@ function SectionQueryResult({
action?: ReactElement action?: ReactElement
queryData?: string queryData?: string
}) { }) {
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const [result, setResult] = useState<QueryResult>() const [result, setResult] = useState<QueryResult>()
const [loading, setLoading] = useState<boolean>() const [loading, setLoading] = useState<boolean>()
useEffect(() => { useEffect(() => {
if (!config?.metadataCacheUri) return if (!metadataCacheUri) return
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
async function init() { async function init() {
@ -58,7 +58,7 @@ function SectionQueryResult({
setLoading(true) setLoading(true)
const result = await queryMetadata( const result = await queryMetadata(
query, query,
config.metadataCacheUri, metadataCacheUri,
source.token source.token
) )
if (result.totalResults <= 15) { if (result.totalResults <= 15) {
@ -83,7 +83,7 @@ function SectionQueryResult({
return () => { return () => {
source.cancel() source.cancel()
} }
}, [query, config?.metadataCacheUri]) }, [metadataCacheUri, query])
return ( return (
<section className={styles.section}> <section className={styles.section}>
@ -128,7 +128,7 @@ export default function HomePage(): ReactElement {
<section className={styles.section}> <section className={styles.section}>
<h3>Bookmarks</h3> <h3>Bookmarks</h3>
<Bookmarks /> {/* <Bookmarks /> */}
</section> </section>
{queryAndDids && ( {queryAndDids && (

View File

@ -24,13 +24,11 @@ export default function PageTemplateAssetDetails({
}, [ddo, error, isInPurgatory, title]) }, [ddo, error, isInPurgatory, title])
return ddo && pageTitle ? ( return ddo && pageTitle ? (
<>
<Page title={pageTitle} uri={uri}> <Page title={pageTitle} uri={uri}>
<Router basepath="/asset"> <Router basepath="/asset">
<AssetContent path=":did" /> <AssetContent path=":did" />
</Router> </Router>
</Page> </Page>
</>
) : error ? ( ) : error ? (
<Page title={pageTitle} noPageHeader uri={uri}> <Page title={pageTitle} noPageHeader uri={uri}>
<Alert title={pageTitle} text={error} state="error" /> <Alert title={pageTitle} text={error} state="error" />

View File

@ -19,7 +19,7 @@ export default function SearchPage({
location: Location location: Location
setTotalResults: (totalResults: number) => void setTotalResults: (totalResults: number) => void
}): ReactElement { }): ReactElement {
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const parsed = queryString.parse(location.search) const parsed = queryString.parse(location.search)
const { text, owner, tags, page, sort, sortOrder, serviceType } = parsed const { text, owner, tags, page, sort, sortOrder, serviceType } = parsed
const [queryResult, setQueryResult] = useState<QueryResult>() const [queryResult, setQueryResult] = useState<QueryResult>()
@ -31,27 +31,18 @@ export default function SearchPage({
) )
useEffect(() => { useEffect(() => {
if (!config?.metadataCacheUri) return if (!metadataCacheUri) return
async function initSearch() { async function initSearch() {
setLoading(true) setLoading(true)
setTotalResults(undefined) setTotalResults(undefined)
const queryResult = await getResults(parsed, config.metadataCacheUri) const queryResult = await getResults(parsed, metadataCacheUri)
setQueryResult(queryResult) setQueryResult(queryResult)
setTotalResults(queryResult.totalResults) setTotalResults(queryResult.totalResults)
setLoading(false) setLoading(false)
} }
initSearch() initSearch()
}, [ }, [text, owner, tags, sort, page, serviceType, sortOrder, metadataCacheUri])
text,
owner,
tags,
sort,
page,
serviceType,
sortOrder,
config.metadataCacheUri
])
function setPage(page: number) { function setPage(page: number) {
const newUrl = updateQueryStringParameter( const newUrl = updateQueryStringParameter(

View File

@ -1,30 +1,18 @@
import React, { ReactElement } from 'react' import React, { ReactElement } from 'react'
import Web3Provider from '../providers/Web3' import Web3Provider from '../providers/Web3'
import appConfig from '../../app.config'
import { UserPreferencesProvider } from '../providers/UserPreferences' import { UserPreferencesProvider } from '../providers/UserPreferences'
import PricesProvider from '../providers/Prices' import PricesProvider from '../providers/Prices'
import ApolloClientProvider from '../providers/ApolloClientProvider' import ApolloClientProvider from '../providers/ApolloClientProvider'
import OceanProvider from '../providers/Ocean' import OceanProvider from '../providers/Ocean'
import { getDevelopmentConfig, getOceanConfig } from '../utils/ocean'
export default function wrapRootElement({ export default function wrapRootElement({
element element
}: { }: {
element: ReactElement element: ReactElement
}): ReactElement { }): ReactElement {
const { network } = appConfig
const oceanInitialConfig = {
...getOceanConfig(network),
// add local dev values
...(network === 'development' && {
...getDevelopmentConfig()
})
}
return ( return (
<Web3Provider> <Web3Provider>
<OceanProvider initialConfig={oceanInitialConfig}> <OceanProvider>
<ApolloClientProvider> <ApolloClientProvider>
<UserPreferencesProvider> <UserPreferencesProvider>
<PricesProvider>{element}</PricesProvider> <PricesProvider>{element}</PricesProvider>

View File

@ -21,7 +21,7 @@ interface UseSiteMetadata {
} }
appConfig: { appConfig: {
infuraProjectId: string infuraProjectId: string
network: string chainIds: number[]
marketFeeAddress: string marketFeeAddress: string
currencies: string[] currencies: string[]
portisId: string portisId: string
@ -53,7 +53,7 @@ const query = graphql`
} }
appConfig { appConfig {
infuraProjectId infuraProjectId
network chainIds
marketFeeAddress marketFeeAddress
currencies currencies
portisId portisId

View File

@ -45,7 +45,7 @@ function AssetProvider({
children: ReactNode children: ReactNode
}): ReactElement { }): ReactElement {
const { networkId } = useWeb3() const { networkId } = useWeb3()
const { config } = useOcean() const { metadataCacheUri } = useOcean()
const [isInPurgatory, setIsInPurgatory] = useState(false) const [isInPurgatory, setIsInPurgatory] = useState(false)
const [purgatoryData, setPurgatoryData] = useState<PurgatoryData>() const [purgatoryData, setPurgatoryData] = useState<PurgatoryData>()
const [ddo, setDDO] = useState<DDO>() const [ddo, setDDO] = useState<DDO>()
@ -60,11 +60,7 @@ function AssetProvider({
const fetchDdo = async (token?: CancelToken) => { const fetchDdo = async (token?: CancelToken) => {
Logger.log('[asset] Init asset, get DDO') Logger.log('[asset] Init asset, get DDO')
const ddo = await retrieveDDO( const ddo = await retrieveDDO(asset as string, metadataCacheUri, token)
asset as string,
config.metadataCacheUri,
token
)
if (!ddo) { if (!ddo) {
setError( setError(
@ -86,7 +82,7 @@ function AssetProvider({
// Get and set DDO based on passed DDO or DID // Get and set DDO based on passed DDO or DID
// //
useEffect(() => { useEffect(() => {
if (!asset || !config?.metadataCacheUri) return if (!asset || !metadataCacheUri) return
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
let isMounted = true let isMounted = true
@ -103,7 +99,7 @@ function AssetProvider({
isMounted = false isMounted = false
source.cancel() source.cancel()
} }
}, [asset, config?.metadataCacheUri]) }, [asset, metadataCacheUri])
const setPurgatory = useCallback(async (did: string): Promise<void> => { const setPurgatory = useCallback(async (did: string): Promise<void> => {
if (!did) return if (!did) return

View File

@ -22,10 +22,13 @@ import {
getUserInfo getUserInfo
} from '../utils/ocean' } from '../utils/ocean'
import { UserBalance } from '../@types/TokenBalance' import { UserBalance } from '../@types/TokenBalance'
import { useSiteMetadata } from '../hooks/useSiteMetadata'
const refreshInterval = 20000 // 20 sec. const refreshInterval = 20000 // 20 sec.
interface OceanProviderValue { interface OceanProviderValue {
oceanConfigs: ConfigHelperConfig[]
metadataCacheUri: string
ocean: Ocean ocean: Ocean
config: ConfigHelperConfig config: ConfigHelperConfig
account: Account account: Account
@ -37,99 +40,85 @@ interface OceanProviderValue {
const OceanContext = createContext({} as OceanProviderValue) const OceanContext = createContext({} as OceanProviderValue)
function OceanProvider({ function OceanProvider({ children }: { children: ReactNode }): ReactElement {
initialConfig, const { appConfig } = useSiteMetadata()
children
}: {
initialConfig: Config | ConfigHelperConfig
children: ReactNode
}): ReactElement {
const { web3, accountId, networkId } = useWeb3() const { web3, accountId, networkId } = useWeb3()
const [oceanConfigs, setOceanConfigs] = useState<ConfigHelperConfig[]>()
const [metadataCacheUri, setMetadataCacheUri] = useState<string>()
const [ocean, setOcean] = useState<Ocean>() const [ocean, setOcean] = useState<Ocean>()
const [account, setAccount] = useState<Account>() const [account, setAccount] = useState<Account>()
const [balance, setBalance] = useState<UserBalance>({ const [balance, setBalance] = useState<UserBalance>({
eth: undefined, eth: undefined,
ocean: undefined ocean: undefined
}) })
const [config, setConfig] = const [config, setConfig] = useState<ConfigHelperConfig | Config>()
useState<ConfigHelperConfig | Config>(initialConfig)
const [loading, setLoading] = useState<boolean>() // -----------------------------------
// 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 // Create Ocean instance
// ----------------------------------- // -----------------------------------
const connect = useCallback( const connect = useCallback(
async (newConfig?: ConfigHelperConfig | Config) => { async (config: ConfigHelperConfig | Config) => {
setLoading(true) if (!web3) return
try { try {
const usedConfig = newConfig || config Logger.log('[ocean] Connecting Ocean...', config)
Logger.log('[ocean] Connecting Ocean...', usedConfig)
usedConfig.web3Provider = web3 || initialConfig.web3Provider
if (newConfig) { config.web3Provider = web3
await setConfig(usedConfig) setConfig(config)
}
if (usedConfig.web3Provider) { const newOcean = await Ocean.getInstance(config)
const newOcean = await Ocean.getInstance(usedConfig) setOcean(newOcean)
await setOcean(newOcean)
Logger.log('[ocean] Ocean instance created.', newOcean) Logger.log('[ocean] Ocean instance created.', newOcean)
}
setLoading(false)
} catch (error) { } catch (error) {
Logger.error('[ocean] Error: ', error.message) Logger.error('[ocean] Error: ', error.message)
} }
}, },
[web3, config, initialConfig.web3Provider] [web3]
) )
async function refreshBalance() { // async function refreshBalance() {
if (!ocean || !account || !web3) return // if (!ocean || !account || !web3) return
const { balance } = await getUserInfo(ocean) // const { balance } = await getUserInfo(ocean)
setBalance(balance) // setBalance(balance)
} // }
// ----------------------------------- // -----------------------------------
// Initial connection // Initial connection
// ----------------------------------- // -----------------------------------
useEffect(() => { useEffect(() => {
async function init() { const config = {
await connect() ...getOceanConfig('mainnet'),
}
init()
// init periodic refresh of wallet balance
const balanceInterval = setInterval(() => refreshBalance(), refreshInterval)
return () => {
clearInterval(balanceInterval)
}
}, [])
// -----------------------------------
// Get user info, handle account change from web3
// -----------------------------------
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 // add local dev values
...(networkId === 8996 && { ...(networkId === 8996 && {
@ -137,28 +126,45 @@ function OceanProvider({
}) })
} }
try { async function init() {
setLoading(true) await connect(config)
await connect(newConfig)
setLoading(false)
} catch (error) {
Logger.error('[ocean] Error: ', error.message)
} }
} init()
reconnect()
}, [networkId]) // init periodic refresh of wallet balance
// const balanceInterval = setInterval(() => refreshBalance(), refreshInterval)
// return () => {
// clearInterval(balanceInterval)
// }
}, [connect, networkId])
// -----------------------------------
// Get user info, handle account change from web3
// -----------------------------------
// useEffect(() => {
// if (!ocean || !accountId || !web3) return
// async function getInfo() {
// const { account, balance } = await getUserInfo(ocean)
// setAccount(account)
// setBalance(balance)
// }
// getInfo()
// }, [ocean, accountId, web3])
return ( return (
<OceanContext.Provider <OceanContext.Provider
value={ value={
{ {
oceanConfigs,
metadataCacheUri,
ocean, ocean,
account, account,
balance, balance,
config, config,
loading, connect
connect, // refreshBalance
refreshBalance
} as OceanProviderValue } as OceanProviderValue
} }
> >

View File

@ -45,8 +45,8 @@ function UserPreferencesProvider({
}: { }: {
children: ReactNode children: ReactNode
}): ReactElement { }): ReactElement {
const { config } = useOcean() // const { config } = useOcean()
const networkName = (config as ConfigHelperConfig).network // const networkName = (config as ConfigHelperConfig).network
const localStorage = getLocalStorage() const localStorage = getLocalStorage()
// Set default values from localStorage // Set default values from localStorage
@ -75,23 +75,23 @@ function UserPreferencesProvider({
setLocale(window.navigator.language) setLocale(window.navigator.language)
}, []) }, [])
function addBookmark(didToAdd: string): void { // function addBookmark(didToAdd: string): void {
const newPinned = { // const newPinned = {
...bookmarks, // ...bookmarks,
[networkName]: [didToAdd].concat(bookmarks[networkName]) // [networkName]: [didToAdd].concat(bookmarks[networkName])
} // }
setBookmarks(newPinned) // setBookmarks(newPinned)
} // }
function removeBookmark(didToAdd: string): void { // function removeBookmark(didToAdd: string): void {
const newPinned = { // const newPinned = {
...bookmarks, // ...bookmarks,
[networkName]: bookmarks[networkName].filter( // [networkName]: bookmarks[networkName].filter(
(did: string) => did !== didToAdd // (did: string) => did !== didToAdd
) // )
} // }
setBookmarks(newPinned) // setBookmarks(newPinned)
} // }
// Bookmarks old data structure migration // Bookmarks old data structure migration
useEffect(() => { useEffect(() => {
@ -109,9 +109,9 @@ function UserPreferencesProvider({
locale, locale,
bookmarks, bookmarks,
setDebug, setDebug,
setCurrency, setCurrency
addBookmark, // addBookmark,
removeBookmark // removeBookmark
} as UserPreferencesValue } as UserPreferencesValue
} }
> >

View File

@ -14,7 +14,7 @@ import { UserBalance } from '../@types/TokenBalance'
export function getOceanConfig( export function getOceanConfig(
network: ConfigHelperNetworkName | ConfigHelperNetworkId network: ConfigHelperNetworkName | ConfigHelperNetworkId
): ConfigHelperConfig { ): ConfigHelperConfig {
return new ConfigHelper().getConfig( const config = new ConfigHelper().getConfig(
network, network,
network === 'polygon' || network === 'polygon' ||
network === 137 || network === 137 ||
@ -22,7 +22,13 @@ export function getOceanConfig(
network === 1287 network === 1287
? undefined ? undefined
: process.env.GATSBY_INFURA_PROJECT_ID : 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<ConfigHelperConfig> { export function getDevelopmentConfig(): Partial<ConfigHelperConfig> {