1
0
mirror of https://github.com/oceanprotocol/react.git synced 2024-12-23 01:29:49 +01:00

consume, ocean=lib update

This commit is contained in:
mihaisc 2020-09-10 17:59:39 +03:00
parent 782d696ac0
commit 19047b3389
No known key found for this signature in database
GPG Key ID: BE522BB8C3A5E2E4
10 changed files with 10158 additions and 203 deletions

View File

@ -22,7 +22,7 @@ export function AllDdos() {
sort: { created: -1 } sort: { created: -1 }
}) })
setDdos(assets.results) setDdos(assets.results.slice(0, 4))
} }
init() init()
}, [ocean, account, chainId]) }, [ocean, account, chainId])

View File

@ -3,12 +3,19 @@ import { useMetadata } from '@oceanprotocol/react'
import { DDO } from '@oceanprotocol/lib' import { DDO } from '@oceanprotocol/lib'
export function MetadataExample({ ddo }: { ddo: DDO }) { export function MetadataExample({ ddo }: { ddo: DDO }) {
const { title, poolAddress, price } = useMetadata(ddo) const { title, price, did } = useMetadata(ddo)
return ( return (
<> <>
<div> <div>
{title} - price = {price} // pool = {poolAddress} {title} - did= {did}
</div>
<div>
{price && (
<span>
price = {price.value} // {price.type} = {price.address}
</span>
)}
</div> </div>
</> </>
) )

View File

@ -32,7 +32,7 @@ export function Publish() {
const publishAsset = async () => { const publishAsset = async () => {
const priceOptions = { const priceOptions = {
price: 10, price: 7,
tokensToMint: 10, tokensToMint: 10,
type: 'fixed', type: 'fixed',
weightOnDataToken: '', weightOnDataToken: '',

10147
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -25,7 +25,7 @@
"dist/" "dist/"
], ],
"dependencies": { "dependencies": {
"@oceanprotocol/lib": "^0.2.3", "@oceanprotocol/lib": "file:../ocean-lib-js",
"axios": "^0.20.0", "axios": "^0.20.0",
"decimal.js": "^10.2.0", "decimal.js": "^10.2.0",
"web3": "^1.2.11", "web3": "^1.2.11",

View File

@ -25,7 +25,7 @@ export const consumeFeedback: { [key in number]: string } = {
} }
function useConsume(): UseConsume { function useConsume(): UseConsume {
const { ocean, account, accountId } = useOcean() const { ocean, account, accountId, config } = useOcean()
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [consumeStep, setConsumeStep] = useState<number | undefined>() const [consumeStep, setConsumeStep] = useState<number | undefined>()
const [consumeStepText, setConsumeStepText] = useState<string | undefined>() const [consumeStepText, setConsumeStepText] = useState<string | undefined>()
@ -47,7 +47,7 @@ function useConsume(): UseConsume {
try { try {
setStep(0) setStep(0)
await checkAndBuyDT(ocean, dataTokenAddress, account) await checkAndBuyDT(ocean, dataTokenAddress, account, config)
setStep(1) setStep(1)
const order = await ocean.assets.order(did, serviceType, accountId) const order = await ocean.assets.order(did, serviceType, accountId)

View File

@ -0,0 +1,5 @@
export default interface BestPrice {
type: 'pool' | 'exchange'
address: string
value: string
}

View File

@ -2,31 +2,28 @@ import { useState, useEffect } from 'react'
import { DID, DDO, Metadata, Logger } from '@oceanprotocol/lib' import { DID, DDO, Metadata, Logger } from '@oceanprotocol/lib'
import { useOcean } from '../../providers' import { useOcean } from '../../providers'
import ProviderStatus from '../../providers/OceanProvider/ProviderStatus' import ProviderStatus from '../../providers/OceanProvider/ProviderStatus'
import { getBestDataTokenPrice, getCheapestPool } from '../../utils/dtUtils' import { getBestDataTokenPrice } from '../../utils/dtUtils'
import Pool from './Pool'
import { isDDO } from '../../utils' import { isDDO } from '../../utils'
import BestPrice from './BestPrice'
interface UseMetadata { interface UseMetadata {
ddo: DDO ddo: DDO
did: DID | string did: DID | string
metadata: Metadata metadata: Metadata
title: string title: string
price: string price: BestPrice
poolAddress: string
isLoaded: boolean isLoaded: boolean
getPrice: (dataTokenAddress?: string) => Promise<string> getPrice: (dataTokenAddress?: string) => Promise<BestPrice>
getPool: (dataTokenAddress?: string) => Promise<Pool>
} }
function useMetadata(asset?: DID | string | DDO): UseMetadata { function useMetadata(asset?: DID | string | DDO): UseMetadata {
const { ocean, status, config, accountId } = useOcean() const { ocean, status, accountId } = useOcean()
const [internalDdo, setDDO] = useState<DDO | undefined>() const [internalDdo, setDDO] = useState<DDO | undefined>()
const [internalDid, setDID] = useState<DID | string | undefined>() const [internalDid, setDID] = useState<DID | string | undefined>()
const [metadata, setMetadata] = useState<Metadata | undefined>() const [metadata, setMetadata] = useState<Metadata | undefined>()
const [title, setTitle] = useState<string | undefined>() const [title, setTitle] = useState<string | undefined>()
const [isLoaded, setIsLoaded] = useState(false) const [isLoaded, setIsLoaded] = useState(false)
const [price, setPrice] = useState<string | undefined>() const [price, setPrice] = useState<BestPrice | undefined>()
const [poolAddress, setPoolAddress] = useState<string | undefined>()
async function getDDO(did: DID | string): Promise<DDO> { async function getDDO(did: DID | string): Promise<DDO> {
if (status === ProviderStatus.CONNECTED) { if (status === ProviderStatus.CONNECTED) {
@ -35,13 +32,9 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
} }
} }
async function getPrice(dataTokenAddress?: string): Promise<string> { async function getPrice(dataTokenAddress?: string): Promise<BestPrice> {
if (!dataTokenAddress) dataTokenAddress = internalDdo.dataToken if (!dataTokenAddress) dataTokenAddress = internalDdo.dataToken
return await getBestDataTokenPrice(ocean, accountId, dataTokenAddress) return await getBestDataTokenPrice(ocean, dataTokenAddress, accountId)
}
async function getPool(dataTokenAddress?: string): Promise<Pool> {
if (!dataTokenAddress) dataTokenAddress = internalDdo.dataToken
return await getCheapestPool(ocean, accountId, dataTokenAddress)
} }
async function getMetadata(): Promise<Metadata> { async function getMetadata(): Promise<Metadata> {
@ -50,11 +43,6 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
return metadata.attributes return metadata.attributes
} }
async function getTitle(): Promise<string> {
const metadata = await getMetadata()
return metadata.main.name
}
useEffect(() => { useEffect(() => {
async function init(): Promise<void> { async function init(): Promise<void> {
if (ocean && status === ProviderStatus.CONNECTED) { if (ocean && status === ProviderStatus.CONNECTED) {
@ -82,18 +70,17 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
const metadata = await getMetadata() const metadata = await getMetadata()
setMetadata(metadata) setMetadata(metadata)
setTitle(metadata.main.name) setTitle(metadata.main.name)
const pool = await getPool() const price = await getPrice()
setPoolAddress(pool.address)
setPrice(pool.price) setPrice(price)
setIsLoaded(true) setIsLoaded(true)
} }
} }
init() init()
const interval = setInterval(async () => { const interval = setInterval(async () => {
const pool = await getPool() const price = await getPrice()
setPoolAddress(pool.address) setPrice(price)
setPrice(pool.price)
}, 10000) }, 10000)
return () => clearInterval(interval) return () => clearInterval(interval)
}, [accountId, internalDdo]) }, [accountId, internalDdo])
@ -104,10 +91,8 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
metadata, metadata,
title, title,
price, price,
poolAddress,
isLoaded, isLoaded,
getPrice, getPrice
getPool
} }
} }

View File

@ -26,7 +26,7 @@ interface UsePublish {
} }
function usePublish(): UsePublish { function usePublish(): UsePublish {
const { ocean, status, account, accountId } = useOcean() const { ocean, status, account, accountId, config } = useOcean()
const [isLoading, setIsLoading] = useState(false) const [isLoading, setIsLoading] = useState(false)
const [publishStep, setPublishStep] = useState<number | undefined>() const [publishStep, setPublishStep] = useState<number | undefined>()
const [publishStepText, setPublishStepText] = useState<string | undefined>() const [publishStepText, setPublishStepText] = useState<string | undefined>()
@ -140,7 +140,7 @@ function usePublish(): UsePublish {
await mint(ddo.dataToken, tokensToMint) await mint(ddo.dataToken, tokensToMint)
Logger.log(`minted ${tokensToMint} tokens`) Logger.log(`minted ${tokensToMint} tokens`)
await createPricing(priceOptions, ddo.dataToken) await createPricing(priceOptions, ddo.dataToken, tokensToMint)
setStep(8) setStep(8)
return ddo return ddo
} catch (error) { } catch (error) {
@ -154,7 +154,8 @@ function usePublish(): UsePublish {
async function createPricing( async function createPricing(
priceOptions: PriceOptions, priceOptions: PriceOptions,
dataTokenAddress: string dataTokenAddress: string,
mintedTokens: string
) { ) {
switch (priceOptions.type) { switch (priceOptions.type) {
case 'dynamic': { case 'dynamic': {
@ -173,7 +174,12 @@ function usePublish(): UsePublish {
priceOptions.price.toString(), priceOptions.price.toString(),
accountId accountId
) )
await ocean.datatokens.approve(
dataTokenAddress,
config.fixedRateExchangeAddress,
mintedTokens,
accountId
)
break break
} }
} }

View File

@ -1,6 +1,8 @@
import { Logger, Ocean, Account } from '@oceanprotocol/lib' import { Logger, Ocean, Account, Config } from '@oceanprotocol/lib'
import { Decimal } from 'decimal.js' import { Decimal } from 'decimal.js'
import Pool from '../hooks/useMetadata/Pool' import Pool from '../hooks/useMetadata/Pool'
import BestPrice from '../hooks/useMetadata/BestPrice'
import Web3 from 'web3'
export async function getCheapestPool( export async function getCheapestPool(
ocean: Ocean, ocean: Ocean,
@ -13,14 +15,14 @@ export async function getCheapestPool(
accountId, accountId,
dataTokenAddress dataTokenAddress
) )
// Logger.log('DT Pool found', tokenPools)
if (tokenPools === undefined || tokenPools.length === 0) { if (tokenPools === undefined || tokenPools.length === 0) {
return { return {
address: '', address: '',
price: '' price: ''
} }
} }
let cheapestPoolAddress let cheapestPoolAddress = tokenPools[0]
let cheapestPoolPrice = new Decimal(999999999999) let cheapestPoolPrice = new Decimal(999999999999)
if (tokenPools) { if (tokenPools) {
@ -31,7 +33,7 @@ export async function getCheapestPool(
'1' '1'
) )
const decimalPoolPrice = new Decimal(poolPrice) const decimalPoolPrice = new Decimal(poolPrice)
Logger.log('Pool price ', tokenPools[i], decimalPoolPrice.toString())
if (decimalPoolPrice < cheapestPoolPrice) { if (decimalPoolPrice < cheapestPoolPrice) {
cheapestPoolPrice = decimalPoolPrice cheapestPoolPrice = decimalPoolPrice
cheapestPoolAddress = tokenPools[i] cheapestPoolAddress = tokenPools[i]
@ -47,12 +49,33 @@ export async function getCheapestPool(
export async function getBestDataTokenPrice( export async function getBestDataTokenPrice(
ocean: Ocean, ocean: Ocean,
accountId: string, dataTokenAddress: string,
dataTokenAddress: string accountId: string
): Promise<string> { ): Promise<BestPrice | undefined> {
const bestPool = await getCheapestPool(ocean, accountId, dataTokenAddress) const cheapestPool = await getCheapestPool(ocean, accountId, dataTokenAddress)
const cheapestExchange = await getCheapestExchange(ocean, dataTokenAddress)
Decimal.set({ precision: 5 })
return bestPool.price const cheapestPoolPrice = new Decimal(
cheapestPool.price !== '' ? cheapestPool.price : 999999999999
)
const cheapestExchangePrice = new Decimal(
cheapestExchange.price !== '' ? cheapestExchange.price : 999999999999
)
if (cheapestPoolPrice < cheapestExchangePrice) {
return {
type: 'pool',
address: cheapestPool.address,
value: cheapestPool.price
} as BestPrice
} else {
return {
type: 'exchange',
address: cheapestExchange.address,
value: cheapestExchange.price
} as BestPrice
}
} }
export async function getCheapestExchange( export async function getCheapestExchange(
ocean: Ocean, ocean: Ocean,
@ -64,30 +87,24 @@ export async function getCheapestExchange(
dataTokenAddress, dataTokenAddress,
'1' '1'
) )
Logger.log('Exchanges found', tokenExchanges)
if (tokenExchanges === undefined || tokenExchanges.length === 0) { if (tokenExchanges === undefined || tokenExchanges.length === 0) {
return { return {
address: '', address: '',
price: '' price: ''
} }
} }
let cheapestExchangeAddress let cheapestExchangeAddress = tokenExchanges[0].exchangeID
let cheapestExchangePrice = new Decimal(999999999999) let cheapestExchangePrice = new Decimal(tokenExchanges[0].fixedRate)
if (tokenExchanges) { for (let i = 0; i < tokenExchanges.length; i++) {
for (let i = 0; i < tokenExchanges.length; i++) { const decimalExchangePrice = new Decimal(
const exchangePrice = tokenExchanges[i].fixedRate Web3.utils.fromWei(tokenExchanges[i].fixedRate)
)
const decimalExchangePrice = new Decimal(exchangePrice) if (decimalExchangePrice < cheapestExchangePrice) {
Logger.log( cheapestExchangePrice = decimalExchangePrice
'Pool price ', cheapestExchangeAddress = tokenExchanges[i].exchangeID
tokenExchanges[i],
decimalExchangePrice.toString()
)
if (decimalExchangePrice < cheapestExchangePrice) {
cheapestExchangePrice = decimalExchangePrice
cheapestExchangeAddress = tokenExchanges[i]
}
} }
} }
@ -100,7 +117,8 @@ export async function getCheapestExchange(
export async function checkAndBuyDT( export async function checkAndBuyDT(
ocean: Ocean, ocean: Ocean,
dataTokenAddress: string, dataTokenAddress: string,
account: Account account: Account,
config: Config
) { ) {
const userOwnedTokens = await ocean.accounts.getTokenBalance( const userOwnedTokens = await ocean.accounts.getTokenBalance(
dataTokenAddress, dataTokenAddress,
@ -108,36 +126,43 @@ export async function checkAndBuyDT(
) )
Logger.log(`User has ${userOwnedTokens} tokens`) Logger.log(`User has ${userOwnedTokens} tokens`)
if (userOwnedTokens === '0') { if (userOwnedTokens === '0') {
const cheapestPool = await getCheapestPool( const bestPrice = await getBestDataTokenPrice(
ocean, ocean,
account.getId(), dataTokenAddress,
dataTokenAddress account.getId()
) )
const cheapestExchange = await getCheapestExchange(ocean, dataTokenAddress)
Decimal.set({ precision: 5 })
const cheapestPoolPrice = new Decimal(cheapestPool.price)
const cheapestExchangePrice = new Decimal(cheapestExchange.price)
if (cheapestExchangePrice > cheapestPoolPrice) { switch (bestPrice.type) {
const price = new Decimal(cheapestPool.price).times(1.05).toString() case 'pool': {
const maxPrice = new Decimal(cheapestPool.price).times(2).toString() const price = new Decimal(bestPrice.value).times(1.05).toString()
Logger.log('Buying token', cheapestPool, account.getId(), price) const maxPrice = new Decimal(bestPrice.value).times(2).toString()
const buyResponse = await ocean.pool.buyDT( Logger.log('Buying token from pool', bestPrice, account.getId(), price)
account.getId(), const buyResponse = await ocean.pool.buyDT(
cheapestPool.address, account.getId(),
'1', bestPrice.address,
price, '1',
maxPrice price,
) maxPrice
Logger.log('DT buy response', buyResponse) )
return buyResponse Logger.log('DT buy response', buyResponse)
} else { return buyResponse
const exchange = await ocean.fixedRateExchange.buyDT( }
cheapestExchange.address, case 'exchange': {
'1', Logger.log('Buying token from exchange', bestPrice, account.getId())
account.getId() await ocean.datatokens.approve(
) config.oceanTokenAddress,
return exchange config.fixedRateExchangeAddress,
bestPrice.value,
account.getId()
)
const exchange = await ocean.fixedRateExchange.buyDT(
bestPrice.address,
'1',
account.getId()
)
Logger.log('DT exchange buy response', exchange)
return exchange
}
} }
} }
} }