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

kick out useWeb3

This commit is contained in:
Matthias Kretschmann 2023-01-18 23:54:31 +00:00
parent da2625a6f8
commit feafce022b
Signed by: m
GPG Key ID: 606EEEF3C479A91F
40 changed files with 263 additions and 254 deletions

View File

@ -11,10 +11,6 @@ jest.mock('../../src/@context/UserPreferences', () => ({
useUserPreferences: () => userPreferences useUserPreferences: () => userPreferences
})) }))
jest.mock('../../src/@context/Web3', () => ({
useWeb3: () => web3
}))
jest.mock('../../../@context/Asset', () => ({ jest.mock('../../../@context/Asset', () => ({
useAsset: () => ({ asset }) useAsset: () => ({ asset })
})) }))

View File

@ -238,12 +238,12 @@ function Component() {
For account purgatory: For account purgatory:
```tsx ```tsx
import { useWeb3 } from '@context/Web3' import { useAccount } from 'wagmi'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory' import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
function Component() { function Component() {
const { accountId } = useWeb3() const { address } = useAccount()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) const { isInPurgatory, purgatoryData } = useAccountPurgatory(address)
return isInPurgatory ? <div>{purgatoryData.reason}</div> : null return isInPurgatory ? <div>{purgatoryData.reason}</div> : 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). 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 ```tsx
export default function NetworkName(): ReactElement { export default function NetworkName(): ReactElement {
const { networkId, isTestnet } = useWeb3() const { isTestnet } = useNetworkMetadata()
const { networksList } = useNetworkMetadata() const { networkData, networkName } = useNetworkMetadata()
const networkData = getNetworkDataById(networksList, networkId)
const networkName = getNetworkDisplayName(networkData)
return ( return (
<> <>

View File

@ -10,7 +10,6 @@ import React, {
import { Config, LoggerInstance, Purgatory } from '@oceanprotocol/lib' import { Config, LoggerInstance, Purgatory } from '@oceanprotocol/lib'
import { CancelToken } from 'axios' import { CancelToken } from 'axios'
import { getAsset } from '@utils/aquarius' import { getAsset } from '@utils/aquarius'
import { useWeb3 } from './Web3'
import { useCancelToken } from '@hooks/useCancelToken' import { useCancelToken } from '@hooks/useCancelToken'
import { getOceanConfig, getDevelopmentConfig } from '@utils/ocean' import { getOceanConfig, getDevelopmentConfig } from '@utils/ocean'
import { getAccessDetails } from '@utils/accessDetailsAndPricing' import { getAccessDetails } from '@utils/accessDetailsAndPricing'
@ -18,6 +17,7 @@ import { useIsMounted } from '@hooks/useIsMounted'
import { useMarketMetadata } from './MarketMetadata' import { useMarketMetadata } from './MarketMetadata'
import { assetStateToString } from '@utils/assetState' import { assetStateToString } from '@utils/assetState'
import { isValidDid } from '@utils/ddo' import { isValidDid } from '@utils/ddo'
import { useAccount, useNetwork } from 'wagmi'
export interface AssetProviderValue { export interface AssetProviderValue {
isInPurgatory: boolean isInPurgatory: boolean
@ -44,8 +44,9 @@ function AssetProvider({
children: ReactNode children: ReactNode
}): ReactElement { }): ReactElement {
const { appConfig } = useMarketMetadata() const { appConfig } = useMarketMetadata()
const { address } = useAccount()
const { chain } = useNetwork()
const { chainId, accountId } = useWeb3()
const [isInPurgatory, setIsInPurgatory] = useState(false) const [isInPurgatory, setIsInPurgatory] = useState(false)
const [purgatoryData, setPurgatoryData] = useState<Purgatory>() const [purgatoryData, setPurgatoryData] = useState<Purgatory>()
const [asset, setAsset] = useState<AssetExtended>() const [asset, setAsset] = useState<AssetExtended>()
@ -127,14 +128,14 @@ function AssetProvider({
asset.chainId, asset.chainId,
asset.services[0].datatokenAddress, asset.services[0].datatokenAddress,
asset.services[0].timeout, asset.services[0].timeout,
accountId address
) )
setAsset((prevState) => ({ setAsset((prevState) => ({
...prevState, ...prevState,
accessDetails accessDetails
})) }))
LoggerInstance.log(`[asset] Got access details for ${did}`, 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 // 1. Get and set asset based on passed DID
@ -152,27 +153,27 @@ function AssetProvider({
if (!isMounted) return if (!isMounted) return
fetchAccessDetails() fetchAccessDetails()
}, [accountId, fetchAccessDetails, isMounted]) }, [address, fetchAccessDetails, isMounted])
// ----------------------------------- // -----------------------------------
// Check user network against asset network // Check user network against asset network
// ----------------------------------- // -----------------------------------
useEffect(() => { 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) setIsAssetNetwork(isAssetNetwork)
}, [chainId, asset?.chainId]) }, [chain?.id, asset?.chainId])
// ----------------------------------- // -----------------------------------
// Asset owner check against wallet user // Asset owner check against wallet user
// ----------------------------------- // -----------------------------------
useEffect(() => { useEffect(() => {
if (!accountId || !owner) return if (!address || !owner) return
const isOwner = accountId?.toLowerCase() === owner.toLowerCase() const isOwner = address?.toLowerCase() === owner.toLowerCase()
setIsOwner(isOwner) setIsOwner(isOwner)
}, [accountId, owner]) }, [address, owner])
// ----------------------------------- // -----------------------------------
// Load ocean config based on asset network // Load ocean config based on asset network

View File

@ -99,7 +99,8 @@ function MarketMetadataProvider({
opcFees, opcFees,
siteContent, siteContent,
appConfig, appConfig,
getOpcFeeForToken getOpcFeeForToken,
approvedBaseTokens
} as MarketMetadataProviderValue } as MarketMetadataProviderValue
} }
> >

View File

@ -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<UserBalance>({
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 (
<Web3Context.Provider value={{ balance }}>{children}</Web3Context.Provider>
)
}
// Helper hook to access the provider values
const useWeb3 = (): Web3ProviderValue => useContext(Web3Context)
export { Web3Provider, useWeb3, Web3Context }
export default Web3Provider

84
src/@hooks/useBalance.tsx Normal file
View File

@ -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<UserBalance>({
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

View File

@ -1,9 +1,9 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { useWeb3 } from '@context/Web3'
import { Config, LoggerInstance } from '@oceanprotocol/lib' import { Config, LoggerInstance } from '@oceanprotocol/lib'
import Web3 from 'web3' import Web3 from 'web3'
import axios, { AxiosResponse } from 'axios' import axios, { AxiosResponse } from 'axios'
import { getOceanConfig } from '@utils/ocean' import { getOceanConfig } from '@utils/ocean'
import { useBlockNumber } from 'wagmi'
const blockDifferenceThreshold = 30 const blockDifferenceThreshold = 30
const ethGraphUrl = `https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks` 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 { export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
const { block, web3Loading } = useWeb3() const { data: block, isError, isLoading } = useBlockNumber()
const [blockGraph, setBlockGraph] = useState<number>() const [blockGraph, setBlockGraph] = useState<number>()
const [blockHead, setBlockHead] = useState<number>() const [blockHead, setBlockHead] = useState<number>()
const [isGraphSynced, setIsGraphSynced] = useState(true) const [isGraphSynced, setIsGraphSynced] = useState(true)
@ -72,7 +72,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
// Get and set head block // Get and set head block
useEffect(() => { useEffect(() => {
if (!oceanConfig?.nodeUri || web3Loading) return if (!oceanConfig?.nodeUri || isLoading || isError) return
async function initBlockHead() { async function initBlockHead() {
const blockHead = block || (await getBlockHead(oceanConfig)) const blockHead = block || (await getBlockHead(oceanConfig))
@ -80,7 +80,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
LoggerInstance.log('[GraphStatus] Head block: ', blockHead) LoggerInstance.log('[GraphStatus] Head block: ', blockHead)
} }
initBlockHead() initBlockHead()
}, [web3Loading, block, oceanConfig]) }, [isLoading, isError, block, oceanConfig])
// Get and set subgraph block // Get and set subgraph block
useEffect(() => { useEffect(() => {
@ -101,7 +101,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
// Set sync status // Set sync status
useEffect(() => { useEffect(() => {
if ((!blockGraph && !blockHead) || web3Loading || subgraphLoading) return if ((!blockGraph && !blockHead) || isLoading || subgraphLoading) return
const difference = blockHead - blockGraph const difference = blockHead - blockGraph
@ -110,7 +110,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
return return
} }
setIsGraphSynced(true) setIsGraphSynced(true)
}, [blockGraph, blockHead, web3Loading, subgraphLoading]) }, [blockGraph, blockHead, isLoading, subgraphLoading])
return { blockHead, blockGraph, isGraphSynced } return { blockHead, blockGraph, isGraphSynced }
} }

View File

@ -1,6 +1,6 @@
import { useEffect, useState } from 'react' import { useEffect, useState } from 'react'
import { NftFactory } from '@oceanprotocol/lib' import { NftFactory } from '@oceanprotocol/lib'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import { getOceanConfig } from '@utils/ocean' import { getOceanConfig } from '@utils/ocean'
function useNftFactory(): NftFactory { function useNftFactory(): NftFactory {

View File

@ -1,6 +1,5 @@
import { FixedRateExchange, PriceAndFees } from '@oceanprotocol/lib' import { FixedRateExchange, PriceAndFees } from '@oceanprotocol/lib'
import { consumeMarketFixedSwapFee } from '../../app.config' import { consumeMarketFixedSwapFee } from '../../app.config'
import Web3 from 'web3'
import { getOceanConfig } from './ocean' import { getOceanConfig } from './ocean'
/** /**
@ -13,14 +12,17 @@ import { getOceanConfig } from './ocean'
export async function getFixedBuyPrice( export async function getFixedBuyPrice(
accessDetails: AccessDetails, accessDetails: AccessDetails,
chainId?: number, chainId?: number,
web3?: Web3 web3Provider?: any
): Promise<PriceAndFees> { ): Promise<PriceAndFees> {
if (!web3 && !chainId) if (!web3Provider && !chainId)
throw new Error("web3 and chainId can't be undefined at the same time!") throw new Error("web3 and chainId can't be undefined at the same time!")
const config = getOceanConfig(chainId) const config = getOceanConfig(chainId)
const fixed = new FixedRateExchange(config.fixedRateExchangeAddress, web3) const fixed = new FixedRateExchange(
config.fixedRateExchangeAddress,
web3Provider
)
const estimatedPrice = await fixed.calcBaseInGivenDatatokensOut( const estimatedPrice = await fixed.calcBaseInGivenDatatokensOut(
accessDetails.addressOrId, accessDetails.addressOrId,
'1', '1',

View File

@ -140,7 +140,7 @@ export async function getTokenBalance(
): Promise<string> { ): Promise<string> {
try { try {
const token = new ethers.Contract(tokenAddress, erc20ABI, web3Provider) 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)}` const adjustedDecimalsBalance = `${balance}${'0'.repeat(18 - decimals)}`
return utils.formatEther(adjustedDecimalsBalance) return utils.formatEther(adjustedDecimalsBalance)
} catch (e) { } catch (e) {

View File

@ -1,10 +1,10 @@
import React, { ReactElement } from 'react' import React, { ReactElement } from 'react'
import classNames from 'classnames/bind' import classNames from 'classnames/bind'
import { addTokenToWallet } from '@utils/web3' import { addTokenToWallet } from '@utils/web3'
import { useWeb3 } from '@context/Web3'
import Button from '@shared/atoms/Button' import Button from '@shared/atoms/Button'
import OceanLogo from '@images/logo.svg' import OceanLogo from '@images/logo.svg'
import styles from './index.module.css' import styles from './index.module.css'
import { useProvider } from 'wagmi'
const cx = classNames.bind(styles) const cx = classNames.bind(styles)
@ -23,7 +23,7 @@ export default function AddToken({
className, className,
minimal minimal
}: AddTokenProps): ReactElement { }: AddTokenProps): ReactElement {
const { web3Provider } = useWeb3() const web3Provider = useProvider()
const styleClasses = cx({ const styleClasses = cx({
button: true, button: true,

View File

@ -8,12 +8,12 @@ import Button from '@shared/atoms/Button'
import { LoggerInstance, ProviderInstance } from '@oceanprotocol/lib' import { LoggerInstance, ProviderInstance } from '@oceanprotocol/lib'
import { FormPublishData } from '@components/Publish/_types' import { FormPublishData } from '@components/Publish/_types'
import { getOceanConfig } from '@utils/ocean' import { getOceanConfig } from '@utils/ocean'
import { useWeb3 } from '@context/Web3'
import axios from 'axios' import axios from 'axios'
import { useCancelToken } from '@hooks/useCancelToken' import { useCancelToken } from '@hooks/useCancelToken'
import { useNetwork } from 'wagmi'
export default function CustomProvider(props: InputProps): ReactElement { export default function CustomProvider(props: InputProps): ReactElement {
const { chainId } = useWeb3() const { chain } = useNetwork()
const newCancelToken = useCancelToken() const newCancelToken = useCancelToken()
const { initialValues, setFieldError } = useFormikContext<FormPublishData>() const { initialValues, setFieldError } = useFormikContext<FormPublishData>()
const [field, meta, helpers] = useField(props.name) const [field, meta, helpers] = useField(props.name)
@ -41,7 +41,7 @@ export default function CustomProvider(props: InputProps): ReactElement {
cancelToken: newCancelToken() cancelToken: newCancelToken()
}) })
const providerChainId = providerResponse?.data?.chainId const providerChainId = providerResponse?.data?.chainId
const userChainId = chainId || 1 const userChainId = chain?.id || 1
if (providerChainId !== userChainId) if (providerChainId !== userChainId)
throw Error( throw Error(
@ -66,7 +66,7 @@ export default function CustomProvider(props: InputProps): ReactElement {
function handleDefault(e: React.SyntheticEvent) { function handleDefault(e: React.SyntheticEvent) {
e.preventDefault() e.preventDefault()
const oceanConfig = getOceanConfig(chainId) const oceanConfig = getOceanConfig(chain?.id)
const providerUrl = const providerUrl =
oceanConfig?.providerUri || initialValues.services[0].providerUrl.url oceanConfig?.providerUri || initialValues.services[0].providerUrl.url

View File

@ -1,5 +1,4 @@
import React, { ReactElement } from 'react' import React, { ReactElement } from 'react'
import { useWeb3 } from '@context/Web3'
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 { addCustomNetwork } from '@utils/web3' import { addCustomNetwork } from '@utils/web3'
@ -8,14 +7,16 @@ import useNetworkMetadata, {
getNetworkDisplayName getNetworkDisplayName
} from '@hooks/useNetworkMetadata' } from '@hooks/useNetworkMetadata'
import { useAsset } from '@context/Asset' import { useAsset } from '@context/Asset'
import { useNetwork, useProvider } from 'wagmi'
export default function WalletNetworkSwitcher(): ReactElement { export default function WalletNetworkSwitcher(): ReactElement {
const { networkId, web3Provider } = useWeb3() const { chain } = useNetwork()
const web3Provider = useProvider()
const { asset } = useAsset() const { asset } = useAsset()
const { networksList } = useNetworkMetadata() const { networksList } = useNetworkMetadata()
const ddoNetworkData = getNetworkDataById(networksList, asset.chainId) const ddoNetworkData = getNetworkDataById(networksList, asset.chainId)
const walletNetworkData = getNetworkDataById(networksList, networkId) const walletNetworkData = getNetworkDataById(networksList, chain?.id)
const ddoNetworkName = ( const ddoNetworkName = (
<strong>{getNetworkDisplayName(ddoNetworkData)}</strong> <strong>{getNetworkDisplayName(ddoNetworkData)}</strong>

View File

@ -2,7 +2,6 @@ import React, { ReactElement } from 'react'
import Alert from '@shared/atoms/Alert' import Alert from '@shared/atoms/Alert'
import Footer from '../Footer/Footer' import Footer from '../Footer/Footer'
import Header from '../Header' import Header from '../Header'
import { useWeb3 } from '@context/Web3'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory' import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
import AnnouncementBanner from '@shared/AnnouncementBanner' import AnnouncementBanner from '@shared/AnnouncementBanner'
import PrivacyPreferenceCenter from '../Privacy/PrivacyPreferenceCenter' import PrivacyPreferenceCenter from '../Privacy/PrivacyPreferenceCenter'
@ -10,6 +9,7 @@ import styles from './index.module.css'
import { ToastContainer } from 'react-toastify' import { ToastContainer } from 'react-toastify'
import contentPurgatory from '../../../content/purgatory.json' import contentPurgatory from '../../../content/purgatory.json'
import { useMarketMetadata } from '@context/MarketMetadata' import { useMarketMetadata } from '@context/MarketMetadata'
import { useAccount } from 'wagmi'
export default function App({ export default function App({
children children
@ -17,8 +17,8 @@ export default function App({
children: ReactElement children: ReactElement
}): ReactElement { }): ReactElement {
const { siteContent, appConfig } = useMarketMetadata() const { siteContent, appConfig } = useMarketMetadata()
const { accountId } = useWeb3() const { address } = useAccount()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) const { isInPurgatory, purgatoryData } = useAccountPurgatory(address)
return ( return (
<div className={styles.app}> <div className={styles.app}>

View File

@ -1,32 +1,32 @@
import { useAsset } from '@context/Asset' import { useAsset } from '@context/Asset'
import { useUserPreferences } from '@context/UserPreferences' import { useUserPreferences } from '@context/UserPreferences'
import { useWeb3 } from '@context/Web3'
import Tooltip from '@shared/atoms/Tooltip' import Tooltip from '@shared/atoms/Tooltip'
import { formatNumber } from '@utils/numbers' import { formatNumber } from '@utils/numbers'
import { getNftOwnAllocation } from '@utils/veAllocation' import { getNftOwnAllocation } from '@utils/veAllocation'
import React, { useEffect, useState } from 'react' import React, { useEffect, useState } from 'react'
import { useAccount } from 'wagmi'
import styles from './index.module.css' import styles from './index.module.css'
export default function AssetStats() { export default function AssetStats() {
const { locale } = useUserPreferences() const { locale } = useUserPreferences()
const { asset } = useAsset() const { asset } = useAsset()
const { accountId } = useWeb3() const { address } = useAccount()
const [ownAllocation, setOwnAllocation] = useState(0) const [ownAllocation, setOwnAllocation] = useState(0)
useEffect(() => { useEffect(() => {
if (!asset || !accountId) return if (!asset || !address) return
async function init() { async function init() {
const allocation = await getNftOwnAllocation( const allocation = await getNftOwnAllocation(
accountId, address,
asset.nftAddress, asset.nftAddress,
asset.chainId asset.chainId
) )
setOwnAllocation(allocation / 100) setOwnAllocation(allocation / 100)
} }
init() init()
}, [accountId, asset]) }, [address, asset])
return ( return (
<footer className={styles.stats}> <footer className={styles.stats}>

View File

@ -2,7 +2,7 @@ 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 { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import Web3 from 'web3' import Web3 from 'web3'
export interface ButtonBuyProps { export interface ButtonBuyProps {

View File

@ -7,7 +7,7 @@ import { compareAsBN } from '@utils/numbers'
import ButtonBuy from '../ButtonBuy' import ButtonBuy from '../ButtonBuy'
import PriceOutput from './PriceOutput' import PriceOutput from './PriceOutput'
import { useAsset } from '@context/Asset' import { useAsset } from '@context/Asset'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import content from '../../../../../content/pages/startComputeDataset.json' import content from '../../../../../content/pages/startComputeDataset.json'
import { Asset, ZERO_ADDRESS } from '@oceanprotocol/lib' import { Asset, ZERO_ADDRESS } from '@oceanprotocol/lib'
import { getAccessDetails } from '@utils/accessDetailsAndPricing' import { getAccessDetails } from '@utils/accessDetailsAndPricing'

View File

@ -5,7 +5,7 @@ import Tooltip from '@shared/atoms/Tooltip'
import styles from './PriceOutput.module.css' import styles from './PriceOutput.module.css'
import { MAX_DECIMALS } from '@utils/constants' import { MAX_DECIMALS } from '@utils/constants'
import Decimal from 'decimal.js' import Decimal from 'decimal.js'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
interface PriceOutputProps { interface PriceOutputProps {
hasPreviousOrder: boolean hasPreviousOrder: boolean

View File

@ -19,7 +19,7 @@ import { toast } from 'react-toastify'
import Price from '@shared/Price' import Price from '@shared/Price'
import FileIcon from '@shared/FileIcon' import FileIcon from '@shared/FileIcon'
import Alert from '@shared/atoms/Alert' import Alert from '@shared/atoms/Alert'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import { Formik } from 'formik' import { Formik } from 'formik'
import { getInitialValues, validationSchema } from './_constants' import { getInitialValues, validationSchema } from './_constants'
import FormStartComputeDataset from './FormComputeDataset' import FormStartComputeDataset from './FormComputeDataset'

View File

@ -2,7 +2,7 @@ import React, { ReactElement, useEffect, useState } from 'react'
import FileIcon from '@shared/FileIcon' import FileIcon from '@shared/FileIcon'
import Price from '@shared/Price' import Price from '@shared/Price'
import { useAsset } from '@context/Asset' import { useAsset } from '@context/Asset'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import ButtonBuy from './ButtonBuy' import ButtonBuy from './ButtonBuy'
import { secondsToString } from '@utils/ddo' import { secondsToString } from '@utils/ddo'
import AlgorithmDatasetsListForCompute from './Compute/AlgorithmDatasetsListForCompute' import AlgorithmDatasetsListForCompute from './Compute/AlgorithmDatasetsListForCompute'

View File

@ -5,7 +5,6 @@ import { FileInfo, LoggerInstance, Datatoken } from '@oceanprotocol/lib'
import Tabs, { TabsItem } from '@shared/atoms/Tabs' import Tabs, { TabsItem } from '@shared/atoms/Tabs'
import { compareAsBN } from '@utils/numbers' import { compareAsBN } from '@utils/numbers'
import { useAsset } from '@context/Asset' import { useAsset } from '@context/Asset'
import { useWeb3 } from '@context/Web3'
import Web3Feedback from '@shared/Web3Feedback' import Web3Feedback from '@shared/Web3Feedback'
import { getFileDidInfo, getFileInfo } from '@utils/provider' import { getFileDidInfo, getFileInfo } from '@utils/provider'
import { getOceanConfig } from '@utils/ocean' import { getOceanConfig } from '@utils/ocean'
@ -16,13 +15,17 @@ import { useFormikContext } from 'formik'
import { FormPublishData } from '@components/Publish/_types' import { FormPublishData } from '@components/Publish/_types'
import { getTokenBalanceFromSymbol } from '@utils/web3' import { getTokenBalanceFromSymbol } from '@utils/web3'
import AssetStats from './AssetStats' import AssetStats from './AssetStats'
import { useAccount, useProvider } from 'wagmi'
import useBalance from '@hooks/useBalance'
export default function AssetActions({ export default function AssetActions({
asset asset
}: { }: {
asset: AssetExtended asset: AssetExtended
}): ReactElement { }): ReactElement {
const { accountId, balance, web3 } = useWeb3() const { address } = useAccount()
const { balance } = useBalance()
const web3Provider = useProvider()
const { isAssetNetwork } = useAsset() const { isAssetNetwork } = useAsset()
const newCancelToken = useCancelToken() const newCancelToken = useCancelToken()
const isMounted = useIsMounted() const isMounted = useIsMounted()
@ -89,14 +92,14 @@ export default function AssetActions({
// Get and set user DT balance // Get and set user DT balance
useEffect(() => { useEffect(() => {
if (!web3 || !accountId || !isAssetNetwork) return if (!web3 || !address || !isAssetNetwork) return
async function init() { async function init() {
try { try {
const datatokenInstance = new Datatoken(web3) const datatokenInstance = new Datatoken(web3Provider as any)
const dtBalance = await datatokenInstance.balance( const dtBalance = await datatokenInstance.balance(
asset.services[0].datatokenAddress, asset.services[0].datatokenAddress,
accountId address
) )
setDtBalance(dtBalance) setDtBalance(dtBalance)
} catch (e) { } catch (e) {
@ -104,7 +107,7 @@ export default function AssetActions({
} }
} }
init() init()
}, [web3, accountId, asset, isAssetNetwork]) }, [web3Provider, address, asset, isAssetNetwork])
// Check user balance against price // Check user balance against price
useEffect(() => { useEffect(() => {
@ -112,7 +115,7 @@ export default function AssetActions({
if ( if (
!asset?.accessDetails?.price || !asset?.accessDetails?.price ||
!asset?.accessDetails?.baseToken?.symbol || !asset?.accessDetails?.baseToken?.symbol ||
!accountId || !address ||
!balance || !balance ||
!dtBalance !dtBalance
) )
@ -130,7 +133,7 @@ export default function AssetActions({
return () => { return () => {
setIsBalanceSufficient(false) setIsBalanceSufficient(false)
} }
}, [balance, accountId, asset?.accessDetails, dtBalance]) }, [balance, address, asset?.accessDetails, dtBalance])
const UseContent = ( const UseContent = (
<> <>
@ -161,7 +164,7 @@ export default function AssetActions({
<Tabs items={tabs} className={styles.actions} /> <Tabs items={tabs} className={styles.actions} />
<Web3Feedback <Web3Feedback
networkId={asset?.chainId} networkId={asset?.chainId}
accountId={accountId} accountId={address}
isAssetNetwork={isAssetNetwork} isAssetNetwork={isAssetNetwork}
/> />
</> </>

View File

@ -1,10 +1,10 @@
import { useAsset } from '@context/Asset' import { useAsset } from '@context/Asset'
import { useWeb3 } from '@context/Web3'
import { Asset } from '@oceanprotocol/lib' import { Asset } from '@oceanprotocol/lib'
import AddToken from '@shared/AddToken' import AddToken from '@shared/AddToken'
import ExplorerLink from '@shared/ExplorerLink' import ExplorerLink from '@shared/ExplorerLink'
import Publisher from '@shared/Publisher' import Publisher from '@shared/Publisher'
import React, { ReactElement } from 'react' import React, { ReactElement } from 'react'
import { useAccount } from 'wagmi'
import styles from './MetaAsset.module.css' import styles from './MetaAsset.module.css'
export default function MetaAsset({ export default function MetaAsset({
@ -15,7 +15,7 @@ export default function MetaAsset({
isBlockscoutExplorer: boolean isBlockscoutExplorer: boolean
}): ReactElement { }): ReactElement {
const { isAssetNetwork } = useAsset() const { isAssetNetwork } = useAsset()
const { web3ProviderInfo } = useWeb3() const { connector: activeConnector } = useAccount()
const dataTokenSymbol = asset?.datatokens[0]?.symbol const dataTokenSymbol = asset?.datatokens[0]?.symbol
@ -36,7 +36,7 @@ export default function MetaAsset({
> >
{`Accessed with ${dataTokenSymbol}`} {`Accessed with ${dataTokenSymbol}`}
</ExplorerLink> </ExplorerLink>
{web3ProviderInfo?.name === 'MetaMask' && isAssetNetwork && ( {activeConnector?.name === 'MetaMask' && isAssetNetwork && (
<span className={styles.addWrap}> <span className={styles.addWrap}>
<AddToken <AddToken
address={asset?.services[0].datatokenAddress} address={asset?.services[0].datatokenAddress}

View File

@ -1,4 +1,4 @@
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import { Formik } from 'formik' import { Formik } from 'formik'
import React, { ReactElement, useState } from 'react' import React, { ReactElement, useState } from 'react'
import FormEditComputeDataset from './FormEditComputeDataset' import FormEditComputeDataset from './FormEditComputeDataset'

View File

@ -12,7 +12,7 @@ import {
import { validationSchema } from './_validation' import { validationSchema } from './_validation'
import { getInitialValues } from './_constants' import { getInitialValues } from './_constants'
import { MetadataEditForm } from './_types' import { MetadataEditForm } from './_types'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import { useUserPreferences } from '@context/UserPreferences' import { useUserPreferences } from '@context/UserPreferences'
import Web3Feedback from '@shared/Web3Feedback' import Web3Feedback from '@shared/Web3Feedback'
import FormEditMetadata from './FormEditMetadata' import FormEditMetadata from './FormEditMetadata'

View File

@ -7,7 +7,7 @@ import Conversion from '@shared/Price/Conversion'
import { getOceanConfig } from '@utils/ocean' import { getOceanConfig } from '@utils/ocean'
import { useNetwork, useProvider, useDisconnect, useAccount } from 'wagmi' import { useNetwork, useProvider, useDisconnect, useAccount } from 'wagmi'
import styles from './Details.module.css' import styles from './Details.module.css'
import { useWeb3 } from '@context/Web3' import useBalance from '@hooks/useBalance'
import { useWeb3Modal } from '@web3modal/react' import { useWeb3Modal } from '@web3modal/react'
import useNetworkMetadata from '@hooks/useNetworkMetadata' import useNetworkMetadata from '@hooks/useNetworkMetadata'
@ -17,7 +17,7 @@ export default function Details(): ReactElement {
const { open: openWeb3Modal } = useWeb3Modal() const { open: openWeb3Modal } = useWeb3Modal()
const { disconnect } = useDisconnect() const { disconnect } = useDisconnect()
const provider = useProvider() const provider = useProvider()
const { balance } = useWeb3() const { balance } = useBalance()
const { networkData } = useNetworkMetadata() const { networkData } = useNetworkMetadata()
const { locale } = useUserPreferences() const { locale } = useUserPreferences()

View File

@ -1,5 +1,4 @@
import React, { ReactElement, useEffect, useState } from 'react' import React, { ReactElement, useEffect, useState } from 'react'
import { useWeb3 } from '@context/Web3'
import { AssetWithOwnAllocation, getOwnAllocations } from '@utils/veAllocation' import { AssetWithOwnAllocation, getOwnAllocations } from '@utils/veAllocation'
import styles from './index.module.css' import styles from './index.module.css'
import { import {
@ -12,9 +11,10 @@ import { useCancelToken } from '@hooks/useCancelToken'
import { useIsMounted } from '@hooks/useIsMounted' import { useIsMounted } from '@hooks/useIsMounted'
import { LoggerInstance } from '@oceanprotocol/lib' import { LoggerInstance } from '@oceanprotocol/lib'
import AssetListTable from './AssetListTable' import AssetListTable from './AssetListTable'
import { useAccount } from 'wagmi'
export default function Allocations(): ReactElement { export default function Allocations(): ReactElement {
const { accountId } = useWeb3() const { address } = useAccount()
const { chainIds } = useUserPreferences() const { chainIds } = useUserPreferences()
const isMounted = useIsMounted() const isMounted = useIsMounted()
const newCancelToken = useCancelToken() const newCancelToken = useCancelToken()
@ -24,18 +24,18 @@ export default function Allocations(): ReactElement {
const [hasAllocations, setHasAllocations] = useState(false) const [hasAllocations, setHasAllocations] = useState(false)
useEffect(() => { useEffect(() => {
if (!accountId) return if (!address) return
async function checkAllocations() { async function checkAllocations() {
try { try {
const allocations = await getOwnAllocations(chainIds, accountId) const allocations = await getOwnAllocations(chainIds, address)
setHasAllocations(allocations && allocations.length > 0) setHasAllocations(allocations && allocations.length > 0)
} catch (error) { } catch (error) {
LoggerInstance.error(error.message) LoggerInstance.error(error.message)
} }
} }
checkAllocations() checkAllocations()
}, [accountId, chainIds]) }, [address, chainIds])
useEffect(() => { useEffect(() => {
async function getAllocationAssets() { async function getAllocationAssets() {
@ -44,7 +44,7 @@ export default function Allocations(): ReactElement {
try { try {
setLoading(true) setLoading(true)
const allocations = await getOwnAllocations(chainIds, accountId) const allocations = await getOwnAllocations(chainIds, address)
setHasAllocations(allocations && allocations.length > 0) setHasAllocations(allocations && allocations.length > 0)
const baseParams = { const baseParams = {
@ -82,7 +82,7 @@ export default function Allocations(): ReactElement {
} }
} }
getAllocationAssets() getAllocationAssets()
}, [hasAllocations, accountId, chainIds, isMounted, newCancelToken]) }, [hasAllocations, address, chainIds, isMounted, newCancelToken])
return ( return (
<section className={styles.section}> <section className={styles.section}>

View File

@ -7,8 +7,8 @@ import Tooltip from '@shared/atoms/Tooltip'
import AssetTitle from '@shared/AssetListTitle' import AssetTitle from '@shared/AssetListTitle'
import { getAssetsFromDids } from '@utils/aquarius' import { getAssetsFromDids } from '@utils/aquarius'
import { useCancelToken } from '@hooks/useCancelToken' import { useCancelToken } from '@hooks/useCancelToken'
import { useWeb3 } from '@context/Web3'
import { useMarketMetadata } from '@context/MarketMetadata' import { useMarketMetadata } from '@context/MarketMetadata'
import { useAccount } from 'wagmi'
const columns: TableOceanColumn<AssetExtended>[] = [ const columns: TableOceanColumn<AssetExtended>[] = [
{ {
@ -38,7 +38,7 @@ const columns: TableOceanColumn<AssetExtended>[] = [
export default function Bookmarks(): ReactElement { export default function Bookmarks(): ReactElement {
const { appConfig } = useMarketMetadata() const { appConfig } = useMarketMetadata()
const { accountId } = useWeb3() const { address } = useAccount()
const { bookmarks } = useUserPreferences() const { bookmarks } = useUserPreferences()
const [pinned, setPinned] = useState<AssetExtended[]>() const [pinned, setPinned] = useState<AssetExtended[]>()
@ -77,7 +77,7 @@ export default function Bookmarks(): ReactElement {
appConfig?.metadataCacheUri, appConfig?.metadataCacheUri,
bookmarks, bookmarks,
chainIds, chainIds,
accountId, address,
newCancelToken newCancelToken
]) ])

View File

@ -8,14 +8,14 @@ import { useProfile } from '@context/Profile'
import { getLocked } from '@utils/veAllocation' import { getLocked } from '@utils/veAllocation'
import PriceUnit from '@shared/Price/PriceUnit' import PriceUnit from '@shared/Price/PriceUnit'
import Button from '@shared/atoms/Button' import Button from '@shared/atoms/Button'
import { useWeb3 } from '@context/Web3' import { useAccount } from 'wagmi'
export default function Stats({ export default function Stats({
accountId accountId
}: { }: {
accountId: string accountId: string
}): ReactElement { }): ReactElement {
const web3 = useWeb3() const { address } = useAccount()
const { chainIds } = useUserPreferences() const { chainIds } = useUserPreferences()
const { assets, assetsTotal, sales } = useProfile() const { assets, assetsTotal, sales } = useProfile()
@ -73,7 +73,7 @@ export default function Stats({
<NumberUnit label="Published" value={assetsTotal} /> <NumberUnit label="Published" value={assetsTotal} />
<NumberUnit <NumberUnit
label={ label={
lockedOcean === 0 && accountId === web3.accountId ? ( lockedOcean === 0 && accountId === address ? (
<Button <Button
className={styles.link} className={styles.link}
style="text" style="text"

View File

@ -10,7 +10,7 @@ import Button from '@shared/atoms/Button'
import styles from './Results.module.css' import styles from './Results.module.css'
import FormHelp from '@shared/FormInput/Help' import FormHelp from '@shared/FormInput/Help'
import content from '../../../../../content/pages/history.json' import content from '../../../../../content/pages/history.json'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import { useCancelToken } from '@hooks/useCancelToken' import { useCancelToken } from '@hooks/useCancelToken'
import { getAsset } from '@utils/aquarius' import { getAsset } from '@utils/aquarius'

View File

@ -2,13 +2,13 @@ import React, { ReactElement, useState } from 'react'
import Time from '@shared/atoms/Time' import Time from '@shared/atoms/Time'
import Table, { TableOceanColumn } from '@shared/atoms/Table' import Table, { TableOceanColumn } from '@shared/atoms/Table'
import Button from '@shared/atoms/Button' import Button from '@shared/atoms/Button'
import { useWeb3 } from '@context/Web3'
import Details from './Details' import Details from './Details'
import Refresh from '@images/refresh.svg' import Refresh from '@images/refresh.svg'
import { useUserPreferences } from '@context/UserPreferences' import { useUserPreferences } from '@context/UserPreferences'
import NetworkName from '@shared/NetworkName' import NetworkName from '@shared/NetworkName'
import styles from './index.module.css' import styles from './index.module.css'
import AssetListTitle from '@shared/AssetListTitle' import AssetListTitle from '@shared/AssetListTitle'
import { useAccount } from 'wagmi'
export function Status({ children }: { children: string }): ReactElement { export function Status({ children }: { children: string }): ReactElement {
return <div className={styles.status}>{children}</div> return <div className={styles.status}>{children}</div>
@ -55,11 +55,11 @@ export default function ComputeJobs({
isLoading?: boolean isLoading?: boolean
refetchJobs?: any refetchJobs?: any
}): ReactElement { }): ReactElement {
const { accountId } = useWeb3() const { address } = useAccount()
const { chainIds } = useUserPreferences() const { chainIds } = useUserPreferences()
const [columnsMinimal] = useState([columns[4], columns[5], columns[3]]) const [columnsMinimal] = useState([columns[4], columns[5], columns[3]])
return accountId ? ( return address ? (
<> <>
{jobs?.length >= 0 && !minimal && ( {jobs?.length >= 0 && !minimal && (
<Button <Button

View File

@ -4,11 +4,11 @@ import PublishedList from './PublishedList'
import Downloads from './Downloads' import Downloads from './Downloads'
import ComputeJobs from './ComputeJobs' import ComputeJobs from './ComputeJobs'
import styles from './index.module.css' import styles from './index.module.css'
import { useWeb3 } from '@context/Web3'
import { getComputeJobs } from '@utils/compute' import { getComputeJobs } from '@utils/compute'
import { useUserPreferences } from '@context/UserPreferences' import { useUserPreferences } from '@context/UserPreferences'
import { useCancelToken } from '@hooks/useCancelToken' import { useCancelToken } from '@hooks/useCancelToken'
import { LoggerInstance } from '@oceanprotocol/lib' import { LoggerInstance } from '@oceanprotocol/lib'
import { useAccount } from 'wagmi'
interface HistoryTab { interface HistoryTab {
title: string title: string
@ -56,7 +56,7 @@ export default function HistoryPage({
}: { }: {
accountIdentifier: string accountIdentifier: string
}): ReactElement { }): ReactElement {
const { accountId } = useWeb3() const { address } = useAccount()
const { chainIds } = useUserPreferences() const { chainIds } = useUserPreferences()
const newCancelToken = useCancelToken() const newCancelToken = useCancelToken()
@ -69,7 +69,7 @@ export default function HistoryPage({
const fetchJobs = useCallback( const fetchJobs = useCallback(
async (type: string) => { async (type: string) => {
if (!chainIds || chainIds.length === 0 || !accountId) { if (!chainIds || chainIds.length === 0 || !address) {
return return
} }
@ -77,7 +77,7 @@ export default function HistoryPage({
type === 'init' && setIsLoadingJobs(true) type === 'init' && setIsLoadingJobs(true)
const computeJobs = await getComputeJobs( const computeJobs = await getComputeJobs(
chainIds, chainIds,
accountId, address,
null, null,
newCancelToken() newCancelToken()
) )
@ -88,7 +88,7 @@ export default function HistoryPage({
setIsLoadingJobs(false) setIsLoadingJobs(false)
} }
}, },
[accountId, chainIds, isLoadingJobs, newCancelToken] [address, chainIds, isLoadingJobs, newCancelToken]
) )
useEffect(() => { useEffect(() => {
@ -107,7 +107,7 @@ export default function HistoryPage({
const tabs = getTabs( const tabs = getTabs(
accountIdentifier, accountIdentifier,
accountId, address,
jobs, jobs,
isLoadingJobs, isLoadingJobs,
refetchJobs, refetchJobs,

View File

@ -5,12 +5,13 @@ import { FormikContextType, useFormikContext } from 'formik'
import { FormPublishData } from '../_types' import { FormPublishData } from '../_types'
import { wizardSteps } from '../_constants' import { wizardSteps } from '../_constants'
import SuccessConfetti from '@shared/SuccessConfetti' import SuccessConfetti from '@shared/SuccessConfetti'
import { useWeb3 } from '@context/Web3'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import Tooltip from '@shared/atoms/Tooltip' import Tooltip from '@shared/atoms/Tooltip'
import AvailableNetworks from '@components/Publish/AvailableNetworks' import AvailableNetworks from '@components/Publish/AvailableNetworks'
import Info from '@images/info.svg' import Info from '@images/info.svg'
import Loader from '@shared/atoms/Loader' import Loader from '@shared/atoms/Loader'
import useNetworkMetadata from '@hooks/useNetworkMetadata'
import { useAccount } from 'wagmi'
export default function Actions({ export default function Actions({
scrollToRef, scrollToRef,
@ -20,21 +21,21 @@ export default function Actions({
did: string did: string
}): ReactElement { }): ReactElement {
const router = useRouter() const router = useRouter()
const { isSupportedOceanNetwork } = useWeb3() const { isSupportedOceanNetwork } = useNetworkMetadata()
const { const {
values, values,
errors, errors,
isValid, isValid,
isSubmitting isSubmitting
}: FormikContextType<FormPublishData> = useFormikContext() }: FormikContextType<FormPublishData> = useFormikContext()
const { connect, accountId } = useWeb3() const { address } = useAccount()
async function handleActivation(e: FormEvent<HTMLButtonElement>) { // async function handleActivation(e: FormEvent<HTMLButtonElement>) {
// prevent accidentially submitting a form the button might be in // // prevent accidentially submitting a form the button might be in
e.preventDefault() // e.preventDefault()
await connect() // await connect()
} // }
function handleAction(action: string) { function handleAction(action: string) {
const currentStep: string = router.query.step as string const currentStep: string = router.query.step as string
@ -92,11 +93,12 @@ export default function Actions({
> >
Continue Continue
</Button> </Button>
) : !accountId ? ( ) : // !address ? (
<Button type="submit" style="primary" onClick={handleActivation}> // <Button type="submit" style="primary" onClick={handleActivation}>
Connect Wallet // Connect Wallet
</Button> // </Button>
) : !isSupportedOceanNetwork ? ( // ) :
!isSupportedOceanNetwork ? (
<Tooltip content={<AvailableNetworks />}> <Tooltip content={<AvailableNetworks />}>
<Button <Button
type="submit" type="submit"

View File

@ -4,7 +4,7 @@ import styles from './Network.module.css'
import Button from '@shared/atoms/Button' import Button from '@shared/atoms/Button'
import useNetworkMetadata from '@hooks/useNetworkMetadata' import useNetworkMetadata from '@hooks/useNetworkMetadata'
import { addCustomNetwork } from '@utils/web3' import { addCustomNetwork } from '@utils/web3'
import { useWeb3 } from '@context/Web3' import { useProvider } from 'wagmi'
export default function Network({ export default function Network({
chainId chainId
@ -12,7 +12,7 @@ export default function Network({
chainId: number chainId: number
}): ReactElement { }): ReactElement {
const { networksList } = useNetworkMetadata() const { networksList } = useNetworkMetadata()
const { web3Provider } = useWeb3() const web3Provider = useProvider()
function changeNetwork(chainId: number) { function changeNetwork(chainId: number) {
const networkNode = networksList.find((data) => data.chainId === chainId) const networkNode = networksList.find((data) => data.chainId === chainId)

View File

@ -4,9 +4,9 @@ import styles from './Fees.module.css'
import Input from '@shared/FormInput' import Input from '@shared/FormInput'
import { getOpcFees } from '@utils/subgraph' import { getOpcFees } from '@utils/subgraph'
import { OpcFeesQuery_opc as OpcFeesData } from '../../../@types/subgraph/OpcFeesQuery' import { OpcFeesQuery_opc as OpcFeesData } from '../../../@types/subgraph/OpcFeesQuery'
import { useWeb3 } from '@context/Web3'
import { useMarketMetadata } from '@context/MarketMetadata' import { useMarketMetadata } from '@context/MarketMetadata'
import Decimal from 'decimal.js' import Decimal from 'decimal.js'
import { useNetwork } from 'wagmi'
const Default = ({ const Default = ({
title, title,
@ -40,18 +40,18 @@ export default function Fees({
tooltips: { [key: string]: string } tooltips: { [key: string]: string }
}): ReactElement { }): ReactElement {
const [oceanCommunitySwapFee, setOceanCommunitySwapFee] = useState<string>('') const [oceanCommunitySwapFee, setOceanCommunitySwapFee] = useState<string>('')
const { chainId } = useWeb3() const { chain } = useNetwork()
const { appConfig } = useMarketMetadata() const { appConfig } = useMarketMetadata()
useEffect(() => { useEffect(() => {
getOpcFees(chainId || 1).then((response: OpcFeesData) => { getOpcFees(chain?.id || 1).then((response: OpcFeesData) => {
setOceanCommunitySwapFee( setOceanCommunitySwapFee(
response?.swapOceanFee response?.swapOceanFee
? new Decimal(response.swapOceanFee).mul(100).toString() ? new Decimal(response.swapOceanFee).mul(100).toString()
: '0' : '0'
) )
}) })
}, [chainId]) }, [chain?.id])
return ( return (
<> <>

View File

@ -7,11 +7,13 @@ import Free from './Free'
import content from '../../../../content/price.json' import content from '../../../../content/price.json'
import styles from './index.module.css' import styles from './index.module.css'
import { useMarketMetadata } from '@context/MarketMetadata' import { useMarketMetadata } from '@context/MarketMetadata'
import { useWeb3 } from '@context/Web3' import { useNetwork } from 'wagmi'
export default function PricingFields(): ReactElement { export default function PricingFields(): ReactElement {
const { appConfig } = useMarketMetadata() const { appConfig } = useMarketMetadata()
const { approvedBaseTokens, chainId } = useWeb3() const { chain } = useNetwork()
const { approvedBaseTokens } = useMarketMetadata()
// Connect with main publish form // Connect with main publish form
const { values, setFieldValue } = useFormikContext<FormPublishData>() const { values, setFieldValue } = useFormikContext<FormPublishData>()
const { pricing } = values const { pricing } = values
@ -22,6 +24,23 @@ export default function PricingFields(): ReactElement {
token.name.toLowerCase().includes('ocean') token.name.toLowerCase().includes('ocean')
) || approvedBaseTokens?.[0] ) || approvedBaseTokens?.[0]
const isBaseTokenSet = !!approvedBaseTokens?.find(
(token) => token?.address === values?.pricing?.baseToken?.address
)
useEffect(() => {
if (!approvedBaseTokens?.length) return
if (isBaseTokenSet) return
setFieldValue('pricing.baseToken', defaultBaseToken)
}, [
approvedBaseTokens,
chain?.id,
defaultBaseToken,
isBaseTokenSet,
setFieldValue,
values.pricing.baseToken
])
// Switch type value upon tab change // Switch type value upon tab change
function handleTabChange(tabName: string) { function handleTabChange(tabName: string) {
const type = tabName.toLowerCase() const type = tabName.toLowerCase()

View File

@ -1,28 +1,29 @@
import { ReactElement, useEffect } from 'react' import { ReactElement, useEffect } from 'react'
import { useFormikContext } from 'formik' import { useFormikContext } from 'formik'
import { wizardSteps, initialPublishFeedback } from './_constants' import { wizardSteps, initialPublishFeedback } from './_constants'
import { useWeb3 } from '@context/Web3'
import { FormPublishData, PublishFeedback } from './_types' import { FormPublishData, PublishFeedback } from './_types'
import { getOceanConfig } from '@utils/ocean' import { getOceanConfig } from '@utils/ocean'
import { useAccount, useNetwork } from 'wagmi'
export function Steps({ export function Steps({
feedback feedback
}: { }: {
feedback: PublishFeedback feedback: PublishFeedback
}): ReactElement { }): ReactElement {
const { chainId, accountId, approvedBaseTokens } = useWeb3() const { address } = useAccount()
const { chain } = useNetwork()
const { values, setFieldValue, touched, setTouched } = const { values, setFieldValue, touched, setTouched } =
useFormikContext<FormPublishData>() useFormikContext<FormPublishData>()
const isCustomProviderUrl = values?.services?.[0]?.providerUrl.custom const isCustomProviderUrl = values?.services?.[0]?.providerUrl.custom
// auto-sync user chainId & account into form data values // auto-sync user chain?.id & account into form data values
useEffect(() => { useEffect(() => {
if (!chainId || !accountId) return if (!chain?.id || !address) return
setFieldValue('user.chainId', chainId) setFieldValue('user.chain?.id', chain?.id)
setFieldValue('user.accountId', accountId) setFieldValue('user.address', address)
}, [chainId, accountId, setFieldValue]) }, [chain?.id, address, setFieldValue])
useEffect(() => { useEffect(() => {
if (!approvedBaseTokens?.length) return if (!approvedBaseTokens?.length) return

View File

@ -3,16 +3,19 @@ import NetworkName from '@shared/NetworkName'
import Tooltip from '@shared/atoms/Tooltip' import Tooltip from '@shared/atoms/Tooltip'
import styles from './index.module.css' import styles from './index.module.css'
import content from '../../../../content/publish/index.json' import content from '../../../../content/publish/index.json'
import { useWeb3 } from '@context/Web3'
import Info from '@images/info.svg' import Info from '@images/info.svg'
import AvailableNetworks from '@components/Publish/AvailableNetworks' import AvailableNetworks from '@components/Publish/AvailableNetworks'
import useNetworkMetadata from '@hooks/useNetworkMetadata'
import { useAccount } from 'wagmi'
export default function Title({ export default function Title({
networkId networkId
}: { }: {
networkId: number networkId: number
}): ReactElement { }): ReactElement {
const { isSupportedOceanNetwork, accountId } = useWeb3() const { address } = useAccount()
const { isSupportedOceanNetwork } = useNetworkMetadata()
return ( return (
<> <>
{content.title}{' '} {content.title}{' '}
@ -22,7 +25,7 @@ export default function Title({
<NetworkName <NetworkName
networkId={networkId} networkId={networkId}
className={ className={
isSupportedOceanNetwork || !accountId isSupportedOceanNetwork || !address
? styles.network ? styles.network
: `${styles.network} ${styles.error}` : `${styles.network} ${styles.error}`
} }
@ -30,7 +33,7 @@ export default function Title({
<Tooltip <Tooltip
content={<AvailableNetworks />} content={<AvailableNetworks />}
className={ className={
isSupportedOceanNetwork || !accountId isSupportedOceanNetwork || !address
? styles.tooltip ? styles.tooltip
: `${styles.tooltip} ${styles.error}` : `${styles.tooltip} ${styles.error}`
} }

View File

@ -2,7 +2,7 @@ import React, { ReactElement, useState, useRef } from 'react'
import { Form, Formik } from 'formik' import { Form, Formik } from 'formik'
import { initialPublishFeedback, initialValues } from './_constants' import { initialPublishFeedback, initialValues } from './_constants'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory' import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@hooks/useBalance'
import { createTokensAndPricing, transformPublishFormToDdo } from './_utils' import { createTokensAndPricing, transformPublishFormToDdo } from './_utils'
import PageHeader from '@shared/Page/PageHeader' import PageHeader from '@shared/Page/PageHeader'
import Title from './Title' import Title from './Title'

View File

@ -13,7 +13,6 @@ 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/web3' import { wagmiClient, ethereumClient } from '@utils/web3'
import Web3Provider from '@context/Web3'
function MyApp({ Component, pageProps }: AppProps): ReactElement { function MyApp({ Component, pageProps }: AppProps): ReactElement {
Decimal.set({ rounding: 1 }) Decimal.set({ rounding: 1 })
@ -21,7 +20,6 @@ function MyApp({ Component, pageProps }: AppProps): ReactElement {
<> <>
<WagmiConfig client={wagmiClient}> <WagmiConfig client={wagmiClient}>
<MarketMetadataProvider> <MarketMetadataProvider>
<Web3Provider>
<UrqlProvider> <UrqlProvider>
<UserPreferencesProvider> <UserPreferencesProvider>
<PricesProvider> <PricesProvider>
@ -33,7 +31,6 @@ function MyApp({ Component, pageProps }: AppProps): ReactElement {
</PricesProvider> </PricesProvider>
</UserPreferencesProvider> </UserPreferencesProvider>
</UrqlProvider> </UrqlProvider>
</Web3Provider>
</MarketMetadataProvider> </MarketMetadataProvider>
</WagmiConfig> </WagmiConfig>

View File

@ -2,15 +2,16 @@ import React, { ReactElement, useEffect, useState } from 'react'
import Page from '@shared/Page' import Page from '@shared/Page'
import ProfilePage from '../../components/Profile' import ProfilePage from '../../components/Profile'
import { accountTruncate } from '@utils/web3' import { accountTruncate } from '@utils/web3'
import { useWeb3 } from '@context/Web3'
import ProfileProvider from '@context/Profile' import ProfileProvider from '@context/Profile'
import { getEnsAddress, getEnsName } from '@utils/ens' import { getEnsAddress, getEnsName } from '@utils/ens'
import { useRouter } from 'next/router' import { useRouter } from 'next/router'
import web3 from 'web3' import { useAccount, useEnsName } from 'wagmi'
import { utils } from 'ethers'
export default function PageProfile(): ReactElement { export default function PageProfile(): ReactElement {
const router = useRouter() const router = useRouter()
const { accountId, accountEns } = useWeb3() const { address } = useAccount()
const { data: accountEns } = useEnsName({ address })
const [finalAccountId, setFinalAccountId] = useState<string>() const [finalAccountId, setFinalAccountId] = useState<string>()
const [finalAccountEns, setFinalAccountEns] = useState<string>() const [finalAccountEns, setFinalAccountEns] = useState<string>()
const [ownAccount, setOwnAccount] = useState(false) const [ownAccount, setOwnAccount] = useState(false)
@ -22,7 +23,7 @@ export default function PageProfile(): ReactElement {
// Path is root /profile, have web3 take over // Path is root /profile, have web3 take over
if (router.asPath === '/profile') { if (router.asPath === '/profile') {
setFinalAccountEns(accountEns) setFinalAccountEns(accountEns)
setFinalAccountId(accountId) setFinalAccountId(address)
setOwnAccount(true) setOwnAccount(true)
return return
} }
@ -30,9 +31,9 @@ export default function PageProfile(): ReactElement {
const pathAccount = router.query.account as string const pathAccount = router.query.account as string
// Path has ETH address // Path has ETH address
if (web3.utils.isAddress(pathAccount)) { if (utils.isAddress(pathAccount)) {
setOwnAccount(pathAccount === accountId) setOwnAccount(pathAccount === address)
const finalAccountId = pathAccount || accountId const finalAccountId = pathAccount || address
setFinalAccountId(finalAccountId) setFinalAccountId(finalAccountId)
const accountEns = await getEnsName(finalAccountId) const accountEns = await getEnsName(finalAccountId)
@ -47,12 +48,12 @@ export default function PageProfile(): ReactElement {
resolvedAccountId === '0x0000000000000000000000000000000000000000' resolvedAccountId === '0x0000000000000000000000000000000000000000'
) )
return return
setOwnAccount(resolvedAccountId === accountId) setOwnAccount(resolvedAccountId === address)
setFinalAccountId(resolvedAccountId) setFinalAccountId(resolvedAccountId)
} }
} }
init() init()
}, [router, accountId, accountEns]) }, [router, address, accountEns])
// Replace pathname with ENS name if present // Replace pathname with ENS name if present
useEffect(() => { useEffect(() => {
@ -61,7 +62,7 @@ export default function PageProfile(): ReactElement {
const newProfilePath = `/profile/${finalAccountEns}` const newProfilePath = `/profile/${finalAccountEns}`
// make sure we only replace path once // make sure we only replace path once
if (newProfilePath !== router.asPath) router.replace(newProfilePath) if (newProfilePath !== router.asPath) router.replace(newProfilePath)
}, [router, finalAccountEns, accountId]) }, [router, finalAccountEns, address])
return ( return (
<Page <Page