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

legacy web3 object for ocean.js

This commit is contained in:
Matthias Kretschmann 2023-01-20 11:56:07 +00:00
parent c8969d6e1f
commit 6ac4758094
Signed by: m
GPG Key ID: 606EEEF3C479A91F
13 changed files with 125 additions and 50 deletions

View File

@ -0,0 +1,63 @@
// init web3.js object for compatibility with ocean.js
import React, {
useContext,
useState,
useEffect,
createContext,
ReactElement,
ReactNode
} from 'react'
import Web3 from 'web3'
import { LoggerInstance } from '@oceanprotocol/lib'
import { useAccount, useNetwork, useProvider } from 'wagmi'
interface Web3LegacyProviderValue {
web3: Web3
web3Loading: boolean
}
const Web3LegacyContext = createContext({} as Web3LegacyProviderValue)
function Web3LegacyProvider({
children
}: {
children: ReactNode
}): ReactElement {
const { address } = useAccount()
const { chain } = useNetwork()
const web3Provider = useProvider()
const [web3, setWeb3] = useState<Web3>()
const [web3Loading, setWeb3Loading] = useState<boolean>(true)
useEffect(() => {
const init = async () => {
if (!web3Provider || !address || !chain?.id) return
try {
setWeb3Loading(true)
const web3 = new Web3(web3Provider as any)
setWeb3(web3)
} catch (error) {
LoggerInstance.error(error.message)
} finally {
setWeb3Loading(false)
}
}
init()
}, [web3Provider, address, chain?.id])
return (
<Web3LegacyContext.Provider value={{ web3, web3Loading }}>
{children}
</Web3LegacyContext.Provider>
)
}
// Helper hook to access the provider values
const useWeb3Legacy = (): Web3LegacyProviderValue =>
useContext(Web3LegacyContext)
export { Web3LegacyProvider, useWeb3Legacy, Web3LegacyContext }
export default Web3LegacyProvider

View File

@ -2,9 +2,11 @@ import { useEffect, useState } from 'react'
import { NftFactory } from '@oceanprotocol/lib' import { NftFactory } from '@oceanprotocol/lib'
import { getOceanConfig } from '@utils/ocean' import { getOceanConfig } from '@utils/ocean'
import { useNetwork } from 'wagmi' import { useNetwork } from 'wagmi'
import { useWeb3Legacy } from '@context/Web3Legacy'
function useNftFactory(): NftFactory { function useNftFactory(): NftFactory {
const { chain } = useNetwork() const { chain } = useNetwork()
const { web3 } = useWeb3Legacy()
const [nftFactory, setNftFactory] = useState<NftFactory>() const [nftFactory, setNftFactory] = useState<NftFactory>()
useEffect(() => { useEffect(() => {

View File

@ -16,7 +16,8 @@ const downloadProps: ButtonBuyProps = {
priceType: 'fixed', priceType: 'fixed',
isConsumable: true, isConsumable: true,
isBalanceSufficient: true, isBalanceSufficient: true,
consumableFeedback: 'TEST: consumableFeedback' consumableFeedback: 'TEST: consumableFeedback',
isAccountConnected: true
} }
const computeProps: ButtonBuyProps = { const computeProps: ButtonBuyProps = {

View File

@ -2,7 +2,6 @@ import React, { FormEvent, ReactElement } from 'react'
import Button from '../../../@shared/atoms/Button' import Button from '../../../@shared/atoms/Button'
import styles from './index.module.css' import styles from './index.module.css'
import Loader from '../../../@shared/atoms/Loader' import Loader from '../../../@shared/atoms/Loader'
import Web3 from 'web3'
export interface ButtonBuyProps { export interface ButtonBuyProps {
action: 'download' | 'compute' action: 'download' | 'compute'
@ -30,6 +29,7 @@ export interface ButtonBuyProps {
algorithmPriceType?: string algorithmPriceType?: string
isAlgorithmConsumable?: boolean isAlgorithmConsumable?: boolean
isSupportedOceanNetwork?: boolean isSupportedOceanNetwork?: boolean
isAccountConnected?: boolean
hasProviderFee?: boolean hasProviderFee?: boolean
retry?: boolean retry?: boolean
} }
@ -45,13 +45,13 @@ function getConsumeHelpText(
isBalanceSufficient: boolean, isBalanceSufficient: boolean,
consumableFeedback: string, consumableFeedback: string,
isSupportedOceanNetwork: boolean, isSupportedOceanNetwork: boolean,
web3: Web3, isAccountConnected: boolean,
priceType: string priceType: string
) { ) {
const text = const text =
isConsumable === false isConsumable === false
? consumableFeedback ? consumableFeedback
: hasPreviousOrder && web3 && isSupportedOceanNetwork : hasPreviousOrder && isAccountConnected && isSupportedOceanNetwork
? `You bought this ${assetType} already allowing you to use it without paying again.` ? `You bought this ${assetType} already allowing you to use it without paying again.`
: hasDatatoken : hasDatatoken
? `You own ${dtBalance} ${dtSymbol} allowing you to use this dataset by spending 1 ${dtSymbol}, but without paying ${btSymbol} again.` ? `You own ${dtBalance} ${dtSymbol} allowing you to use this dataset by spending 1 ${dtSymbol}, but without paying ${btSymbol} again.`
@ -73,7 +73,7 @@ function getAlgoHelpText(
hasDatatokenSelectedComputeAsset: boolean, hasDatatokenSelectedComputeAsset: boolean,
isBalanceSufficient: boolean, isBalanceSufficient: boolean,
isSupportedOceanNetwork: boolean, isSupportedOceanNetwork: boolean,
web3: Web3, isAccountConnected: boolean,
algorithmPriceType: string algorithmPriceType: string
) { ) {
const text = const text =
@ -81,11 +81,13 @@ function getAlgoHelpText(
isConsumable === false || isConsumable === false ||
isAlgorithmConsumable === false isAlgorithmConsumable === false
? '' ? ''
: hasPreviousOrderSelectedComputeAsset && web3 && isSupportedOceanNetwork : hasPreviousOrderSelectedComputeAsset &&
isAccountConnected &&
isSupportedOceanNetwork
? `You already bought the selected ${selectedComputeAssetType}, allowing you to use it without paying again.` ? `You already bought the selected ${selectedComputeAssetType}, allowing you to use it without paying again.`
: hasDatatokenSelectedComputeAsset : hasDatatokenSelectedComputeAsset
? `You own ${dtBalanceSelectedComputeAsset} ${dtSymbolSelectedComputeAsset} allowing you to use the selected ${selectedComputeAssetType} by spending 1 ${dtSymbolSelectedComputeAsset}, but without paying OCEAN again.` ? `You own ${dtBalanceSelectedComputeAsset} ${dtSymbolSelectedComputeAsset} allowing you to use the selected ${selectedComputeAssetType} by spending 1 ${dtSymbolSelectedComputeAsset}, but without paying OCEAN again.`
: web3 && !isSupportedOceanNetwork : isAccountConnected && !isSupportedOceanNetwork
? `Connect to the correct network to interact with this asset.` ? `Connect to the correct network to interact with this asset.`
: isBalanceSufficient === false : isBalanceSufficient === false
? '' ? ''
@ -114,7 +116,7 @@ function getComputeAssetHelpText(
selectedComputeAssetType?: string, selectedComputeAssetType?: string,
isAlgorithmConsumable?: boolean, isAlgorithmConsumable?: boolean,
isSupportedOceanNetwork?: boolean, isSupportedOceanNetwork?: boolean,
web3?: Web3, isAccountConnected?: boolean,
hasProviderFee?: boolean hasProviderFee?: boolean
) { ) {
const computeAssetHelpText = getConsumeHelpText( const computeAssetHelpText = getConsumeHelpText(
@ -128,7 +130,7 @@ function getComputeAssetHelpText(
isBalanceSufficient, isBalanceSufficient,
consumableFeedback, consumableFeedback,
isSupportedOceanNetwork, isSupportedOceanNetwork,
web3, isAccountConnected,
priceType priceType
) )
@ -142,7 +144,7 @@ function getComputeAssetHelpText(
hasDatatokenSelectedComputeAsset, hasDatatokenSelectedComputeAsset,
isBalanceSufficient, isBalanceSufficient,
isSupportedOceanNetwork, isSupportedOceanNetwork,
web3, isAccountConnected,
algorithmPriceType algorithmPriceType
) )
@ -182,7 +184,8 @@ export default function ButtonBuy({
isAlgorithmConsumable, isAlgorithmConsumable,
hasProviderFee, hasProviderFee,
retry, retry,
isSupportedOceanNetwork isSupportedOceanNetwork,
isAccountConnected
}: ButtonBuyProps): ReactElement { }: ButtonBuyProps): ReactElement {
const buttonText = retry const buttonText = retry
? 'Retry' ? 'Retry'
@ -214,7 +217,7 @@ export default function ButtonBuy({
isBalanceSufficient, isBalanceSufficient,
consumableFeedback, consumableFeedback,
isSupportedOceanNetwork, isSupportedOceanNetwork,
web3, isAccountConnected,
priceType priceType
) )
} else { } else {
@ -237,7 +240,7 @@ export default function ButtonBuy({
selectedComputeAssetType, selectedComputeAssetType,
isAlgorithmConsumable, isAlgorithmConsumable,
isSupportedOceanNetwork, isSupportedOceanNetwork,
web3, isAccountConnected,
hasProviderFee hasProviderFee
) )
} }

View File

@ -79,7 +79,7 @@ export default function FormStartCompute({
retry: boolean retry: boolean
}): ReactElement { }): ReactElement {
const { siteContent } = useMarketMetadata() const { siteContent } = useMarketMetadata()
const { address: accountId } = useAccount() const { address: accountId, isConnected } = useAccount()
const { balance } = useBalance() const { balance } = useBalance()
const { isSupportedOceanNetwork } = useNetworkMetadata() const { isSupportedOceanNetwork } = useNetworkMetadata()
const { isValid, values }: FormikContextType<{ algorithm: string }> = const { isValid, values }: FormikContextType<{ algorithm: string }> =
@ -312,6 +312,7 @@ export default function FormStartCompute({
isSupportedOceanNetwork={isSupportedOceanNetwork} isSupportedOceanNetwork={isSupportedOceanNetwork}
hasProviderFee={providerFeeAmount && providerFeeAmount !== '0'} hasProviderFee={providerFeeAmount && providerFeeAmount !== '0'}
retry={retry} retry={retry}
isAccountConnected={isConnected}
/> />
</Form> </Form>
) )

View File

@ -44,8 +44,8 @@ import { handleComputeOrder } from '@utils/order'
import { getComputeFeedback } from '@utils/feedback' import { getComputeFeedback } from '@utils/feedback'
import { initializeProviderForCompute } from '@utils/provider' import { initializeProviderForCompute } from '@utils/provider'
import { useUserPreferences } from '@context/UserPreferences' import { useUserPreferences } from '@context/UserPreferences'
import { useAsset } from '@context/Asset'
import { useAccount } from 'wagmi' import { useAccount } from 'wagmi'
import { useWeb3Legacy } from '@context/Web3Legacy'
const refreshInterval = 10000 // 10 sec. const refreshInterval = 10000 // 10 sec.
@ -64,7 +64,7 @@ export default function Compute({
}): ReactElement { }): ReactElement {
const { address: accountId } = useAccount() const { address: accountId } = useAccount()
const { chainIds } = useUserPreferences() const { chainIds } = useUserPreferences()
const { isAssetNetwork } = useAsset() const { web3 } = useWeb3Legacy()
const newAbortController = useAbortController() const newAbortController = useAbortController()
const newCancelToken = useCancelToken() const newCancelToken = useCancelToken()
@ -187,6 +187,7 @@ export default function Compute({
const datasetPriceAndFees = await getOrderPriceAndFees( const datasetPriceAndFees = await getOrderPriceAndFees(
asset, asset,
ZERO_ADDRESS, ZERO_ADDRESS,
web3,
initializedProvider?.datasets?.[0]?.providerFee initializedProvider?.datasets?.[0]?.providerFee
) )
if (!datasetPriceAndFees) if (!datasetPriceAndFees)
@ -210,6 +211,7 @@ export default function Compute({
const algorithmOrderPriceAndFees = await getOrderPriceAndFees( const algorithmOrderPriceAndFees = await getOrderPriceAndFees(
selectedAlgorithmAsset, selectedAlgorithmAsset,
ZERO_ADDRESS, ZERO_ADDRESS,
web3,
initializedProvider.algorithm.providerFee initializedProvider.algorithm.providerFee
) )
if (!algorithmOrderPriceAndFees) if (!algorithmOrderPriceAndFees)

View File

@ -18,7 +18,7 @@ import Alert from '@shared/atoms/Alert'
import Loader from '@shared/atoms/Loader' import Loader from '@shared/atoms/Loader'
import { useAccount } from 'wagmi' import { useAccount } from 'wagmi'
import useNetworkMetadata from '@hooks/useNetworkMetadata' import useNetworkMetadata from '@hooks/useNetworkMetadata'
import Web3 from 'web3' import { useWeb3Legacy } from '@context/Web3Legacy'
export default function Download({ export default function Download({
asset, asset,
@ -35,7 +35,8 @@ export default function Download({
fileIsLoading?: boolean fileIsLoading?: boolean
consumableFeedback?: string consumableFeedback?: string
}): ReactElement { }): ReactElement {
const { address: accountId, connector, isConnected } = useAccount() const { address: accountId, isConnected } = useAccount()
const { web3 } = useWeb3Legacy()
const { isSupportedOceanNetwork } = useNetworkMetadata() const { isSupportedOceanNetwork } = useNetworkMetadata()
const { getOpcFeeForToken } = useMarketMetadata() const { getOpcFeeForToken } = useMarketMetadata()
const { isInPurgatory, isAssetNetwork } = useAsset() const { isInPurgatory, isAssetNetwork } = useAsset()
@ -52,7 +53,6 @@ export default function Download({
const [orderPriceAndFees, setOrderPriceAndFees] = const [orderPriceAndFees, setOrderPriceAndFees] =
useState<OrderPriceAndFees>() useState<OrderPriceAndFees>()
const [retry, setRetry] = useState<boolean>(false) const [retry, setRetry] = useState<boolean>(false)
const [web3, setWeb3] = useState<Web3>()
const isUnsupportedPricing = const isUnsupportedPricing =
!asset?.accessDetails || !asset?.accessDetails ||
@ -62,21 +62,6 @@ export default function Download({
(asset?.accessDetails?.type === 'fixed' && (asset?.accessDetails?.type === 'fixed' &&
!asset?.accessDetails?.baseToken?.symbol) !asset?.accessDetails?.baseToken?.symbol)
// init web3.js object for compatibility with ocean.js
useEffect(() => {
const init = async () => {
if (!connector || !isConnected) return
try {
const web3 = new Web3(await connector.getProvider())
setWeb3(web3)
} catch (error) {
LoggerInstance.error(error.message)
}
}
init()
}, [connector, isConnected])
useEffect(() => { useEffect(() => {
Number(asset?.nft.state) === 4 && setIsOrderDisabled(true) Number(asset?.nft.state) === 4 && setIsOrderDisabled(true)
}, [asset?.nft.state]) }, [asset?.nft.state])
@ -219,6 +204,7 @@ export default function Download({
consumableFeedback={consumableFeedback} consumableFeedback={consumableFeedback}
retry={retry} retry={retry}
isSupportedOceanNetwork={isSupportedOceanNetwork} isSupportedOceanNetwork={isSupportedOceanNetwork}
isAccountConnected={isConnected}
/> />
) )

View File

@ -4,15 +4,18 @@ import styles from './MetaFull.module.css'
import Publisher from '@shared/Publisher' import Publisher from '@shared/Publisher'
import { useAsset } from '@context/Asset' import { useAsset } from '@context/Asset'
import { Asset, Datatoken, LoggerInstance } from '@oceanprotocol/lib' import { Asset, Datatoken, LoggerInstance } from '@oceanprotocol/lib'
import { useWeb3Legacy } from '@context/Web3Legacy'
export default function MetaFull({ ddo }: { ddo: Asset }): ReactElement { export default function MetaFull({ ddo }: { ddo: Asset }): ReactElement {
const { web3 } = useWeb3Legacy()
const [paymentCollector, setPaymentCollector] = useState<string>() const [paymentCollector, setPaymentCollector] = useState<string>()
const { isInPurgatory, assetState } = useAsset() const { isInPurgatory, assetState } = useAsset()
useEffect(() => { useEffect(() => {
if (!ddo || !web3) return
async function getInitialPaymentCollector() { async function getInitialPaymentCollector() {
try { try {
if (!ddo) return
const datatoken = new Datatoken(web3) const datatoken = new Datatoken(web3)
setPaymentCollector( setPaymentCollector(
await datatoken.getPaymentCollector(ddo.datatokens[0].address) await datatoken.getPaymentCollector(ddo.datatokens[0].address)
@ -22,7 +25,7 @@ export default function MetaFull({ ddo }: { ddo: Asset }): ReactElement {
} }
} }
getInitialPaymentCollector() getInitialPaymentCollector()
}, [ddo]) }, [ddo, web3])
function DockerImage() { function DockerImage() {
const containerInfo = ddo?.metadata?.algorithm?.container const containerInfo = ddo?.metadata?.algorithm?.container

View File

@ -24,6 +24,7 @@ import EditFeedback from './EditFeedback'
import { setNftMetadata } from '@utils/nft' import { setNftMetadata } from '@utils/nft'
import { ComputeEditForm } from './_types' import { ComputeEditForm } from './_types'
import { useAccount } from 'wagmi' import { useAccount } from 'wagmi'
import { useWeb3Legacy } from '@context/Web3Legacy'
export default function EditComputeDataset({ export default function EditComputeDataset({
asset asset
@ -33,6 +34,8 @@ export default function EditComputeDataset({
const { debug } = useUserPreferences() const { debug } = useUserPreferences()
const { address: accountId } = useAccount() const { address: accountId } = useAccount()
const { fetchAsset, isAssetNetwork } = useAsset() const { fetchAsset, isAssetNetwork } = useAsset()
const { web3 } = useWeb3Legacy()
const [success, setSuccess] = useState<string>() const [success, setSuccess] = useState<string>()
const [error, setError] = useState<string>() const [error, setError] = useState<string>()
const newAbortController = useAbortController() const newAbortController = useAbortController()

View File

@ -28,6 +28,7 @@ import { sanitizeUrl } from '@utils/url'
import { getEncryptedFiles } from '@utils/provider' import { getEncryptedFiles } from '@utils/provider'
import { assetStateToNumber } from '@utils/assetState' import { assetStateToNumber } from '@utils/assetState'
import { useAccount } from 'wagmi' import { useAccount } from 'wagmi'
import { useWeb3Legacy } from '@context/Web3Legacy'
export default function Edit({ export default function Edit({
asset asset
@ -37,7 +38,9 @@ export default function Edit({
const { debug } = useUserPreferences() const { debug } = useUserPreferences()
const { fetchAsset, isAssetNetwork, assetState } = useAsset() const { fetchAsset, isAssetNetwork, assetState } = useAsset()
const { address: accountId } = useAccount() const { address: accountId } = useAccount()
const { web3 } = useWeb3Legacy()
const newAbortController = useAbortController() const newAbortController = useAbortController()
const [success, setSuccess] = useState<string>() const [success, setSuccess] = useState<string>()
const [paymentCollector, setPaymentCollector] = useState<string>() const [paymentCollector, setPaymentCollector] = useState<string>()
const [error, setError] = useState<string>() const [error, setError] = useState<string>()

View File

@ -13,6 +13,7 @@ import content from '../../../../../content/pages/history.json'
import { useCancelToken } from '@hooks/useCancelToken' import { useCancelToken } from '@hooks/useCancelToken'
import { getAsset } from '@utils/aquarius' import { getAsset } from '@utils/aquarius'
import { useAccount } from 'wagmi' import { useAccount } from 'wagmi'
import { useWeb3Legacy } from '@context/Web3Legacy'
export default function Results({ export default function Results({
job job
@ -21,11 +22,13 @@ export default function Results({
}): ReactElement { }): ReactElement {
const providerInstance = new Provider() const providerInstance = new Provider()
const { address: accountId } = useAccount() const { address: accountId } = useAccount()
const isFinished = job.dateFinished !== null const { web3 } = useWeb3Legacy()
const [datasetProvider, setDatasetProvider] = useState<string>() const [datasetProvider, setDatasetProvider] = useState<string>()
const newCancelToken = useCancelToken() const newCancelToken = useCancelToken()
const isFinished = job.dateFinished !== null
useEffect(() => { useEffect(() => {
async function getAssetMetadata() { async function getAssetMetadata() {
const ddo = await getAsset(job.inputDID[0], newCancelToken()) const ddo = await getAsset(job.inputDID[0], newCancelToken())

View File

@ -19,6 +19,7 @@ import { validationSchema } from './_validation'
import { useAbortController } from '@hooks/useAbortController' import { useAbortController } from '@hooks/useAbortController'
import { setNFTMetadataAndTokenURI } from '@utils/nft' import { setNFTMetadataAndTokenURI } from '@utils/nft'
import { useAccount, useNetwork } from 'wagmi' import { useAccount, useNetwork } from 'wagmi'
import { useWeb3Legacy } from '@context/Web3Legacy'
export default function PublishPage({ export default function PublishPage({
content content
@ -28,6 +29,7 @@ export default function PublishPage({
const { debug } = useUserPreferences() const { debug } = useUserPreferences()
const { address: accountId } = useAccount() const { address: accountId } = useAccount()
const { chain } = useNetwork() const { chain } = useNetwork()
const { web3 } = useWeb3Legacy()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId)
const scrollToRef = useRef() const scrollToRef = useRef()
const nftFactory = useNftFactory() const nftFactory = useNftFactory()

View File

@ -13,25 +13,28 @@ import MarketMetadataProvider from '@context/MarketMetadata'
import { WagmiConfig } from 'wagmi' import { WagmiConfig } from 'wagmi'
import { Web3Modal } from '@web3modal/react' import { Web3Modal } from '@web3modal/react'
import { wagmiClient, ethereumClient } from '@utils/wallet' import { wagmiClient, ethereumClient } from '@utils/wallet'
import Web3LegacyProvider from '@context/Web3Legacy'
function MyApp({ Component, pageProps }: AppProps): ReactElement { function MyApp({ Component, pageProps }: AppProps): ReactElement {
Decimal.set({ rounding: 1 }) Decimal.set({ rounding: 1 })
return ( return (
<> <>
<WagmiConfig client={wagmiClient}> <WagmiConfig client={wagmiClient}>
<MarketMetadataProvider> <Web3LegacyProvider>
<UrqlProvider> <MarketMetadataProvider>
<UserPreferencesProvider> <UrqlProvider>
<PricesProvider> <UserPreferencesProvider>
<ConsentProvider> <PricesProvider>
<App> <ConsentProvider>
<Component {...pageProps} /> <App>
</App> <Component {...pageProps} />
</ConsentProvider> </App>
</PricesProvider> </ConsentProvider>
</UserPreferencesProvider> </PricesProvider>
</UrqlProvider> </UserPreferencesProvider>
</MarketMetadataProvider> </UrqlProvider>
</MarketMetadataProvider>
</Web3LegacyProvider>
</WagmiConfig> </WagmiConfig>
<Web3Modal <Web3Modal