From 476147f65acaf1418ce1309fc308b8525285aa17 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 26 May 2021 18:44:24 +0200 Subject: [PATCH 01/60] add network icon components --- src/components/atoms/Network.module.css | 14 +++++ src/components/atoms/Network.tsx | 55 +++++++++++++++++++ .../molecules/AssetTeaser.module.css | 13 +++-- src/components/molecules/AssetTeaser.tsx | 11 ++-- .../molecules/Wallet/Network.module.css | 2 - src/components/molecules/Wallet/Network.tsx | 9 +-- src/images/eth.svg | 8 +++ src/images/polygon.svg | 3 + 8 files changed, 100 insertions(+), 15 deletions(-) create mode 100644 src/components/atoms/Network.module.css create mode 100644 src/components/atoms/Network.tsx create mode 100644 src/images/eth.svg create mode 100644 src/images/polygon.svg diff --git a/src/components/atoms/Network.module.css b/src/components/atoms/Network.module.css new file mode 100644 index 000000000..2f03f5ac4 --- /dev/null +++ b/src/components/atoms/Network.module.css @@ -0,0 +1,14 @@ +.network { + text-transform: capitalize; + display: inline-flex; + align-items: center; + color: var(--color-secondary); +} + +.icon { + display: inline-block; + width: 1.2em; + height: 1.2em; + fill: var(--color-secondary); + margin-right: calc(var(--spacer) / 12); +} diff --git a/src/components/atoms/Network.tsx b/src/components/atoms/Network.tsx new file mode 100644 index 000000000..9c3e15726 --- /dev/null +++ b/src/components/atoms/Network.tsx @@ -0,0 +1,55 @@ +import { graphql, useStaticQuery } from 'gatsby' +import React, { FunctionComponent, ReactElement } from 'react' +import { ReactComponent as EthIcon } from '../../images/eth.svg' +import { ReactComponent as PolygonIcon } from '../../images/polygon.svg' +import { + EthereumListsChain, + getNetworkData, + getNetworkDisplayName +} from '../../utils/web3' +import styles from './Network.module.css' + +const networksQuery = graphql` + query { + allNetworksMetadataJson { + edges { + node { + chain + network + networkId + chainId + } + } + } + } +` + +const icons: { + [key: string]: FunctionComponent> +} = { ETH: EthIcon, Matic: PolygonIcon } + +export function NetworkIcon({ name }: { name: string }): ReactElement { + const IconMapped = name.includes('ETH') ? icons.ETH : icons[name.trim()] + + return IconMapped ? : null +} + +export default function Network({ + networkId, + className +}: { + networkId: number + className?: string +}): ReactElement { + const data = useStaticQuery(networksQuery) + const networksList: { node: EthereumListsChain }[] = + data.allNetworksMetadataJson.edges + const networkData = getNetworkData(networksList, networkId) + const networkName = getNetworkDisplayName(networkData, networkId) + + return ( + + {networkName} + + ) +} diff --git a/src/components/molecules/AssetTeaser.module.css b/src/components/molecules/AssetTeaser.module.css index d18707c42..de1e37c82 100644 --- a/src/components/molecules/AssetTeaser.module.css +++ b/src/components/molecules/AssetTeaser.module.css @@ -57,11 +57,6 @@ display: block; } -.date { - font-size: var(--font-size-mini); - margin-top: calc(var(--spacer) / 2); -} - .typeDetails { position: absolute; top: calc(var(--spacer) / 3); @@ -69,3 +64,11 @@ width: auto; font-size: var(--font-size-mini); } + +.network { + font-size: var(--font-size-mini); + position: absolute; + right: calc(var(--spacer) / 3); + bottom: calc(var(--spacer) / 3); + text-transform: uppercase !important; +} diff --git a/src/components/molecules/AssetTeaser.tsx b/src/components/molecules/AssetTeaser.tsx index f05bbec8e..2ffca75c0 100644 --- a/src/components/molecules/AssetTeaser.tsx +++ b/src/components/molecules/AssetTeaser.tsx @@ -6,8 +6,9 @@ import styles from './AssetTeaser.module.css' import { DDO, BestPrice } from '@oceanprotocol/lib' import removeMarkdown from 'remove-markdown' import Publisher from '../atoms/Publisher' -import Time from '../atoms/Time' import AssetType from '../atoms/AssetType' +import Network from '../atoms/Network' +import { useOcean } from '../../providers/Ocean' declare type AssetTeaserProps = { ddo: DDO @@ -18,6 +19,7 @@ const AssetTeaser: React.FC = ({ ddo, price }: AssetTeaserProps) => { + const { config } = useOcean() const { attributes } = ddo.findServiceByType('metadata') const { name, type } = attributes.main const { dataTokenInfo } = ddo @@ -52,9 +54,10 @@ const AssetTeaser: React.FC = ({
-

-

+ {/* TODO: networkId needs to come from the multinetwork DDO for each asset */} + {config?.networkId && ( + + )}
diff --git a/src/components/molecules/Wallet/Network.module.css b/src/components/molecules/Wallet/Network.module.css index 8e676b984..c01a9b01a 100644 --- a/src/components/molecules/Wallet/Network.module.css +++ b/src/components/molecules/Wallet/Network.module.css @@ -12,8 +12,6 @@ .name { font-size: var(--font-size-small); - display: inline-block; - text-transform: capitalize; } .badge { diff --git a/src/components/molecules/Wallet/Network.tsx b/src/components/molecules/Wallet/Network.tsx index 675d31f14..d66d391b6 100644 --- a/src/components/molecules/Wallet/Network.tsx +++ b/src/components/molecules/Wallet/Network.tsx @@ -2,13 +2,14 @@ import React, { useState, useEffect, ReactElement } from 'react' import { useOcean } from '../../../providers/Ocean' import Status from '../../atoms/Status' import { ConfigHelper, ConfigHelperConfig } from '@oceanprotocol/lib' -import styles from './Network.module.css' import Badge from '../../atoms/Badge' import Tooltip from '../../atoms/Tooltip' import { useWeb3 } from '../../../providers/Web3' +import NetworkName from '../../atoms/Network' +import styles from './Network.module.css' export default function Network(): ReactElement { - const { networkId, networkDisplayName, isTestnet } = useWeb3() + const { networkId, isTestnet } = useWeb3() const { config } = useOcean() const networkIdConfig = (config as ConfigHelperConfig).networkId @@ -28,14 +29,14 @@ export default function Network(): ReactElement { setIsSupportedNetwork(isSupportedNetwork) }, [networkId, networkIdConfig]) - return !isEthMainnet && networkDisplayName ? ( + return !isEthMainnet && networkId ? (
{!isSupportedNetwork && ( )} - {networkDisplayName} + {isTestnet && }
) : null diff --git a/src/images/eth.svg b/src/images/eth.svg new file mode 100644 index 000000000..6abd31517 --- /dev/null +++ b/src/images/eth.svg @@ -0,0 +1,8 @@ + + + + + + + + diff --git a/src/images/polygon.svg b/src/images/polygon.svg new file mode 100644 index 000000000..4c041a336 --- /dev/null +++ b/src/images/polygon.svg @@ -0,0 +1,3 @@ + + + From 10b29c6e375b83663c2944f734da523e736c104a Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Thu, 27 May 2021 12:51:47 +0200 Subject: [PATCH 02/60] unify network names, more icons --- src/components/atoms/AssetType.module.css | 12 +++++++++ src/components/atoms/AssetType.tsx | 19 +++++++++++--- ...work.module.css => NetworkName.module.css} | 0 .../atoms/{Network.tsx => NetworkName.tsx} | 24 +++++++++++++----- src/components/molecules/AssetTeaser.tsx | 8 ++---- .../molecules/UserPreferences/Chain.tsx | 14 ++++++++--- src/components/molecules/Wallet/Network.tsx | 2 +- src/images/moonbeam.svg | 16 ++++++++++++ src/utils/web3.ts | 25 +++++++++++++++---- 9 files changed, 95 insertions(+), 25 deletions(-) rename src/components/atoms/{Network.module.css => NetworkName.module.css} (100%) rename src/components/atoms/{Network.tsx => NetworkName.tsx} (65%) create mode 100644 src/images/moonbeam.svg diff --git a/src/components/atoms/AssetType.module.css b/src/components/atoms/AssetType.module.css index a578aa0f8..0c16f1982 100644 --- a/src/components/atoms/AssetType.module.css +++ b/src/components/atoms/AssetType.module.css @@ -13,4 +13,16 @@ border-right: 1px solid var(--border-color); padding-right: calc(var(--spacer) / 3.5); margin-right: calc(var(--spacer) / 4); + border-left: 1px solid var(--border-color); + padding-left: calc(var(--spacer) / 3.5); + margin-left: calc(var(--spacer) / 4); +} + +.network { + display: inline-block; +} + +.network svg { + vertical-align: baseline; + margin-bottom: -0.1em; } diff --git a/src/components/atoms/AssetType.tsx b/src/components/atoms/AssetType.tsx index c1776ec20..235d72b5d 100644 --- a/src/components/atoms/AssetType.tsx +++ b/src/components/atoms/AssetType.tsx @@ -4,6 +4,8 @@ import classNames from 'classnames/bind' import { ReactComponent as Compute } from '../../images/compute.svg' import { ReactComponent as Download } from '../../images/download.svg' import { ReactComponent as Lock } from '../../images/lock.svg' +import NetworkName from './NetworkName' +import { useOcean } from '../../providers/Ocean' const cx = classNames.bind(styles) @@ -16,14 +18,13 @@ export default function AssetType({ accessType: string className?: string }): ReactElement { + const { config } = useOcean() + const styleClasses = cx({ [className]: className }) return (
-
- {type === 'dataset' ? 'data set' : 'algorithm'} -
{accessType === 'access' ? ( ) : accessType === 'compute' && type === 'algorithm' ? ( @@ -31,6 +32,18 @@ export default function AssetType({ ) : ( )} + +
+ {type === 'dataset' ? 'data set' : 'algorithm'} +
+ {/* TODO: networkId needs to come from the multinetwork DDO for each asset */} + {config?.networkId && ( + + )}
) } diff --git a/src/components/atoms/Network.module.css b/src/components/atoms/NetworkName.module.css similarity index 100% rename from src/components/atoms/Network.module.css rename to src/components/atoms/NetworkName.module.css diff --git a/src/components/atoms/Network.tsx b/src/components/atoms/NetworkName.tsx similarity index 65% rename from src/components/atoms/Network.tsx rename to src/components/atoms/NetworkName.tsx index 9c3e15726..502b16e76 100644 --- a/src/components/atoms/Network.tsx +++ b/src/components/atoms/NetworkName.tsx @@ -2,12 +2,13 @@ import { graphql, useStaticQuery } from 'gatsby' import React, { FunctionComponent, ReactElement } from 'react' import { ReactComponent as EthIcon } from '../../images/eth.svg' import { ReactComponent as PolygonIcon } from '../../images/polygon.svg' +import { ReactComponent as MoonbeamIcon } from '../../images/moonbeam.svg' import { EthereumListsChain, getNetworkData, getNetworkDisplayName } from '../../utils/web3' -import styles from './Network.module.css' +import styles from './NetworkName.module.css' const networksQuery = graphql` query { @@ -26,19 +27,27 @@ const networksQuery = graphql` const icons: { [key: string]: FunctionComponent> -} = { ETH: EthIcon, Matic: PolygonIcon } +} = { ETH: EthIcon, Polygon: PolygonIcon, Moonbeam: MoonbeamIcon } export function NetworkIcon({ name }: { name: string }): ReactElement { - const IconMapped = name.includes('ETH') ? icons.ETH : icons[name.trim()] + const IconMapped = name.includes('ETH') + ? icons.ETH + : name.includes('Polygon') + ? icons.Polygon + : name.includes('Moon') + ? icons.Moonbeam + : icons[name.trim()] return IconMapped ? : null } -export default function Network({ +export default function NetworkName({ networkId, + minimal, className }: { networkId: number + minimal?: boolean className?: string }): ReactElement { const data = useStaticQuery(networksQuery) @@ -48,8 +57,11 @@ export default function Network({ const networkName = getNetworkDisplayName(networkData, networkId) return ( - - {networkName} + + {!minimal && networkName} ) } diff --git a/src/components/molecules/AssetTeaser.tsx b/src/components/molecules/AssetTeaser.tsx index 2ffca75c0..82e91f9ae 100644 --- a/src/components/molecules/AssetTeaser.tsx +++ b/src/components/molecules/AssetTeaser.tsx @@ -2,13 +2,13 @@ import React from 'react' import { Link } from 'gatsby' import Dotdotdot from 'react-dotdotdot' import Price from '../atoms/Price' -import styles from './AssetTeaser.module.css' import { DDO, BestPrice } from '@oceanprotocol/lib' import removeMarkdown from 'remove-markdown' import Publisher from '../atoms/Publisher' import AssetType from '../atoms/AssetType' -import Network from '../atoms/Network' +import NetworkName from '../atoms/NetworkName' import { useOcean } from '../../providers/Ocean' +import styles from './AssetTeaser.module.css' declare type AssetTeaserProps = { ddo: DDO @@ -54,10 +54,6 @@ const AssetTeaser: React.FC = ({
- {/* TODO: networkId needs to come from the multinetwork DDO for each asset */} - {config?.networkId && ( - - )}
diff --git a/src/components/molecules/UserPreferences/Chain.tsx b/src/components/molecules/UserPreferences/Chain.tsx index 71cad403b..312e861ba 100644 --- a/src/components/molecules/UserPreferences/Chain.tsx +++ b/src/components/molecules/UserPreferences/Chain.tsx @@ -6,6 +6,9 @@ import { getOceanConfig } from '../../../utils/ocean' import FormHelp from '../../atoms/Input/Help' import Label from '../../atoms/Input/Label' import BoxSelection, { BoxSelectionOption } from '../FormFields/BoxSelection' +import { ReactComponent as EthIcon } from '../../../images/eth.svg' +import { ReactComponent as PolygonIcon } from '../../../images/polygon.svg' +import { ReactComponent as MoonbeamIcon } from '../../../images/moonbeam.svg' import styles from './Chain.module.css' export default function Chain(): ReactElement { @@ -26,19 +29,22 @@ export default function Chain(): ReactElement { name: 'mainnet', checked: isNetworkSelected('mainnet'), title: 'ETH', - text: 'Mainnet' + text: 'Mainnet', + icon: }, { name: 'polygon', checked: isNetworkSelected('polygon'), - title: 'Polygon/Matic', - text: 'Mainnet' + title: 'Polygon', + text: 'Mainnet', + icon: }, { name: 'moonbeamalpha', checked: isNetworkSelected('moonbeamalpha'), title: 'Moonbase Alpha', - text: 'Testnet' + text: 'Testnet', + icon: } ] diff --git a/src/components/molecules/Wallet/Network.tsx b/src/components/molecules/Wallet/Network.tsx index d66d391b6..26fbf363b 100644 --- a/src/components/molecules/Wallet/Network.tsx +++ b/src/components/molecules/Wallet/Network.tsx @@ -5,7 +5,7 @@ import { ConfigHelper, ConfigHelperConfig } from '@oceanprotocol/lib' import Badge from '../../atoms/Badge' import Tooltip from '../../atoms/Tooltip' import { useWeb3 } from '../../../providers/Web3' -import NetworkName from '../../atoms/Network' +import NetworkName from '../../atoms/NetworkName' import styles from './Network.module.css' export default function Network(): ReactElement { diff --git a/src/images/moonbeam.svg b/src/images/moonbeam.svg new file mode 100644 index 000000000..b649d23f1 --- /dev/null +++ b/src/images/moonbeam.svg @@ -0,0 +1,16 @@ + + + + + + + + + + + + + + + + diff --git a/src/utils/web3.ts b/src/utils/web3.ts index d35841009..fa5ce829a 100644 --- a/src/utils/web3.ts +++ b/src/utils/web3.ts @@ -30,11 +30,26 @@ export function getNetworkDisplayName( data: EthereumListsChain, networkId: number ): string { - const displayName = data - ? `${data.chain} ${data.network === 'mainnet' ? '' : data.network}` - : networkId === 8996 - ? 'Development' - : 'Unknown' + if (!data) return 'Unknown' + + let displayName + + switch (networkId) { + case 1287: + displayName = 'Moonbase Alpha' + break + case 137: + displayName = 'Polygon' + break + case 8996: + displayName = 'Development' + break + default: + displayName = `${data.chain} ${ + data.network === 'mainnet' ? '' : data.network + }` + break + } return displayName } From fa682dad1ed85ae7237ef110d45fef6f04d0ffea Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Thu, 27 May 2021 13:01:14 +0200 Subject: [PATCH 03/60] show network at all times in wallet component --- src/components/molecules/Wallet/Network.tsx | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/components/molecules/Wallet/Network.tsx b/src/components/molecules/Wallet/Network.tsx index 26fbf363b..8118a940f 100644 --- a/src/components/molecules/Wallet/Network.tsx +++ b/src/components/molecules/Wallet/Network.tsx @@ -13,15 +13,12 @@ export default function Network(): ReactElement { const { config } = useOcean() const networkIdConfig = (config as ConfigHelperConfig).networkId - const [isEthMainnet, setIsEthMainnet] = useState() const [isSupportedNetwork, setIsSupportedNetwork] = useState() useEffect(() => { // take network from user when present, // otherwise use the default configured one of app const network = networkId || networkIdConfig - const isEthMainnet = network === 1 - setIsEthMainnet(isEthMainnet) // Check networkId against ocean.js ConfigHelper configs // to figure out if network is supported. @@ -29,7 +26,7 @@ export default function Network(): ReactElement { setIsSupportedNetwork(isSupportedNetwork) }, [networkId, networkIdConfig]) - return !isEthMainnet && networkId ? ( + return networkId ? (
{!isSupportedNetwork && ( From 9d7486d626e623d8ac84a70435bb757532a65604 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Thu, 27 May 2021 13:58:52 +0200 Subject: [PATCH 04/60] prototype network feedback based on asset network checks --- src/components/atoms/AssetType.module.css | 2 +- .../molecules/MetadataPreview.module.css | 1 - src/components/molecules/MetadataPreview.tsx | 10 ++++++++- src/components/molecules/Wallet/Details.tsx | 2 +- .../molecules/Wallet/index.stories.tsx | 2 +- ...ack.module.css => Web3Feedback.module.css} | 3 +-- .../{Wallet/Feedback.tsx => Web3Feedback.tsx} | 22 ++++++++++++++----- .../Compute/FormComputeDataset.tsx | 4 ++-- .../organisms/AssetActions/Compute/index.tsx | 6 +---- .../organisms/AssetActions/Consume.tsx | 8 +++---- .../organisms/AssetActions/Edit/index.tsx | 2 +- .../organisms/AssetActions/index.tsx | 15 +++++++++++-- src/components/pages/Publish/index.tsx | 2 +- src/providers/Asset.tsx | 17 +++++++++++++- 14 files changed, 66 insertions(+), 30 deletions(-) rename src/components/molecules/{Wallet/Feedback.module.css => Web3Feedback.module.css} (85%) rename src/components/molecules/{Wallet/Feedback.tsx => Web3Feedback.tsx} (68%) diff --git a/src/components/atoms/AssetType.module.css b/src/components/atoms/AssetType.module.css index 0c16f1982..814a2d575 100644 --- a/src/components/atoms/AssetType.module.css +++ b/src/components/atoms/AssetType.module.css @@ -24,5 +24,5 @@ .network svg { vertical-align: baseline; - margin-bottom: -0.1em; + margin-bottom: -0.15em; } diff --git a/src/components/molecules/MetadataPreview.module.css b/src/components/molecules/MetadataPreview.module.css index e14eab2a9..c440d7ef1 100644 --- a/src/components/molecules/MetadataPreview.module.css +++ b/src/components/molecules/MetadataPreview.module.css @@ -33,7 +33,6 @@ } .datatoken { - margin-top: calc(var(--spacer) / 8); margin-bottom: 0; color: var(--color-secondary); } diff --git a/src/components/molecules/MetadataPreview.tsx b/src/components/molecules/MetadataPreview.tsx index a1a85c126..852c7b8f9 100644 --- a/src/components/molecules/MetadataPreview.tsx +++ b/src/components/molecules/MetadataPreview.tsx @@ -3,7 +3,6 @@ import { File as FileMetadata } from '@oceanprotocol/lib/dist/node/ddo/interface import Markdown from '../atoms/Markdown' import Tags from '../atoms/Tags' import MetaItem from '../organisms/AssetContent/MetaItem' -import styles from './MetadataPreview.module.css' import File from '../atoms/File' import { MetadataPublishFormDataset, @@ -11,6 +10,9 @@ import { } from '../../@types/MetaData' import Button from '../atoms/Button' import { transformTags } from '../../utils/metadata' +import NetworkName from '../atoms/NetworkName' +import { useWeb3 } from '../../providers/Web3' +import styles from './MetadataPreview.module.css' function Description({ description }: { description: string }) { const [fullDescription, setFullDescription] = useState(false) @@ -92,10 +94,13 @@ export function MetadataPreview({ }: { values: Partial }): ReactElement { + const { networkId } = useWeb3() + return (

Preview

+ {networkId && } {values.name &&

{values.name}

} {values.dataTokenOptions?.name && (

}): ReactElement { + const { networkId } = useWeb3() + return (

Preview

+ {networkId && } {values.name &&

{values.name}

} {values.dataTokenOptions?.name && (

= useFormikContext() - const { price, ddo } = useAsset() + const { price, ddo, isAssetNetwork } = useAsset() const [totalPrice, setTotalPrice] = useState(price?.value) function getAlgorithmAsset(algorithmId: string): DDO { @@ -149,7 +149,7 @@ export default function FormStartCompute({ () @@ -418,9 +417,6 @@ export default function Compute({ action={} /> )} - {type !== 'algorithm' && ( - - )} ) diff --git a/src/components/organisms/AssetActions/Consume.tsx b/src/components/organisms/AssetActions/Consume.tsx index fd5d3e78a..5044c567e 100644 --- a/src/components/organisms/AssetActions/Consume.tsx +++ b/src/components/organisms/AssetActions/Consume.tsx @@ -3,7 +3,6 @@ import { toast } from 'react-toastify' import { File as FileMetadata, DDO } from '@oceanprotocol/lib' import File from '../../atoms/File' import Price from '../../atoms/Price' -import Web3Feedback from '../../molecules/Wallet/Feedback' import styles from './Consume.module.css' import { useSiteMetadata } from '../../../hooks/useSiteMetadata' import { useAsset } from '../../../providers/Asset' @@ -47,7 +46,7 @@ export default function Consume({ const { appConfig } = useSiteMetadata() const [hasPreviousOrder, setHasPreviousOrder] = useState(false) const [previousOrderId, setPreviousOrderId] = useState() - const { isInPurgatory, price, type } = useAsset() + const { isInPurgatory, price, type, isAssetNetwork } = useAsset() const { buyDT, pricingStepText, pricingError, pricingIsLoading } = usePricing() const { consumeStepText, consume, consumeError } = useConsume() @@ -105,6 +104,7 @@ export default function Consume({ setIsDisabled( (!ocean || !isBalanceSufficient || + !isAssetNetwork || typeof consumeStepText !== 'undefined' || pricingIsLoading || !isConsumable) && @@ -115,6 +115,7 @@ export default function Consume({ ocean, hasPreviousOrder, isBalanceSufficient, + isAssetNetwork, consumeStepText, pricingIsLoading, isConsumable, @@ -166,9 +167,6 @@ export default function Consume({ {!isInPurgatory && }

-
- -
) } diff --git a/src/components/organisms/AssetActions/Edit/index.tsx b/src/components/organisms/AssetActions/Edit/index.tsx index dfafa3a6f..5d5e7b537 100644 --- a/src/components/organisms/AssetActions/Edit/index.tsx +++ b/src/components/organisms/AssetActions/Edit/index.tsx @@ -9,7 +9,7 @@ import { useAsset } from '../../../../providers/Asset' import { useUserPreferences } from '../../../../providers/UserPreferences' import { MetadataPreview } from '../../../molecules/MetadataPreview' import Debug from './DebugEditMetadata' -import Web3Feedback from '../../../molecules/Wallet/Feedback' +import Web3Feedback from '../../../molecules/Web3Feedback' import FormEditMetadata from './FormEditMetadata' import { mapTimeoutStringToSeconds } from '../../../../utils/metadata' import styles from './index.module.css' diff --git a/src/components/organisms/AssetActions/index.tsx b/src/components/organisms/AssetActions/index.tsx index 967760a57..81f89ba6f 100644 --- a/src/components/organisms/AssetActions/index.tsx +++ b/src/components/organisms/AssetActions/index.tsx @@ -10,11 +10,12 @@ import Trade from './Trade' import { useAsset } from '../../../providers/Asset' import { useOcean } from '../../../providers/Ocean' import { useWeb3 } from '../../../providers/Web3' +import Web3Feedback from '../../molecules/Web3Feedback' export default function AssetActions(): ReactElement { const { accountId } = useWeb3() const { ocean, balance, account } = useOcean() - const { price, ddo, metadata } = useAsset() + const { price, ddo, metadata, type, isAssetNetwork } = useAsset() const [isBalanceSufficient, setIsBalanceSufficient] = useState() const [dtBalance, setDtBalance] = useState() @@ -85,5 +86,15 @@ export default function AssetActions(): ReactElement { } ) - return + return ( + <> + + {type !== 'algorithm' && ( + + )} + + ) } diff --git a/src/components/pages/Publish/index.tsx b/src/components/pages/Publish/index.tsx index 31dce4427..a5b08b4cd 100644 --- a/src/components/pages/Publish/index.tsx +++ b/src/components/pages/Publish/index.tsx @@ -4,7 +4,7 @@ import { usePublish } from '../../../hooks/usePublish' import styles from './index.module.css' import FormPublish from './FormPublish' import FormAlgoPublish from './FormAlgoPublish' -import Web3Feedback from '../../molecules/Wallet/Feedback' +import Web3Feedback from '../../molecules/Web3Feedback' import Tabs from '../../atoms/Tabs' import { initialValues, validationSchema } from '../../../models/FormPublish' import { diff --git a/src/providers/Asset.tsx b/src/providers/Asset.tsx index f49bf6ef2..b8bfc1ee7 100644 --- a/src/providers/Asset.tsx +++ b/src/providers/Asset.tsx @@ -15,6 +15,7 @@ import { retrieveDDO } from '../utils/aquarius' import { getPrice } from '../utils/subgraph' import { MetadataMarket } from '../@types/MetaData' import { useOcean } from './Ocean' +import { useWeb3 } from './Web3' interface AssetProviderValue { isInPurgatory: boolean @@ -28,6 +29,7 @@ interface AssetProviderValue { type: MetadataMain['type'] | undefined error?: string refreshInterval: number + isAssetNetwork: boolean refreshDdo: (token?: CancelToken) => Promise } @@ -42,6 +44,7 @@ function AssetProvider({ asset: string | DDO children: ReactNode }): ReactElement { + const { networkId } = useWeb3() const { config } = useOcean() const [isInPurgatory, setIsInPurgatory] = useState(false) const [purgatoryData, setPurgatoryData] = useState() @@ -53,6 +56,7 @@ function AssetProvider({ const [owner, setOwner] = useState() const [error, setError] = useState() const [type, setType] = useState() + const [isAssetNetwork, setIsAssetNetwork] = useState() const fetchDdo = async (token?: CancelToken) => { Logger.log('[asset] Init asset, get DDO') @@ -137,6 +141,16 @@ function AssetProvider({ initMetadata(ddo) }, [ddo, initMetadata]) + // Check user network against asset network + useEffect(() => { + if (!networkId || !ddo) return + + // TODO: replace with actual check against multinetwork DDO + // const isAssetNetwork = networkId === ddo.networkId + const isAssetNetwork = true + setIsAssetNetwork(isAssetNetwork) + }, [networkId, ddo]) + return ( From 6bc37b9b7bf65ea95c18588046dcc0e07d2579fe Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Thu, 27 May 2021 14:01:20 +0200 Subject: [PATCH 05/60] remove NetworkBanner --- src/components/App.tsx | 5 +- src/components/molecules/NetworkBanner.tsx | 84 ---------------------- 2 files changed, 1 insertion(+), 88 deletions(-) delete mode 100644 src/components/molecules/NetworkBanner.tsx diff --git a/src/components/App.tsx b/src/components/App.tsx index a4fc74a0f..99ab88e0c 100644 --- a/src/components/App.tsx +++ b/src/components/App.tsx @@ -7,10 +7,9 @@ import Styles from '../global/Styles' import { useWeb3 } from '../providers/Web3' import { useSiteMetadata } from '../hooks/useSiteMetadata' import { useAccountPurgatory } from '../hooks/useAccountPurgatory' -import NetworkBanner from './molecules/NetworkBanner' -import styles from './App.module.css' import AnnouncementBanner from './atoms/AnnouncementBanner' import { useGraphSyncStatus } from '../hooks/useGraphSyncStatus' +import styles from './App.module.css' const contentQuery = graphql` query AppQuery { @@ -52,8 +51,6 @@ export default function App({ state="error" /> )} - {!location.pathname.includes('/asset/did') && } -
{(props as PageProps).uri === '/' && ( diff --git a/src/components/molecules/NetworkBanner.tsx b/src/components/molecules/NetworkBanner.tsx deleted file mode 100644 index 57dba707f..000000000 --- a/src/components/molecules/NetworkBanner.tsx +++ /dev/null @@ -1,84 +0,0 @@ -import React, { ReactElement, useEffect, useState } from 'react' -import { useWeb3 } from '../../providers/Web3' -import { addCustomNetwork, NetworkObject } from '../../utils/web3' -import { getOceanConfig } from '../../utils/ocean' -import { useOcean } from '../../providers/Ocean' -import { useSiteMetadata } from '../../hooks/useSiteMetadata' -import AnnouncementBanner, { - AnnouncementAction -} from '../atoms/AnnouncementBanner' - -const networkMatic: NetworkObject = { - chainId: 137, - name: 'Matic Network', - urlList: [ - 'https://rpc-mainnet.matic.network', - 'https://rpc-mainnet.maticvigil.com/' - ] -} - -export default function NetworkBanner(): ReactElement { - const { web3Provider, web3ProviderInfo } = useWeb3() - const { config, connect } = useOcean() - const { announcement } = useSiteMetadata() - - const [text, setText] = useState(announcement.main) - const [action, setAction] = useState() - - const addCustomNetworkAction = { - name: 'Add custom network', - handleAction: () => addCustomNetwork(web3Provider, networkMatic) - } - const switchToPolygonAction = { - name: 'Switch to Polygon', - handleAction: async () => { - const config = getOceanConfig('polygon') - await connect(config) - } - } - const switchToEthAction = { - name: 'Switch to ETH', - handleAction: async () => { - const config = getOceanConfig('mainnet') - await connect(config) - } - } - - function setBannerForMatic() { - setText(announcement.polygon) - setAction(undefined) - } - - useEffect(() => { - if (!web3ProviderInfo || (!web3Provider && !config)) return - - switch (web3ProviderInfo.name) { - case 'Web3': - if (config.networkId !== 137) { - setText(announcement.main) - setAction(switchToPolygonAction) - } else { - setText(announcement.polygon) - setAction(switchToEthAction) - } - break - case 'MetaMask': - if (config.networkId === 137) { - setBannerForMatic() - } else { - setText(announcement.main) - setAction(addCustomNetworkAction) - } - break - default: - if (config.networkId === 137) { - setBannerForMatic() - } else { - setText(announcement.main) - setAction(undefined) - } - } - }, [web3Provider, web3ProviderInfo, config, announcement]) - - return -} From 3332249928ed87d4e08f367cf47df2e9cd907aaa Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Fri, 28 May 2021 14:47:47 +0200 Subject: [PATCH 06/60] 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 { From 21792e9d4fedc7d1c8abe751517c456444b0869a Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Mon, 31 May 2021 14:27:04 +0200 Subject: [PATCH 07/60] move OceanProvider to asset route --- README.md | 12 +- app.config.js | 1 + package-lock.json | 2 + src/components/molecules/AssetListTitle.tsx | 13 +- src/components/molecules/Bookmarks.tsx | 9 +- src/components/molecules/Wallet/Details.tsx | 36 ++++-- .../organisms/AssetActions/Compute/index.tsx | 6 +- .../Edit/FormEditComputeDataset.tsx | 10 +- .../pages/History/ComputeJobs/Details.tsx | 11 +- .../pages/History/ComputeJobs/index.tsx | 10 +- src/components/pages/Home.tsx | 51 +++++--- src/components/templates/Search/index.tsx | 20 ++- src/helpers/wrapRootElement.tsx | 14 +- src/hooks/useSiteMetadata.ts | 2 + src/pages/asset/index.tsx | 5 +- src/providers/ApolloClientProvider.tsx | 15 ++- src/providers/Asset.tsx | 15 ++- src/providers/Ocean.tsx | 122 +++++------------- src/providers/Web3.tsx | 48 +++++++ src/utils/ocean.ts | 77 +++++++---- 20 files changed, 287 insertions(+), 192 deletions(-) diff --git a/README.md b/README.md index 03af3a048..44d87ec70 100644 --- a/README.md +++ b/README.md @@ -132,15 +132,19 @@ const queryLatest = { } function Component() { - const { metadataCacheUri } = useOcean() + const { appConfig } = useSiteMetadata() const [result, setResult] = useState() useEffect(() => { - if (!metadataCacheUri) return + if (!appConfig.metadataCacheUri) return const source = axios.CancelToken.source() async function init() { - const result = await queryMetadata(query, metadataCacheUri, source.token) + const result = await queryMetadata( + query, + appConfig.metadataCacheUri, + source.token + ) setResult(result) } init() @@ -148,7 +152,7 @@ function Component() { return () => { source.cancel() } - }, [metadataCacheUri, query]) + }, [appConfig.metadataCacheUri, query]) return
    {result}
    } diff --git a/app.config.js b/app.config.js index 9226d2f28..cdcfe7228 100644 --- a/app.config.js +++ b/app.config.js @@ -1,4 +1,5 @@ module.exports = { + metadataCacheUri: 'https://aquarius.mainnet.oceanprotocol.com', // List of supported chainIds which metadata cache queries // will return by default chainIds: [1, 3, 4, 137, 1287], diff --git a/package-lock.json b/package-lock.json index 744c08cc1..95f89b505 100644 --- a/package-lock.json +++ b/package-lock.json @@ -43525,6 +43525,7 @@ "node-abort-controller": "^2.0.0", "save-file": "^2.3.1", "uuid": "^8.3.2", + "web3": "^1.3.5", "web3-eth-contract": "^1.3.6" } }, @@ -43599,6 +43600,7 @@ "integrity": "sha512-5vwpq6kbvwkQwKqAoOU3L72GZ3Ta8RRrewKj9OJRolx28KLJJ8Dg9Rf7obRwt5jQA9bkYd8gqzMTrI7H3xLfaw==", "dev": true, "requires": { + "@oclif/config": "^1.15.1", "@oclif/errors": "^1.3.3", "@oclif/parser": "^3.8.3", "@oclif/plugin-help": "^3", diff --git a/src/components/molecules/AssetListTitle.tsx b/src/components/molecules/AssetListTitle.tsx index 7b93b24fa..815a7f8d2 100644 --- a/src/components/molecules/AssetListTitle.tsx +++ b/src/components/molecules/AssetListTitle.tsx @@ -5,6 +5,7 @@ import React, { ReactElement, useEffect, useState } from 'react' import { getAssetsNames } from '../../utils/aquarius' import styles from './AssetListTitle.module.css' import axios from 'axios' +import { useSiteMetadata } from '../../hooks/useSiteMetadata' export default function AssetListTitle({ ddo, @@ -15,11 +16,11 @@ export default function AssetListTitle({ did?: string title?: string }): ReactElement { - const { metadataCacheUri } = useOcean() + const { appConfig } = useSiteMetadata() const [assetTitle, setAssetTitle] = useState(title) useEffect(() => { - if (title || !metadataCacheUri) return + if (title || !appConfig.metadataCacheUri) return if (ddo) { const { attributes } = ddo.findServiceByType('metadata') setAssetTitle(attributes.main.name) @@ -29,7 +30,11 @@ export default function AssetListTitle({ const source = axios.CancelToken.source() async function getAssetName() { - const title = await getAssetsNames([did], metadataCacheUri, source.token) + const title = await getAssetsNames( + [did], + appConfig.metadataCacheUri, + source.token + ) setAssetTitle(title[did]) } @@ -38,7 +43,7 @@ export default function AssetListTitle({ return () => { source.cancel() } - }, [assetTitle, metadataCacheUri, ddo, did, title]) + }, [assetTitle, appConfig.metadataCacheUri, ddo, did, title]) return (

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

    () + const [oceanTokenMetadata, setOceanTokenMetadata] = + useState<{ + address: string + symbol: string + }>() // const [portisNetwork, setPortisNetwork] = useState() useEffect(() => { if (!networkData) return setMainCurrency(networkData.nativeCurrency.symbol) - }, [networkData]) + + oceanConfigs && + setOceanTokenMetadata(getOceanTokenData(networkId || 1, oceanConfigs)) + }, [networkData, networkId, oceanConfigs]) // Handle network change for Portis // async function handlePortisNetworkChange(e: ChangeEvent) { @@ -38,17 +54,17 @@ export default function Details(): ReactElement { return (
      - {/* {Object.entries(balance).map(([key, value]) => ( + {Object.entries(balance).map(([key, value]) => (
    • - {key === 'eth' ? mainCurrency : config.oceanTokenSymbol} + {key === 'eth' ? mainCurrency : oceanTokenMetadata?.symbol} {' '} {formatCurrency(Number(value), '', locale, false, { significantFigures: 4 })} {key === 'ocean' && }
    • - ))} */} + ))}
    • @@ -66,14 +82,14 @@ export default function Details(): ReactElement { onChange={handlePortisNetworkChange} /> )} */} - {/* {web3ProviderInfo?.name === 'MetaMask' && ( + {web3ProviderInfo?.name === 'MetaMask' && ( - )} */} + )}

      {web3ProviderInfo?.name === 'Portis' && ( diff --git a/src/components/organisms/AssetActions/Compute/index.tsx b/src/components/organisms/AssetActions/Compute/index.tsx index 8cc9a4f74..53ef7b592 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, metadataCacheUri } = useOcean() + const { ocean, account } = 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 ), - metadataCacheUri, + appConfig.metadataCacheUri, source.token ) setDdoAlgorithmList(gueryResults.results) algorithmSelectionList = await transformDDOToAssetSelection( gueryResults.results, - metadataCacheUri, + appConfig.metadataCacheUri, [] ) } diff --git a/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx b/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx index 3b769b72a..c806e02b2 100644 --- a/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx +++ b/src/components/organisms/AssetActions/Edit/FormEditComputeDataset.tsx @@ -16,6 +16,7 @@ import { useAsset } from '../../../../providers/Asset' import { ComputePrivacyForm } from '../../../../models/FormEditComputeDataset' import { publisherTrustedAlgorithm as PublisherTrustedAlgorithm } from '@oceanprotocol/lib' import axios from 'axios' +import { useSiteMetadata } from '../../../../hooks/useSiteMetadata' export default function FormEditComputeDataset({ data, @@ -26,8 +27,9 @@ export default function FormEditComputeDataset({ title: string setShowEdit: (show: boolean) => void }): ReactElement { + const { appConfig } = useSiteMetadata() const { accountId } = useWeb3() - const { ocean, metadataCacheUri } = useOcean() + const { ocean } = useOcean() const { ddo } = useAsset() const { isValid, values }: FormikContextType = useFormikContext() @@ -51,12 +53,12 @@ export default function FormEditComputeDataset({ } const querryResult = await queryMetadata( query, - metadataCacheUri, + appConfig.metadataCacheUri, source.token ) const algorithmSelectionList = await transformDDOToAssetSelection( querryResult.results, - metadataCacheUri, + appConfig.metadataCacheUri, publisherTrustedAlgorithms ) return algorithmSelectionList @@ -66,7 +68,7 @@ export default function FormEditComputeDataset({ getAlgorithmList(publisherTrustedAlgorithms).then((algorithms) => { setAllAlgorithms(algorithms) }) - }, [metadataCacheUri, publisherTrustedAlgorithms]) + }, [appConfig.metadataCacheUri, publisherTrustedAlgorithms]) return ( diff --git a/src/components/pages/History/ComputeJobs/Details.tsx b/src/components/pages/History/ComputeJobs/Details.tsx index 88d1e19fa..9a7e378f0 100644 --- a/src/components/pages/History/ComputeJobs/Details.tsx +++ b/src/components/pages/History/ComputeJobs/Details.tsx @@ -10,6 +10,7 @@ import { retrieveDDO } from '../../../../utils/aquarius' import { useOcean } from '../../../../providers/Ocean' import Results from './Results' import styles from './Details.module.css' +import { useSiteMetadata } from '../../../../hooks/useSiteMetadata' function Asset({ title, @@ -41,7 +42,7 @@ function Asset({ } function DetailsAssets({ job }: { job: ComputeJobMetaData }) { - const { metadataCacheUri } = useOcean() + const { appConfig } = useSiteMetadata() const [algoName, setAlgoName] = useState() const [algoDtSymbol, setAlgoDtSymbol] = useState() @@ -49,14 +50,18 @@ function DetailsAssets({ job }: { job: ComputeJobMetaData }) { async function getAlgoMetadata() { 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) const { attributes } = ddo.findServiceByType('metadata') setAlgoName(attributes?.main.name) } getAlgoMetadata() - }, [metadataCacheUri, job.algoDID]) + }, [appConfig.metadataCacheUri, job.algoDID]) return ( <> diff --git a/src/components/pages/History/ComputeJobs/index.tsx b/src/components/pages/History/ComputeJobs/index.tsx index 49fd6da26..86f428b28 100644 --- a/src/components/pages/History/ComputeJobs/index.tsx +++ b/src/components/pages/History/ComputeJobs/index.tsx @@ -17,6 +17,7 @@ import Details from './Details' import { ComputeJob } from '@oceanprotocol/lib/dist/node/ocean/interfaces/Compute' import { ReactComponent as Refresh } from '../../../../images/refresh.svg' import styles from './index.module.css' +import { useSiteMetadata } from '../../../../hooks/useSiteMetadata' const getComputeOrders = gql` query ComputeOrders($user: String!) { @@ -99,7 +100,8 @@ async function getAssetMetadata( } export default function ComputeJobs(): ReactElement { - const { ocean, account, metadataCacheUri, config } = useOcean() + const { appConfig } = useSiteMetadata() + const { ocean, account } = useOcean() const { accountId } = useWeb3() const [isLoading, setIsLoading] = useState(true) const [jobs, setJobs] = useState([]) @@ -128,7 +130,7 @@ export default function ComputeJobs(): ReactElement { const source = axios.CancelToken.source() const assets = await getAssetMetadata( queryDtList, - metadataCacheUri, + appConfig.metadataCacheUri, source.token ) const providers: Provider[] = [] @@ -232,12 +234,12 @@ export default function ComputeJobs(): ReactElement { } useEffect(() => { - if (data === undefined || !metadataCacheUri) { + if (data === undefined || !appConfig.metadataCacheUri) { setIsLoading(false) return } getJobs() - }, [ocean, account, data, metadataCacheUri]) + }, [ocean, account, data, appConfig.metadataCacheUri]) return ( <> diff --git a/src/components/pages/Home.tsx b/src/components/pages/Home.tsx index a7b6458ca..5627bf857 100644 --- a/src/components/pages/Home.tsx +++ b/src/components/pages/Home.tsx @@ -15,16 +15,21 @@ import { queryMetadata } from '../../utils/aquarius' import { getHighestLiquidityDIDs } from '../../utils/subgraph' import { DDO, Logger } from '@oceanprotocol/lib' import { useWeb3 } from '../../providers/Web3' +import { useSiteMetadata } from '../../hooks/useSiteMetadata' +import { getOceanConfig } from '../../utils/ocean' -const queryLatest = { - page: 1, - offset: 9, - query: { - query_string: { - query: `-isInPurgatory:true` - } - }, - sort: { created: -1 } +// TODO: these queries need to adapt to chainIds +function getQueryHighest(chainIds: number[]) { + return { + page: 1, + offset: 9, + query: { + query_string: { + query: `(price.type:pool) -isInPurgatory:true` + } + }, + sort: { 'price.ocean': -1 } + } } function sortElements(items: DDO[], sorted: string[]) { @@ -34,6 +39,20 @@ function sortElements(items: DDO[], sorted: string[]) { return items } +function getQueryLatest(chainIds: number[]) { + return { + page: 1, + offset: 9, + query: { + query_string: { + query: `-isInPurgatory:true` + } + }, + sort: { created: -1 } + } + return items +} + function SectionQueryResult({ title, query, @@ -45,12 +64,12 @@ function SectionQueryResult({ action?: ReactElement queryData?: string }) { - const { metadataCacheUri } = useOcean() + const { appConfig } = useSiteMetadata() const [result, setResult] = useState() const [loading, setLoading] = useState() useEffect(() => { - if (!metadataCacheUri) return + if (!appConfig.metadataCacheUri) return const source = axios.CancelToken.source() async function init() { @@ -58,7 +77,7 @@ function SectionQueryResult({ setLoading(true) const result = await queryMetadata( query, - metadataCacheUri, + appConfig.metadataCacheUri, source.token ) if (result.totalResults <= 15) { @@ -83,7 +102,7 @@ function SectionQueryResult({ return () => { source.cancel() } - }, [metadataCacheUri, query]) + }, [appConfig.metadataCacheUri, query]) return (

      @@ -99,8 +118,9 @@ function SectionQueryResult({ } 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 { appConfig } = useSiteMetadata() const { web3Loading, web3Provider } = useWeb3() useEffect(() => { @@ -135,13 +155,14 @@ export default function HomePage(): ReactElement { )} All data sets and algorithms → diff --git a/src/components/templates/Search/index.tsx b/src/components/templates/Search/index.tsx index 66a1c3437..1e92eb50e 100644 --- a/src/components/templates/Search/index.tsx +++ b/src/components/templates/Search/index.tsx @@ -9,8 +9,7 @@ import Sort from './sort' import { getResults } from './utils' import { navigate } from 'gatsby' import { updateQueryStringParameter } from '../../../utils' -import Loader from '../../atoms/Loader' -import { useOcean } from '../../../providers/Ocean' +import { useSiteMetadata } from '../../../hooks/useSiteMetadata' export default function SearchPage({ location, @@ -19,7 +18,7 @@ export default function SearchPage({ location: Location setTotalResults: (totalResults: number) => void }): ReactElement { - const { metadataCacheUri } = useOcean() + const { appConfig } = useSiteMetadata() const parsed = queryString.parse(location.search) const { text, owner, tags, page, sort, sortOrder, serviceType } = parsed const [queryResult, setQueryResult] = useState() @@ -31,18 +30,27 @@ export default function SearchPage({ ) useEffect(() => { - if (!metadataCacheUri) return + if (!appConfig.metadataCacheUri) return async function initSearch() { setLoading(true) setTotalResults(undefined) - const queryResult = await getResults(parsed, metadataCacheUri) + const queryResult = await getResults(parsed, appConfig.metadataCacheUri) setQueryResult(queryResult) setTotalResults(queryResult.totalResults) setLoading(false) } initSearch() - }, [text, owner, tags, sort, page, serviceType, sortOrder, metadataCacheUri]) + }, [ + text, + owner, + tags, + sort, + page, + serviceType, + sortOrder, + appConfig.metadataCacheUri + ]) function setPage(page: number) { const newUrl = updateQueryStringParameter( diff --git a/src/helpers/wrapRootElement.tsx b/src/helpers/wrapRootElement.tsx index 3ad24560f..0efd88f55 100644 --- a/src/helpers/wrapRootElement.tsx +++ b/src/helpers/wrapRootElement.tsx @@ -12,13 +12,13 @@ export default function wrapRootElement({ }): ReactElement { return ( - - - - {element} - - - + {/* */} + + + {element} + + + {/* */} ) } diff --git a/src/hooks/useSiteMetadata.ts b/src/hooks/useSiteMetadata.ts index 63cef169a..b68e24eb7 100644 --- a/src/hooks/useSiteMetadata.ts +++ b/src/hooks/useSiteMetadata.ts @@ -20,6 +20,7 @@ interface UseSiteMetadata { polygon: string } appConfig: { + metadataCacheUri: string infuraProjectId: string chainIds: number[] marketFeeAddress: string @@ -52,6 +53,7 @@ const query = graphql` polygon } appConfig { + metadataCacheUri infuraProjectId chainIds marketFeeAddress diff --git a/src/pages/asset/index.tsx b/src/pages/asset/index.tsx index 61d335698..fb0ffb184 100644 --- a/src/pages/asset/index.tsx +++ b/src/pages/asset/index.tsx @@ -2,6 +2,7 @@ import React, { ReactElement, useEffect, useState } from 'react' import { PageProps } from 'gatsby' import PageTemplateAssetDetails from '../../components/templates/PageAssetDetails' import AssetProvider from '../../providers/Asset' +import OceanProvider from '../../providers/Ocean' export default function PageGatsbyAssetDetails(props: PageProps): ReactElement { const [did, setDid] = useState() @@ -12,7 +13,9 @@ export default function PageGatsbyAssetDetails(props: PageProps): ReactElement { return ( - + + + ) } diff --git a/src/providers/ApolloClientProvider.tsx b/src/providers/ApolloClientProvider.tsx index ec60215ee..3f34df684 100644 --- a/src/providers/ApolloClientProvider.tsx +++ b/src/providers/ApolloClientProvider.tsx @@ -5,10 +5,11 @@ import { InMemoryCache, NormalizedCacheObject } from '@apollo/client' -import { Logger, ConfigHelperConfig } from '@oceanprotocol/lib' -import { useOcean } from './Ocean' +import { Logger } from '@oceanprotocol/lib' import fetch from 'cross-fetch' import React, { useState, useEffect, ReactNode, ReactElement } from 'react' +import { useWeb3 } from './Web3' +import { getOceanConfig } from '../utils/ocean' let apolloClient: ApolloClient function createClient(subgraphUri: string) { @@ -32,21 +33,23 @@ export default function ApolloClientProvider({ }: { children: ReactNode }): ReactElement { - const { config } = useOcean() + const { networkId } = useWeb3() const [client, setClient] = useState>() useEffect(() => { - if (!(config as ConfigHelperConfig)?.subgraphUri) { + const { subgraphUri } = getOceanConfig(networkId || 1) + + if (!subgraphUri) { Logger.error( 'No subgraphUri defined, preventing ApolloProvider from initialization.' ) return } - const newClient = createClient((config as ConfigHelperConfig).subgraphUri) + const newClient = createClient(subgraphUri) apolloClient = newClient setClient(newClient) - }, [config]) + }, [networkId]) return client ? ( {children} diff --git a/src/providers/Asset.tsx b/src/providers/Asset.tsx index 9df9857c3..8fb5b2a3b 100644 --- a/src/providers/Asset.tsx +++ b/src/providers/Asset.tsx @@ -16,6 +16,8 @@ import { getPrice } from '../utils/subgraph' import { MetadataMarket } from '../@types/MetaData' import { useOcean } from './Ocean' import { useWeb3 } from './Web3' +import { getOceanConfig } from '../utils/ocean' +import { useSiteMetadata } from '../hooks/useSiteMetadata' interface AssetProviderValue { isInPurgatory: boolean @@ -44,8 +46,9 @@ function AssetProvider({ asset: string | DDO children: ReactNode }): ReactElement { + const { appConfig } = useSiteMetadata() + const { networkId } = useWeb3() - const { metadataCacheUri } = useOcean() const [isInPurgatory, setIsInPurgatory] = useState(false) const [purgatoryData, setPurgatoryData] = useState() const [ddo, setDDO] = useState() @@ -60,7 +63,11 @@ function AssetProvider({ const fetchDdo = async (token?: CancelToken) => { 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) { setError( @@ -82,7 +89,7 @@ function AssetProvider({ // Get and set DDO based on passed DDO or DID // useEffect(() => { - if (!asset || !metadataCacheUri) return + if (!asset || !appConfig.metadataCacheUri) return const source = axios.CancelToken.source() let isMounted = true @@ -99,7 +106,7 @@ function AssetProvider({ isMounted = false source.cancel() } - }, [asset, metadataCacheUri]) + }, [asset, appConfig.metadataCacheUri]) const setPurgatory = useCallback(async (did: string): Promise => { if (!did) return diff --git a/src/providers/Ocean.tsx b/src/providers/Ocean.tsx index 93cfdc52c..6add08d0e 100644 --- a/src/providers/Ocean.tsx +++ b/src/providers/Ocean.tsx @@ -16,112 +16,59 @@ import { } from '@oceanprotocol/lib' import { useWeb3 } from './Web3' -import { - getDevelopmentConfig, - getOceanConfig, - getUserInfo -} from '../utils/ocean' -import { UserBalance } from '../@types/TokenBalance' -import { useSiteMetadata } from '../hooks/useSiteMetadata' - -const refreshInterval = 20000 // 20 sec. +import { getDevelopmentConfig, getOceanConfig } from '../utils/ocean' +import { useAsset } from './Asset' interface OceanProviderValue { - oceanConfigs: ConfigHelperConfig[] - metadataCacheUri: string ocean: Ocean - config: ConfigHelperConfig account: Account - balance: UserBalance - loading: boolean - connect: (config?: Config) => Promise - refreshBalance: () => Promise + connect: (config: Config) => Promise } const OceanContext = createContext({} as OceanProviderValue) function OceanProvider({ children }: { children: ReactNode }): ReactElement { - const { appConfig } = useSiteMetadata() - const { web3, accountId, networkId } = useWeb3() + const { web3, accountId } = useWeb3() + const { ddo } = useAsset() - 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() // ----------------------------------- - // 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 + // Helper: Create Ocean instance // ----------------------------------- const connect = useCallback( async (config: ConfigHelperConfig | Config) => { - if (!web3) return + if (!web3 || !ddo) return + + const newConfig: Config = { + ...config, + web3Provider: web3 + } try { - Logger.log('[ocean] Connecting Ocean...', config) - - config.web3Provider = web3 - setConfig(config) - - const newOcean = await Ocean.getInstance(config) + Logger.log('[ocean] Connecting Ocean...', newConfig) + const newOcean = await Ocean.getInstance(newConfig) setOcean(newOcean) Logger.log('[ocean] Ocean instance created.', newOcean) } catch (error) { 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 // ----------------------------------- useEffect(() => { + if (!ddo?.chainId) return + const config = { - ...getOceanConfig('mainnet'), + ...getOceanConfig(ddo.chainId), // add local dev values - ...(networkId === 8996 && { + ...(ddo.chainId === 8996 && { ...getDevelopmentConfig() }) } @@ -130,39 +77,28 @@ function OceanProvider({ children }: { children: ReactNode }): ReactElement { await connect(config) } init() - - // init periodic refresh of wallet balance - // const balanceInterval = setInterval(() => refreshBalance(), refreshInterval) - - // return () => { - // clearInterval(balanceInterval) - // } - }, [connect, networkId]) + }, [connect, ddo?.chainId]) // ----------------------------------- // 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]) + async function getInfo() { + const account = (await ocean.accounts.list())[0] + Logger.log('[ocean] Account: ', account) + setAccount(account) + } + getInfo() + }, [ocean, accountId, web3]) return ( () const [accountId, setAccountId] = useState() const [web3Loading, setWeb3Loading] = useState(true) + const [balance, setBalance] = useState({ + eth: '0', + ocean: '0' + }) + // ----------------------------------- + // Helper: connect to web3 + // ----------------------------------- const connect = useCallback(async () => { if (!web3Modal) { setWeb3Loading(false) @@ -146,6 +158,24 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement { } }, [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 // ----------------------------------- @@ -180,6 +210,20 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement { connectCached() }, [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 // ----------------------------------- @@ -274,6 +318,7 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement { web3Modal, web3ProviderInfo, accountId, + balance, networkId, networkDisplayName, networkData, @@ -294,3 +339,6 @@ const useWeb3 = (): Web3ProviderValue => useContext(Web3Context) export { Web3Provider, useWeb3, Web3ProviderValue, Web3Context } export default Web3Provider +function getTokenBalance() { + throw new Error('Function not implemented.') +} diff --git a/src/utils/ocean.ts b/src/utils/ocean.ts index 652f6e6da..3d10a17c0 100644 --- a/src/utils/ocean.ts +++ b/src/utils/ocean.ts @@ -1,15 +1,13 @@ import { - Account, - Logger, - Ocean, ConfigHelper, ConfigHelperConfig, ConfigHelperNetworkId, - ConfigHelperNetworkName + ConfigHelperNetworkName, + Logger } from '@oceanprotocol/lib' import contractAddresses from '@oceanprotocol/contracts/artifacts/address.json' - -import { UserBalance } from '../@types/TokenBalance' +import { AbiItem } from 'web3-utils/types' +import Web3 from 'web3' export function getOceanConfig( network: ConfigHelperNetworkName | ConfigHelperNetworkId @@ -24,11 +22,7 @@ export function getOceanConfig( : process.env.GATSBY_INFURA_PROJECT_ID ) - return { - ...config, - // TODO: remove faking one Aquarius for all networks - metadataCacheUri: 'https://aquarius.mainnet.oceanprotocol.com' - } as ConfigHelperConfig + return config as ConfigHelperConfig } export function getDevelopmentConfig(): Partial { @@ -43,19 +37,54 @@ export function getDevelopmentConfig(): Partial { } } -export async function getUserInfo( - ocean: Ocean -): Promise<{ account: Account; balance: UserBalance }> { - if (!ocean) return { account: null, balance: { eth: '0', ocean: '0' } } +export async function getOceanBalance( + accountId: string, + networkId: number, + web3: Web3 +): Promise { + 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] - Logger.log('[ocean] Account: ', account) - - const balance = { - eth: await account.getEtherBalance(), - ocean: await account.getOceanBalance() + try { + const token = new web3.eth.Contract( + minABI, + getOceanConfig(networkId).oceanTokenAddress, + { from: accountId } + ) + 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 } } From fa5c2ed684d9b0613bb49fff4da123ed27fe3732 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Fri, 4 Jun 2021 15:27:41 +0200 Subject: [PATCH 08/60] refactor new frontpage queries --- src/components/pages/Home.tsx | 59 +++++++++++++++-------------------- 1 file changed, 26 insertions(+), 33 deletions(-) diff --git a/src/components/pages/Home.tsx b/src/components/pages/Home.tsx index 5627bf857..a9a227574 100644 --- a/src/components/pages/Home.tsx +++ b/src/components/pages/Home.tsx @@ -18,28 +18,28 @@ import { useWeb3 } from '../../providers/Web3' import { useSiteMetadata } from '../../hooks/useSiteMetadata' import { getOceanConfig } from '../../utils/ocean' -// TODO: these queries need to adapt to chainIds -function getQueryHighest(chainIds: number[]) { - return { +async function getQueryHighest( + chainIds: number[] +): Promise<[SearchQuery, string]> { + const dids = await getHighestLiquidityDIDs() + + // TODO: this query needs to adapt to chainIds + const queryHighest = { page: 1, - offset: 9, + offset: 15, query: { query_string: { - query: `(price.type:pool) -isInPurgatory:true` + query: `(${dids}) AND -isInPurgatory:true`, + fields: ['dataToken'] } - }, - sort: { 'price.ocean': -1 } + } } + + return [queryHighest, dids] } -function sortElements(items: DDO[], sorted: string[]) { - items.sort(function (a, b) { - return sorted.indexOf(a.dataToken) - sorted.indexOf(b.dataToken) - }) - return items -} - -function getQueryLatest(chainIds: number[]) { +function getQueryLatest(chainIds: number[]): SearchQuery { + // TODO: this query needs to adapt to chainIds return { page: 1, offset: 9, @@ -50,6 +50,12 @@ function getQueryLatest(chainIds: number[]) { }, sort: { created: -1 } } +} + +function sortElements(items: DDO[], sorted: string[]) { + items.sort(function (a, b) { + return sorted.indexOf(a.dataToken) - sorted.indexOf(b.dataToken) + }) return items } @@ -102,7 +108,7 @@ function SectionQueryResult({ return () => { source.cancel() } - }, [appConfig.metadataCacheUri, query]) + }, [appConfig.metadataCacheUri, query, queryData]) return (
      @@ -118,27 +124,15 @@ function SectionQueryResult({ } export default function HomePage(): ReactElement { - // TODO: appConfig.chainIds needs to come from UserPreferences instead const [queryAndDids, setQueryAndDids] = useState<[SearchQuery, string]>() + // TODO: appConfig.chainIds needs to come from UserPreferences instead const { appConfig } = useSiteMetadata() - const { web3Loading, web3Provider } = useWeb3() useEffect(() => { - if (loading || (web3Loading && web3Provider)) return - getHighestLiquidityDIDs().then((results) => { - const queryHighest = { - page: 1, - offset: 15, - query: { - query_string: { - query: `(${results}) AND -isInPurgatory:true`, - fields: ['dataToken'] - } - } - } - setQueryAndDids([queryHighest, results]) + getQueryHighest(appConfig.chainIds).then((results) => { + setQueryAndDids(results) }) - }, [config.subgraphUri, loading, web3Loading]) + }, [appConfig.chainIds]) return ( <> @@ -155,7 +149,6 @@ export default function HomePage(): ReactElement { )} From 796fc6be81ba51b55d0429424de94a46e13871b3 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Fri, 4 Jun 2021 15:50:24 +0200 Subject: [PATCH 09/60] get all screens to render again --- app.config.js | 5 ++++- src/components/atoms/AssetType.tsx | 4 ++-- src/components/atoms/ExplorerLink.tsx | 4 ++-- .../molecules/FormFields/FilesInput/index.tsx | 13 +++++-------- src/components/organisms/AssetContent/index.tsx | 2 +- src/components/pages/History/PublishedList.tsx | 9 ++++++--- src/components/pages/Home.tsx | 3 --- src/providers/Ocean.tsx | 6 +++++- 8 files changed, 25 insertions(+), 21 deletions(-) diff --git a/app.config.js b/app.config.js index cdcfe7228..4d3c8f82a 100644 --- a/app.config.js +++ b/app.config.js @@ -1,5 +1,8 @@ module.exports = { - metadataCacheUri: 'https://aquarius.mainnet.oceanprotocol.com', + metadataCacheUri: + process.env.METADATACACHE_URI || + 'https://aquarius.mainnet.oceanprotocol.com', + // List of supported chainIds which metadata cache queries // will return by default chainIds: [1, 3, 4, 137, 1287], diff --git a/src/components/atoms/AssetType.tsx b/src/components/atoms/AssetType.tsx index 235d72b5d..7a3878551 100644 --- a/src/components/atoms/AssetType.tsx +++ b/src/components/atoms/AssetType.tsx @@ -37,9 +37,9 @@ export default function AssetType({ {type === 'dataset' ? 'data set' : 'algorithm'}
    {/* TODO: networkId needs to come from the multinetwork DDO for each asset */} - {config?.networkId && ( + {(config?.networkId || 1) && ( diff --git a/src/components/atoms/ExplorerLink.tsx b/src/components/atoms/ExplorerLink.tsx index 4104e4e86..bde8f5fad 100644 --- a/src/components/atoms/ExplorerLink.tsx +++ b/src/components/atoms/ExplorerLink.tsx @@ -26,13 +26,13 @@ export default function ExplorerLink({ }) useEffect(() => { - setUrl((config as ConfigHelperConfig).explorerUri) + setUrl((config as ConfigHelperConfig)?.explorerUri) }, [config]) return ( () - const { config } = useOcean() function loadFileInfo() { const source = axios.CancelToken.source() async function validateUrl() { + // TODO: get the providerUri + const providerUri = '' + try { setIsLoading(true) - const checkedFile = await fileinfo( - fileUrl, - config.providerUri, - source.token - ) + const checkedFile = await fileinfo(fileUrl, providerUri, source.token) checkedFile && helpers.setValue([checkedFile]) } catch (error) { toast.error('Could not fetch file info. Please check URL and try again') @@ -43,7 +40,7 @@ export default function FilesInput(props: InputProps): ReactElement { useEffect(() => { loadFileInfo() - }, [fileUrl, config.providerUri]) + }, [fileUrl]) async function handleButtonClick(e: React.SyntheticEvent, url: string) { // hack so the onBlur-triggered validation does not show, diff --git a/src/components/organisms/AssetContent/index.tsx b/src/components/organisms/AssetContent/index.tsx index abd48cbe6..ef4550209 100644 --- a/src/components/organisms/AssetContent/index.tsx +++ b/src/components/organisms/AssetContent/index.tsx @@ -80,7 +80,7 @@ export default function AssetContent(props: AssetContentProps): ReactElement { {showPricing && }
    - + {/* */} {isInPurgatory ? ( () const [isLoading, setIsLoading] = useState(false) @@ -20,6 +21,8 @@ export default function PublishedList(): ReactElement { useEffect(() => { async function getPublished() { if (!accountId) return + + // TODO: this query needs to adapt to chainIds const queryPublishedAssets = { page: page, offset: 9, @@ -34,7 +37,7 @@ export default function PublishedList(): ReactElement { queryResult || setIsLoading(true) const result = await queryMetadata( queryPublishedAssets, - metadataCacheUri, + appConfig.metadataCacheUri, source.token ) setQueryResult(result) @@ -45,7 +48,7 @@ export default function PublishedList(): ReactElement { } } getPublished() - }, [accountId, page, metadataCacheUri]) + }, [accountId, page, appConfig.metadataCacheUri]) return accountId ? ( Promise } @@ -33,6 +34,7 @@ function OceanProvider({ children }: { children: ReactNode }): ReactElement { const [ocean, setOcean] = useState() const [account, setAccount] = useState() + const [config, setConfig] = useState() // ----------------------------------- // Helper: Create Ocean instance @@ -50,6 +52,7 @@ function OceanProvider({ children }: { children: ReactNode }): ReactElement { Logger.log('[ocean] Connecting Ocean...', newConfig) const newOcean = await Ocean.getInstance(newConfig) setOcean(newOcean) + setConfig(newConfig) Logger.log('[ocean] Ocean instance created.', newOcean) } catch (error) { Logger.error('[ocean] Error: ', error.message) @@ -99,7 +102,8 @@ function OceanProvider({ children }: { children: ReactNode }): ReactElement { { ocean, account, - connect + connect, + config // refreshBalance } as OceanProviderValue } From 15b036f462661c1a6633f775601702eac196d266 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Tue, 8 Jun 2021 10:46:53 +0200 Subject: [PATCH 10/60] capture chainIds in user preferences provider --- src/providers/UserPreferences.tsx | 28 ++++++++++++++++++++++------ 1 file changed, 22 insertions(+), 6 deletions(-) diff --git a/src/providers/UserPreferences.tsx b/src/providers/UserPreferences.tsx index 7e877df38..96325b78b 100644 --- a/src/providers/UserPreferences.tsx +++ b/src/providers/UserPreferences.tsx @@ -6,17 +6,20 @@ import React, { useState, useEffect } from 'react' -import { Logger, LogLevel, ConfigHelperConfig } from '@oceanprotocol/lib' -import { useOcean } from './Ocean' +import { Logger, LogLevel } from '@oceanprotocol/lib' import { isBrowser } from '../utils' +import { useSiteMetadata } from '../hooks/useSiteMetadata' interface UserPreferencesValue { debug: boolean currency: string locale: string + chainIds: number[] bookmarks: { [network: string]: string[] } + addChainId: (chain: number) => void + removeChainId: (chain: number) => void setDebug: (value: boolean) => void setCurrency: (value: string) => void addBookmark: (did: string) => void @@ -45,8 +48,7 @@ function UserPreferencesProvider({ }: { children: ReactNode }): ReactElement { - // const { config } = useOcean() - // const networkName = (config as ConfigHelperConfig).network + const { appConfig } = useSiteMetadata() const localStorage = getLocalStorage() // Set default values from localStorage @@ -55,12 +57,13 @@ function UserPreferencesProvider({ localStorage?.currency || 'EUR' ) const [locale, setLocale] = useState() + const [chainIds, setChainIds] = useState(appConfig.chainIds) const [bookmarks, setBookmarks] = useState(localStorage?.bookmarks || {}) // Write values to localStorage on change useEffect(() => { - setLocalStorage({ debug, currency, bookmarks }) - }, [debug, currency, bookmarks]) + setLocalStorage({ chainIds, debug, currency, bookmarks }) + }, [chainIds, debug, currency, bookmarks]) // Set ocean.js log levels, default: Error useEffect(() => { @@ -75,6 +78,16 @@ function UserPreferencesProvider({ setLocale(window.navigator.language) }, []) + function addChainId(chain: number): void { + const newChainIds = [...chainIds, chain] + setChainIds(newChainIds) + } + + function removeChainId(chain: number): void { + const newChainIds = chainIds.filter((chainId) => chainId !== chain) + setChainIds(newChainIds) + } + // function addBookmark(didToAdd: string): void { // const newPinned = { // ...bookmarks, @@ -107,7 +120,10 @@ function UserPreferencesProvider({ debug, currency, locale, + chainIds, bookmarks, + addChainId, + removeChainId, setDebug, setCurrency // addBookmark, From ef218a9d9e9a8ae4e2f72b161bdf4a120ac67157 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 9 Jun 2021 11:45:36 +0200 Subject: [PATCH 11/60] chainId switching mechanism --- app.config.js | 9 +- src/components/atoms/NetworkName.module.css | 4 +- .../UserPreferences/Chain.module.css | 51 ++++++----- .../molecules/UserPreferences/Chain.tsx | 87 +++++++++---------- .../molecules/UserPreferences/Debug.tsx | 12 ++- .../UserPreferences/index.module.css | 8 +- .../molecules/UserPreferences/index.tsx | 4 +- .../pages/History/PublishedList.tsx | 9 +- src/components/pages/Home.tsx | 10 +-- src/hooks/useSiteMetadata.ts | 2 + src/providers/UserPreferences.tsx | 20 ++--- src/utils/index.ts | 8 ++ 12 files changed, 112 insertions(+), 112 deletions(-) diff --git a/app.config.js b/app.config.js index 4d3c8f82a..756154b8f 100644 --- a/app.config.js +++ b/app.config.js @@ -3,9 +3,12 @@ module.exports = { process.env.METADATACACHE_URI || 'https://aquarius.mainnet.oceanprotocol.com', - // List of supported chainIds which metadata cache queries - // will return by default - chainIds: [1, 3, 4, 137, 1287], + // List of chainIds which metadata cache queries will return by default. + // This preselects the Chains user preferences. + chainIds: [1, 137], + + // List of all supported chainIds. Used to populate the Chains user preferences list. + chainIdsSupported: [1, 3, 4, 137, 1287], infuraProjectId: process.env.GATSBY_INFURA_PROJECT_ID || 'xxx', diff --git a/src/components/atoms/NetworkName.module.css b/src/components/atoms/NetworkName.module.css index 2f03f5ac4..13ff67afb 100644 --- a/src/components/atoms/NetworkName.module.css +++ b/src/components/atoms/NetworkName.module.css @@ -9,6 +9,6 @@ display: inline-block; width: 1.2em; height: 1.2em; - fill: var(--color-secondary); - margin-right: calc(var(--spacer) / 12); + fill: currentColor; + margin-right: calc(var(--spacer) / 8); } diff --git a/src/components/molecules/UserPreferences/Chain.module.css b/src/components/molecules/UserPreferences/Chain.module.css index 568fc76cb..10f587861 100644 --- a/src/components/molecules/UserPreferences/Chain.module.css +++ b/src/components/molecules/UserPreferences/Chain.module.css @@ -1,30 +1,37 @@ -.buttons { - composes: buttons from './Appearance.module.css'; +.chains { + composes: box from '../../atoms/Box.module.css'; + box-shadow: none; + padding: 0; } -.button { - composes: button from './Appearance.module.css'; +.radioWrap { + composes: radioWrap from '../../atoms/Input/InputElement.module.css'; + padding: calc(var(--spacer) / 6) calc(var(--spacer) / 3); + border-bottom: 1px solid var(--border-color); } -.button span { - display: block; - font-size: var(--font-size-small); - font-family: var(--font-family-base); +.radioWrap:last-child { + border-bottom: none; +} + +.input { + composes: checkbox from '../../atoms/Input/InputElement.module.css'; + vertical-align: baseline; + margin-right: calc(var(--spacer) / 3); + margin-top: 0; +} + +.radioLabel { + composes: radioLabel from '../../atoms/Input/InputElement.module.css'; font-weight: var(--font-weight-base); - margin-top: calc(var(--spacer) / 10); + display: flex; + align-items: center; + margin: 0; + padding: 0; + width: 100%; } -.selected { - composes: selected from './Appearance.module.css'; -} - -.chains div[class*='boxSelectionsWrapper'] { - display: grid; - gap: calc(var(--spacer) / 4); - grid-template-columns: repeat(auto-fit, minmax(6rem, 1fr)); - padding-bottom: calc(var(--spacer) / 8); -} - -.chains label[class*='boxSelection'] { - padding: calc(var(--spacer) / 3) calc(var(--spacer) / 4) !important; +.input:checked + span { + color: var(--font-color-text); + font-weight: var(--font-weight-bold); } diff --git a/src/components/molecules/UserPreferences/Chain.tsx b/src/components/molecules/UserPreferences/Chain.tsx index 628a25410..f3b1e5f46 100644 --- a/src/components/molecules/UserPreferences/Chain.tsx +++ b/src/components/molecules/UserPreferences/Chain.tsx @@ -1,59 +1,50 @@ -import { ConfigHelperConfig } from '@oceanprotocol/lib' -import React, { ReactElement, ChangeEvent } from 'react' -import { useOcean } from '../../../providers/Ocean' -import { getOceanConfig } from '../../../utils/ocean' -import FormHelp from '../../atoms/Input/Help' +import React, { ChangeEvent, ReactElement } from 'react' import Label from '../../atoms/Input/Label' -import BoxSelection, { BoxSelectionOption } from '../FormFields/BoxSelection' -import { ReactComponent as EthIcon } from '../../../images/eth.svg' -import { ReactComponent as PolygonIcon } from '../../../images/polygon.svg' -import { ReactComponent as MoonbeamIcon } from '../../../images/moonbeam.svg' +import { useUserPreferences } from '../../../providers/UserPreferences' +import { useSiteMetadata } from '../../../hooks/useSiteMetadata' +import NetworkName from '../../atoms/NetworkName' +import { removeItemFromArray } from '../../../utils' +import FormHelp from '../../atoms/Input/Help' import styles from './Chain.module.css' export default function Chain(): ReactElement { - const { config, connect } = useOcean() + const { appConfig } = useSiteMetadata() + const { chainIds, setChainIds } = useUserPreferences() - async function connectOcean(event: ChangeEvent) { - const config = getOceanConfig(event.target.value) - await connect(config) + function handleChainChanged(e: ChangeEvent) { + const { value } = e.target + + // storing all chainId everywhere as a number so convert from here + const valueAsNumber = Number(value) + + const newChainIds = chainIds.includes(valueAsNumber) + ? [...removeItemFromArray(chainIds, valueAsNumber)] + : [...chainIds, valueAsNumber] + setChainIds(newChainIds) } - function isNetworkSelected(oceanConfig: string) { - return (config as ConfigHelperConfig).network === oceanConfig - } - - const options: BoxSelectionOption[] = [ - { - name: 'mainnet', - checked: isNetworkSelected('mainnet'), - title: 'ETH', - text: 'Mainnet', - icon: - }, - { - name: 'polygon', - checked: isNetworkSelected('polygon'), - title: 'Polygon', - text: 'Mainnet', - icon: - }, - { - name: 'moonbeamalpha', - checked: isNetworkSelected('moonbeamalpha'), - title: 'Moonbase Alpha', - text: 'Testnet', - icon: - } - ] - return ( -
  • - - +
  • + +
    + {appConfig.chainIdsSupported.map((chainId) => ( +
    + +
    + ))} +
    + Switch the data source for the interface.
  • ) diff --git a/src/components/molecules/UserPreferences/Debug.tsx b/src/components/molecules/UserPreferences/Debug.tsx index 5aef8a52e..ce1630e07 100644 --- a/src/components/molecules/UserPreferences/Debug.tsx +++ b/src/components/molecules/UserPreferences/Debug.tsx @@ -1,23 +1,21 @@ import React, { ReactElement } from 'react' import { useUserPreferences } from '../../../providers/UserPreferences' -import FormHelp from '../../atoms/Input/Help' -import InputElement from '../../atoms/Input/InputElement' +import Input from '../../atoms/Input' export default function Debug(): ReactElement { const { debug, setDebug } = useUserPreferences() return (
  • - setDebug(!debug)} /> - - Show geeky information in some places, and in your console. -
  • ) } diff --git a/src/components/molecules/UserPreferences/index.module.css b/src/components/molecules/UserPreferences/index.module.css index 1adc1a58c..922dd6c25 100644 --- a/src/components/molecules/UserPreferences/index.module.css +++ b/src/components/molecules/UserPreferences/index.module.css @@ -40,16 +40,16 @@ max-width: 20rem; } -.preferencesDetails li > div, -.preferencesDetails li p { - margin: 0; +.preferencesDetails > li > div, +.preferencesDetails p:last-child { + margin-bottom: 0; } .preferencesDetails li p { margin-top: calc(var(--spacer) / 8); } -.preferencesDetails li { +.preferencesDetails > li { padding-top: calc(var(--spacer) / 3); padding-bottom: calc(var(--spacer) / 3); } diff --git a/src/components/molecules/UserPreferences/index.tsx b/src/components/molecules/UserPreferences/index.tsx index 1c5a1ae30..7c4c861b4 100644 --- a/src/components/molecules/UserPreferences/index.tsx +++ b/src/components/molecules/UserPreferences/index.tsx @@ -11,16 +11,16 @@ import { darkModeConfig } from '../../../../app.config' import Chain from './Chain' export default function UserPreferences(): ReactElement { - // Calling this here because is not mounted on first load + // Calling this here because