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

more web3.js usage removal

This commit is contained in:
Matthias Kretschmann 2023-01-19 01:38:01 +00:00
parent 25d17b4d7d
commit 00c145ad99
Signed by: m
GPG Key ID: 606EEEF3C479A91F
12 changed files with 49 additions and 66 deletions

1
package-lock.json generated
View File

@ -56,7 +56,6 @@
"swr": "^1.3.0", "swr": "^1.3.0",
"urql": "^3.0.3", "urql": "^3.0.3",
"wagmi": "^0.10.11", "wagmi": "^0.10.11",
"web3": "^1.8.1",
"yup": "^0.32.11" "yup": "^0.32.11"
}, },
"devDependencies": { "devDependencies": {

View File

@ -69,7 +69,6 @@
"swr": "^1.3.0", "swr": "^1.3.0",
"urql": "^3.0.3", "urql": "^3.0.3",
"wagmi": "^0.10.11", "wagmi": "^0.10.11",
"web3": "^1.8.1",
"yup": "^0.32.11" "yup": "^0.32.11"
}, },
"devDependencies": { "devDependencies": {

View File

@ -81,9 +81,12 @@ function MarketMetadataProvider({
try { try {
const approvedTokensList = await getOpcsApprovedTokens(chainId) const approvedTokensList = await getOpcsApprovedTokens(chainId)
setApprovedBaseTokens(approvedTokensList) setApprovedBaseTokens(approvedTokensList)
LoggerInstance.log('[web3] Approved baseTokens', approvedTokensList) LoggerInstance.log(
'[MarketMetadata] Approved baseTokens',
approvedTokensList
)
} catch (error) { } catch (error) {
LoggerInstance.error('[web3] Error: ', error.message) LoggerInstance.error('[MarketMetadata] Error: ', error.message)
} }
}, []) }, [])

View File

@ -1,14 +1,10 @@
import { useState, useEffect } from 'react' import { useState, useEffect } from 'react'
import { Config, LoggerInstance } from '@oceanprotocol/lib' import { Config, LoggerInstance } from '@oceanprotocol/lib'
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' import { useBlockNumber } from 'wagmi'
const blockDifferenceThreshold = 30 const blockDifferenceThreshold = 30
const ethGraphUrl = `https://api.thegraph.com/subgraphs/name/blocklytics/ethereum-blocks`
const ethGraphQueryBody =
'{"query":" query Blocks{ blocks(first: 1, skip: 0, orderBy: number, orderDirection: desc, where: {number_gt: 9300000}) { id number timestamp author difficulty gasUsed gasLimit } }","variables":{},"operationName":"Blocks"}'
const graphQueryBody = const graphQueryBody =
'{"query": "query Meta { _meta { block { hash number } deployment hasIndexingErrors } }", "variables": {},"operationName":"Meta"}' '{"query": "query Meta { _meta { block { hash number } deployment hasIndexingErrors } }", "variables": {},"operationName":"Meta"}'
@ -30,21 +26,6 @@ async function fetchGraph(
} }
} }
async function getBlockHead(config: Config) {
if (!config) return
// for ETH main, get block from graph fetch
if (config.network === 'mainnet') {
const response: any = await fetchGraph(ethGraphUrl, ethGraphQueryBody)
return Number(response?.data?.blocks[0]?.number)
}
// for everything else, create new web3 instance with infura
// TODO: this fails randomly , WHY!?!?!?!?!
const web3Instance = new Web3(config.nodeUri)
const blockHead = await web3Instance.eth.getBlockNumber()
return blockHead
}
async function getBlockSubgraph(subgraphUri: string) { async function getBlockSubgraph(subgraphUri: string) {
const response: any = await fetchGraph( const response: any = await fetchGraph(
`${subgraphUri}/subgraphs/name/oceanprotocol/ocean-subgraph`, `${subgraphUri}/subgraphs/name/oceanprotocol/ocean-subgraph`,
@ -55,11 +36,10 @@ async function getBlockSubgraph(subgraphUri: string) {
} }
export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus { export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
const { data: block, isError, isLoading } = useBlockNumber() const { data: blockHead, isLoading } = useBlockNumber()
const [blockGraph, setBlockGraph] = useState<number>() const [blockGraph, setBlockGraph] = useState<number>()
const [blockHead, setBlockHead] = useState<number>()
const [isGraphSynced, setIsGraphSynced] = useState(true) const [isGraphSynced, setIsGraphSynced] = useState(true)
const [subgraphLoading, setSubgraphLoading] = useState(false) const [isSubgraphLoading, setIsSubgraphLoading] = useState(false)
const [oceanConfig, setOceanConfig] = useState<Config>() const [oceanConfig, setOceanConfig] = useState<Config>()
// Grab ocean config based on passed networkId // Grab ocean config based on passed networkId
@ -70,27 +50,21 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
setOceanConfig(oceanConfig) setOceanConfig(oceanConfig)
}, [networkId]) }, [networkId])
// Get and set head block // Log head block
useEffect(() => { useEffect(() => {
if (!oceanConfig?.nodeUri || isLoading || isError) return if (blockHead) return
LoggerInstance.log('[GraphStatus] Head block: ', blockHead)
async function initBlockHead() { }, [blockHead])
const blockHead = block || (await getBlockHead(oceanConfig))
setBlockHead(blockHead)
LoggerInstance.log('[GraphStatus] Head block: ', blockHead)
}
initBlockHead()
}, [isLoading, isError, block, oceanConfig])
// Get and set subgraph block // Get and set subgraph block
useEffect(() => { useEffect(() => {
if (!oceanConfig?.subgraphUri) return if (!oceanConfig?.subgraphUri) return
async function initBlockSubgraph() { async function initBlockSubgraph() {
setSubgraphLoading(true) setIsSubgraphLoading(true)
const blockGraph = await getBlockSubgraph(oceanConfig.subgraphUri) const blockGraph = await getBlockSubgraph(oceanConfig.subgraphUri)
setBlockGraph(blockGraph) setBlockGraph(blockGraph)
setSubgraphLoading(false) setIsSubgraphLoading(false)
LoggerInstance.log( LoggerInstance.log(
'[GraphStatus] Latest block from subgraph: ', '[GraphStatus] Latest block from subgraph: ',
blockGraph blockGraph
@ -101,7 +75,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
// Set sync status // Set sync status
useEffect(() => { useEffect(() => {
if ((!blockGraph && !blockHead) || isLoading || subgraphLoading) return if ((!blockGraph && !blockHead) || isLoading || isSubgraphLoading) return
const difference = blockHead - blockGraph const difference = blockHead - blockGraph
@ -110,7 +84,7 @@ export function useGraphSyncStatus(networkId: number): UseGraphSyncStatus {
return return
} }
setIsGraphSynced(true) setIsGraphSynced(true)
}, [blockGraph, blockHead, isLoading, subgraphLoading]) }, [blockGraph, blockHead, isLoading, isSubgraphLoading])
return { blockHead, blockGraph, isGraphSynced } return { blockHead, blockGraph, isGraphSynced }
} }

View File

@ -149,8 +149,9 @@ function getAccessDetailsFromTokenPrice(
*/ */
export async function getOrderPriceAndFees( export async function getOrderPriceAndFees(
asset: AssetExtended, asset: AssetExtended,
accountId?: string, accountId: string | undefined,
providerFees?: ProviderFees providerFees: ProviderFees | undefined,
web3: Web3
): Promise<OrderPriceAndFees> { ): Promise<OrderPriceAndFees> {
const orderPriceAndFee = { const orderPriceAndFee = {
price: String(asset?.stats?.price?.value || '0'), price: String(asset?.stats?.price?.value || '0'),
@ -178,7 +179,11 @@ export async function getOrderPriceAndFees(
// fetch price and swap fees // fetch price and swap fees
if (asset?.accessDetails?.type === 'fixed') { if (asset?.accessDetails?.type === 'fixed') {
const fixed = await getFixedBuyPrice(asset?.accessDetails, asset?.chainId) const fixed = await getFixedBuyPrice(
asset?.accessDetails,
asset?.chainId,
web3
)
orderPriceAndFee.price = fixed.baseTokenAmount orderPriceAndFee.price = fixed.baseTokenAmount
orderPriceAndFee.opcFee = fixed.oceanFeeAmount orderPriceAndFee.opcFee = fixed.oceanFeeAmount
orderPriceAndFee.publisherMarketFixedSwapFee = fixed.marketFeeAmount orderPriceAndFee.publisherMarketFixedSwapFee = fixed.marketFeeAmount

View File

@ -11,18 +11,15 @@ import { getOceanConfig } from './ocean'
*/ */
export async function getFixedBuyPrice( export async function getFixedBuyPrice(
accessDetails: AccessDetails, accessDetails: AccessDetails,
chainId?: number, chainId: number,
web3Provider?: any web3: Web3
): Promise<PriceAndFees> { ): Promise<PriceAndFees> {
if (!web3Provider && !chainId) if (!web3 && !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( const fixed = new FixedRateExchange(config.fixedRateExchangeAddress, web3)
config.fixedRateExchangeAddress,
web3Provider
)
const estimatedPrice = await fixed.calcBaseInGivenDatatokensOut( const estimatedPrice = await fixed.calcBaseInGivenDatatokensOut(
accessDetails.addressOrId, accessDetails.addressOrId,
'1', '1',

View File

@ -33,11 +33,11 @@ export default function Web3Feedback({
if (!accountId) { if (!accountId) {
setState('error') setState('error')
setTitle('No account connected') setTitle('No account connected')
setMessage('Please connect your Web3 wallet.') setMessage('Please connect your wallet.')
} else if (isAssetNetwork === false) { } else if (isAssetNetwork === false) {
setState('error') setState('error')
setTitle('Not connected to asset network') setTitle('Not connected to asset network')
setMessage('Please connect your Web3 wallet.') setMessage('Please connect your wallet.')
} else if (isGraphSynced === false) { } else if (isGraphSynced === false) {
setState('warning') setState('warning')
setTitle('Data out of sync') setTitle('Data out of sync')

View File

@ -79,11 +79,18 @@ export default function Download({
) )
return return
!orderPriceAndFees && setIsPriceLoading(true) try {
!orderPriceAndFees && setIsPriceLoading(true)
const _orderPriceAndFees = await getOrderPriceAndFees(asset, ZERO_ADDRESS) const _orderPriceAndFees = await getOrderPriceAndFees(
setOrderPriceAndFees(_orderPriceAndFees) asset,
!orderPriceAndFees && setIsPriceLoading(false) ZERO_ADDRESS
)
setOrderPriceAndFees(_orderPriceAndFees)
!orderPriceAndFees && setIsPriceLoading(false)
} catch (error) {
LoggerInstance.error(error.message)
setIsPriceLoading(false)
}
} }
init() init()

View File

@ -13,7 +13,6 @@ import EditHistory from './EditHistory'
import styles from './index.module.css' import styles from './index.module.css'
import NetworkName from '@shared/NetworkName' import NetworkName from '@shared/NetworkName'
import content from '../../../../content/purgatory.json' import content from '../../../../content/purgatory.json'
import Web3 from 'web3'
import Button from '@shared/atoms/Button' import Button from '@shared/atoms/Button'
import RelatedAssets from '../RelatedAssets' import RelatedAssets from '../RelatedAssets'
@ -28,11 +27,11 @@ export default function AssetContent({
const [nftPublisher, setNftPublisher] = useState<string>() const [nftPublisher, setNftPublisher] = useState<string>()
useEffect(() => { useEffect(() => {
setNftPublisher( if (!receipts.length) return
Web3.utils.toChecksumAddress(
receipts?.find((e) => e.type === 'METADATA_CREATED')?.nft?.owner const publisher = receipts?.find((e) => e.type === 'METADATA_CREATED')?.nft
) ?.owner
) setNftPublisher(publisher)
}, [receipts]) }, [receipts])
return ( return (

View File

@ -84,6 +84,6 @@ export default function ComputeJobs({
/> />
</> </>
) : ( ) : (
<div>Please connect your Web3 wallet.</div> <div>Please connect your wallet.</div>
) )
} }

View File

@ -42,6 +42,6 @@ export default function ComputeDownloads({
emptyMessage={chainIds.length === 0 ? 'No network selected' : null} emptyMessage={chainIds.length === 0 ? 'No network selected' : null}
/> />
) : ( ) : (
<div>Please connect your Web3 wallet.</div> <div>Please connect your wallet.</div>
) )
} }

View File

@ -97,6 +97,6 @@ export default function PublishedList({
/> />
</> </>
) : ( ) : (
<div>Please connect your Web3 wallet.</div> <div>Please connect your wallet.</div>
) )
} }