From 8074a6143cf56ec6d79786fbd55f2c1d243c31ce Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Thu, 3 Feb 2022 14:31:43 +0000 Subject: [PATCH 1/2] Refactor Asset context provider (#1055) * refactor Asset context provider * use useIsMounted hook * typings and effect tweaks * use chainId * effect tweak --- src/@context/Asset.tsx | 136 +++++++++--------- src/@utils/accessDetailsAndPricing.ts | 49 ++++--- src/components/@shared/AssetList/index.tsx | 2 +- .../@shared/AssetTeaser/AssetTeaser.tsx | 21 ++- .../@shared/TokenApproval/index.tsx | 4 +- .../@shared/WalletNetworkSwitcher/index.tsx | 10 +- .../Compute/FormComputeDataset.tsx | 14 +- .../AssetActions/Compute/PriceOutput.tsx | 4 +- .../Asset/AssetActions/Pool/index.tsx | 43 +++--- .../Asset/AssetActions/Trade/FormTrade.tsx | 6 +- .../Asset/AssetActions/Trade/Swap.tsx | 18 ++- .../Asset/AssetActions/Trade/index.tsx | 16 +-- src/components/Asset/AssetActions/index.tsx | 58 ++++---- .../Asset/AssetContent/EditHistory.tsx | 17 +-- src/components/Asset/AssetContent/index.tsx | 14 +- .../Asset/Edit/EditComputeDataset.tsx | 4 +- .../Asset/Edit/FormEditComputeDataset.tsx | 8 +- src/components/Asset/Edit/index.tsx | 10 +- src/components/Asset/index.tsx | 11 +- .../Profile/History/ComputeJobs/index.tsx | 4 +- src/components/Publish/Preview/index.tsx | 2 +- 21 files changed, 216 insertions(+), 235 deletions(-) diff --git a/src/@context/Asset.tsx b/src/@context/Asset.tsx index f66a863bc..d6e78a654 100644 --- a/src/@context/Asset.tsx +++ b/src/@context/Asset.tsx @@ -7,7 +7,7 @@ import React, { useCallback, ReactNode } from 'react' -import { Asset, Config, LoggerInstance, Purgatory } from '@oceanprotocol/lib' +import { Config, LoggerInstance, Purgatory } from '@oceanprotocol/lib' import { CancelToken } from 'axios' import { retrieveAsset } from '@utils/aquarius' import { useWeb3 } from './Web3' @@ -16,20 +16,20 @@ import { useCancelToken } from '@hooks/useCancelToken' import { getOceanConfig, getDevelopmentConfig } from '@utils/ocean' import { AssetExtended } from 'src/@types/AssetExtended' import { getAccessDetails } from '@utils/accessDetailsAndPricing' +import { useIsMounted } from '@hooks/useIsMounted' interface AssetProviderValue { isInPurgatory: boolean purgatoryData: Purgatory - assetExtended: AssetExtended + asset: AssetExtended title: string owner: string - accessDetails: AccessDetails error?: string refreshInterval: number isAssetNetwork: boolean oceanConfig: Config loading: boolean - refreshAsset: (token?: CancelToken) => Promise + fetchAsset: (token?: CancelToken) => Promise } const AssetContext = createContext({} as AssetProviderValue) @@ -45,12 +45,11 @@ function AssetProvider({ }): ReactElement { const { appConfig } = useSiteMetadata() - const { networkId, accountId } = useWeb3() + const { chainId, accountId } = useWeb3() const [isInPurgatory, setIsInPurgatory] = useState(false) const [purgatoryData, setPurgatoryData] = useState() - const [assetExtended, setAssetExtended] = useState() + const [asset, setAsset] = useState() const [title, setTitle] = useState() - const [accessDetails, setConsumeDetails] = useState() const [owner, setOwner] = useState() const [error, setError] = useState() const [loading, setLoading] = useState(false) @@ -58,126 +57,121 @@ function AssetProvider({ const [oceanConfig, setOceanConfig] = useState() const newCancelToken = useCancelToken() + const isMounted = useIsMounted() + // ----------------------------------- + // Helper: Get and set asset based on passed DID + // ----------------------------------- const fetchAsset = useCallback( async (token?: CancelToken) => { - LoggerInstance.log('[asset] Init asset, get assetExtended') - setLoading(true) - const assetExtended = await retrieveAsset(did, token) + if (!did) return - if (!assetExtended) { + LoggerInstance.log('[asset] Fetching asset...') + setLoading(true) + const asset = await retrieveAsset(did, token) + + if (!asset) { setError( - `[asset] The assetExtended for ${did} was not found in MetadataCache. If you just published a new data set, wait some seconds and refresh this page.` + `[asset] The asset for ${did} was not found in MetadataCache. If you just published a new data set, wait some seconds and refresh this page.` ) + LoggerInstance.error(`[asset] Failed getting asset for ${did}`, asset) } else { setError(undefined) } + + setAsset((prevState) => ({ + ...prevState, + ...asset + })) + setTitle(asset.metadata.name) + setOwner(asset.nft.owner) + setIsInPurgatory((asset.purgatory?.state as unknown as string) === 'true') + setPurgatoryData(asset.purgatory) + LoggerInstance.log('[asset] Got asset', asset) + setLoading(false) - return assetExtended }, [did] ) - const refreshAsset = async (token?: CancelToken) => { - setLoading(true) - const assetExtended = await fetchAsset(token) - LoggerInstance.debug('[asset] Got assetExtended', assetExtended) - setAssetExtended(assetExtended) - setLoading(false) - } + // ----------------------------------- + // Helper: Get and set asset access details + // ----------------------------------- + const fetchAccessDetails = useCallback(async (): Promise => { + if (!asset?.chainId || !asset?.services) return + + const accessDetails = await getAccessDetails( + asset.chainId, + asset.services[0].datatokenAddress, + asset.services[0].timeout, + accountId + ) + setAsset((prevState) => ({ + ...prevState, + accessDetails + })) + LoggerInstance.log(`[asset] Got access details for ${did}`, accessDetails) + }, [asset?.chainId, asset?.services, accountId, did]) // ----------------------------------- - // Get and set assetExtended based on passed DID + // 1. Get and set asset based on passed DID // ----------------------------------- useEffect(() => { - if (!did || !appConfig.metadataCacheUri) return + if (!isMounted || !appConfig?.metadataCacheUri) return - let isMounted = true - - async function init() { - const assetExtended = await fetchAsset(newCancelToken()) - if (!isMounted || !assetExtended) return - LoggerInstance.debug('[asset] Got assetExtended', assetExtended) - setAssetExtended(assetExtended) - setTitle(assetExtended.metadata.name) - setOwner(assetExtended.nft.owner) - setIsInPurgatory( - (assetExtended.purgatory?.state as unknown as string) === 'true' - ) - setPurgatoryData(assetExtended.purgatory) - } - init() - return () => { - isMounted = false - } - }, [did, appConfig.metadataCacheUri, fetchAsset, newCancelToken]) + fetchAsset(newCancelToken()) + }, [appConfig?.metadataCacheUri, fetchAsset, newCancelToken, isMounted]) // ----------------------------------- - // Attach price to asset + // 2. Attach access details to asset // ----------------------------------- - const initPrice = useCallback( - async (assetExtended: AssetExtended, accountId: string): Promise => { - if (!assetExtended) return - const accessDetails = await getAccessDetails( - assetExtended.chainId, - assetExtended.services[0].datatokenAddress, - assetExtended.services[0].timeout, - accountId - ) - assetExtended.accessDetails = accessDetails - setConsumeDetails({ ...accessDetails }) - setAssetExtended(assetExtended) - }, - [] - ) - useEffect(() => { - if (!assetExtended) return - initPrice(assetExtended, accountId) - }, [accountId, assetExtended, initPrice]) + if (!isMounted) return + + fetchAccessDetails() + }, [accountId, fetchAccessDetails, isMounted]) // ----------------------------------- // Check user network against asset network // ----------------------------------- useEffect(() => { - if (!networkId || !assetExtended) return + if (!chainId || !asset?.chainId) return - const isAssetNetwork = networkId === assetExtended?.chainId + const isAssetNetwork = chainId === asset?.chainId setIsAssetNetwork(isAssetNetwork) - }, [networkId, assetExtended]) + }, [chainId, asset?.chainId]) // ----------------------------------- // Load ocean config based on asset network // ----------------------------------- useEffect(() => { - if (!assetExtended?.chainId) return + if (!asset?.chainId) return const oceanConfig = { - ...getOceanConfig(assetExtended?.chainId), + ...getOceanConfig(asset?.chainId), // add local dev values - ...(assetExtended?.chainId === 8996 && { + ...(asset?.chainId === 8996 && { ...getDevelopmentConfig() }) } setOceanConfig(oceanConfig) - }, [assetExtended]) + }, [asset?.chainId]) return ( { - let accessDetails = {} as AccessDetails const queryContext = getQueryContext(Number(chain)) - const tokenQueryResult: OperationResult = - await fetchData( - TokenPriceQuery, - { - datatokenId: datatokenAddress.toLowerCase(), - account: account.toLowerCase() - }, - queryContext - ) + const tokenQueryResult: OperationResult< + TokenPriceQuery, + { datatokenId: string; account: string } + > = await fetchData( + TokenPriceQuery, + { + datatokenId: datatokenAddress.toLowerCase(), + account: account.toLowerCase() + }, + queryContext + ) const tokenPrice: TokenPrice = tokenQueryResult.data.token - accessDetails = getAccessDetailsFromTokenPrice(tokenPrice, timeout) + const accessDetails = getAccessDetailsFromTokenPrice(tokenPrice, timeout) return accessDetails } @@ -243,7 +244,7 @@ export async function getAccessDetailsForAssets( account = '' ): Promise { const assetsExtended: AssetExtended[] = assets - const chainAssetLists: any = {} + const chainAssetLists: { [key: number]: string[] } = {} for (const asset of assets) { // harcoded until we have chainId on assets @@ -261,15 +262,17 @@ export async function getAccessDetailsForAssets( for (const chainKey in chainAssetLists) { const queryContext = getQueryContext(Number(chainKey)) - const tokenQueryResult: OperationResult = - await fetchData( - TokensPriceQuery, - { - datatokenIds: chainAssetLists[chainKey], - account: account.toLowerCase() - }, - queryContext - ) + const tokenQueryResult: OperationResult< + TokensPriceQuery, + { datatokenId: string; account: string } + > = await fetchData( + TokensPriceQuery, + { + datatokenIds: chainAssetLists[chainKey], + account: account.toLowerCase() + }, + queryContext + ) tokenQueryResult.data?.tokens.forEach((token) => { const accessDetails = getAccessDetailsFromTokenPrice(token) const currentAsset = assetsExtended.find( diff --git a/src/components/@shared/AssetList/index.tsx b/src/components/@shared/AssetList/index.tsx index 12ef26638..9ce17b46d 100644 --- a/src/components/@shared/AssetList/index.tsx +++ b/src/components/@shared/AssetList/index.tsx @@ -80,7 +80,7 @@ export default function AssetList({ {assetsWithPrices.length > 0 ? ( assetsWithPrices.map((assetWithPrice) => ( diff --git a/src/components/@shared/AssetTeaser/AssetTeaser.tsx b/src/components/@shared/AssetTeaser/AssetTeaser.tsx index 64155cad0..5061631be 100644 --- a/src/components/@shared/AssetTeaser/AssetTeaser.tsx +++ b/src/components/@shared/AssetTeaser/AssetTeaser.tsx @@ -11,22 +11,22 @@ import { getServiceByName } from '@utils/ddo' import { AssetExtended } from 'src/@types/AssetExtended' declare type AssetTeaserProps = { - assetExtended: AssetExtended + asset: AssetExtended noPublisher?: boolean } export default function AssetTeaser({ - assetExtended, + asset, noPublisher }: AssetTeaserProps): ReactElement { - const { name, type, description } = assetExtended.metadata - const { datatokens } = assetExtended - const isCompute = Boolean(getServiceByName(assetExtended, 'compute')) + const { name, type, description } = asset.metadata + const { datatokens } = asset + const isCompute = Boolean(getServiceByName(asset, 'compute')) const accessType = isCompute ? 'compute' : 'access' - const { owner } = assetExtended.nft + const { owner } = asset.nft return (
- +
{datatokens[0]?.symbol}
@@ -51,11 +51,8 @@ export default function AssetTeaser({
- - + +
diff --git a/src/components/@shared/TokenApproval/index.tsx b/src/components/@shared/TokenApproval/index.tsx index 127932e98..29a95937f 100644 --- a/src/components/@shared/TokenApproval/index.tsx +++ b/src/components/@shared/TokenApproval/index.tsx @@ -18,12 +18,12 @@ export default function TokenApproval({ tokenAddress: string tokenSymbol: string }): ReactElement { - const { accessDetails, isAssetNetwork } = useAsset() + const { asset, isAssetNetwork } = useAsset() const [tokenApproved, setTokenApproved] = useState(false) const [loading, setLoading] = useState(false) const { web3, accountId } = useWeb3() - const spender = accessDetails?.addressOrId + const spender = asset?.accessDetails?.addressOrId const checkTokenApproval = useCallback(async () => { if (!web3 || !tokenAddress || !spender || !isAssetNetwork || !amount) return diff --git a/src/components/@shared/WalletNetworkSwitcher/index.tsx b/src/components/@shared/WalletNetworkSwitcher/index.tsx index de077dcd7..cecd33fc9 100644 --- a/src/components/@shared/WalletNetworkSwitcher/index.tsx +++ b/src/components/@shared/WalletNetworkSwitcher/index.tsx @@ -11,15 +11,13 @@ import { useAsset } from '@context/Asset' export default function WalletNetworkSwitcher(): ReactElement { const { networkId, web3Provider } = useWeb3() - const { assetExtended } = useAsset() + const { asset } = useAsset() const { networksList } = useNetworkMetadata() - const ddoNetworkData = getNetworkDataById(networksList, assetExtended.chainId) + const ddoNetworkData = getNetworkDataById(networksList, asset.chainId) const walletNetworkData = getNetworkDataById(networksList, networkId) const ddoNetworkName = ( - - {getNetworkDisplayName(ddoNetworkData, assetExtended.chainId)} - + {getNetworkDisplayName(ddoNetworkData, asset.chainId)} ) const walletNetworkName = ( {getNetworkDisplayName(walletNetworkData, networkId)} @@ -27,7 +25,7 @@ export default function WalletNetworkSwitcher(): ReactElement { async function switchWalletNetwork() { const networkNode = await networksList.find( - (data) => data.chainId === assetExtended.chainId + (data) => data.chainId === asset.chainId ) addCustomNetwork(web3Provider, networkNode) } diff --git a/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx b/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx index cb1d0a129..5c1bcf0e9 100644 --- a/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx +++ b/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx @@ -62,8 +62,8 @@ export default function FormStartCompute({ }): ReactElement { const { isValid, values }: FormikContextType<{ algorithm: string }> = useFormikContext() - const { accessDetails, assetExtended, isAssetNetwork } = useAsset() - const [totalPrice, setTotalPrice] = useState(accessDetails?.price) + const { asset, isAssetNetwork } = useAsset() + const [totalPrice, setTotalPrice] = useState(asset?.accessDetails?.price) const [isBalanceSufficient, setIsBalanceSufficient] = useState(false) const { accountId, balance } = useWeb3() const [algorithmConsumableStatus, setAlgorithmConsumableStatus] = @@ -97,10 +97,10 @@ export default function FormStartCompute({ // Set price for calculation output // useEffect(() => { - if (!accessDetails || !algorithmConsumeDetails) return + if (!asset?.accessDetails || !algorithmConsumeDetails) return const priceDataset = - hasPreviousOrder || hasDatatoken ? 0 : Number(accessDetails.price) + hasPreviousOrder || hasDatatoken ? 0 : Number(asset.accessDetails.price) const priceAlgo = hasPreviousOrderSelectedComputeAsset || hasDatatokenSelectedComputeAsset ? 0 @@ -108,7 +108,7 @@ export default function FormStartCompute({ setTotalPrice(priceDataset + priceAlgo) }, [ - accessDetails, + asset?.accessDetails, algorithmConsumeDetails, hasPreviousOrder, hasDatatoken, @@ -159,7 +159,7 @@ export default function FormStartCompute({ } hasPreviousOrder={hasPreviousOrder} hasDatatoken={hasDatatoken} - dtSymbol={assetExtended?.datatokens[0]?.symbol} + dtSymbol={asset?.datatokens[0]?.symbol} dtBalance={dtBalance} datasetLowPoolLiquidity={datasetLowPoolLiquidity} assetTimeout={assetTimeout} @@ -177,7 +177,7 @@ export default function FormStartCompute({ stepText={stepText} isLoading={isLoading} type="submit" - priceType={accessDetails?.type} + priceType={asset?.accessDetails?.type} algorithmPriceType={algorithmConsumeDetails?.type} isBalanceSufficient={isBalanceSufficient} isConsumable={isConsumable} diff --git a/src/components/Asset/AssetActions/Compute/PriceOutput.tsx b/src/components/Asset/AssetActions/Compute/PriceOutput.tsx index e9019d5a5..5e75c1a04 100644 --- a/src/components/Asset/AssetActions/Compute/PriceOutput.tsx +++ b/src/components/Asset/AssetActions/Compute/PriceOutput.tsx @@ -63,7 +63,7 @@ export default function PriceOutput({ algorithmConsumeDetails, selectedComputeAssetTimeout }: PriceOutputProps): ReactElement { - const { accessDetails } = useAsset() + const { asset } = useAsset() return (
@@ -74,7 +74,7 @@ export default function PriceOutput({ diff --git a/src/components/Asset/AssetActions/Pool/index.tsx b/src/components/Asset/AssetActions/Pool/index.tsx index 84e9d5426..3f45217dc 100644 --- a/src/components/Asset/AssetActions/Pool/index.tsx +++ b/src/components/Asset/AssetActions/Pool/index.tsx @@ -60,14 +60,8 @@ const initialPoolInfoCreator: Partial = initialPoolInfoUser export default function Pool(): ReactElement { const { accountId } = useWeb3() - const { - isInPurgatory, - assetExtended, - owner, - accessDetails, - refreshInterval, - isAssetNetwork - } = useAsset() + const { isInPurgatory, asset, owner, refreshInterval, isAssetNetwork } = + useAsset() const [poolData, setPoolData] = useState() const [poolInfo, setPoolInfo] = useState( @@ -88,11 +82,11 @@ export default function Pool(): ReactElement { const [fetchInterval, setFetchInterval] = useState() const fetchAllData = useCallback(async () => { - if (!assetExtended?.chainId || !accessDetails?.addressOrId || !owner) return + if (!asset?.chainId || !asset?.accessDetails?.addressOrId || !owner) return const response = await getPoolData( - assetExtended.chainId, - accessDetails.addressOrId, + asset.chainId, + asset.accessDetails.addressOrId, owner, accountId || '' ) @@ -107,7 +101,7 @@ export default function Pool(): ReactElement { LoggerInstance.log('[pool] Fetched pool data:', response.poolData) LoggerInstance.log('[pool] Fetched user data:', response.poolDataUser) LoggerInstance.log('[pool] Fetched pool snapshots:', response.poolSnapshots) - }, [assetExtended?.chainId, accessDetails?.addressOrId, owner, accountId]) + }, [asset?.chainId, asset?.accessDetails?.addressOrId, owner, accountId]) // Helper: start interval fetching const initFetchInterval = useCallback(() => { @@ -242,7 +236,7 @@ export default function Pool(): ReactElement { if ( !poolData || !poolInfo?.totalPoolTokens || - !assetExtended?.chainId || + !asset?.chainId || !accountId ) return @@ -310,7 +304,7 @@ export default function Pool(): ReactElement { poolData, poolInfoUser?.poolShares, accountId, - assetExtended?.chainId, + asset?.chainId, owner, poolInfo?.totalPoolTokens ]) @@ -328,7 +322,7 @@ export default function Pool(): ReactElement { {showAdd ? (
Pool Datatoken @@ -478,8 +471,8 @@ export default function Pool(): ReactElement { diff --git a/src/components/Asset/AssetActions/Trade/FormTrade.tsx b/src/components/Asset/AssetActions/Trade/FormTrade.tsx index eb212eafc..b5fa5e2aa 100644 --- a/src/components/Asset/AssetActions/Trade/FormTrade.tsx +++ b/src/components/Asset/AssetActions/Trade/FormTrade.tsx @@ -17,12 +17,12 @@ import content from '../../../../../content/price.json' import { AssetExtended } from 'src/@types/AssetExtended' export default function FormTrade({ - assetExtended, + asset, balance, maxDt, maxOcean }: { - assetExtended: AssetExtended + asset: AssetExtended balance: PoolBalance maxDt: string maxOcean: string @@ -110,7 +110,7 @@ export default function FormTrade({ <> {isWarningAccepted ? ( ({ amount: '0', - token: assetExtended.accessDetails.baseToken?.symbol, + token: asset.accessDetails.baseToken?.symbol, maxAmount: '0' }) const [dtItem, setDtItem] = useState({ amount: '0', - token: assetExtended.accessDetails.datatoken.symbol, + token: asset.accessDetails.datatoken.symbol, maxAmount: '0' }) @@ -58,7 +58,7 @@ export default function Swap({ const [tokenAmount, setTokenAmount] = useState() useEffect(() => { - if (!assetExtended || !balance || !values?.type) return + if (!asset || !balance || !values?.type) return async function calculateMaximum() { const amountDataToken = @@ -114,7 +114,7 @@ export default function Swap({ } calculateMaximum() }, [ - assetExtended, + asset, maxOcean, maxDt, balance, @@ -125,9 +125,7 @@ export default function Swap({ const switchTokens = () => { setFieldValue('type', values.type === 'buy' ? 'sell' : 'buy') - setCoin( - values.type === 'sell' ? 'OCEAN' : assetExtended.datatokens[0].symbol - ) + setCoin(values.type === 'sell' ? 'OCEAN' : asset.datatokens[0].symbol) // don't reset form because we don't want to reset type setFieldValue('datatoken', 0) setFieldValue('ocean', 0) @@ -223,7 +221,7 @@ export default function Swap({ () - const { assetExtended } = useAsset() + const { asset } = useAsset() const [maxDt, setMaxDt] = useState('0') const [maxOcean, setMaxOcean] = useState('0') @@ -23,14 +23,14 @@ export default function Trade(): ReactElement { !isAssetNetwork || !balance?.ocean || !accountId || - !assetExtended?.services[0].datatokenAddress + !asset?.services[0].datatokenAddress ) return async function getTokenBalance() { const datatokenInstance = new Datatoken(web3) const dtBalance = await datatokenInstance.balance( - assetExtended.services[0].datatokenAddress, + asset.services[0].datatokenAddress, accountId ) setTokenBalance({ @@ -39,14 +39,14 @@ export default function Trade(): ReactElement { }) } getTokenBalance() - }, [web3, balance.ocean, accountId, assetExtended, isAssetNetwork]) + }, [web3, balance.ocean, accountId, asset, isAssetNetwork]) // Get maximum amount for either OCEAN or datatoken useEffect(() => { if ( !isAssetNetwork || - !assetExtended.accessDetails || - assetExtended.accessDetails.price === 0 + !asset.accessDetails || + asset.accessDetails.price === 0 ) return @@ -69,11 +69,11 @@ export default function Trade(): ReactElement { // ) } getMaximum() - }, [isAssetNetwork, balance.ocean, assetExtended]) + }, [isAssetNetwork, balance.ocean, asset]) return ( () const [fileIsLoading, setFileIsLoading] = useState(false) const isCompute = Boolean( - ddo?.services.filter((service) => service.type === 'compute')[0] + asset?.services.filter((service) => service.type === 'compute')[0] ) const [isConsumable, setIsConsumable] = useState(true) @@ -68,14 +62,14 @@ export default function AssetActions({ // }, [accountId, isAssetNetwork, ddo, ocean]) useEffect(() => { - const oceanConfig = getOceanConfig(ddo?.chainId) + const oceanConfig = getOceanConfig(asset?.chainId) if (!oceanConfig) return async function initFileInfo() { setFileIsLoading(true) const fileUrl = formikState?.values?.services?.[0].files?.[0].url || - (ddo.metadata?.links ? ddo.metadata?.links[0] : ' ') + (asset.metadata?.links ? asset.metadata?.links[0] : ' ') const providerUrl = formikState?.values?.services[0].providerUrl.url || oceanConfig.providerUri @@ -89,7 +83,7 @@ export default function AssetActions({ } } initFileInfo() - }, [ddo, isMounted, newCancelToken, formikState?.values?.services]) + }, [asset, isMounted, newCancelToken, formikState?.values?.services]) // Get and set user DT balance useEffect(() => { @@ -99,7 +93,7 @@ export default function AssetActions({ try { const datatokenInstance = new Datatoken(web3) const dtBalance = await datatokenInstance.balance( - ddo.services[0].datatokenAddress, + asset.services[0].datatokenAddress, accountId ) setDtBalance(dtBalance) @@ -108,28 +102,33 @@ export default function AssetActions({ } } init() - }, [web3, accountId, ddo, isAssetNetwork]) + }, [web3, accountId, asset, isAssetNetwork]) // Check user balance against price useEffect(() => { - if (accessDetails?.type === 'free') setIsBalanceSufficient(true) - if (!accessDetails?.price || !accountId || !balance?.ocean || !dtBalance) + if (asset?.accessDetails?.type === 'free') setIsBalanceSufficient(true) + if ( + !asset?.accessDetails?.price || + !accountId || + !balance?.ocean || + !dtBalance + ) return setIsBalanceSufficient( - compareAsBN(balance.ocean, `${accessDetails.price}`) || + compareAsBN(balance.ocean, `${asset?.accessDetails.price}`) || Number(dtBalance) >= 1 ) return () => { setIsBalanceSufficient(false) } - }, [balance, accountId, accessDetails, dtBalance]) + }, [balance, accountId, asset?.accessDetails, dtBalance]) const UseContent = isCompute ? ( ) : ( , - disabled: !accessDetails.datatoken + disabled: !asset?.accessDetails.datatoken }, { title: 'Trade', content: , - disabled: !accessDetails.datatoken + disabled: !asset?.accessDetails.datatoken } ) return ( <> - + ) } diff --git a/src/components/Asset/AssetContent/EditHistory.tsx b/src/components/Asset/AssetContent/EditHistory.tsx index c8fb4ccb1..f295e7f26 100644 --- a/src/components/Asset/AssetContent/EditHistory.tsx +++ b/src/components/Asset/AssetContent/EditHistory.tsx @@ -26,7 +26,7 @@ const getReceipts = gql` ` export default function EditHistory(): ReactElement { - const { assetExtended } = useAsset() + const { asset } = useAsset() function getUpdateType(type: string): string { switch (type) { @@ -49,17 +49,17 @@ export default function EditHistory(): ReactElement { const [queryContext, setQueryContext] = useState() useEffect(() => { - if (!assetExtended) return + if (!asset) return - const queryContext = getQueryContext(assetExtended.chainId) + const queryContext = getQueryContext(asset.chainId) setQueryContext(queryContext) - }, [assetExtended]) + }, [asset]) const [result] = useQuery({ query: getReceipts, - variables: { address: assetExtended?.nft.address.toLowerCase() }, + variables: { address: asset?.nft.address.toLowerCase() }, context: queryContext, - pause: !assetExtended || !queryContext + pause: !asset || !queryContext }) const { data } = result @@ -80,10 +80,7 @@ export default function EditHistory(): ReactElement {
    {receipts?.map((receipt) => (
  • - + {getUpdateType(receipt.type)}{' '} diff --git a/src/components/Asset/AssetContent/index.tsx b/src/components/Asset/AssetContent/index.tsx index 1177530c4..5eb5246ba 100644 --- a/src/components/Asset/AssetContent/index.tsx +++ b/src/components/Asset/AssetContent/index.tsx @@ -13,14 +13,12 @@ import EditHistory from './EditHistory' import styles from './index.module.css' import NetworkName from '@shared/NetworkName' import content from '../../../../content/purgatory.json' -import { Asset } from '@oceanprotocol/lib' +import { AssetExtended } from 'src/@types/AssetExtended' export default function AssetContent({ - asset, - accessDetails + asset }: { - asset: Asset - accessDetails: AccessDetails + asset: AssetExtended }): ReactElement { const { debug } = useUserPreferences() const { isInPurgatory, purgatoryData } = useAsset() @@ -35,7 +33,9 @@ export default function AssetContent({
    - {accessDetails?.datatoken !== null && } + {asset?.accessDetails?.datatoken !== null && ( + + )} {isInPurgatory === true ? (
    - + {/* TODO: restore edit actions, ideally put edit screens on new page diff --git a/src/components/Asset/Edit/EditComputeDataset.tsx b/src/components/Asset/Edit/EditComputeDataset.tsx index e3aedb7a4..a7c5b4684 100644 --- a/src/components/Asset/Edit/EditComputeDataset.tsx +++ b/src/components/Asset/Edit/EditComputeDataset.tsx @@ -19,7 +19,7 @@ export default function EditComputeDataset({ }): ReactElement { const { debug } = useUserPreferences() const { accountId } = useWeb3() - const { assetExtended, isAssetNetwork, refreshAsset } = useAsset() + const { asset, isAssetNetwork, fetchAsset } = useAsset() const [success, setSuccess] = useState() const [error, setError] = useState() @@ -111,7 +111,7 @@ export default function EditComputeDataset({ />
{debug === true && ( diff --git a/src/components/Asset/Edit/FormEditComputeDataset.tsx b/src/components/Asset/Edit/FormEditComputeDataset.tsx index 651bb867b..5f9a9ccf6 100644 --- a/src/components/Asset/Edit/FormEditComputeDataset.tsx +++ b/src/components/Asset/Edit/FormEditComputeDataset.tsx @@ -28,12 +28,12 @@ export default function FormEditComputeDataset({ setShowEdit: (show: boolean) => void }): ReactElement { const { appConfig } = useSiteMetadata() - const { assetExtended } = useAsset() + const { asset } = useAsset() const { values }: FormikContextType = useFormikContext() const [allAlgorithms, setAllAlgorithms] = useState() const newCancelToken = useCancelToken() const { publisherTrustedAlgorithms } = getServiceByName( - assetExtended, + asset, 'compute' ).compute @@ -41,14 +41,14 @@ export default function FormEditComputeDataset({ publisherTrustedAlgorithms: PublisherTrustedAlgorithm[] ): Promise { const baseParams = { - chainIds: [assetExtended.chainId], + chainIds: [asset.chainId], sort: { sortBy: SortTermOptions.Created }, filters: [getFilterTerm('service.attributes.main.type', 'algorithm')] } as BaseQueryParams const query = generateBaseQuery(baseParams) const querryResult = await queryMetadata(query, newCancelToken()) - const datasetComputeService = getServiceByName(assetExtended, 'compute') + const datasetComputeService = getServiceByName(asset, 'compute') const algorithmSelectionList = await transformDDOToAssetSelection( datasetComputeService?.serviceEndpoint, querryResult.results, diff --git a/src/components/Asset/Edit/index.tsx b/src/components/Asset/Edit/index.tsx index 356bda743..7172bb372 100644 --- a/src/components/Asset/Edit/index.tsx +++ b/src/components/Asset/Edit/index.tsx @@ -22,11 +22,11 @@ export default function Edit({ }): ReactElement { const { debug } = useUserPreferences() const { accountId } = useWeb3() - const { assetExtended, refreshAsset, accessDetails } = useAsset() + const { asset, fetchAsset } = useAsset() const [success, setSuccess] = useState() const [error, setError] = useState() const [timeoutStringValue, setTimeoutStringValue] = useState() - const { timeout } = assetExtended.services[0] + const { timeout } = asset.services[0] const hasFeedback = error || success @@ -119,9 +119,9 @@ export default function Edit({ return ( { @@ -148,7 +148,7 @@ export default function Edit({ /> */} {/* {debug === true && } */} diff --git a/src/components/Asset/index.tsx b/src/components/Asset/index.tsx index 9aa9df365..d0d57eeca 100644 --- a/src/components/Asset/index.tsx +++ b/src/components/Asset/index.tsx @@ -6,21 +6,20 @@ import { useAsset } from '@context/Asset' import AssetContent from './AssetContent' export default function AssetDetails({ uri }: { uri: string }): ReactElement { - const { assetExtended, title, error, isInPurgatory, loading, accessDetails } = - useAsset() + const { asset, title, error, isInPurgatory, loading } = useAsset() const [pageTitle, setPageTitle] = useState() useEffect(() => { - if (!assetExtended || error) { + if (!asset || error) { setPageTitle('Could not retrieve asset') return } setPageTitle(isInPurgatory ? '' : title) - }, [assetExtended, error, isInPurgatory, title]) + }, [asset, error, isInPurgatory, title]) - return assetExtended && pageTitle !== undefined && !loading ? ( + return asset && pageTitle !== undefined && !loading ? ( - + ) : error ? ( diff --git a/src/components/Profile/History/ComputeJobs/index.tsx b/src/components/Profile/History/ComputeJobs/index.tsx index 31c0033b1..a74411089 100644 --- a/src/components/Profile/History/ComputeJobs/index.tsx +++ b/src/components/Profile/History/ComputeJobs/index.tsx @@ -74,7 +74,7 @@ export default function ComputeJobs({ minimal?: boolean }): ReactElement { const { accountId, networkId } = useWeb3() - const { assetExtended } = useAsset() + const { asset } = useAsset() const { chainIds } = useUserPreferences() const [isLoading, setIsLoading] = useState(false) const [jobs, setJobs] = useState([]) @@ -96,7 +96,7 @@ export default function ComputeJobs({ } catch (error) { LoggerInstance.error(error.message) } - }, [chainIds, accountId, assetExtended, isMounted]) + }, [chainIds, accountId, asset, isMounted]) useEffect(() => { fetchJobs() diff --git a/src/components/Publish/Preview/index.tsx b/src/components/Publish/Preview/index.tsx index 6e704a358..2db5e6fd3 100644 --- a/src/components/Publish/Preview/index.tsx +++ b/src/components/Publish/Preview/index.tsx @@ -44,7 +44,7 @@ export default function Preview(): ReactElement {

Preview

{values.metadata.name}

- + ) } From 64255f2b371ec53713d444819c4732966f7193f5 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Thu, 3 Feb 2022 15:26:49 +0000 Subject: [PATCH 2/2] Remove asset purgatory workaround (#1056) * revert asset purgatory workaround * reverts #1016 * asset loading fix --- src/@context/Asset.tsx | 19 +++++++++---------- src/@utils/aquarius.ts | 2 +- 2 files changed, 10 insertions(+), 11 deletions(-) diff --git a/src/@context/Asset.tsx b/src/@context/Asset.tsx index d6e78a654..689d6ef22 100644 --- a/src/@context/Asset.tsx +++ b/src/@context/Asset.tsx @@ -77,18 +77,17 @@ function AssetProvider({ LoggerInstance.error(`[asset] Failed getting asset for ${did}`, asset) } else { setError(undefined) + setAsset((prevState) => ({ + ...prevState, + ...asset + })) + setTitle(asset.metadata?.name) + setOwner(asset.nft?.owner) + setIsInPurgatory(asset.purgatory?.state) + setPurgatoryData(asset.purgatory) + LoggerInstance.log('[asset] Got asset', asset) } - setAsset((prevState) => ({ - ...prevState, - ...asset - })) - setTitle(asset.metadata.name) - setOwner(asset.nft.owner) - setIsInPurgatory((asset.purgatory?.state as unknown as string) === 'true') - setPurgatoryData(asset.purgatory) - LoggerInstance.log('[asset] Got asset', asset) - setLoading(false) }, [did] diff --git a/src/@utils/aquarius.ts b/src/@utils/aquarius.ts index a7fea4977..4c8d0866c 100644 --- a/src/@utils/aquarius.ts +++ b/src/@utils/aquarius.ts @@ -48,7 +48,7 @@ export function generateBaseQuery( getFilterTerm('_index', 'aquarius'), ...(baseQueryParams.ignorePurgatory ? [] - : [getFilterTerm('purgatory.state', 'false')]) + : [getFilterTerm('purgatory.state', false)]) ] } }