Skip to content
This repository has been archived by the owner on Aug 3, 2021. It is now read-only.

Feature/fixed price #105

Merged
merged 13 commits into from
Sep 7, 2020
2 changes: 1 addition & 1 deletion example/src/AllDdos.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function AllDdos() {

useEffect(() => {
async function init() {
if (ocean === undefined || account === undefined) return
if (!ocean || !account) return

const assets = await ocean.assets.query({
page: 1,
Expand Down
11 changes: 0 additions & 11 deletions example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,11 @@ import './App.css'
import { OceanProvider } from '@oceanprotocol/react'
import { Wallet } from './Wallet'
import { Publish } from './Publish'
// import { Config } from '@oceanprotocol/lib'
import { ConfigHelper } from '@oceanprotocol/lib'
import { AllDdos } from './AllDdos'
import { ConsumeDdo } from './ConsumeDdo'
import { NetworkMonitor } from './NetworkMonitor'

// factory Address needs to be updated each time you deploy the contract on local network
// const config: Config = {
// metadataStoreUri: 'http://aquarius:5000',
// providerUri: 'http://localhost:8030',
// nodeUri: `http://localhost:8545`,
// factoryAddress: '0x2fC1fd21cb222Dc180Ef817dE4c426fd9230b5A5'
// }

const configRinkeby = new ConfigHelper().getConfig('rinkeby')

const providerOptions = {}
Expand All @@ -43,11 +34,9 @@ function App() {
<div>
<AllDdos />
</div>

<div>
<Publish />
</div>

<div>
<ConsumeDdo />
</div>
Expand Down
4 changes: 2 additions & 2 deletions example/src/ConsumeDdo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,14 @@ export function ConsumeDdo() {
}, [ocean])

const consumeDid = async () => {
if (did === undefined) return
if (!did) return
const ddo = await ocean.assets.resolve(did)

await consume(did, ddo.dataToken, 'access')
}

const computeDid = async () => {
if (did === undefined) return
if (!did) return
const ddo = await ocean.assets.resolve(did)
console.log(ddo)
console.log('ocean dt', ocean.datatokens)
Expand Down
15 changes: 1 addition & 14 deletions example/src/NetworkMonitor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,7 @@ export const NetworkMonitor = () => {

const handleNetworkChanged = useCallback(
(chainId: number) => {
// const config = getOceanConfig(chainId)
// temp hack
let network = ''
switch (chainId) {
case 1: {
network = 'mainnet'
break
}
case 4: {
network = 'rinkeby'
break
}
}
const config = new ConfigHelper().getConfig(network)
const config = new ConfigHelper().getConfigById(chainId)
connect(config)
},
[connect]
Expand Down
20 changes: 10 additions & 10 deletions example/src/Publish.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import { useState } from 'react'
import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata'

export function Publish() {
// const { accountId, ocean } = useOcean()
const { publish, publishStepText, isLoading } = usePublish()
const [ddo, setDdo] = useState<DDO | undefined>()

Expand All @@ -32,14 +31,16 @@ export function Publish() {
}

const publishAsset = async () => {
const ddo = await publish(asset as Metadata, '90', 'access', '', '')
// const pool = ocean.pool.createDTPool(
// accountId,
// ddo.dataToken,
// '90',
// '9',
// '0.03'
// )
const priceOptions = {
price: 10,
tokensToMint: 10,
type: 'fixed',
weightOnDataToken: '',
liquidityProviderFee: ''
}

const ddo = await publish(asset as Metadata, priceOptions, 'access', '', '')
console.log(ddo)
setDdo(ddo)
}
return (
Expand All @@ -51,7 +52,6 @@ export function Publish() {
<div>
IsLoading: {isLoading.toString()} || Status: {publishStepText}
</div>

<div>DID: {ddo && ddo.id} </div>
</>
)
Expand Down
2 changes: 0 additions & 2 deletions example/src/Wallet.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,9 @@ export function Wallet() {
<div>
<button onClick={conn}>Connect</button>
</div>

<div>
<button onClick={disc}>Disconnect</button>
</div>

<div>{accountId}</div>
</>
)
Expand Down
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -85,5 +85,8 @@
},
"publishConfig": {
"access": "public"
},
"directories": {
"example": "example"
}
}
7 changes: 7 additions & 0 deletions src/hooks/usePublish/PriceOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface PriceOptions {
price?: number
tokensToMint: number
type: 'fixed' | 'dynamic' | string
weightOnDataToken: string
liquidityProviderFee: string
}
5 changes: 0 additions & 5 deletions src/hooks/usePublish/ServiceConfig.ts

This file was deleted.

2 changes: 1 addition & 1 deletion src/hooks/usePublish/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
export * from './usePublish'
export * from './ServiceConfig'
export * from './PriceOptions'
53 changes: 41 additions & 12 deletions src/hooks/usePublish/usePublish.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { useEffect, useState } from 'react'
import { DDO, Metadata, DataTokens, Logger } from '@oceanprotocol/lib'
import { useState } from 'react'
import { DDO, Metadata, Logger } from '@oceanprotocol/lib'
import { useOcean } from '../../providers'
import ProviderStatus from '../../providers/OceanProvider/ProviderStatus'
import {
Service,
ServiceComputePrivacy,
ServiceType
} from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service'
import { ServiceConfig } from './ServiceConfig'
import { PriceOptions } from './PriceOptions'
import { publishFeedback } from '../../utils'

interface UsePublish {
publish: (
asset: Metadata,
tokensToMint: string,
priceOptions: PriceOptions,
serviceConfigs: ServiceType,
mpAddress: string,
mpFee: string
Expand All @@ -26,7 +26,7 @@ interface UsePublish {
}

function usePublish(): UsePublish {
const { ocean, status, account, accountId, config } = useOcean()
const { ocean, status, account, accountId } = useOcean()
const [isLoading, setIsLoading] = useState(false)
const [publishStep, setPublishStep] = useState<number | undefined>()
const [publishStepText, setPublishStepText] = useState<string | undefined>()
Expand All @@ -40,23 +40,23 @@ function usePublish(): UsePublish {
/**
* Publish an asset.It also creates the datatoken, mints tokens and gives the market allowance
* @param {Metadata} asset The metadata of the asset.
* @param {string} tokensToMint Numer of tokens to mint and give allowance to market
* @param {ServiceConfig[]} serviceConfigs Desired services of the asset, ex: [{serviceType: 'access', cost:'1'}]
* @param {PriceOptions} priceOptions : number of tokens to mint, datatoken weight , liquidity fee, type : fixed, dynamic
* @param {ServiceType} serviceType Desired service type of the asset access or compute
* @param {string} mpAddress The address of the market
* @param {string} mpFee The fee of the market
* @return {Promise<DDO>} Returns the newly published ddo
*/
async function publish(
asset: Metadata,
tokensToMint: string,
serviceType: ServiceType,
mpAddress: string,
mpFee: string
priceOptions: PriceOptions,
serviceType: ServiceType
): Promise<DDO> {
if (status !== ProviderStatus.CONNECTED || !ocean || !account) return
setIsLoading(true)
setPublishError(undefined)
try {
const tokensToMint = priceOptions.tokensToMint.toString()

const publishedDate =
new Date(Date.now()).toISOString().split('.')[0] + 'Z'
const timeout = 0
Expand Down Expand Up @@ -132,8 +132,9 @@ function usePublish(): UsePublish {
setStep(7)
await mint(ddo.dataToken, tokensToMint)
Logger.log(`minted ${tokensToMint} tokens`)
setStep(8)

await createPricing(priceOptions, ddo.dataToken)
setStep(8)
return ddo
} catch (error) {
setPublishError(error.message)
Expand All @@ -144,6 +145,34 @@ function usePublish(): UsePublish {
}
}

async function createPricing(
priceOptions: PriceOptions,
dataTokenAddress: string
) {
switch (priceOptions.type) {
case 'dynamic': {
// weight is hardcoded at 9 (90%) and publisher fee at 0.03(this was a random value set by me)
const pool = await ocean.pool.createDTPool(
accountId,
dataTokenAddress,
priceOptions.tokensToMint.toString(),
priceOptions.weightOnDataToken,
priceOptions.liquidityProviderFee
)
break
}
case 'fixed': {
const fixedPriceExchange = await ocean.fixedRateExchange.create(
dataTokenAddress,
priceOptions.price.toString(),
accountId
)
await ocean.fixedRateExchange.activate(fixedPriceExchange, accountId)
break
}
}
}

async function mint(tokenAddress: string, tokensToMint: string) {
Logger.log('mint function', tokenAddress, accountId)
await ocean.datatokens.mint(tokenAddress, accountId, tokensToMint)
Expand Down
82 changes: 68 additions & 14 deletions src/utils/dtUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,48 @@ export async function getBestDataTokenPrice(

return bestPool.price
}
export async function getCheapestExchange(
ocean: Ocean,
dataTokenAddress: string
) {
if (!ocean || !dataTokenAddress) return

const tokenExchanges = await ocean.fixedRateExchange.searchforDT(
dataTokenAddress,
'1'
)
Logger.log('Exchanges found', tokenExchanges)
if (tokenExchanges === undefined || tokenExchanges.length === 0) {
return {
address: '',
price: ''
}
}
let cheapestExchangeAddress
let cheapestExchangePrice = new Decimal(999999999999)

if (tokenExchanges) {
for (let i = 0; i < tokenExchanges.length; i++) {
const exchangePrice = tokenExchanges[i].fixedRate

const decimalExchangePrice = new Decimal(exchangePrice)
Logger.log(
'Pool price ',
tokenExchanges[i],
decimalExchangePrice.toString()
)
if (decimalExchangePrice < cheapestExchangePrice) {
cheapestExchangePrice = decimalExchangePrice
cheapestExchangeAddress = tokenExchanges[i]
}
}
}

return {
address: cheapestExchangeAddress,
price: cheapestExchangePrice.toString()
}
}

export async function checkAndBuyDT(
ocean: Ocean,
Expand All @@ -65,25 +107,37 @@ export async function checkAndBuyDT(
account
)
Logger.log(`User has ${userOwnedTokens} tokens`)
let cheapestPool
if (userOwnedTokens === '0') {
cheapestPool = await getCheapestPool(
const cheapestPool = await getCheapestPool(
ocean,
account.getId(),
dataTokenAddress
)
const cheapestExchange = await getCheapestExchange(ocean, dataTokenAddress)
Decimal.set({ precision: 5 })
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
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
}
}
}