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

fixes and cleanups

This commit is contained in:
Bogdan Fazakas 2022-03-08 00:09:53 +02:00
parent 809429b728
commit f1f1c17535
2 changed files with 49 additions and 77 deletions

View File

@ -12,8 +12,7 @@ export default function Blockies({
if (!accountId) return null if (!accountId) return null
// TODO: just put this back once finished // TODO: just put this back once finished
// const blockies = toDataUrl(accountId) const blockies = toDataUrl(accountId)
const blockies = 'randomstring12345'
return ( return (
<img <img

View File

@ -5,67 +5,40 @@ import {
ComputeOutput, ComputeOutput,
Asset, Asset,
DDO, DDO,
PublisherTrustedAlgorithm,
FileMetadata, FileMetadata,
Datatoken, Datatoken,
ProviderInstance, ProviderInstance,
ProviderFees,
Pool,
OrderParams,
FreOrderParams,
ComputeAsset, ComputeAsset,
approve,
TokenInOutMarket,
AmountsInMaxFee,
AmountsOutMaxFee,
Service,
ZERO_ADDRESS ZERO_ADDRESS
} from '@oceanprotocol/lib' } from '@oceanprotocol/lib'
import { toast } from 'react-toastify' 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 { useSiteMetadata } from '@hooks/useSiteMetadata'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@context/Web3'
import {
generateBaseQuery,
getFilterTerm,
queryMetadata
} from '@utils/aquarius'
import { Formik } from 'formik' import { Formik } from 'formik'
import { getInitialValues, validationSchema } from './_constants' import { getInitialValues, validationSchema } from './_constants'
import axios from 'axios'
import FormStartComputeDataset from './FormComputeDataset' import FormStartComputeDataset from './FormComputeDataset'
import styles from './index.module.css' import styles from './index.module.css'
import SuccessConfetti from '@shared/SuccessConfetti' import SuccessConfetti from '@shared/SuccessConfetti'
import { getServiceByName, secondsToString } from '@utils/ddo' import { getServiceByName } from '@utils/ddo'
import { import {
isOrderable, isOrderable,
getAlgorithmAssetSelectionList, getAlgorithmAssetSelectionList,
getAlgorithmsForAsset, getAlgorithmsForAsset,
getQuerryString,
getValidUntilTime, getValidUntilTime,
getComputeEnviroment getComputeEnviroment
} from '@utils/compute' } from '@utils/compute'
import AssetSelection, { import { AssetSelectionAsset } from '@shared/FormFields/AssetSelection'
AssetSelectionAsset
} from '@shared/FormFields/AssetSelection'
import AlgorithmDatasetsListForCompute from './AlgorithmDatasetsListForCompute' import AlgorithmDatasetsListForCompute from './AlgorithmDatasetsListForCompute'
import { getPreviousOrders } from '@utils/subgraph'
import AssetActionHistoryTable from '../AssetActionHistoryTable' import AssetActionHistoryTable from '../AssetActionHistoryTable'
import ComputeJobs from '../../../Profile/History/ComputeJobs' import ComputeJobs from '../../../Profile/History/ComputeJobs'
import { useCancelToken } from '@hooks/useCancelToken' import { useCancelToken } from '@hooks/useCancelToken'
import { useIsMounted } from '@hooks/useIsMounted' import { useIsMounted } from '@hooks/useIsMounted'
import { SortTermOptions } from '../../../../@types/aquarius/SearchQuery'
import { Decimal } from 'decimal.js' import { Decimal } from 'decimal.js'
import { TransactionReceipt } from 'web3-core'
import { useAbortController } from '@hooks/useAbortController' import { useAbortController } from '@hooks/useAbortController'
import { import { getOrderPriceAndFees } from '@utils/accessDetailsAndPricing'
getAccessDetails, import { OrderPriceAndFees } from 'src/@types/Price'
getOrderPriceAndFees
} from '@utils/accessDetailsAndPricing'
import { AccessDetails, OrderPriceAndFees } from 'src/@types/Price'
import { transformAssetToAssetSelection } from '@utils/assetConvertor'
import { buyDtFromPool } from '@utils/pool' import { buyDtFromPool } from '@utils/pool'
import { order } from '@utils/order' import { order } from '@utils/order'
import { AssetExtended } from 'src/@types/AssetExtended' import { AssetExtended } from 'src/@types/AssetExtended'
@ -85,7 +58,6 @@ export default function Compute({
isConsumable?: boolean isConsumable?: boolean
consumableFeedback?: string consumableFeedback?: string
}): ReactElement { }): ReactElement {
const { appConfig } = useSiteMetadata()
const { accountId, web3 } = useWeb3() const { accountId, web3 } = useWeb3()
const [isJobStarting, setIsJobStarting] = useState(false) const [isJobStarting, setIsJobStarting] = useState(false)
const [error, setError] = useState<string>() const [error, setError] = useState<string>()
@ -97,11 +69,7 @@ export default function Compute({
useState<AssetExtended>() useState<AssetExtended>()
const [hasAlgoAssetDatatoken, setHasAlgoAssetDatatoken] = useState<boolean>() const [hasAlgoAssetDatatoken, setHasAlgoAssetDatatoken] = useState<boolean>()
const [isPublished, setIsPublished] = useState(false) const [isPublished, setIsPublished] = useState(false)
const [hasPreviousAlgorithmOrder, setHasPreviousAlgorithmOrder] =
useState(false)
const [algorithmDTBalance, setAlgorithmDTBalance] = useState<string>() const [algorithmDTBalance, setAlgorithmDTBalance] = useState<string>()
const [algorithmConsumeDetails, setAlgorithmConsumeDetails] =
useState<AccessDetails>()
const [isOwned, setIsOwned] = useState(false) const [isOwned, setIsOwned] = useState(false)
const [validOrderTx, setValidOrderTx] = useState('') const [validOrderTx, setValidOrderTx] = useState('')
@ -112,8 +80,6 @@ export default function Compute({
const [orderAlgorithmPriceAndFees, setOrderAlgorithmPriceAndFees] = const [orderAlgorithmPriceAndFees, setOrderAlgorithmPriceAndFees] =
useState<OrderPriceAndFees>() useState<OrderPriceAndFees>()
const [datasetTimeout, setDatasetTimeout] = useState<string>()
const [algorithmTimeout, setAlgorithmTimeout] = useState<string>()
const hasDatatoken = Number(dtBalance) >= 1 const hasDatatoken = Number(dtBalance) >= 1
const isMounted = useIsMounted() const isMounted = useIsMounted()
const newCancelToken = useCancelToken() const newCancelToken = useCancelToken()
@ -123,9 +89,7 @@ export default function Compute({
isJobStarting === true || isJobStarting === true ||
file === null || file === null ||
(!validOrderTx && !hasDatatoken && !isConsumablePrice) || (!validOrderTx && !hasDatatoken && !isConsumablePrice) ||
(!hasPreviousAlgorithmOrder && (!validAlgorithmOrderTx && !hasAlgoAssetDatatoken && !isAlgoConsumablePrice)
!hasAlgoAssetDatatoken &&
!isAlgoConsumablePrice)
async function checkAssetDTBalance(asset: DDO) { async function checkAssetDTBalance(asset: DDO) {
if (!asset?.services[0].datatokenAddress) return if (!asset?.services[0].datatokenAddress) return
@ -149,13 +113,13 @@ export default function Compute({
if (asset?.accessDetails?.addressOrId === ZERO_ADDRESS) return if (asset?.accessDetails?.addressOrId === ZERO_ADDRESS) return
const computeEnv = await getComputeEnviroment(asset) const computeEnv = await getComputeEnviroment(asset)
const validUntil = getValidUntilTime( const validUntil = getValidUntilTime(
computeEnv.maxJobDuration, computeEnv?.maxJobDuration,
asset?.services[0]?.timeout asset?.services[0]?.timeout
) )
const orderPriceAndFees = await getOrderPriceAndFees( const orderPriceAndFees = await getOrderPriceAndFees(
asset, asset,
ZERO_ADDRESS, ZERO_ADDRESS,
computeEnv.id, computeEnv?.id,
validUntil validUntil
) )
setOrderPriceAndFees(orderPriceAndFees) setOrderPriceAndFees(orderPriceAndFees)
@ -164,6 +128,10 @@ export default function Compute({
}, [asset?.accessDetails]) }, [asset?.accessDetails])
useEffect(() => { useEffect(() => {
console.log(
'selectedAlgorithmAsset?.accessDetails == ',
selectedAlgorithmAsset?.accessDetails
)
if (!selectedAlgorithmAsset?.accessDetails || !accountId) return if (!selectedAlgorithmAsset?.accessDetails || !accountId) return
checkAssetDTBalance(selectedAlgorithmAsset) checkAssetDTBalance(selectedAlgorithmAsset)
@ -178,24 +146,22 @@ export default function Compute({
return return
const computeEnv = await getComputeEnviroment(selectedAlgorithmAsset) const computeEnv = await getComputeEnviroment(selectedAlgorithmAsset)
const validUntil = getValidUntilTime( const validUntil = getValidUntilTime(
computeEnv.maxJobDuration, computeEnv?.maxJobDuration,
asset?.services[0]?.timeout,
selectedAlgorithmAsset?.services[0]?.timeout selectedAlgorithmAsset?.services[0]?.timeout
) )
const orderPriceAndFees = await getOrderPriceAndFees( const orderPriceAndFees = await getOrderPriceAndFees(
selectedAlgorithmAsset, selectedAlgorithmAsset,
ZERO_ADDRESS, ZERO_ADDRESS,
computeEnv.id, computeEnv?.id,
validUntil validUntil
) )
setOrderAlgorithmPriceAndFees(orderPriceAndFees) setOrderAlgorithmPriceAndFees(orderPriceAndFees)
console.log('orderPriceAndFees ', orderPriceAndFees)
} }
init() init()
}, [selectedAlgorithmAsset]) }, [selectedAlgorithmAsset])
// useEffect(() => {
// setDatasetTimeout(secondsToString(timeout))
// }, [ddo])
useEffect(() => { useEffect(() => {
if (!asset) return if (!asset) return
@ -216,7 +182,7 @@ export default function Compute({
toast.error(newError) toast.error(newError)
}, [error]) }, [error])
async function startJob(algorithmId: string): Promise<string> { async function startJob(): Promise<string> {
try { try {
setIsJobStarting(true) setIsJobStarting(true)
setIsPublished(false) // would be nice to rename this setIsPublished(false) // would be nice to rename this
@ -245,12 +211,15 @@ export default function Compute({
const computeEnv = await getComputeEnviroment(asset) const computeEnv = await getComputeEnviroment(asset)
const validUntil = getValidUntilTime( const validUntil = getValidUntilTime(
computeEnv.maxJobDuration, computeEnv?.maxJobDuration,
asset.services[0].timeout, asset.services[0].timeout,
selectedAlgorithmAsset.services[0].timeout selectedAlgorithmAsset.services[0].timeout
) )
let datasetOrderTx let datasetOrderTx
if (!isOwned) { if (isOwned) {
datasetOrderTx = validOrderTx
LoggerInstance.log('[compute] Dataset owned txId:', validOrderTx)
} else {
try { try {
if (!hasDatatoken && asset?.accessDetails.type === 'dynamic') { if (!hasDatatoken && asset?.accessDetails.type === 'dynamic') {
const tx = await buyDtFromPool( const tx = await buyDtFromPool(
@ -258,7 +227,6 @@ export default function Compute({
accountId, accountId,
web3 web3
) )
LoggerInstance.log('[compute] Buy dataset dt from pool: ', tx) LoggerInstance.log('[compute] Buy dataset dt from pool: ', tx)
if (!tx) { if (!tx) {
toast.error('Failed to buy datatoken from pool!') toast.error('Failed to buy datatoken from pool!')
@ -271,9 +239,9 @@ export default function Compute({
asset, asset,
orderPriceAndFees, orderPriceAndFees,
accountId, accountId,
computeEnv.id, computeEnv?.id,
validUntil, validUntil,
computeEnv.consumerAddress computeEnv?.consumerAddress
) )
if (!orderTx) { if (!orderTx) {
toast.error('Failed to order dataset asset!') toast.error('Failed to order dataset asset!')
@ -288,14 +256,19 @@ export default function Compute({
datasetOrderTx = orderTx.transactionHash datasetOrderTx = orderTx.transactionHash
} catch (e) { } catch (e) {
LoggerInstance.log(e.message) LoggerInstance.log(e.message)
toast.error('Failed to order dataset asset!')
return
} }
} else {
datasetOrderTx = validOrderTx
LoggerInstance.log('[compute] Dataset owned txId:', validOrderTx)
} }
let algorithmOrderTx let algorithmOrderTx
if (!isAlgorithmOwned) { if (isAlgorithmOwned) {
algorithmOrderTx = validAlgorithmOrderTx
LoggerInstance.log(
'[compute] Algorithm owned txId:',
validAlgorithmOrderTx
)
} else {
try { try {
if ( if (
!hasAlgoAssetDatatoken && !hasAlgoAssetDatatoken &&
@ -321,9 +294,9 @@ export default function Compute({
selectedAlgorithmAsset, selectedAlgorithmAsset,
orderAlgorithmPriceAndFees, orderAlgorithmPriceAndFees,
accountId, accountId,
computeEnv.id, computeEnv?.id,
validUntil, validUntil,
computeEnv.consumerAddress computeEnv?.consumerAddress
) )
if (!orderTx) { if (!orderTx) {
toast.error('Failed to order algorithm asset!') toast.error('Failed to order algorithm asset!')
@ -338,13 +311,9 @@ export default function Compute({
algorithmOrderTx = orderTx.transactionHash algorithmOrderTx = orderTx.transactionHash
} catch (e) { } catch (e) {
LoggerInstance.log(e.message) LoggerInstance.log(e.message)
toast.error('Failed to order algorithm asset!')
return
} }
} else {
algorithmOrderTx = validAlgorithmOrderTx
LoggerInstance.log(
'[compute] Algorithm owned txId:',
validAlgorithmOrderTx
)
} }
LoggerInstance.log('[compute] Starting compute job.') LoggerInstance.log('[compute] Starting compute job.')
@ -362,19 +331,18 @@ export default function Compute({
asset.services[0].serviceEndpoint, asset.services[0].serviceEndpoint,
web3, web3,
accountId, accountId,
computeEnv.id, computeEnv?.id,
computeAsset, computeAsset,
computeAlgorithm, computeAlgorithm,
newAbortController(), newAbortController(),
null, null,
null output
) )
if (!response) { if (!response) {
setError('Error starting compute job.') setError('Error starting compute job.')
return return
} }
LoggerInstance.log('[compute] Starting compute job response: ', response) LoggerInstance.log('[compute] Starting compute job response: ', response)
setIsPublished(true) setIsPublished(true)
} catch (error) { } catch (error) {
setError('Failed to start job!') setError('Failed to start job!')
@ -408,7 +376,8 @@ export default function Compute({
validateOnMount validateOnMount
validationSchema={validationSchema} validationSchema={validationSchema}
onSubmit={async (values) => { onSubmit={async (values) => {
await startJob(values.algorithm) if (!values.algorithm) return
await startJob()
}} }}
> >
<FormStartComputeDataset <FormStartComputeDataset
@ -418,13 +387,15 @@ export default function Compute({
setSelectedAlgorithm={setSelectedAlgorithmAsset} setSelectedAlgorithm={setSelectedAlgorithmAsset}
isLoading={isJobStarting} isLoading={isJobStarting}
isComputeButtonDisabled={isComputeButtonDisabled} isComputeButtonDisabled={isComputeButtonDisabled}
hasPreviousOrder={validOrderTx !== ''} hasPreviousOrder={validOrderTx !== undefined}
hasDatatoken={hasDatatoken} hasDatatoken={hasDatatoken}
dtBalance={dtBalance} dtBalance={dtBalance}
datasetLowPoolLiquidity={!isConsumablePrice} datasetLowPoolLiquidity={!isConsumablePrice}
assetType={asset?.metadata.type} assetType={asset?.metadata.type}
assetTimeout={datasetTimeout} assetTimeout={asset?.services[0].timeout}
hasPreviousOrderSelectedComputeAsset={hasPreviousAlgorithmOrder} hasPreviousOrderSelectedComputeAsset={
validAlgorithmOrderTx !== undefined
}
hasDatatokenSelectedComputeAsset={hasAlgoAssetDatatoken} hasDatatokenSelectedComputeAsset={hasAlgoAssetDatatoken}
oceanSymbol={ oceanSymbol={
asset?.accessDetails ? asset?.accessDetails.baseToken.symbol : '' asset?.accessDetails ? asset?.accessDetails.baseToken.symbol : ''
@ -435,7 +406,9 @@ export default function Compute({
dtBalanceSelectedComputeAsset={algorithmDTBalance} dtBalanceSelectedComputeAsset={algorithmDTBalance}
selectedComputeAssetLowPoolLiquidity={!isAlgoConsumablePrice} selectedComputeAssetLowPoolLiquidity={!isAlgoConsumablePrice}
selectedComputeAssetType="algorithm" selectedComputeAssetType="algorithm"
selectedComputeAssetTimeout={algorithmTimeout} selectedComputeAssetTimeout={
selectedAlgorithmAsset?.services[0]?.timeout
}
// lazy comment when removing pricingStepText // lazy comment when removing pricingStepText
stepText={'pricingStepText' || 'Starting Compute Job...'} stepText={'pricingStepText' || 'Starting Compute Job...'}
isConsumable={isConsumable} isConsumable={isConsumable}