1
0
mirror of https://github.com/oceanprotocol/react.git synced 2024-12-22 17:23:32 +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 }
})
setDdos(assets.results)
setDdos(assets.results.slice(0, 4))
}
init()
}, [ocean, account, chainId])

View File

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

View File

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

10147
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

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

View File

@ -25,7 +25,7 @@ export const consumeFeedback: { [key in number]: string } = {
}
function useConsume(): UseConsume {
const { ocean, account, accountId } = useOcean()
const { ocean, account, accountId, config } = useOcean()
const [isLoading, setIsLoading] = useState(false)
const [consumeStep, setConsumeStep] = useState<number | undefined>()
const [consumeStepText, setConsumeStepText] = useState<string | undefined>()
@ -47,7 +47,7 @@ function useConsume(): UseConsume {
try {
setStep(0)
await checkAndBuyDT(ocean, dataTokenAddress, account)
await checkAndBuyDT(ocean, dataTokenAddress, account, config)
setStep(1)
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 { useOcean } from '../../providers'
import ProviderStatus from '../../providers/OceanProvider/ProviderStatus'
import { getBestDataTokenPrice, getCheapestPool } from '../../utils/dtUtils'
import Pool from './Pool'
import { getBestDataTokenPrice } from '../../utils/dtUtils'
import { isDDO } from '../../utils'
import BestPrice from './BestPrice'
interface UseMetadata {
ddo: DDO
did: DID | string
metadata: Metadata
title: string
price: string
poolAddress: string
price: BestPrice
isLoaded: boolean
getPrice: (dataTokenAddress?: string) => Promise<string>
getPool: (dataTokenAddress?: string) => Promise<Pool>
getPrice: (dataTokenAddress?: string) => Promise<BestPrice>
}
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 [internalDid, setDID] = useState<DID | string | undefined>()
const [metadata, setMetadata] = useState<Metadata | undefined>()
const [title, setTitle] = useState<string | undefined>()
const [isLoaded, setIsLoaded] = useState(false)
const [price, setPrice] = useState<string | undefined>()
const [poolAddress, setPoolAddress] = useState<string | undefined>()
const [price, setPrice] = useState<BestPrice | undefined>()
async function getDDO(did: DID | string): Promise<DDO> {
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
return await getBestDataTokenPrice(ocean, accountId, dataTokenAddress)
}
async function getPool(dataTokenAddress?: string): Promise<Pool> {
if (!dataTokenAddress) dataTokenAddress = internalDdo.dataToken
return await getCheapestPool(ocean, accountId, dataTokenAddress)
return await getBestDataTokenPrice(ocean, dataTokenAddress, accountId)
}
async function getMetadata(): Promise<Metadata> {
@ -50,11 +43,6 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
return metadata.attributes
}
async function getTitle(): Promise<string> {
const metadata = await getMetadata()
return metadata.main.name
}
useEffect(() => {
async function init(): Promise<void> {
if (ocean && status === ProviderStatus.CONNECTED) {
@ -82,18 +70,17 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
const metadata = await getMetadata()
setMetadata(metadata)
setTitle(metadata.main.name)
const pool = await getPool()
setPoolAddress(pool.address)
setPrice(pool.price)
const price = await getPrice()
setPrice(price)
setIsLoaded(true)
}
}
init()
const interval = setInterval(async () => {
const pool = await getPool()
setPoolAddress(pool.address)
setPrice(pool.price)
const price = await getPrice()
setPrice(price)
}, 10000)
return () => clearInterval(interval)
}, [accountId, internalDdo])
@ -104,10 +91,8 @@ function useMetadata(asset?: DID | string | DDO): UseMetadata {
metadata,
title,
price,
poolAddress,
isLoaded,
getPrice,
getPool
getPrice
}
}

View File

@ -26,7 +26,7 @@ interface UsePublish {
}
function usePublish(): UsePublish {
const { ocean, status, account, accountId } = useOcean()
const { ocean, status, account, accountId, config } = useOcean()
const [isLoading, setIsLoading] = useState(false)
const [publishStep, setPublishStep] = useState<number | undefined>()
const [publishStepText, setPublishStepText] = useState<string | undefined>()
@ -140,7 +140,7 @@ function usePublish(): UsePublish {
await mint(ddo.dataToken, tokensToMint)
Logger.log(`minted ${tokensToMint} tokens`)
await createPricing(priceOptions, ddo.dataToken)
await createPricing(priceOptions, ddo.dataToken, tokensToMint)
setStep(8)
return ddo
} catch (error) {
@ -154,7 +154,8 @@ function usePublish(): UsePublish {
async function createPricing(
priceOptions: PriceOptions,
dataTokenAddress: string
dataTokenAddress: string,
mintedTokens: string
) {
switch (priceOptions.type) {
case 'dynamic': {
@ -173,7 +174,12 @@ function usePublish(): UsePublish {
priceOptions.price.toString(),
accountId
)
await ocean.datatokens.approve(
dataTokenAddress,
config.fixedRateExchangeAddress,
mintedTokens,
accountId
)
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 Pool from '../hooks/useMetadata/Pool'
import BestPrice from '../hooks/useMetadata/BestPrice'
import Web3 from 'web3'
export async function getCheapestPool(
ocean: Ocean,
@ -13,14 +15,14 @@ export async function getCheapestPool(
accountId,
dataTokenAddress
)
// Logger.log('DT Pool found', tokenPools)
if (tokenPools === undefined || tokenPools.length === 0) {
return {
address: '',
price: ''
}
}
let cheapestPoolAddress
let cheapestPoolAddress = tokenPools[0]
let cheapestPoolPrice = new Decimal(999999999999)
if (tokenPools) {
@ -31,7 +33,7 @@ export async function getCheapestPool(
'1'
)
const decimalPoolPrice = new Decimal(poolPrice)
Logger.log('Pool price ', tokenPools[i], decimalPoolPrice.toString())
if (decimalPoolPrice < cheapestPoolPrice) {
cheapestPoolPrice = decimalPoolPrice
cheapestPoolAddress = tokenPools[i]
@ -47,12 +49,33 @@ export async function getCheapestPool(
export async function getBestDataTokenPrice(
ocean: Ocean,
accountId: string,
dataTokenAddress: string
): Promise<string> {
const bestPool = await getCheapestPool(ocean, accountId, dataTokenAddress)
dataTokenAddress: string,
accountId: string
): Promise<BestPrice | undefined> {
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(
ocean: Ocean,
@ -64,30 +87,24 @@ export async function getCheapestExchange(
dataTokenAddress,
'1'
)
Logger.log('Exchanges found', tokenExchanges)
if (tokenExchanges === undefined || tokenExchanges.length === 0) {
return {
address: '',
price: ''
}
}
let cheapestExchangeAddress
let cheapestExchangePrice = new Decimal(999999999999)
let cheapestExchangeAddress = tokenExchanges[0].exchangeID
let cheapestExchangePrice = new Decimal(tokenExchanges[0].fixedRate)
if (tokenExchanges) {
for (let i = 0; i < tokenExchanges.length; i++) {
const exchangePrice = tokenExchanges[i].fixedRate
for (let i = 0; i < tokenExchanges.length; i++) {
const decimalExchangePrice = new Decimal(
Web3.utils.fromWei(tokenExchanges[i].fixedRate)
)
const decimalExchangePrice = new Decimal(exchangePrice)
Logger.log(
'Pool price ',
tokenExchanges[i],
decimalExchangePrice.toString()
)
if (decimalExchangePrice < cheapestExchangePrice) {
cheapestExchangePrice = decimalExchangePrice
cheapestExchangeAddress = tokenExchanges[i]
}
if (decimalExchangePrice < cheapestExchangePrice) {
cheapestExchangePrice = decimalExchangePrice
cheapestExchangeAddress = tokenExchanges[i].exchangeID
}
}
@ -100,7 +117,8 @@ export async function getCheapestExchange(
export async function checkAndBuyDT(
ocean: Ocean,
dataTokenAddress: string,
account: Account
account: Account,
config: Config
) {
const userOwnedTokens = await ocean.accounts.getTokenBalance(
dataTokenAddress,
@ -108,36 +126,43 @@ export async function checkAndBuyDT(
)
Logger.log(`User has ${userOwnedTokens} tokens`)
if (userOwnedTokens === '0') {
const cheapestPool = await getCheapestPool(
const bestPrice = await getBestDataTokenPrice(
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) {
const price = new Decimal(cheapestPool.price).times(1.05).toString()
const maxPrice = new Decimal(cheapestPool.price).times(2).toString()
Logger.log('Buying token', cheapestPool, account.getId(), price)
const buyResponse = await ocean.pool.buyDT(
account.getId(),
cheapestPool.address,
'1',
price,
maxPrice
)
Logger.log('DT buy response', buyResponse)
return buyResponse
} else {
const exchange = await ocean.fixedRateExchange.buyDT(
cheapestExchange.address,
'1',
account.getId()
)
return exchange
switch (bestPrice.type) {
case 'pool': {
const price = new Decimal(bestPrice.value).times(1.05).toString()
const maxPrice = new Decimal(bestPrice.value).times(2).toString()
Logger.log('Buying token from pool', bestPrice, account.getId(), price)
const buyResponse = await ocean.pool.buyDT(
account.getId(),
bestPrice.address,
'1',
price,
maxPrice
)
Logger.log('DT buy response', buyResponse)
return buyResponse
}
case 'exchange': {
Logger.log('Buying token from exchange', bestPrice, account.getId())
await ocean.datatokens.approve(
config.oceanTokenAddress,
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
}
}
}
}