diff --git a/.jest/__mocks__/hooksMocks.ts b/.jest/__mocks__/hooksMocks.ts index 6646a7335..1cd5a00d9 100644 --- a/.jest/__mocks__/hooksMocks.ts +++ b/.jest/__mocks__/hooksMocks.ts @@ -11,10 +11,6 @@ jest.mock('../../src/@context/UserPreferences', () => ({ useUserPreferences: () => userPreferences })) -jest.mock('../../src/@context/Web3', () => ({ - useWeb3: () => web3 -})) - jest.mock('../../../@context/Asset', () => ({ useAsset: () => ({ asset }) })) diff --git a/README.md b/README.md index 92674441e..0cdc488b5 100644 --- a/README.md +++ b/README.md @@ -238,12 +238,12 @@ function Component() { For account purgatory: ```tsx -import { useWeb3 } from '@context/Web3' +import { useAccount } from 'wagmi' import { useAccountPurgatory } from '@hooks/useAccountPurgatory' function Component() { - const { accountId } = useWeb3() - const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) + const { address } = useAccount() + const { isInPurgatory, purgatoryData } = useAccountPurgatory(address) return isInPurgatory ?
{purgatoryData.reason}
: null } ``` @@ -252,14 +252,12 @@ function Component() { All displayed chain & network metadata is retrieved from `https://chainid.network` on build time and integrated into NEXT's GraphQL layer. This data source is a community-maintained GitHub repository under [ethereum-lists/chains](https://github.com/ethereum-lists/chains). -Within components this metadata can be queried for under `allNetworksMetadataJson`. The `useWeb3()` hook does this in the background to expose the final `networkDisplayName` for use in components: +Within components this metadata can be queried for under `allNetworksMetadataJson`. The `useNetworkMetadata()` hook does this in the background to expose the final `networkDisplayName` for use in components: ```tsx export default function NetworkName(): ReactElement { - const { networkId, isTestnet } = useWeb3() - const { networksList } = useNetworkMetadata() - const networkData = getNetworkDataById(networksList, networkId) - const networkName = getNetworkDisplayName(networkData) + const { isTestnet } = useNetworkMetadata() + const { networkData, networkName } = useNetworkMetadata() return ( <> diff --git a/src/@context/Asset.tsx b/src/@context/Asset.tsx index d1ad226ec..b9ebdca95 100644 --- a/src/@context/Asset.tsx +++ b/src/@context/Asset.tsx @@ -10,7 +10,6 @@ import React, { import { Config, LoggerInstance, Purgatory } from '@oceanprotocol/lib' import { CancelToken } from 'axios' import { getAsset } from '@utils/aquarius' -import { useWeb3 } from './Web3' import { useCancelToken } from '@hooks/useCancelToken' import { getOceanConfig, getDevelopmentConfig } from '@utils/ocean' import { getAccessDetails } from '@utils/accessDetailsAndPricing' @@ -18,6 +17,7 @@ import { useIsMounted } from '@hooks/useIsMounted' import { useMarketMetadata } from './MarketMetadata' import { assetStateToString } from '@utils/assetState' import { isValidDid } from '@utils/ddo' +import { useAccount, useNetwork } from 'wagmi' export interface AssetProviderValue { isInPurgatory: boolean @@ -44,8 +44,9 @@ function AssetProvider({ children: ReactNode }): ReactElement { const { appConfig } = useMarketMetadata() + const { address } = useAccount() + const { chain } = useNetwork() - const { chainId, accountId } = useWeb3() const [isInPurgatory, setIsInPurgatory] = useState(false) const [purgatoryData, setPurgatoryData] = useState() const [asset, setAsset] = useState() @@ -127,14 +128,14 @@ function AssetProvider({ asset.chainId, asset.services[0].datatokenAddress, asset.services[0].timeout, - accountId + address ) setAsset((prevState) => ({ ...prevState, accessDetails })) LoggerInstance.log(`[asset] Got access details for ${did}`, accessDetails) - }, [asset?.chainId, asset?.services, accountId, did]) + }, [asset?.chainId, asset?.services, address, did]) // ----------------------------------- // 1. Get and set asset based on passed DID @@ -152,27 +153,27 @@ function AssetProvider({ if (!isMounted) return fetchAccessDetails() - }, [accountId, fetchAccessDetails, isMounted]) + }, [address, fetchAccessDetails, isMounted]) // ----------------------------------- // Check user network against asset network // ----------------------------------- useEffect(() => { - if (!chainId || !asset?.chainId) return + if (!chain?.id || !asset?.chainId) return - const isAssetNetwork = chainId === asset?.chainId + const isAssetNetwork = chain?.id === asset?.chainId setIsAssetNetwork(isAssetNetwork) - }, [chainId, asset?.chainId]) + }, [chain?.id, asset?.chainId]) // ----------------------------------- // Asset owner check against wallet user // ----------------------------------- useEffect(() => { - if (!accountId || !owner) return + if (!address || !owner) return - const isOwner = accountId?.toLowerCase() === owner.toLowerCase() + const isOwner = address?.toLowerCase() === owner.toLowerCase() setIsOwner(isOwner) - }, [accountId, owner]) + }, [address, owner]) // ----------------------------------- // Load ocean config based on asset network diff --git a/src/@context/MarketMetadata/index.tsx b/src/@context/MarketMetadata/index.tsx index 2f8fe981a..75a3b82ad 100644 --- a/src/@context/MarketMetadata/index.tsx +++ b/src/@context/MarketMetadata/index.tsx @@ -99,7 +99,8 @@ function MarketMetadataProvider({ opcFees, siteContent, appConfig, - getOpcFeeForToken + getOpcFeeForToken, + approvedBaseTokens } as MarketMetadataProviderValue } > diff --git a/src/@context/Web3.tsx b/src/@context/Web3.tsx deleted file mode 100644 index adf2a0ceb..000000000 --- a/src/@context/Web3.tsx +++ /dev/null @@ -1,100 +0,0 @@ -import React, { - useContext, - useState, - useEffect, - createContext, - ReactElement, - ReactNode, - useCallback -} from 'react' -import { LoggerInstance } from '@oceanprotocol/lib' -import { useMarketMetadata } from './MarketMetadata' -import { useNetwork, useAccount, useProvider } from 'wagmi' -import { utils } from 'ethers' -import { getTokenBalance } from '@utils/web3' -import useNetworkMetadata from '@hooks/useNetworkMetadata' - -interface Web3ProviderValue { - balance: UserBalance -} - -// const web3ModalTheme = { -// background: 'var(--background-body)', -// main: 'var(--font-color-heading)', -// secondary: 'var(--brand-grey-light)', -// border: 'var(--border-color)', -// hover: 'var(--background-highlight)' -// } - -const refreshInterval = 20000 // 20 sec. - -const Web3Context = createContext({} as Web3ProviderValue) - -function Web3Provider({ children }: { children: ReactNode }): ReactElement { - const { approvedBaseTokens } = useMarketMetadata() - const { networkData } = useNetworkMetadata() - const { chain } = useNetwork() - const { address } = useAccount() - const provider = useProvider() - - const [balance, setBalance] = useState({ - eth: '0' - }) - - // ----------------------------------- - // Helper: Get user balance - // ----------------------------------- - const getUserBalance = useCallback(async () => { - if (!address || !chain?.id || !provider) return - - try { - const userBalance = utils.formatEther(await provider.getBalance('latest')) - const key = networkData.nativeCurrency.symbol.toLowerCase() - const balance: UserBalance = { [key]: userBalance } - - if (approvedBaseTokens?.length > 0) { - await Promise.all( - approvedBaseTokens.map(async (token) => { - const { address, decimals, symbol } = token - const tokenBalance = await getTokenBalance( - address, - decimals, - address, - provider - ) - balance[symbol.toLocaleLowerCase()] = tokenBalance - }) - ) - } - - setBalance(balance) - LoggerInstance.log('[web3] Balance: ', balance) - } catch (error) { - LoggerInstance.error('[web3] Error: ', error.message) - } - }, [address, approvedBaseTokens, chain?.id, provider]) - - // ----------------------------------- - // Get and set user balance - // ----------------------------------- - useEffect(() => { - getUserBalance() - - // init periodic refresh of wallet balance - const balanceInterval = setInterval(() => getUserBalance(), refreshInterval) - - return () => { - clearInterval(balanceInterval) - } - }, [getUserBalance]) - - return ( - {children} - ) -} - -// Helper hook to access the provider values -const useWeb3 = (): Web3ProviderValue => useContext(Web3Context) - -export { Web3Provider, useWeb3, Web3Context } -export default Web3Provider diff --git a/src/@hooks/useBalance.tsx b/src/@hooks/useBalance.tsx new file mode 100644 index 000000000..8de79290e --- /dev/null +++ b/src/@hooks/useBalance.tsx @@ -0,0 +1,84 @@ +import React, { + useContext, + useState, + useEffect, + createContext, + ReactElement, + ReactNode, + useCallback +} from 'react' +import { LoggerInstance } from '@oceanprotocol/lib' +import { useMarketMetadata } from '../@context/MarketMetadata' +import { + useNetwork, + useAccount, + useProvider, + useBalance as useBalanceWagmi +} from 'wagmi' +import { utils } from 'ethers' +import { getTokenBalance } from '@utils/web3' + +interface BalanceProviderValue { + balance: UserBalance +} + +function useBalance(): BalanceProviderValue { + const { address } = useAccount() + const { data: balanceNativeToken } = useBalanceWagmi({ address }) + + const { approvedBaseTokens } = useMarketMetadata() + const { chain } = useNetwork() + + const web3provider = useProvider() + + const [balance, setBalance] = useState({ + eth: '0' + }) + + // ----------------------------------- + // Helper: Get user balance + // ----------------------------------- + const getUserBalance = useCallback(async () => { + if ( + !balanceNativeToken?.formatted || + !address || + !chain?.id || + !web3provider + ) + return + + try { + const userBalance = balanceNativeToken?.formatted + const key = balanceNativeToken?.symbol.toLowerCase() + const newBalance: UserBalance = { [key]: userBalance } + + if (approvedBaseTokens?.length > 0) { + await Promise.all( + approvedBaseTokens.map(async (token) => { + const { address: tokenAddress, decimals, symbol } = token + const tokenBalance = await getTokenBalance( + address, + decimals, + tokenAddress, + web3provider + ) + newBalance[symbol.toLocaleLowerCase()] = tokenBalance + }) + ) + } + + setBalance(newBalance) + LoggerInstance.log('[useBalance] Balance: ', newBalance) + } catch (error) { + LoggerInstance.error('[useBalance] Error: ', error.message) + } + }, [address, approvedBaseTokens, chain?.id, web3provider, balanceNativeToken]) + + useEffect(() => { + getUserBalance() + }, [getUserBalance]) + + return { balance } +} + +export default useBalance diff --git a/src/@hooks/useGraphSyncStatus.ts b/src/@hooks/useGraphSyncStatus.ts index bef81fdeb..905a83b84 100644 --- a/src/@hooks/useGraphSyncStatus.ts +++ b/src/@hooks/useGraphSyncStatus.ts @@ -1,9 +1,9 @@ import { useState, useEffect } from 'react' -import { useWeb3 } from '@context/Web3' import { Config, LoggerInstance } from '@oceanprotocol/lib' import Web3 from 'web3' import axios, { AxiosResponse } from 'axios' import { getOceanConfig } from '@utils/ocean' +import { useBlockNumber } from 'wagmi' const blockDifferenceThreshold = 30 const ethGraphUrl = `https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks` @@ -55,7 +55,7 @@ async function getBlockSubgraph(subgraphUri: string) { } export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus { - const { block, web3Loading } = useWeb3() + const { data: block, isError, isLoading } = useBlockNumber() const [blockGraph, setBlockGraph] = useState() const [blockHead, setBlockHead] = useState() const [isGraphSynced, setIsGraphSynced] = useState(true) @@ -72,7 +72,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus { // Get and set head block useEffect(() => { - if (!oceanConfig?.nodeUri || web3Loading) return + if (!oceanConfig?.nodeUri || isLoading || isError) return async function initBlockHead() { const blockHead = block || (await getBlockHead(oceanConfig)) @@ -80,7 +80,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus { LoggerInstance.log('[GraphStatus] Head block: ', blockHead) } initBlockHead() - }, [web3Loading, block, oceanConfig]) + }, [isLoading, isError, block, oceanConfig]) // Get and set subgraph block useEffect(() => { @@ -101,7 +101,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus { // Set sync status useEffect(() => { - if ((!blockGraph && !blockHead) || web3Loading || subgraphLoading) return + if ((!blockGraph && !blockHead) || isLoading || subgraphLoading) return const difference = blockHead - blockGraph @@ -110,7 +110,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus { return } setIsGraphSynced(true) - }, [blockGraph, blockHead, web3Loading, subgraphLoading]) + }, [blockGraph, blockHead, isLoading, subgraphLoading]) return { blockHead, blockGraph, isGraphSynced } } diff --git a/src/@hooks/useNftFactory.ts b/src/@hooks/useNftFactory.ts index 49435659b..30055e888 100644 --- a/src/@hooks/useNftFactory.ts +++ b/src/@hooks/useNftFactory.ts @@ -1,6 +1,6 @@ import { useEffect, useState } from 'react' import { NftFactory } from '@oceanprotocol/lib' -import { useWeb3 } from '@context/Web3' +import { useWeb3 } from '@hooks/useBalance' import { getOceanConfig } from '@utils/ocean' function useNftFactory(): NftFactory { diff --git a/src/@utils/fixedRateExchange.ts b/src/@utils/fixedRateExchange.ts index d04d88703..bef673abd 100644 --- a/src/@utils/fixedRateExchange.ts +++ b/src/@utils/fixedRateExchange.ts @@ -1,6 +1,5 @@ import { FixedRateExchange, PriceAndFees } from '@oceanprotocol/lib' import { consumeMarketFixedSwapFee } from '../../app.config' -import Web3 from 'web3' import { getOceanConfig } from './ocean' /** @@ -13,14 +12,17 @@ import { getOceanConfig } from './ocean' export async function getFixedBuyPrice( accessDetails: AccessDetails, chainId?: number, - web3?: Web3 + web3Provider?: any ): Promise { - if (!web3 && !chainId) + if (!web3Provider && !chainId) throw new Error("web3 and chainId can't be undefined at the same time!") const config = getOceanConfig(chainId) - const fixed = new FixedRateExchange(config.fixedRateExchangeAddress, web3) + const fixed = new FixedRateExchange( + config.fixedRateExchangeAddress, + web3Provider + ) const estimatedPrice = await fixed.calcBaseInGivenDatatokensOut( accessDetails.addressOrId, '1', diff --git a/src/@utils/web3.ts b/src/@utils/web3.ts index 449491618..2cf977222 100644 --- a/src/@utils/web3.ts +++ b/src/@utils/web3.ts @@ -140,7 +140,7 @@ export async function getTokenBalance( ): Promise { try { const token = new ethers.Contract(tokenAddress, erc20ABI, web3Provider) - const balance = await token.methods.balanceOf(accountId).call() + const balance = await token.balanceOf(accountId) const adjustedDecimalsBalance = `${balance}${'0'.repeat(18 - decimals)}` return utils.formatEther(adjustedDecimalsBalance) } catch (e) { diff --git a/src/components/@shared/AddToken/index.tsx b/src/components/@shared/AddToken/index.tsx index f5e727e69..dccb2d2ba 100644 --- a/src/components/@shared/AddToken/index.tsx +++ b/src/components/@shared/AddToken/index.tsx @@ -1,10 +1,10 @@ import React, { ReactElement } from 'react' import classNames from 'classnames/bind' import { addTokenToWallet } from '@utils/web3' -import { useWeb3 } from '@context/Web3' import Button from '@shared/atoms/Button' import OceanLogo from '@images/logo.svg' import styles from './index.module.css' +import { useProvider } from 'wagmi' const cx = classNames.bind(styles) @@ -23,7 +23,7 @@ export default function AddToken({ className, minimal }: AddTokenProps): ReactElement { - const { web3Provider } = useWeb3() + const web3Provider = useProvider() const styleClasses = cx({ button: true, diff --git a/src/components/@shared/FormInput/InputElement/Provider/index.tsx b/src/components/@shared/FormInput/InputElement/Provider/index.tsx index 5b735db0d..88ed42a18 100644 --- a/src/components/@shared/FormInput/InputElement/Provider/index.tsx +++ b/src/components/@shared/FormInput/InputElement/Provider/index.tsx @@ -8,12 +8,12 @@ import Button from '@shared/atoms/Button' import { LoggerInstance, ProviderInstance } from '@oceanprotocol/lib' import { FormPublishData } from '@components/Publish/_types' import { getOceanConfig } from '@utils/ocean' -import { useWeb3 } from '@context/Web3' import axios from 'axios' import { useCancelToken } from '@hooks/useCancelToken' +import { useNetwork } from 'wagmi' export default function CustomProvider(props: InputProps): ReactElement { - const { chainId } = useWeb3() + const { chain } = useNetwork() const newCancelToken = useCancelToken() const { initialValues, setFieldError } = useFormikContext() const [field, meta, helpers] = useField(props.name) @@ -41,7 +41,7 @@ export default function CustomProvider(props: InputProps): ReactElement { cancelToken: newCancelToken() }) const providerChainId = providerResponse?.data?.chainId - const userChainId = chainId || 1 + const userChainId = chain?.id || 1 if (providerChainId !== userChainId) throw Error( @@ -66,7 +66,7 @@ export default function CustomProvider(props: InputProps): ReactElement { function handleDefault(e: React.SyntheticEvent) { e.preventDefault() - const oceanConfig = getOceanConfig(chainId) + const oceanConfig = getOceanConfig(chain?.id) const providerUrl = oceanConfig?.providerUri || initialValues.services[0].providerUrl.url diff --git a/src/components/@shared/WalletNetworkSwitcher/index.tsx b/src/components/@shared/WalletNetworkSwitcher/index.tsx index 6d917b3f3..65e3775b7 100644 --- a/src/components/@shared/WalletNetworkSwitcher/index.tsx +++ b/src/components/@shared/WalletNetworkSwitcher/index.tsx @@ -1,5 +1,4 @@ import React, { ReactElement } from 'react' -import { useWeb3 } from '@context/Web3' import Button from '@shared/atoms/Button' import styles from './index.module.css' import { addCustomNetwork } from '@utils/web3' @@ -8,14 +7,16 @@ import useNetworkMetadata, { getNetworkDisplayName } from '@hooks/useNetworkMetadata' import { useAsset } from '@context/Asset' +import { useNetwork, useProvider } from 'wagmi' export default function WalletNetworkSwitcher(): ReactElement { - const { networkId, web3Provider } = useWeb3() + const { chain } = useNetwork() + const web3Provider = useProvider() const { asset } = useAsset() const { networksList } = useNetworkMetadata() const ddoNetworkData = getNetworkDataById(networksList, asset.chainId) - const walletNetworkData = getNetworkDataById(networksList, networkId) + const walletNetworkData = getNetworkDataById(networksList, chain?.id) const ddoNetworkName = ( {getNetworkDisplayName(ddoNetworkData)} diff --git a/src/components/App/index.tsx b/src/components/App/index.tsx index e9eb4580a..026c469bb 100644 --- a/src/components/App/index.tsx +++ b/src/components/App/index.tsx @@ -2,7 +2,6 @@ import React, { ReactElement } from 'react' import Alert from '@shared/atoms/Alert' import Footer from '../Footer/Footer' import Header from '../Header' -import { useWeb3 } from '@context/Web3' import { useAccountPurgatory } from '@hooks/useAccountPurgatory' import AnnouncementBanner from '@shared/AnnouncementBanner' import PrivacyPreferenceCenter from '../Privacy/PrivacyPreferenceCenter' @@ -10,6 +9,7 @@ import styles from './index.module.css' import { ToastContainer } from 'react-toastify' import contentPurgatory from '../../../content/purgatory.json' import { useMarketMetadata } from '@context/MarketMetadata' +import { useAccount } from 'wagmi' export default function App({ children @@ -17,8 +17,8 @@ export default function App({ children: ReactElement }): ReactElement { const { siteContent, appConfig } = useMarketMetadata() - const { accountId } = useWeb3() - const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) + const { address } = useAccount() + const { isInPurgatory, purgatoryData } = useAccountPurgatory(address) return (
diff --git a/src/components/Asset/AssetActions/AssetStats/index.tsx b/src/components/Asset/AssetActions/AssetStats/index.tsx index cc414890c..fe8fc8603 100644 --- a/src/components/Asset/AssetActions/AssetStats/index.tsx +++ b/src/components/Asset/AssetActions/AssetStats/index.tsx @@ -1,32 +1,32 @@ import { useAsset } from '@context/Asset' import { useUserPreferences } from '@context/UserPreferences' -import { useWeb3 } from '@context/Web3' import Tooltip from '@shared/atoms/Tooltip' import { formatNumber } from '@utils/numbers' import { getNftOwnAllocation } from '@utils/veAllocation' import React, { useEffect, useState } from 'react' +import { useAccount } from 'wagmi' import styles from './index.module.css' export default function AssetStats() { const { locale } = useUserPreferences() const { asset } = useAsset() - const { accountId } = useWeb3() + const { address } = useAccount() const [ownAllocation, setOwnAllocation] = useState(0) useEffect(() => { - if (!asset || !accountId) return + if (!asset || !address) return async function init() { const allocation = await getNftOwnAllocation( - accountId, + address, asset.nftAddress, asset.chainId ) setOwnAllocation(allocation / 100) } init() - }, [accountId, asset]) + }, [address, asset]) return (
diff --git a/src/components/Asset/AssetActions/ButtonBuy/index.tsx b/src/components/Asset/AssetActions/ButtonBuy/index.tsx index 6bd77e2dc..6e65df2fb 100644 --- a/src/components/Asset/AssetActions/ButtonBuy/index.tsx +++ b/src/components/Asset/AssetActions/ButtonBuy/index.tsx @@ -2,7 +2,7 @@ import React, { FormEvent, ReactElement } from 'react' import Button from '../../../@shared/atoms/Button' import styles from './index.module.css' import Loader from '../../../@shared/atoms/Loader' -import { useWeb3 } from '@context/Web3' +import { useWeb3 } from '@hooks/useBalance' import Web3 from 'web3' export interface ButtonBuyProps { diff --git a/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx b/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx index a84e7af13..40792b021 100644 --- a/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx +++ b/src/components/Asset/AssetActions/Compute/FormComputeDataset.tsx @@ -7,7 +7,7 @@ import { compareAsBN } from '@utils/numbers' import ButtonBuy from '../ButtonBuy' import PriceOutput from './PriceOutput' import { useAsset } from '@context/Asset' -import { useWeb3 } from '@context/Web3' +import { useWeb3 } from '@hooks/useBalance' import content from '../../../../../content/pages/startComputeDataset.json' import { Asset, ZERO_ADDRESS } from '@oceanprotocol/lib' import { getAccessDetails } from '@utils/accessDetailsAndPricing' diff --git a/src/components/Asset/AssetActions/Compute/PriceOutput.tsx b/src/components/Asset/AssetActions/Compute/PriceOutput.tsx index 52069e975..b0e8daef5 100644 --- a/src/components/Asset/AssetActions/Compute/PriceOutput.tsx +++ b/src/components/Asset/AssetActions/Compute/PriceOutput.tsx @@ -5,7 +5,7 @@ import Tooltip from '@shared/atoms/Tooltip' import styles from './PriceOutput.module.css' import { MAX_DECIMALS } from '@utils/constants' import Decimal from 'decimal.js' -import { useWeb3 } from '@context/Web3' +import { useWeb3 } from '@hooks/useBalance' interface PriceOutputProps { hasPreviousOrder: boolean diff --git a/src/components/Asset/AssetActions/Compute/index.tsx b/src/components/Asset/AssetActions/Compute/index.tsx index ade565249..02463ba96 100644 --- a/src/components/Asset/AssetActions/Compute/index.tsx +++ b/src/components/Asset/AssetActions/Compute/index.tsx @@ -19,7 +19,7 @@ import { toast } from 'react-toastify' import Price from '@shared/Price' import FileIcon from '@shared/FileIcon' import Alert from '@shared/atoms/Alert' -import { useWeb3 } from '@context/Web3' +import { useWeb3 } from '@hooks/useBalance' import { Formik } from 'formik' import { getInitialValues, validationSchema } from './_constants' import FormStartComputeDataset from './FormComputeDataset' diff --git a/src/components/Asset/AssetActions/Download.tsx b/src/components/Asset/AssetActions/Download.tsx index 4aad6a9f8..b438873a4 100644 --- a/src/components/Asset/AssetActions/Download.tsx +++ b/src/components/Asset/AssetActions/Download.tsx @@ -2,7 +2,7 @@ import React, { ReactElement, useEffect, useState } from 'react' import FileIcon from '@shared/FileIcon' import Price from '@shared/Price' import { useAsset } from '@context/Asset' -import { useWeb3 } from '@context/Web3' +import { useWeb3 } from '@hooks/useBalance' import ButtonBuy from './ButtonBuy' import { secondsToString } from '@utils/ddo' import AlgorithmDatasetsListForCompute from './Compute/AlgorithmDatasetsListForCompute' diff --git a/src/components/Asset/AssetActions/index.tsx b/src/components/Asset/AssetActions/index.tsx index 197e1a898..50f722498 100644 --- a/src/components/Asset/AssetActions/index.tsx +++ b/src/components/Asset/AssetActions/index.tsx @@ -5,7 +5,6 @@ import { FileInfo, LoggerInstance, Datatoken } from '@oceanprotocol/lib' import Tabs, { TabsItem } from '@shared/atoms/Tabs' import { compareAsBN } from '@utils/numbers' import { useAsset } from '@context/Asset' -import { useWeb3 } from '@context/Web3' import Web3Feedback from '@shared/Web3Feedback' import { getFileDidInfo, getFileInfo } from '@utils/provider' import { getOceanConfig } from '@utils/ocean' @@ -16,13 +15,17 @@ import { useFormikContext } from 'formik' import { FormPublishData } from '@components/Publish/_types' import { getTokenBalanceFromSymbol } from '@utils/web3' import AssetStats from './AssetStats' +import { useAccount, useProvider } from 'wagmi' +import useBalance from '@hooks/useBalance' export default function AssetActions({ asset }: { asset: AssetExtended }): ReactElement { - const { accountId, balance, web3 } = useWeb3() + const { address } = useAccount() + const { balance } = useBalance() + const web3Provider = useProvider() const { isAssetNetwork } = useAsset() const newCancelToken = useCancelToken() const isMounted = useIsMounted() @@ -89,14 +92,14 @@ export default function AssetActions({ // Get and set user DT balance useEffect(() => { - if (!web3 || !accountId || !isAssetNetwork) return + if (!web3 || !address || !isAssetNetwork) return async function init() { try { - const datatokenInstance = new Datatoken(web3) + const datatokenInstance = new Datatoken(web3Provider as any) const dtBalance = await datatokenInstance.balance( asset.services[0].datatokenAddress, - accountId + address ) setDtBalance(dtBalance) } catch (e) { @@ -104,7 +107,7 @@ export default function AssetActions({ } } init() - }, [web3, accountId, asset, isAssetNetwork]) + }, [web3Provider, address, asset, isAssetNetwork]) // Check user balance against price useEffect(() => { @@ -112,7 +115,7 @@ export default function AssetActions({ if ( !asset?.accessDetails?.price || !asset?.accessDetails?.baseToken?.symbol || - !accountId || + !address || !balance || !dtBalance ) @@ -130,7 +133,7 @@ export default function AssetActions({ return () => { setIsBalanceSufficient(false) } - }, [balance, accountId, asset?.accessDetails, dtBalance]) + }, [balance, address, asset?.accessDetails, dtBalance]) const UseContent = ( <> @@ -161,7 +164,7 @@ export default function AssetActions({ diff --git a/src/components/Asset/AssetContent/MetaMain/MetaAsset.tsx b/src/components/Asset/AssetContent/MetaMain/MetaAsset.tsx index 1713d180c..d4f160622 100644 --- a/src/components/Asset/AssetContent/MetaMain/MetaAsset.tsx +++ b/src/components/Asset/AssetContent/MetaMain/MetaAsset.tsx @@ -1,10 +1,10 @@ import { useAsset } from '@context/Asset' -import { useWeb3 } from '@context/Web3' import { Asset } from '@oceanprotocol/lib' import AddToken from '@shared/AddToken' import ExplorerLink from '@shared/ExplorerLink' import Publisher from '@shared/Publisher' import React, { ReactElement } from 'react' +import { useAccount } from 'wagmi' import styles from './MetaAsset.module.css' export default function MetaAsset({ @@ -15,7 +15,7 @@ export default function MetaAsset({ isBlockscoutExplorer: boolean }): ReactElement { const { isAssetNetwork } = useAsset() - const { web3ProviderInfo } = useWeb3() + const { connector: activeConnector } = useAccount() const dataTokenSymbol = asset?.datatokens[0]?.symbol @@ -36,7 +36,7 @@ export default function MetaAsset({ > {`Accessed with ${dataTokenSymbol}`} - {web3ProviderInfo?.name === 'MetaMask' && isAssetNetwork && ( + {activeConnector?.name === 'MetaMask' && isAssetNetwork && ( { - if (!accountId) return + if (!address) return async function checkAllocations() { try { - const allocations = await getOwnAllocations(chainIds, accountId) + const allocations = await getOwnAllocations(chainIds, address) setHasAllocations(allocations && allocations.length > 0) } catch (error) { LoggerInstance.error(error.message) } } checkAllocations() - }, [accountId, chainIds]) + }, [address, chainIds]) useEffect(() => { async function getAllocationAssets() { @@ -44,7 +44,7 @@ export default function Allocations(): ReactElement { try { setLoading(true) - const allocations = await getOwnAllocations(chainIds, accountId) + const allocations = await getOwnAllocations(chainIds, address) setHasAllocations(allocations && allocations.length > 0) const baseParams = { @@ -82,7 +82,7 @@ export default function Allocations(): ReactElement { } } getAllocationAssets() - }, [hasAllocations, accountId, chainIds, isMounted, newCancelToken]) + }, [hasAllocations, address, chainIds, isMounted, newCancelToken]) return (
diff --git a/src/components/Home/Bookmarks.tsx b/src/components/Home/Bookmarks.tsx index cd3037dac..ff72241f4 100644 --- a/src/components/Home/Bookmarks.tsx +++ b/src/components/Home/Bookmarks.tsx @@ -7,8 +7,8 @@ import Tooltip from '@shared/atoms/Tooltip' import AssetTitle from '@shared/AssetListTitle' import { getAssetsFromDids } from '@utils/aquarius' import { useCancelToken } from '@hooks/useCancelToken' -import { useWeb3 } from '@context/Web3' import { useMarketMetadata } from '@context/MarketMetadata' +import { useAccount } from 'wagmi' const columns: TableOceanColumn[] = [ { @@ -38,7 +38,7 @@ const columns: TableOceanColumn[] = [ export default function Bookmarks(): ReactElement { const { appConfig } = useMarketMetadata() - const { accountId } = useWeb3() + const { address } = useAccount() const { bookmarks } = useUserPreferences() const [pinned, setPinned] = useState() @@ -77,7 +77,7 @@ export default function Bookmarks(): ReactElement { appConfig?.metadataCacheUri, bookmarks, chainIds, - accountId, + address, newCancelToken ]) diff --git a/src/components/Profile/Header/Stats.tsx b/src/components/Profile/Header/Stats.tsx index fbd474761..00613f3f9 100644 --- a/src/components/Profile/Header/Stats.tsx +++ b/src/components/Profile/Header/Stats.tsx @@ -8,14 +8,14 @@ import { useProfile } from '@context/Profile' import { getLocked } from '@utils/veAllocation' import PriceUnit from '@shared/Price/PriceUnit' import Button from '@shared/atoms/Button' -import { useWeb3 } from '@context/Web3' +import { useAccount } from 'wagmi' export default function Stats({ accountId }: { accountId: string }): ReactElement { - const web3 = useWeb3() + const { address } = useAccount() const { chainIds } = useUserPreferences() const { assets, assetsTotal, sales } = useProfile() @@ -73,7 +73,7 @@ export default function Stats({ {children}
@@ -55,11 +55,11 @@ export default function ComputeJobs({ isLoading?: boolean refetchJobs?: any }): ReactElement { - const { accountId } = useWeb3() + const { address } = useAccount() const { chainIds } = useUserPreferences() const [columnsMinimal] = useState([columns[4], columns[5], columns[3]]) - return accountId ? ( + return address ? ( <> {jobs?.length >= 0 && !minimal && ( - ) : !accountId ? ( - - ) : !isSupportedOceanNetwork ? ( + ) : // !address ? ( + // + // ) : + !isSupportedOceanNetwork ? ( }>