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 { NetworkMonitor } from './NetworkMonitor'
import { LogLevel } from '@oceanprotocol/lib/dist/node/utils'
import { Trade } from './Trade'
import { Pricing } from './Pricing'
const configRinkeby = new ConfigHelper().getConfig('rinkeby')
const providerOptions = {}
@ -41,7 +41,7 @@ function App() {
<Publish />
</div>
<div>
<Trade />
<Pricing />
</div>
<div>
<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 { usePublish, useCreatePricing } from '@oceanprotocol/react'
// import { useOcean, usePublish } from '@oceanprotocol/react'
import { 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 Publish() {
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 asset = {
@ -32,37 +31,16 @@ export function Publish() {
}
const publishAsset = async () => {
const priceOptions = {
price: 7,
dtAmount: 10,
type: 'fixed',
weightOnDataToken: '',
swapFee: ''
}
const datatokenOptions = {
tokensToMint:10
}
const ddo = await publish(asset as Metadata, 'access', datatokenOptions)
console.log(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 (
<>
<div>Publish</div>
@ -73,13 +51,7 @@ export function Publish() {
IsLoading: {isLoading.toString()} || Status: {publishStepText}
</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 './usePublish'
export * from './useCompute'
export * from './useCreatePricing'
export * from './useTrade'
export * from './usePricing'

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`
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
@ -13,7 +13,7 @@ export default function MyComponent() {
const { accountId } = useOcean()
const dataTokenAddress = '0x00000'
// Publish helpers
const { createPricing } = useCreatePricing()
const { createPricing } = usePricing()
const priceOptions = {
price: 10,
@ -27,13 +27,25 @@ export default function MyComponent() {
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 (
<div>
<h1>Post for sale</h1>
<p>Your account: {accountId}</p>
<button onClick={handleMint}>Mint DT</button>
<button onClick={handleCreatePricing}>Post for sale</button>
<button onClick={handleBuyDT}>Buy DT</button>
<button onClick={handleSellDT}>Sell DT</button>
</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 { 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 UseTrade {
interface UsePricing {
createPricing: (
dataTokenAddress: string,
priceOptions: PriceOptions
) => Promise<TransactionReceipt | string | null>
buyDT: (
dataTokenAddress: string,
dtAmount: number | string
@ -14,12 +19,19 @@ interface UseTrade {
dataTokenAddress: string,
dtAmount: number | string
) => Promise<TransactionReceipt | null>
tradeStep?: number
tradeStepText?: string
tradeError?: string
tradeIsLoading: boolean
mint: (tokenAddress: string, tokensToMint: string) => void
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'
}
export const buyDTFeedback: { [key in number]: string } = {
0: '1/3 Approving OCEAN ...',
1: '2/3 Buying DT ...',
@ -30,34 +42,48 @@ export const sellDTFeedback: { [key in number]: string } = {
1: '2/3 Selling DT ...',
2: '3/3 DT sold'
}
function useTrade(): UseTrade {
function usePricing(): UsePricing {
const { ocean, status, account, accountId, config } = useOcean()
const [tradeIsLoading, setTradeIsLoading] = useState(false)
const [tradeStep, setTradeStep] = useState<number | undefined>()
const [tradeStepText, setTradeStepText] = useState<string | undefined>()
const [tradeError, setTradeError] = useState<string | undefined>()
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)
}
}
function setStepBuyDT(index?: number) {
setTradeStep(index)
setPricingStep(index)
let message
if (index) {
if (dtSymbol) message = buyDTFeedback[index].replace(/DT/g, dtSymbol)
else message = buyDTFeedback[index]
setTradeStepText(message)
setPricingStepText(message)
}
}
function setStepSellDT(index?: number) {
setTradeStep(index)
setPricingStep(index)
let message
if (index) {
if (dtSymbol) message = sellDTFeedback[index].replace(/DT/g, dtSymbol)
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(
dataTokenAddress: string,
dtAmount: number | string
@ -66,8 +92,8 @@ function useTrade(): UseTrade {
try {
setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress))
setTradeIsLoading(true)
setTradeError(undefined)
setPricingIsLoading(true)
setPricingError(undefined)
setStepBuyDT(0)
const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress)
switch (bestPrice?.type) {
@ -120,12 +146,12 @@ function useTrade(): UseTrade {
}
}
} catch (error) {
setTradeError(error.message)
setPricingError(error.message)
Logger.error(error)
} finally {
setTradeStep(undefined)
setTradeStepText(undefined)
setTradeIsLoading(false)
setStepBuyDT(undefined)
setPricingStepText(undefined)
setPricingIsLoading(false)
}
return null
}
@ -141,8 +167,8 @@ function useTrade(): UseTrade {
}
try {
setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress))
setTradeIsLoading(true)
setTradeError(undefined)
setPricingIsLoading(true)
setPricingError(undefined)
setStepSellDT(0)
const pool = await getFirstPool(ocean, dataTokenAddress)
if (!pool || pool.price === 0) return null
@ -159,25 +185,85 @@ function useTrade(): UseTrade {
Logger.log('DT sell response', sellResponse)
return sellResponse
} catch (error) {
setTradeError(error.message)
setPricingError(error.message)
Logger.error(error)
} finally {
setStepSellDT(undefined)
setTradeStepText(undefined)
setTradeIsLoading(false)
setPricingStepText(undefined)
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 {
createPricing,
buyDT,
sellDT,
tradeStep,
tradeStepText,
tradeIsLoading,
tradeError
mint,
pricingStep,
pricingStepText,
pricingIsLoading,
pricingError
}
}
export { useTrade, UseTrade }
export default useTrade
export { usePricing, UsePricing }
export default usePricing

View File

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

View File

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

View File

@ -18,7 +18,6 @@ interface UsePublish {
timeout?: number,
providerUri?: string
) => Promise<DDO | undefined | null>
mint: (tokenAddress: string, tokensToMint: string) => void
publishStep?: number
publishStepText?: string
publishError?: string
@ -36,12 +35,6 @@ function usePublish(): UsePublish {
setPublishStep(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
* @param {Metadata} asset The metadata of the asset.
@ -62,8 +55,6 @@ function usePublish(): UsePublish {
setPublishError(undefined)
try {
const tokensToMint = dataTokenOptions.tokensToMint.toString()
const publishedDate =
new Date(Date.now()).toISOString().split('.')[0] + 'Z'
let timeout = 0
@ -151,9 +142,6 @@ function usePublish(): UsePublish {
.next(setStep)
Logger.log('ddo created', ddo)
setStep(7)
await mint(ddo.dataToken, tokensToMint)
Logger.log(`minted ${tokensToMint} tokens`)
// await createPricing(priceOptions, ddo.dataToken, tokensToMint)
// setStep(8)
return ddo
@ -168,7 +156,6 @@ function usePublish(): UsePublish {
return {
publish,
mint,
publishStep,
publishStepText,
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'