1
0
mirror of https://github.com/oceanprotocol/react.git synced 2025-01-05 11:25:18 +01:00

move to usePricing

This commit is contained in:
alexcos20 2020-10-19 02:47:12 -07:00
parent e39f41403d
commit 6e5ae7b2ce
16 changed files with 202 additions and 295 deletions

View File

@ -8,7 +8,7 @@ import { AllDdos } from './AllDdos'
import { ConsumeDdo } from './ConsumeDdo' import { ConsumeDdo } from './ConsumeDdo'
import { NetworkMonitor } from './NetworkMonitor' import { NetworkMonitor } from './NetworkMonitor'
import { LogLevel } from '@oceanprotocol/lib/dist/node/utils' import { LogLevel } from '@oceanprotocol/lib/dist/node/utils'
import { Trade } from './Trade' import { Pricing } from './Pricing'
const configRinkeby = new ConfigHelper().getConfig('rinkeby') const configRinkeby = new ConfigHelper().getConfig('rinkeby')
const providerOptions = {} const providerOptions = {}
@ -41,7 +41,7 @@ function App() {
<Publish /> <Publish />
</div> </div>
<div> <div>
<Trade /> <Pricing />
</div> </div>
<div> <div>
<ConsumeDdo /> <ConsumeDdo />

57
example/src/Pricing.tsx Normal file
View File

@ -0,0 +1,57 @@
import React from 'react'
import { useOcean, usePricing } from '@oceanprotocol/react'
// import { useOcean, usePublish } from '@oceanprotocol/react'
import { DDO } from '@oceanprotocol/lib'
import { useState } from 'react'
import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata'
export function Trade() {
const { ocean, accountId } = useOcean()
const { createPricing,buyDT,sellDT,mint,pricingStep,pricingStepText,pricingIsLoading, pricingError} = usePricing()
const [datatoken, setDatatoken] = useState<string | undefined>()
const handleBuy = async () => {
const tx = await buyDT(datatoken,'1')
console.log(tx)
}
const handleSell = async () => {
const tx = await buyDT(datatoken,'1')
console.log(tx)
}
const handleChange = (e: any) => {
setDatatoken(e.target.value)
}
const handlePostForSale = async () => {
if(datatoken){
const priceOptions = {
price: 7,
dtAmount: 10,
type: 'fixed',
weightOnDataToken: '',
swapFee: ''
}
const tx = await createPricing(datatoken,priceOptions)
console.log(tx)
}
}
return (
<>
<div>Trade Datatoken</div>
<div>
Datatoken <input onChange={handleChange}></input>
</div>
<div>
<button onClick={handlePostForSale}>Post for sale</button>
</div>
<div>
<button onClick={handleBuy}>Buy 1 DT</button>
</div>
<div>
<button onClick={handleSell}>Sell 1 DT</button>
</div>
<div>
IsLoading: {pricingIsLoading.toString()} || Status: {pricingStepText}
</div>
</>
)
}

View File

@ -1,13 +1,12 @@
import React from 'react' import React from 'react'
import { usePublish, useCreatePricing } from '@oceanprotocol/react' import { usePublish } from '@oceanprotocol/react'
// import { useOcean, usePublish } from '@oceanprotocol/react'
import { DDO } from '@oceanprotocol/lib' import { DDO } from '@oceanprotocol/lib'
import { useState } from 'react' import { useState } from 'react'
import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata' import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata'
export function Publish() { export function Publish() {
const { publish, publishStepText, isLoading } = usePublish() const { publish, publishStepText, isLoading } = usePublish()
const { createPricing, pricingStep, pricingStepText, pricingIsLoading, pricingError} = useCreatePricing() const { createPricing, pricingStep, pricingStepText, pricingIsLoading, pricingError} = usePricing()
const [ddo, setDdo] = useState<DDO | undefined | null>() const [ddo, setDdo] = useState<DDO | undefined | null>()
const asset = { const asset = {
@ -32,37 +31,16 @@ export function Publish() {
} }
const publishAsset = async () => { const publishAsset = async () => {
const priceOptions = {
price: 7,
dtAmount: 10,
type: 'fixed',
weightOnDataToken: '',
swapFee: ''
}
const datatokenOptions = { const datatokenOptions = {
tokensToMint:10
} }
const ddo = await publish(asset as Metadata, 'access', datatokenOptions) const ddo = await publish(asset as Metadata, 'access', datatokenOptions)
console.log(ddo) console.log(ddo)
setDdo(ddo) setDdo(ddo)
} }
const handlePostForSale = async () => {
if(ddo){
const priceOptions = {
price: 7,
dtAmount: 10,
type: 'fixed',
weightOnDataToken: '',
swapFee: ''
}
const tx = await createPricing(ddo.dataToken,priceOptions)
console.log(tx)
}
else{
console.error("Publish the asset first")
}
}
return ( return (
<> <>
<div>Publish</div> <div>Publish</div>
@ -73,12 +51,6 @@ export function Publish() {
IsLoading: {isLoading.toString()} || Status: {publishStepText} IsLoading: {isLoading.toString()} || Status: {publishStepText}
</div> </div>
<div>DID: {ddo && ddo.id} </div> <div>DID: {ddo && ddo.id} </div>
<div>
<button onClick={handlePostForSale}>Post for sale</button>
</div>
<div>
IsLoading: {pricingIsLoading.toString()} || pricingStatus: {pricingStepText}
</div>
</> </>
) )

View File

@ -1,55 +0,0 @@
import React from 'react'
import { useOcean, useTrade } from '@oceanprotocol/react'
// import { useOcean, usePublish } from '@oceanprotocol/react'
import { DDO } from '@oceanprotocol/lib'
import { useState } from 'react'
import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata'
export function Trade() {
const { ocean, accountId } = useOcean()
const { buyDT, sellDT, tradeStep, tradeStepText, tradeIsLoading, tradeError} = useTrade()
const [did, setDid] = useState<string | undefined>()
const handleBuy = async () => {
if (!did) { console.error("No DID"); return}
const ddo = await ocean.assets.resolve(did)
if(ddo){
const tx = await buyDT(ddo.dataToken,'1')
console.log(tx)
}
else{
console.error("Publish the asset first and create a pricing")
}
}
const handleSell = async () => {
if (!did) { console.error("No DID"); return}
const ddo = await ocean.assets.resolve(did)
if(ddo){
const tx = await buyDT(ddo.dataToken,'1')
console.log(tx)
}
else{
console.error("Publish the asset first and create a pricing")
}
}
const handleChange = (e: any) => {
setDid(e.target.value)
}
return (
<>
<div>Trade Datatoken</div>
<div>
DID <input onChange={handleChange}></input>
</div>
<div>
<button onClick={handleBuy}>Buy 1 DT</button>
</div>
<div>
<button onClick={handleSell}>Sell 1 DT</button>
</div>
<div>
IsLoading: {tradeIsLoading.toString()} || Status: {tradeStepText}
</div>
</>
)
}

View File

@ -2,5 +2,4 @@ export * from './useConsume'
export * from './useMetadata' export * from './useMetadata'
export * from './usePublish' export * from './usePublish'
export * from './useCompute' export * from './useCompute'
export * from './useCreatePricing' export * from './usePricing'
export * from './useTrade'

View File

@ -1,2 +0,0 @@
export * from './useCreatePricing'
export * from './PriceOptions'

View File

@ -1,114 +0,0 @@
import { Logger } from '@oceanprotocol/lib'
import { useState } from 'react'
import { useOcean } from 'providers'
import { PriceOptions } from './PriceOptions'
import { TransactionReceipt } from 'web3-core'
import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils'
import { Decimal } from 'decimal.js'
interface UseCreatePricing {
createPricing: (
dataTokenAddress: string,
priceOptions: PriceOptions
) => Promise<TransactionReceipt | string | null>
pricingStep?: number
pricingStepText?: string
pricingError?: string
pricingIsLoading: boolean
}
export const createPricingFeedback: { [key in number]: string } = {
0: '1/4 Approving DT ...',
1: '2/4 Approving Ocean ...',
2: '3/4 Creating ....',
3: '4/4 Pricing created'
}
function useCreatePricing(): UseCreatePricing {
const { ocean, status, account, accountId, config } = useOcean()
const [pricingIsLoading, setPricingIsLoading] = useState(false)
const [pricingStep, setPricingStep] = useState<number | undefined>()
const [pricingStepText, setPricingStepText] = useState<string | undefined>()
const [pricingError, setPricingError] = useState<string | undefined>()
const [dtSymbol, setDtSymbol] = useState<string>()
function setStepCreatePricing(index?: number) {
setPricingStep(index)
let message
if (index) {
if (dtSymbol)
message = createPricingFeedback[index].replace(/DT/g, dtSymbol)
else message = createPricingFeedback[index]
setPricingStepText(message)
}
}
async function createPricing(
dataTokenAddress: string,
priceOptions: PriceOptions
): Promise<TransactionReceipt | string | null> {
if (!ocean || !account || !accountId) return null
let response = null
try {
setPricingIsLoading(true)
setPricingError(undefined)
setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress))
setStepCreatePricing(0)
switch (priceOptions.type) {
case 'dynamic': {
setStepCreatePricing(2)
response = await ocean.pool.createDTPool(
accountId,
dataTokenAddress,
priceOptions.dtAmount.toString(),
priceOptions.weightOnDataToken,
priceOptions.swapFee
)
setStepCreatePricing(3)
return response
}
case 'fixed': {
if (!config.fixedRateExchangeAddress) {
Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`)
return null
}
setStepCreatePricing(2)
response = await ocean.fixedRateExchange.create(
dataTokenAddress,
priceOptions.price.toString(),
accountId
)
setStepCreatePricing(1)
await ocean.datatokens.approve(
dataTokenAddress,
config.fixedRateExchangeAddress,
String(priceOptions.dtAmount),
accountId
)
setStepCreatePricing(3)
return response
}
}
} catch (error) {
setPricingError(error.message)
Logger.error(error)
} finally {
setPricingStep(undefined)
setPricingStepText(undefined)
setPricingIsLoading(false)
}
return null
}
return {
createPricing,
pricingStep,
pricingStepText,
pricingIsLoading,
pricingError
}
}
export { useCreatePricing, UseCreatePricing }
export default useCreatePricing

View File

@ -1,6 +1,6 @@
# `usePricing` # `usePricing`
Hook with helper utilities to create fixed price exchanges or liquidity pools for your data set Hook with helper utilities to create fixed price exchanges or liquidity pools for your data set, mint datatokens , buy and sell datatokens
## Usage ## Usage
@ -13,7 +13,7 @@ export default function MyComponent() {
const { accountId } = useOcean() const { accountId } = useOcean()
const dataTokenAddress = '0x00000' const dataTokenAddress = '0x00000'
// Publish helpers // Publish helpers
const { createPricing } = useCreatePricing() const { createPricing } = usePricing()
const priceOptions = { const priceOptions = {
price: 10, price: 10,
@ -27,13 +27,25 @@ export default function MyComponent() {
await createPricing(dataTokenAddress, priceOptions) await createPricing(dataTokenAddress, priceOptions)
} }
async function handleMint() {
await mint(dataTokenAddress, '1')
}
async function handleBuyDT() {
await buyDT(dataTokenAddress, '1')
}
async function handleSellDT() {
await sellDT(dataTokenAddress, '1')
}
return ( return (
<div> <div>
<h1>Post for sale</h1> <h1>Post for sale</h1>
<p>Your account: {accountId}</p> <p>Your account: {accountId}</p>
<button onClick={handleMint}>Mint DT</button>
<button onClick={handleCreatePricing}>Post for sale</button> <button onClick={handleCreatePricing}>Post for sale</button>
<button onClick={handleBuyDT}>Buy DT</button>
<button onClick={handleSellDT}>Sell DT</button>
</div> </div>
) )
} }

View File

@ -0,0 +1,2 @@
export * from './usePricing'
export * from './PriceOptions'

View File

@ -1,11 +1,16 @@
import { Logger } from '@oceanprotocol/lib' import { Logger } from '@oceanprotocol/lib'
import { useState } from 'react' import { useState } from 'react'
import { useOcean } from 'providers' import { useOcean } from 'providers'
import { PriceOptions } from './PriceOptions'
import { TransactionReceipt } from 'web3-core' import { TransactionReceipt } from 'web3-core'
import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils' import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils'
import { Decimal } from 'decimal.js' import { Decimal } from 'decimal.js'
interface UseTrade { interface UsePricing {
createPricing: (
dataTokenAddress: string,
priceOptions: PriceOptions
) => Promise<TransactionReceipt | string | null>
buyDT: ( buyDT: (
dataTokenAddress: string, dataTokenAddress: string,
dtAmount: number | string dtAmount: number | string
@ -14,12 +19,19 @@ interface UseTrade {
dataTokenAddress: string, dataTokenAddress: string,
dtAmount: number | string dtAmount: number | string
) => Promise<TransactionReceipt | null> ) => Promise<TransactionReceipt | null>
tradeStep?: number mint: (tokenAddress: string, tokensToMint: string) => void
tradeStepText?: string pricingStep?: number
tradeError?: string pricingStepText?: string
tradeIsLoading: boolean pricingError?: string
pricingIsLoading: boolean
} }
export const createPricingFeedback: { [key in number]: string } = {
0: '1/4 Approving DT ...',
1: '2/4 Approving Ocean ...',
2: '3/4 Creating ....',
3: '4/4 Pricing created'
}
export const buyDTFeedback: { [key in number]: string } = { export const buyDTFeedback: { [key in number]: string } = {
0: '1/3 Approving OCEAN ...', 0: '1/3 Approving OCEAN ...',
1: '2/3 Buying DT ...', 1: '2/3 Buying DT ...',
@ -30,34 +42,48 @@ export const sellDTFeedback: { [key in number]: string } = {
1: '2/3 Selling DT ...', 1: '2/3 Selling DT ...',
2: '3/3 DT sold' 2: '3/3 DT sold'
} }
function usePricing(): UsePricing {
function useTrade(): UseTrade {
const { ocean, status, account, accountId, config } = useOcean() const { ocean, status, account, accountId, config } = useOcean()
const [tradeIsLoading, setTradeIsLoading] = useState(false) const [pricingIsLoading, setPricingIsLoading] = useState(false)
const [tradeStep, setTradeStep] = useState<number | undefined>() const [pricingStep, setPricingStep] = useState<number | undefined>()
const [tradeStepText, setTradeStepText] = useState<string | undefined>() const [pricingStepText, setPricingStepText] = useState<string | undefined>()
const [tradeError, setTradeError] = useState<string | undefined>() const [pricingError, setPricingError] = useState<string | undefined>()
const [dtSymbol, setDtSymbol] = useState<string>() const [dtSymbol, setDtSymbol] = useState<string>()
function setStepCreatePricing(index?: number) {
setPricingStep(index)
let message
if (index) {
if (dtSymbol)
message = createPricingFeedback[index].replace(/DT/g, dtSymbol)
else message = createPricingFeedback[index]
setPricingStepText(message)
}
}
function setStepBuyDT(index?: number) { function setStepBuyDT(index?: number) {
setTradeStep(index) setPricingStep(index)
let message let message
if (index) { if (index) {
if (dtSymbol) message = buyDTFeedback[index].replace(/DT/g, dtSymbol) if (dtSymbol) message = buyDTFeedback[index].replace(/DT/g, dtSymbol)
else message = buyDTFeedback[index] else message = buyDTFeedback[index]
setTradeStepText(message) setPricingStepText(message)
} }
} }
function setStepSellDT(index?: number) { function setStepSellDT(index?: number) {
setTradeStep(index) setPricingStep(index)
let message let message
if (index) { if (index) {
if (dtSymbol) message = sellDTFeedback[index].replace(/DT/g, dtSymbol) if (dtSymbol) message = sellDTFeedback[index].replace(/DT/g, dtSymbol)
else message = sellDTFeedback[index] else message = sellDTFeedback[index]
setTradeStepText(message) setPricingStepText(message)
} }
} }
async function mint(tokenAddress: string, tokensToMint: string) {
Logger.log('mint function', tokenAddress, accountId)
await ocean.datatokens.mint(tokenAddress, accountId, tokensToMint)
}
async function buyDT( async function buyDT(
dataTokenAddress: string, dataTokenAddress: string,
dtAmount: number | string dtAmount: number | string
@ -66,8 +92,8 @@ function useTrade(): UseTrade {
try { try {
setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress))
setTradeIsLoading(true) setPricingIsLoading(true)
setTradeError(undefined) setPricingError(undefined)
setStepBuyDT(0) setStepBuyDT(0)
const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress)
switch (bestPrice?.type) { switch (bestPrice?.type) {
@ -120,12 +146,12 @@ function useTrade(): UseTrade {
} }
} }
} catch (error) { } catch (error) {
setTradeError(error.message) setPricingError(error.message)
Logger.error(error) Logger.error(error)
} finally { } finally {
setTradeStep(undefined) setStepBuyDT(undefined)
setTradeStepText(undefined) setPricingStepText(undefined)
setTradeIsLoading(false) setPricingIsLoading(false)
} }
return null return null
} }
@ -141,8 +167,8 @@ function useTrade(): UseTrade {
} }
try { try {
setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress))
setTradeIsLoading(true) setPricingIsLoading(true)
setTradeError(undefined) setPricingError(undefined)
setStepSellDT(0) setStepSellDT(0)
const pool = await getFirstPool(ocean, dataTokenAddress) const pool = await getFirstPool(ocean, dataTokenAddress)
if (!pool || pool.price === 0) return null if (!pool || pool.price === 0) return null
@ -159,25 +185,85 @@ function useTrade(): UseTrade {
Logger.log('DT sell response', sellResponse) Logger.log('DT sell response', sellResponse)
return sellResponse return sellResponse
} catch (error) { } catch (error) {
setTradeError(error.message) setPricingError(error.message)
Logger.error(error) Logger.error(error)
} finally { } finally {
setStepSellDT(undefined) setStepSellDT(undefined)
setTradeStepText(undefined) setPricingStepText(undefined)
setTradeIsLoading(false) setPricingIsLoading(false)
}
return null
}
async function createPricing(
dataTokenAddress: string,
priceOptions: PriceOptions
): Promise<TransactionReceipt | string | null> {
if (!ocean || !account || !accountId) return null
let response = null
try {
setPricingIsLoading(true)
setPricingError(undefined)
setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress))
setStepCreatePricing(0)
switch (priceOptions.type) {
case 'dynamic': {
setStepCreatePricing(2)
response = await ocean.pool.createDTPool(
accountId,
dataTokenAddress,
priceOptions.dtAmount.toString(),
priceOptions.weightOnDataToken,
priceOptions.swapFee
)
setStepCreatePricing(3)
return response
}
case 'fixed': {
if (!config.fixedRateExchangeAddress) {
Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`)
return null
}
setStepCreatePricing(2)
response = await ocean.fixedRateExchange.create(
dataTokenAddress,
priceOptions.price.toString(),
accountId
)
setStepCreatePricing(1)
await ocean.datatokens.approve(
dataTokenAddress,
config.fixedRateExchangeAddress,
String(priceOptions.dtAmount),
accountId
)
setStepCreatePricing(3)
return response
}
}
} catch (error) {
setPricingError(error.message)
Logger.error(error)
} finally {
setPricingStep(undefined)
setPricingStepText(undefined)
setPricingIsLoading(false)
} }
return null return null
} }
return { return {
createPricing,
buyDT, buyDT,
sellDT, sellDT,
tradeStep, mint,
tradeStepText, pricingStep,
tradeIsLoading, pricingStepText,
tradeError pricingIsLoading,
pricingError
} }
} }
export { useTrade, UseTrade } export { usePricing, UsePricing }
export default useTrade export default usePricing

View File

@ -1,5 +1,4 @@
export interface DataTokenOptions { export interface DataTokenOptions {
tokensToMint: number
cap?: string cap?: string
name?: string name?: string
symbol?: string symbol?: string

View File

@ -1,6 +1,6 @@
# `usePublish` # `usePublish`
Create data tokens, Mint and Publish data sets Create datatoken and publish data sets
## Usage ## Usage
@ -25,7 +25,7 @@ export default function MyComponent() {
} }
const dataTokenOptions = { const dataTokenOptions = {
tokensToMint: 10
} }
async function handlePublish() { async function handlePublish() {

View File

@ -18,7 +18,6 @@ interface UsePublish {
timeout?: number, timeout?: number,
providerUri?: string providerUri?: string
) => Promise<DDO | undefined | null> ) => Promise<DDO | undefined | null>
mint: (tokenAddress: string, tokensToMint: string) => void
publishStep?: number publishStep?: number
publishStepText?: string publishStepText?: string
publishError?: string publishError?: string
@ -36,12 +35,6 @@ function usePublish(): UsePublish {
setPublishStep(index) setPublishStep(index)
index && setPublishStepText(publishFeedback[index]) index && setPublishStepText(publishFeedback[index])
} }
async function mint(tokenAddress: string, tokensToMint: string) {
Logger.log('mint function', tokenAddress, accountId)
await ocean.datatokens.mint(tokenAddress, accountId, tokensToMint)
}
/** /**
* Publish an asset.It also creates the datatoken, mints tokens and gives the market allowance * Publish an asset.It also creates the datatoken, mints tokens and gives the market allowance
* @param {Metadata} asset The metadata of the asset. * @param {Metadata} asset The metadata of the asset.
@ -62,8 +55,6 @@ function usePublish(): UsePublish {
setPublishError(undefined) setPublishError(undefined)
try { try {
const tokensToMint = dataTokenOptions.tokensToMint.toString()
const publishedDate = const publishedDate =
new Date(Date.now()).toISOString().split('.')[0] + 'Z' new Date(Date.now()).toISOString().split('.')[0] + 'Z'
let timeout = 0 let timeout = 0
@ -151,9 +142,6 @@ function usePublish(): UsePublish {
.next(setStep) .next(setStep)
Logger.log('ddo created', ddo) Logger.log('ddo created', ddo)
setStep(7) setStep(7)
await mint(ddo.dataToken, tokensToMint)
Logger.log(`minted ${tokensToMint} tokens`)
// await createPricing(priceOptions, ddo.dataToken, tokensToMint) // await createPricing(priceOptions, ddo.dataToken, tokensToMint)
// setStep(8) // setStep(8)
return ddo return ddo
@ -168,7 +156,6 @@ function usePublish(): UsePublish {
return { return {
publish, publish,
mint,
publishStep, publishStep,
publishStepText, publishStepText,
isLoading, isLoading,

View File

@ -1,35 +0,0 @@
# `usePricing`
Hook to buy and sell datatokens
## Usage
```tsx
import React from 'react'
import { useOcean, useTrade } from '@oceanprotocol/react'
import { Metadata } from '@oceanprotocol/lib'
export default function MyComponent() {
const { accountId } = useOcean()
const dataTokenAddress = '0x00000'
// Publish helpers
const { buyDT, sellDT } = useTrade()
async function handleBuyDT() {
await buyDT(dataTokenAddress, '1')
}
async function handleSellDT() {
await sellDT(dataTokenAddress, '1')
}
return (
<div>
<h1>Trade</h1>
<button onClick={handleBuyDT}>Buy DT</button>
<button onClick={handleSellDT}>Sell DT</button>
</div>
)
}
```

View File

@ -1 +0,0 @@
export * from './useTrade'