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

move OceanProvider to asset route

This commit is contained in:
Matthias Kretschmann 2021-05-31 14:27:04 +02:00
parent 3332249928
commit 21792e9d4f
Signed by: m
GPG Key ID: 606EEEF3C479A91F
20 changed files with 287 additions and 192 deletions

View File

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

View File

@ -1,4 +1,5 @@
module.exports = { module.exports = {
metadataCacheUri: 'https://aquarius.mainnet.oceanprotocol.com',
// List of supported chainIds which metadata cache queries // List of supported chainIds which metadata cache queries
// will return by default // will return by default
chainIds: [1, 3, 4, 137, 1287], chainIds: [1, 3, 4, 137, 1287],

2
package-lock.json generated
View File

@ -43525,6 +43525,7 @@
"node-abort-controller": "^2.0.0", "node-abort-controller": "^2.0.0",
"save-file": "^2.3.1", "save-file": "^2.3.1",
"uuid": "^8.3.2", "uuid": "^8.3.2",
"web3": "^1.3.5",
"web3-eth-contract": "^1.3.6" "web3-eth-contract": "^1.3.6"
} }
}, },
@ -43599,6 +43600,7 @@
"integrity": "sha512-5vwpq6kbvwkQwKqAoOU3L72GZ3Ta8RRrewKj9OJRolx28KLJJ8Dg9Rf7obRwt5jQA9bkYd8gqzMTrI7H3xLfaw==", "integrity": "sha512-5vwpq6kbvwkQwKqAoOU3L72GZ3Ta8RRrewKj9OJRolx28KLJJ8Dg9Rf7obRwt5jQA9bkYd8gqzMTrI7H3xLfaw==",
"dev": true, "dev": true,
"requires": { "requires": {
"@oclif/config": "^1.15.1",
"@oclif/errors": "^1.3.3", "@oclif/errors": "^1.3.3",
"@oclif/parser": "^3.8.3", "@oclif/parser": "^3.8.3",
"@oclif/plugin-help": "^3", "@oclif/plugin-help": "^3",

View File

@ -5,6 +5,7 @@ import React, { ReactElement, useEffect, useState } from 'react'
import { getAssetsNames } from '../../utils/aquarius' import { getAssetsNames } from '../../utils/aquarius'
import styles from './AssetListTitle.module.css' import styles from './AssetListTitle.module.css'
import axios from 'axios' import axios from 'axios'
import { useSiteMetadata } from '../../hooks/useSiteMetadata'
export default function AssetListTitle({ export default function AssetListTitle({
ddo, ddo,
@ -15,11 +16,11 @@ export default function AssetListTitle({
did?: string did?: string
title?: string title?: string
}): ReactElement { }): ReactElement {
const { metadataCacheUri } = useOcean() const { appConfig } = useSiteMetadata()
const [assetTitle, setAssetTitle] = useState<string>(title) const [assetTitle, setAssetTitle] = useState<string>(title)
useEffect(() => { useEffect(() => {
if (title || !metadataCacheUri) return if (title || !appConfig.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,7 +30,11 @@ export default function AssetListTitle({
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
async function getAssetName() { async function getAssetName() {
const title = await getAssetsNames([did], metadataCacheUri, source.token) const title = await getAssetsNames(
[did],
appConfig.metadataCacheUri,
source.token
)
setAssetTitle(title[did]) setAssetTitle(title[did])
} }
@ -38,7 +43,7 @@ export default function AssetListTitle({
return () => { return () => {
source.cancel() source.cancel()
} }
}, [assetTitle, metadataCacheUri, ddo, did, title]) }, [assetTitle, appConfig.metadataCacheUri, ddo, did, title])
return ( return (
<h3 className={styles.title}> <h3 className={styles.title}>

View File

@ -8,6 +8,7 @@ import Tooltip from '../atoms/Tooltip'
import AssetTitle from './AssetListTitle' import AssetTitle from './AssetListTitle'
import { queryMetadata } from '../../utils/aquarius' import { queryMetadata } from '../../utils/aquarius'
import axios, { CancelToken } from 'axios' import axios, { CancelToken } from 'axios'
import { useSiteMetadata } from '../../hooks/useSiteMetadata'
async function getAssetsBookmarked( async function getAssetsBookmarked(
bookmarks: string[], bookmarks: string[],
@ -78,7 +79,7 @@ const columns = [
] ]
export default function Bookmarks(): ReactElement { export default function Bookmarks(): ReactElement {
const { metadataCacheUri } = useOcean() const { appConfig } = useSiteMetadata()
const { bookmarks } = useUserPreferences() const { bookmarks } = useUserPreferences()
const [pinned, setPinned] = useState<DDO[]>() const [pinned, setPinned] = useState<DDO[]>()
@ -87,7 +88,7 @@ export default function Bookmarks(): ReactElement {
const networkName = (config as ConfigHelperConfig)?.network const networkName = (config as ConfigHelperConfig)?.network
useEffect(() => { useEffect(() => {
if (!metadataCacheUri || !networkName || bookmarks === {}) return if (!appConfig.metadataCacheUri || !networkName || bookmarks === {}) return
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
@ -102,7 +103,7 @@ export default function Bookmarks(): ReactElement {
try { try {
const resultPinned = await getAssetsBookmarked( const resultPinned = await getAssetsBookmarked(
bookmarks[networkName], bookmarks[networkName],
metadataCacheUri, appConfig.metadataCacheUri,
source.token source.token
) )
setPinned(resultPinned?.results) setPinned(resultPinned?.results)
@ -117,7 +118,7 @@ export default function Bookmarks(): ReactElement {
return () => { return () => {
source.cancel() source.cancel()
} }
}, [bookmarks, metadataCacheUri, networkName]) }, [bookmarks, appConfig.metadataCacheUri, networkName])
return ( return (
<Table <Table

View File

@ -9,21 +9,37 @@ import { useWeb3 } from '../../../providers/Web3'
import Web3Feedback from '../Web3Feedback' import Web3Feedback from '../Web3Feedback'
import styles from './Details.module.css' import styles from './Details.module.css'
import { getOceanTokenData } from '../../../utils/ocean'
export default function Details(): ReactElement { export default function Details(): ReactElement {
const { web3Provider, web3ProviderInfo, connect, logout, networkData } = const {
web3Provider,
web3ProviderInfo,
connect,
logout,
networkData,
networkId,
balance
} = useWeb3() } = useWeb3()
// const { balance, config } = useOcean() const { oceanConfigs } = useOcean()
const { locale } = useUserPreferences() const { locale } = useUserPreferences()
const [mainCurrency, setMainCurrency] = useState<string>() const [mainCurrency, setMainCurrency] = useState<string>()
const [oceanTokenMetadata, setOceanTokenMetadata] =
useState<{
address: string
symbol: string
}>()
// const [portisNetwork, setPortisNetwork] = useState<string>() // const [portisNetwork, setPortisNetwork] = useState<string>()
useEffect(() => { useEffect(() => {
if (!networkData) return if (!networkData) return
setMainCurrency(networkData.nativeCurrency.symbol) setMainCurrency(networkData.nativeCurrency.symbol)
}, [networkData])
oceanConfigs &&
setOceanTokenMetadata(getOceanTokenData(networkId || 1, oceanConfigs))
}, [networkData, networkId, oceanConfigs])
// Handle network change for Portis // Handle network change for Portis
// async function handlePortisNetworkChange(e: ChangeEvent<HTMLSelectElement>) { // async function handlePortisNetworkChange(e: ChangeEvent<HTMLSelectElement>) {
@ -38,17 +54,17 @@ 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 : oceanTokenMetadata?.symbol}
</span>{' '} </span>{' '}
{formatCurrency(Number(value), '', locale, false, { {formatCurrency(Number(value), '', locale, false, {
significantFigures: 4 significantFigures: 4
})} })}
{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 +82,14 @@ export default function Details(): ReactElement {
onChange={handlePortisNetworkChange} onChange={handlePortisNetworkChange}
/> />
)} */} )} */}
{/* {web3ProviderInfo?.name === 'MetaMask' && ( {web3ProviderInfo?.name === 'MetaMask' && (
<AddToken <AddToken
address={config.oceanTokenAddress} address={oceanTokenMetadata?.address}
symbol={config.oceanTokenSymbol} symbol={oceanTokenMetadata?.symbol}
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

@ -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, metadataCacheUri } = useOcean() const { ocean, account } = 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
), ),
metadataCacheUri, appConfig.metadataCacheUri,
source.token source.token
) )
setDdoAlgorithmList(gueryResults.results) setDdoAlgorithmList(gueryResults.results)
algorithmSelectionList = await transformDDOToAssetSelection( algorithmSelectionList = await transformDDOToAssetSelection(
gueryResults.results, gueryResults.results,
metadataCacheUri, appConfig.metadataCacheUri,
[] []
) )
} }

View File

@ -16,6 +16,7 @@ import { useAsset } from '../../../../providers/Asset'
import { ComputePrivacyForm } from '../../../../models/FormEditComputeDataset' import { ComputePrivacyForm } from '../../../../models/FormEditComputeDataset'
import { publisherTrustedAlgorithm as PublisherTrustedAlgorithm } from '@oceanprotocol/lib' import { publisherTrustedAlgorithm as PublisherTrustedAlgorithm } from '@oceanprotocol/lib'
import axios from 'axios' import axios from 'axios'
import { useSiteMetadata } from '../../../../hooks/useSiteMetadata'
export default function FormEditComputeDataset({ export default function FormEditComputeDataset({
data, data,
@ -26,8 +27,9 @@ export default function FormEditComputeDataset({
title: string title: string
setShowEdit: (show: boolean) => void setShowEdit: (show: boolean) => void
}): ReactElement { }): ReactElement {
const { appConfig } = useSiteMetadata()
const { accountId } = useWeb3() const { accountId } = useWeb3()
const { ocean, metadataCacheUri } = useOcean() const { ocean } = useOcean()
const { ddo } = useAsset() const { ddo } = useAsset()
const { isValid, values }: FormikContextType<ComputePrivacyForm> = const { isValid, values }: FormikContextType<ComputePrivacyForm> =
useFormikContext() useFormikContext()
@ -51,12 +53,12 @@ export default function FormEditComputeDataset({
} }
const querryResult = await queryMetadata( const querryResult = await queryMetadata(
query, query,
metadataCacheUri, appConfig.metadataCacheUri,
source.token source.token
) )
const algorithmSelectionList = await transformDDOToAssetSelection( const algorithmSelectionList = await transformDDOToAssetSelection(
querryResult.results, querryResult.results,
metadataCacheUri, appConfig.metadataCacheUri,
publisherTrustedAlgorithms publisherTrustedAlgorithms
) )
return algorithmSelectionList return algorithmSelectionList
@ -66,7 +68,7 @@ export default function FormEditComputeDataset({
getAlgorithmList(publisherTrustedAlgorithms).then((algorithms) => { getAlgorithmList(publisherTrustedAlgorithms).then((algorithms) => {
setAllAlgorithms(algorithms) setAllAlgorithms(algorithms)
}) })
}, [metadataCacheUri, publisherTrustedAlgorithms]) }, [appConfig.metadataCacheUri, publisherTrustedAlgorithms])
return ( return (
<Form className={styles.form}> <Form className={styles.form}>

View File

@ -10,6 +10,7 @@ import { retrieveDDO } from '../../../../utils/aquarius'
import { useOcean } from '../../../../providers/Ocean' import { useOcean } from '../../../../providers/Ocean'
import Results from './Results' import Results from './Results'
import styles from './Details.module.css' import styles from './Details.module.css'
import { useSiteMetadata } from '../../../../hooks/useSiteMetadata'
function Asset({ function Asset({
title, title,
@ -41,7 +42,7 @@ function Asset({
} }
function DetailsAssets({ job }: { job: ComputeJobMetaData }) { function DetailsAssets({ job }: { job: ComputeJobMetaData }) {
const { metadataCacheUri } = useOcean() const { appConfig } = useSiteMetadata()
const [algoName, setAlgoName] = useState<string>() const [algoName, setAlgoName] = useState<string>()
const [algoDtSymbol, setAlgoDtSymbol] = useState<string>() const [algoDtSymbol, setAlgoDtSymbol] = useState<string>()
@ -49,14 +50,18 @@ 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(job.algoDID, metadataCacheUri, source.token) const ddo = await retrieveDDO(
job.algoDID,
appConfig.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()
}, [metadataCacheUri, job.algoDID]) }, [appConfig.metadataCacheUri, job.algoDID])
return ( return (
<> <>

View File

@ -17,6 +17,7 @@ import Details from './Details'
import { ComputeJob } from '@oceanprotocol/lib/dist/node/ocean/interfaces/Compute' import { ComputeJob } from '@oceanprotocol/lib/dist/node/ocean/interfaces/Compute'
import { ReactComponent as Refresh } from '../../../../images/refresh.svg' import { ReactComponent as Refresh } from '../../../../images/refresh.svg'
import styles from './index.module.css' import styles from './index.module.css'
import { useSiteMetadata } from '../../../../hooks/useSiteMetadata'
const getComputeOrders = gql` const getComputeOrders = gql`
query ComputeOrders($user: String!) { query ComputeOrders($user: String!) {
@ -99,7 +100,8 @@ async function getAssetMetadata(
} }
export default function ComputeJobs(): ReactElement { export default function ComputeJobs(): ReactElement {
const { ocean, account, metadataCacheUri, config } = useOcean() const { appConfig } = useSiteMetadata()
const { ocean, account } = 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 +130,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,
metadataCacheUri, appConfig.metadataCacheUri,
source.token source.token
) )
const providers: Provider[] = [] const providers: Provider[] = []
@ -232,12 +234,12 @@ export default function ComputeJobs(): ReactElement {
} }
useEffect(() => { useEffect(() => {
if (data === undefined || !metadataCacheUri) { if (data === undefined || !appConfig.metadataCacheUri) {
setIsLoading(false) setIsLoading(false)
return return
} }
getJobs() getJobs()
}, [ocean, account, data, metadataCacheUri]) }, [ocean, account, data, appConfig.metadataCacheUri])
return ( return (
<> <>

View File

@ -15,16 +15,21 @@ import { queryMetadata } from '../../utils/aquarius'
import { getHighestLiquidityDIDs } from '../../utils/subgraph' import { getHighestLiquidityDIDs } from '../../utils/subgraph'
import { DDO, Logger } from '@oceanprotocol/lib' import { DDO, Logger } from '@oceanprotocol/lib'
import { useWeb3 } from '../../providers/Web3' import { useWeb3 } from '../../providers/Web3'
import { useSiteMetadata } from '../../hooks/useSiteMetadata'
import { getOceanConfig } from '../../utils/ocean'
const queryLatest = { // TODO: these queries need to adapt to chainIds
page: 1, function getQueryHighest(chainIds: number[]) {
offset: 9, return {
query: { page: 1,
query_string: { offset: 9,
query: `-isInPurgatory:true` query: {
} query_string: {
}, query: `(price.type:pool) -isInPurgatory:true`
sort: { created: -1 } }
},
sort: { 'price.ocean': -1 }
}
} }
function sortElements(items: DDO[], sorted: string[]) { function sortElements(items: DDO[], sorted: string[]) {
@ -34,6 +39,20 @@ function sortElements(items: DDO[], sorted: string[]) {
return items return items
} }
function getQueryLatest(chainIds: number[]) {
return {
page: 1,
offset: 9,
query: {
query_string: {
query: `-isInPurgatory:true`
}
},
sort: { created: -1 }
}
return items
}
function SectionQueryResult({ function SectionQueryResult({
title, title,
query, query,
@ -45,12 +64,12 @@ function SectionQueryResult({
action?: ReactElement action?: ReactElement
queryData?: string queryData?: string
}) { }) {
const { metadataCacheUri } = useOcean() const { appConfig } = useSiteMetadata()
const [result, setResult] = useState<QueryResult>() const [result, setResult] = useState<QueryResult>()
const [loading, setLoading] = useState<boolean>() const [loading, setLoading] = useState<boolean>()
useEffect(() => { useEffect(() => {
if (!metadataCacheUri) return if (!appConfig.metadataCacheUri) return
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
async function init() { async function init() {
@ -58,7 +77,7 @@ function SectionQueryResult({
setLoading(true) setLoading(true)
const result = await queryMetadata( const result = await queryMetadata(
query, query,
metadataCacheUri, appConfig.metadataCacheUri,
source.token source.token
) )
if (result.totalResults <= 15) { if (result.totalResults <= 15) {
@ -83,7 +102,7 @@ function SectionQueryResult({
return () => { return () => {
source.cancel() source.cancel()
} }
}, [metadataCacheUri, query]) }, [appConfig.metadataCacheUri, query])
return ( return (
<section className={styles.section}> <section className={styles.section}>
@ -99,8 +118,9 @@ function SectionQueryResult({
} }
export default function HomePage(): ReactElement { export default function HomePage(): ReactElement {
const { config, loading } = useOcean() // TODO: appConfig.chainIds needs to come from UserPreferences instead
const [queryAndDids, setQueryAndDids] = useState<[SearchQuery, string]>() const [queryAndDids, setQueryAndDids] = useState<[SearchQuery, string]>()
const { appConfig } = useSiteMetadata()
const { web3Loading, web3Provider } = useWeb3() const { web3Loading, web3Provider } = useWeb3()
useEffect(() => { useEffect(() => {
@ -135,13 +155,14 @@ export default function HomePage(): ReactElement {
<SectionQueryResult <SectionQueryResult
title="Highest Liquidity" title="Highest Liquidity"
query={queryAndDids[0]} query={queryAndDids[0]}
// query={getQueryHighest(appConfig.chainIds)}
queryData={queryAndDids[1]} queryData={queryAndDids[1]}
/> />
)} )}
<SectionQueryResult <SectionQueryResult
title="Recently Published" title="Recently Published"
query={queryLatest} query={getQueryLatest(appConfig.chainIds)}
action={ action={
<Button style="text" to="/search?sort=created&sortOrder=desc"> <Button style="text" to="/search?sort=created&sortOrder=desc">
All data sets and algorithms All data sets and algorithms

View File

@ -9,8 +9,7 @@ import Sort from './sort'
import { getResults } from './utils' import { getResults } from './utils'
import { navigate } from 'gatsby' import { navigate } from 'gatsby'
import { updateQueryStringParameter } from '../../../utils' import { updateQueryStringParameter } from '../../../utils'
import Loader from '../../atoms/Loader' import { useSiteMetadata } from '../../../hooks/useSiteMetadata'
import { useOcean } from '../../../providers/Ocean'
export default function SearchPage({ export default function SearchPage({
location, location,
@ -19,7 +18,7 @@ export default function SearchPage({
location: Location location: Location
setTotalResults: (totalResults: number) => void setTotalResults: (totalResults: number) => void
}): ReactElement { }): ReactElement {
const { metadataCacheUri } = useOcean() const { appConfig } = useSiteMetadata()
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,18 +30,27 @@ export default function SearchPage({
) )
useEffect(() => { useEffect(() => {
if (!metadataCacheUri) return if (!appConfig.metadataCacheUri) return
async function initSearch() { async function initSearch() {
setLoading(true) setLoading(true)
setTotalResults(undefined) setTotalResults(undefined)
const queryResult = await getResults(parsed, metadataCacheUri) const queryResult = await getResults(parsed, appConfig.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,
appConfig.metadataCacheUri
])
function setPage(page: number) { function setPage(page: number) {
const newUrl = updateQueryStringParameter( const newUrl = updateQueryStringParameter(

View File

@ -12,13 +12,13 @@ export default function wrapRootElement({
}): ReactElement { }): ReactElement {
return ( return (
<Web3Provider> <Web3Provider>
<OceanProvider> {/* <OceanProvider> */}
<ApolloClientProvider> <ApolloClientProvider>
<UserPreferencesProvider> <UserPreferencesProvider>
<PricesProvider>{element}</PricesProvider> <PricesProvider>{element}</PricesProvider>
</UserPreferencesProvider> </UserPreferencesProvider>
</ApolloClientProvider> </ApolloClientProvider>
</OceanProvider> {/* </OceanProvider> */}
</Web3Provider> </Web3Provider>
) )
} }

View File

@ -20,6 +20,7 @@ interface UseSiteMetadata {
polygon: string polygon: string
} }
appConfig: { appConfig: {
metadataCacheUri: string
infuraProjectId: string infuraProjectId: string
chainIds: number[] chainIds: number[]
marketFeeAddress: string marketFeeAddress: string
@ -52,6 +53,7 @@ const query = graphql`
polygon polygon
} }
appConfig { appConfig {
metadataCacheUri
infuraProjectId infuraProjectId
chainIds chainIds
marketFeeAddress marketFeeAddress

View File

@ -2,6 +2,7 @@ import React, { ReactElement, useEffect, useState } from 'react'
import { PageProps } from 'gatsby' import { PageProps } from 'gatsby'
import PageTemplateAssetDetails from '../../components/templates/PageAssetDetails' import PageTemplateAssetDetails from '../../components/templates/PageAssetDetails'
import AssetProvider from '../../providers/Asset' import AssetProvider from '../../providers/Asset'
import OceanProvider from '../../providers/Ocean'
export default function PageGatsbyAssetDetails(props: PageProps): ReactElement { export default function PageGatsbyAssetDetails(props: PageProps): ReactElement {
const [did, setDid] = useState<string>() const [did, setDid] = useState<string>()
@ -12,7 +13,9 @@ export default function PageGatsbyAssetDetails(props: PageProps): ReactElement {
return ( return (
<AssetProvider asset={did}> <AssetProvider asset={did}>
<PageTemplateAssetDetails uri={props.location.pathname} /> <OceanProvider>
<PageTemplateAssetDetails uri={props.location.pathname} />
</OceanProvider>
</AssetProvider> </AssetProvider>
) )
} }

View File

@ -5,10 +5,11 @@ import {
InMemoryCache, InMemoryCache,
NormalizedCacheObject NormalizedCacheObject
} from '@apollo/client' } from '@apollo/client'
import { Logger, ConfigHelperConfig } from '@oceanprotocol/lib' import { Logger } from '@oceanprotocol/lib'
import { useOcean } from './Ocean'
import fetch from 'cross-fetch' import fetch from 'cross-fetch'
import React, { useState, useEffect, ReactNode, ReactElement } from 'react' import React, { useState, useEffect, ReactNode, ReactElement } from 'react'
import { useWeb3 } from './Web3'
import { getOceanConfig } from '../utils/ocean'
let apolloClient: ApolloClient<NormalizedCacheObject> let apolloClient: ApolloClient<NormalizedCacheObject>
function createClient(subgraphUri: string) { function createClient(subgraphUri: string) {
@ -32,21 +33,23 @@ export default function ApolloClientProvider({
}: { }: {
children: ReactNode children: ReactNode
}): ReactElement { }): ReactElement {
const { config } = useOcean() const { networkId } = useWeb3()
const [client, setClient] = useState<ApolloClient<NormalizedCacheObject>>() const [client, setClient] = useState<ApolloClient<NormalizedCacheObject>>()
useEffect(() => { useEffect(() => {
if (!(config as ConfigHelperConfig)?.subgraphUri) { const { subgraphUri } = getOceanConfig(networkId || 1)
if (!subgraphUri) {
Logger.error( Logger.error(
'No subgraphUri defined, preventing ApolloProvider from initialization.' 'No subgraphUri defined, preventing ApolloProvider from initialization.'
) )
return return
} }
const newClient = createClient((config as ConfigHelperConfig).subgraphUri) const newClient = createClient(subgraphUri)
apolloClient = newClient apolloClient = newClient
setClient(newClient) setClient(newClient)
}, [config]) }, [networkId])
return client ? ( return client ? (
<ApolloProvider client={client}>{children}</ApolloProvider> <ApolloProvider client={client}>{children}</ApolloProvider>

View File

@ -16,6 +16,8 @@ import { getPrice } from '../utils/subgraph'
import { MetadataMarket } from '../@types/MetaData' import { MetadataMarket } from '../@types/MetaData'
import { useOcean } from './Ocean' import { useOcean } from './Ocean'
import { useWeb3 } from './Web3' import { useWeb3 } from './Web3'
import { getOceanConfig } from '../utils/ocean'
import { useSiteMetadata } from '../hooks/useSiteMetadata'
interface AssetProviderValue { interface AssetProviderValue {
isInPurgatory: boolean isInPurgatory: boolean
@ -44,8 +46,9 @@ function AssetProvider({
asset: string | DDO asset: string | DDO
children: ReactNode children: ReactNode
}): ReactElement { }): ReactElement {
const { appConfig } = useSiteMetadata()
const { networkId } = useWeb3() const { networkId } = useWeb3()
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,7 +63,11 @@ 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(asset as string, metadataCacheUri, token) const ddo = await retrieveDDO(
asset as string,
appConfig.metadataCacheUri,
token
)
if (!ddo) { if (!ddo) {
setError( setError(
@ -82,7 +89,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 || !metadataCacheUri) return if (!asset || !appConfig.metadataCacheUri) return
const source = axios.CancelToken.source() const source = axios.CancelToken.source()
let isMounted = true let isMounted = true
@ -99,7 +106,7 @@ function AssetProvider({
isMounted = false isMounted = false
source.cancel() source.cancel()
} }
}, [asset, metadataCacheUri]) }, [asset, appConfig.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

@ -16,112 +16,59 @@ import {
} from '@oceanprotocol/lib' } from '@oceanprotocol/lib'
import { useWeb3 } from './Web3' import { useWeb3 } from './Web3'
import { import { getDevelopmentConfig, getOceanConfig } from '../utils/ocean'
getDevelopmentConfig, import { useAsset } from './Asset'
getOceanConfig,
getUserInfo
} from '../utils/ocean'
import { UserBalance } from '../@types/TokenBalance'
import { useSiteMetadata } from '../hooks/useSiteMetadata'
const refreshInterval = 20000 // 20 sec.
interface OceanProviderValue { interface OceanProviderValue {
oceanConfigs: ConfigHelperConfig[]
metadataCacheUri: string
ocean: Ocean ocean: Ocean
config: ConfigHelperConfig
account: Account account: Account
balance: UserBalance connect: (config: Config) => Promise<void>
loading: boolean
connect: (config?: Config) => Promise<void>
refreshBalance: () => Promise<void>
} }
const OceanContext = createContext({} as OceanProviderValue) const OceanContext = createContext({} as OceanProviderValue)
function OceanProvider({ children }: { children: ReactNode }): ReactElement { function OceanProvider({ children }: { children: ReactNode }): ReactElement {
const { appConfig } = useSiteMetadata() const { web3, accountId } = useWeb3()
const { web3, accountId, networkId } = useWeb3() const { ddo } = useAsset()
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>({
eth: undefined,
ocean: undefined
})
const [config, setConfig] = useState<ConfigHelperConfig | Config>()
// ----------------------------------- // -----------------------------------
// Initially get all supported configs // Helper: Create Ocean instance
// 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( const connect = useCallback(
async (config: ConfigHelperConfig | Config) => { async (config: ConfigHelperConfig | Config) => {
if (!web3) return if (!web3 || !ddo) return
const newConfig: Config = {
...config,
web3Provider: web3
}
try { try {
Logger.log('[ocean] Connecting Ocean...', config) Logger.log('[ocean] Connecting Ocean...', newConfig)
const newOcean = await Ocean.getInstance(newConfig)
config.web3Provider = web3
setConfig(config)
const newOcean = await Ocean.getInstance(config)
setOcean(newOcean) setOcean(newOcean)
Logger.log('[ocean] Ocean instance created.', newOcean) Logger.log('[ocean] Ocean instance created.', newOcean)
} catch (error) { } catch (error) {
Logger.error('[ocean] Error: ', error.message) Logger.error('[ocean] Error: ', error.message)
} }
}, },
[web3] [web3, ddo]
) )
// async function refreshBalance() {
// if (!ocean || !account || !web3) return
// const { balance } = await getUserInfo(ocean)
// setBalance(balance)
// }
// ----------------------------------- // -----------------------------------
// Initial connection // Initial connection
// ----------------------------------- // -----------------------------------
useEffect(() => { useEffect(() => {
if (!ddo?.chainId) return
const config = { const config = {
...getOceanConfig('mainnet'), ...getOceanConfig(ddo.chainId),
// add local dev values // add local dev values
...(networkId === 8996 && { ...(ddo.chainId === 8996 && {
...getDevelopmentConfig() ...getDevelopmentConfig()
}) })
} }
@ -130,39 +77,28 @@ function OceanProvider({ children }: { children: ReactNode }): ReactElement {
await connect(config) await connect(config)
} }
init() init()
}, [connect, ddo?.chainId])
// init periodic refresh of wallet balance
// const balanceInterval = setInterval(() => refreshBalance(), refreshInterval)
// return () => {
// clearInterval(balanceInterval)
// }
}, [connect, networkId])
// ----------------------------------- // -----------------------------------
// Get user info, handle account change from web3 // Get user info, handle account change from web3
// ----------------------------------- // -----------------------------------
// useEffect(() => { useEffect(() => {
// if (!ocean || !accountId || !web3) return if (!ocean || !accountId || !web3) return
// async function getInfo() { async function getInfo() {
// const { account, balance } = await getUserInfo(ocean) const account = (await ocean.accounts.list())[0]
// setAccount(account) Logger.log('[ocean] Account: ', account)
// setBalance(balance) setAccount(account)
// } }
// getInfo() getInfo()
// }, [ocean, accountId, web3]) }, [ocean, accountId, web3])
return ( return (
<OceanContext.Provider <OceanContext.Provider
value={ value={
{ {
oceanConfigs,
metadataCacheUri,
ocean, ocean,
account, account,
balance,
config,
connect connect
// refreshBalance // refreshBalance
} as OceanProviderValue } as OceanProviderValue

View File

@ -19,6 +19,8 @@ import {
getNetworkDisplayName getNetworkDisplayName
} from '../utils/web3' } from '../utils/web3'
import { graphql, useStaticQuery } from 'gatsby' import { graphql, useStaticQuery } from 'gatsby'
import { UserBalance } from '../@types/TokenBalance'
import { getOceanBalance } from '../utils/ocean'
interface Web3ProviderValue { interface Web3ProviderValue {
web3: Web3 web3: Web3
@ -26,6 +28,7 @@ interface Web3ProviderValue {
web3Modal: Web3Modal web3Modal: Web3Modal
web3ProviderInfo: IProviderInfo web3ProviderInfo: IProviderInfo
accountId: string accountId: string
balance: UserBalance
networkId: number networkId: number
networkDisplayName: string networkDisplayName: string
networkData: EthereumListsChain networkData: EthereumListsChain
@ -77,6 +80,8 @@ export const web3ModalOpts = {
theme: web3ModalTheme theme: web3ModalTheme
} }
const refreshInterval = 20000 // 20 sec.
const networksQuery = graphql` const networksQuery = graphql`
query { query {
allNetworksMetadataJson { allNetworksMetadataJson {
@ -115,7 +120,14 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement {
const [isTestnet, setIsTestnet] = useState<boolean>() const [isTestnet, setIsTestnet] = useState<boolean>()
const [accountId, setAccountId] = useState<string>() const [accountId, setAccountId] = useState<string>()
const [web3Loading, setWeb3Loading] = useState<boolean>(true) const [web3Loading, setWeb3Loading] = useState<boolean>(true)
const [balance, setBalance] = useState<UserBalance>({
eth: '0',
ocean: '0'
})
// -----------------------------------
// Helper: connect to web3
// -----------------------------------
const connect = useCallback(async () => { const connect = useCallback(async () => {
if (!web3Modal) { if (!web3Modal) {
setWeb3Loading(false) setWeb3Loading(false)
@ -146,6 +158,24 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement {
} }
}, [web3Modal]) }, [web3Modal])
// -----------------------------------
// Helper: Get user balance
// -----------------------------------
const getUserBalance = useCallback(async () => {
if (!accountId || !networkId || !web3) return
try {
const balance = {
eth: web3.utils.fromWei(await web3.eth.getBalance(accountId, 'latest')),
ocean: await getOceanBalance(accountId, networkId, web3)
}
setBalance(balance)
Logger.log('[web3] Balance: ', balance)
} catch (error) {
Logger.error('[web3] Error: ', error.message)
}
}, [accountId, networkId, web3])
// ----------------------------------- // -----------------------------------
// Create initial Web3Modal instance // Create initial Web3Modal instance
// ----------------------------------- // -----------------------------------
@ -180,6 +210,20 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement {
connectCached() connectCached()
}, [connect, web3Modal]) }, [connect, web3Modal])
// -----------------------------------
// Get and set user balance
// -----------------------------------
useEffect(() => {
getUserBalance()
// init periodic refresh of wallet balance
const balanceInterval = setInterval(() => getUserBalance(), refreshInterval)
return () => {
clearInterval(balanceInterval)
}
}, [getUserBalance])
// ----------------------------------- // -----------------------------------
// Get and set network metadata // Get and set network metadata
// ----------------------------------- // -----------------------------------
@ -274,6 +318,7 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement {
web3Modal, web3Modal,
web3ProviderInfo, web3ProviderInfo,
accountId, accountId,
balance,
networkId, networkId,
networkDisplayName, networkDisplayName,
networkData, networkData,
@ -294,3 +339,6 @@ const useWeb3 = (): Web3ProviderValue => useContext(Web3Context)
export { Web3Provider, useWeb3, Web3ProviderValue, Web3Context } export { Web3Provider, useWeb3, Web3ProviderValue, Web3Context }
export default Web3Provider export default Web3Provider
function getTokenBalance() {
throw new Error('Function not implemented.')
}

View File

@ -1,15 +1,13 @@
import { import {
Account,
Logger,
Ocean,
ConfigHelper, ConfigHelper,
ConfigHelperConfig, ConfigHelperConfig,
ConfigHelperNetworkId, ConfigHelperNetworkId,
ConfigHelperNetworkName ConfigHelperNetworkName,
Logger
} from '@oceanprotocol/lib' } from '@oceanprotocol/lib'
import contractAddresses from '@oceanprotocol/contracts/artifacts/address.json' import contractAddresses from '@oceanprotocol/contracts/artifacts/address.json'
import { AbiItem } from 'web3-utils/types'
import { UserBalance } from '../@types/TokenBalance' import Web3 from 'web3'
export function getOceanConfig( export function getOceanConfig(
network: ConfigHelperNetworkName | ConfigHelperNetworkId network: ConfigHelperNetworkName | ConfigHelperNetworkId
@ -24,11 +22,7 @@ export function getOceanConfig(
: process.env.GATSBY_INFURA_PROJECT_ID : process.env.GATSBY_INFURA_PROJECT_ID
) )
return { return config as ConfigHelperConfig
...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> {
@ -43,19 +37,54 @@ export function getDevelopmentConfig(): Partial<ConfigHelperConfig> {
} }
} }
export async function getUserInfo( export async function getOceanBalance(
ocean: Ocean accountId: string,
): Promise<{ account: Account; balance: UserBalance }> { networkId: number,
if (!ocean) return { account: null, balance: { eth: '0', ocean: '0' } } web3: Web3
): Promise<string> {
const minABI = [
{
constant: true,
inputs: [
{
name: '_owner',
type: 'address'
}
],
name: 'balanceOf',
outputs: [
{
name: 'balance',
type: 'uint256'
}
],
payable: false,
stateMutability: 'view',
type: 'function'
}
] as AbiItem[]
const account = (await ocean.accounts.list())[0] try {
Logger.log('[ocean] Account: ', account) const token = new web3.eth.Contract(
minABI,
const balance = { getOceanConfig(networkId).oceanTokenAddress,
eth: await account.getEtherBalance(), { from: accountId }
ocean: await account.getOceanBalance() )
const result = web3.utils.fromWei(
await token.methods.balanceOf(accountId).call()
)
return result
} catch (e) {
Logger.error(`ERROR: Failed to get the balance: ${e.message}`)
} }
Logger.log('[ocean] Balance: ', JSON.stringify(balance)) }
return { account, balance } export function getOceanTokenData(
networkId: number,
configs: ConfigHelperConfig[]
): { address: string; symbol: string } {
const { oceanTokenSymbol, oceanTokenAddress } = configs.filter(
(config) => config.networkId === networkId
)[0]
return { address: oceanTokenAddress, symbol: oceanTokenSymbol }
} }