From 9d9360230c3205bf832a4b125f70f1d0a0a30bd2 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 01:11:49 -0700 Subject: [PATCH 01/31] split flows for Publish and Buy --- src/hooks/useBuy/README.md | 38 ++++++ src/hooks/useBuy/index.ts | 1 + src/hooks/useBuy/useBuy.ts | 110 ++++++++++++++++++ src/hooks/useCompute/useCompute.ts | 86 +++++++------- src/hooks/useConsume/useConsume.ts | 56 ++++----- .../usePublish/PriceOptions.ts | 2 +- src/hooks/usePostForSale/usePublish/README.md | 39 +++++++ src/hooks/usePostForSale/usePublish/index.ts | 2 + .../usePublish/usePostforSale.ts | 84 +++++++++++++ src/hooks/usePublish/DataTokenOptions.ts | 1 + src/hooks/usePublish/README.md | 12 +- src/hooks/usePublish/index.ts | 1 - src/hooks/usePublish/usePublish.ts | 53 +-------- src/utils/dtUtils.ts | 88 +++++--------- src/utils/index.ts | 11 +- 15 files changed, 385 insertions(+), 199 deletions(-) create mode 100644 src/hooks/useBuy/README.md create mode 100644 src/hooks/useBuy/index.ts create mode 100644 src/hooks/useBuy/useBuy.ts rename src/hooks/{ => usePostForSale}/usePublish/PriceOptions.ts (85%) create mode 100644 src/hooks/usePostForSale/usePublish/README.md create mode 100644 src/hooks/usePostForSale/usePublish/index.ts create mode 100644 src/hooks/usePostForSale/usePublish/usePostforSale.ts diff --git a/src/hooks/useBuy/README.md b/src/hooks/useBuy/README.md new file mode 100644 index 0000000..8680615 --- /dev/null +++ b/src/hooks/useBuy/README.md @@ -0,0 +1,38 @@ +# `useBuy` + +Buy datatoken. + +## Usage + +```tsx +import React from 'react' +import { useOcean, useConsume } from '@oceanprotocol/react' + +const did = 'did:op:0x000000000' + +export default function MyComponent() { + const { accountId } = useOcean() + + // Get metadata for this asset + const { title, price, ddo } = useMetadata(did) + + // Consume helpers + const { consume, consumeStep } = useConsume() + + async function handleDownload() { + await consume(did, ddo.dataToken, 'access') + } + + return ( +
+

{title}

+

Price: {price}

+ +

Your account: {accountId}

+ +
+ ) +} +``` diff --git a/src/hooks/useBuy/index.ts b/src/hooks/useBuy/index.ts new file mode 100644 index 0000000..0518fcf --- /dev/null +++ b/src/hooks/useBuy/index.ts @@ -0,0 +1 @@ +export * from './useBuy' diff --git a/src/hooks/useBuy/useBuy.ts b/src/hooks/useBuy/useBuy.ts new file mode 100644 index 0000000..1c3592a --- /dev/null +++ b/src/hooks/useBuy/useBuy.ts @@ -0,0 +1,110 @@ +import { useState } from 'react' +import { useOcean } from 'providers' +import { feedback } from 'utils' +import { DID, Logger, ServiceType } from '@oceanprotocol/lib' +import { getBestDataTokenPrice } from 'utils/dtUtils' +import { TransactionReceipt } from 'web3-core' +import { Decimal } from 'decimal.js' + +interface UseBuy { + buyDT: ( + dataTokenAddress: string, + dtAmount: number | string, + ) => Promise + consumeStep?: number + consumeStepText?: string + consumeError?: string + isLoading: boolean +} + +export const buyFeedback: { [key in number]: string } = { + 0: '1/2 Approving OCEAN Tokens', + 1: '2/3 Buying Datatoken', + 2: '3/3 Bought Datatoken' +} + +function useBuy(): UseBuy { + const { ocean, account, accountId, config } = useOcean() + const [isLoading, setIsLoading] = useState(false) + const [consumeStep, setConsumeStep] = useState() + const [consumeStepText, setConsumeStepText] = useState() + const [consumeError, setConsumeError] = useState() + + function setStep(index: number) { + setConsumeStep(index) + setConsumeStepText(buyFeedback[index]) + } + + async function buyDT( + dataTokenAddress: string, + dtAmount: number | string, + ): Promise { + if (!ocean || !account || !accountId) return + + setIsLoading(true) + setConsumeError(undefined) + setStep(0) + + try { + const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) + 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, + String(dtAmount), + price, + maxPrice + ) + setStep(2) + Logger.log('DT buy response', buyResponse) + return buyResponse + } + case 'exchange': { + if (!config.oceanTokenAddress) { + Logger.error(`'oceanTokenAddress' not set in config`) + return + } + if (!config.fixedRateExchangeAddress) { + Logger.error(`'fixedRateExchangeAddress' not set in config`) + return + } + Logger.log('Buying token from exchange', bestPrice, account.getId()) + await ocean.datatokens.approve( + config.oceanTokenAddress, + config.fixedRateExchangeAddress, + bestPrice.value.toString(), + account.getId() + ) + setStep(1) + const exchange = await ocean.fixedRateExchange.buyDT( + bestPrice.address, + String(dtAmount), + account.getId() + ) + setStep(2) + Logger.log('DT exchange buy response', exchange) + return exchange + } + } + } catch (error) { + setConsumeError(error.message) + Logger.error(error) + } finally { + setConsumeStep(undefined) + setConsumeStepText(undefined) + setIsLoading(false) + } + } + + return { buyDT, consumeStep, consumeStepText, consumeError, isLoading } +} + +export { useBuy, UseBuy } +export default useBuy + + + diff --git a/src/hooks/useCompute/useCompute.ts b/src/hooks/useCompute/useCompute.ts index 2cb10d3..36f4fa1 100644 --- a/src/hooks/useCompute/useCompute.ts +++ b/src/hooks/useCompute/useCompute.ts @@ -4,7 +4,6 @@ import { ComputeValue } from './ComputeOptions' import { Logger, ServiceCompute } from '@oceanprotocol/lib' import { MetadataAlgorithm } from '@oceanprotocol/lib/dist/node/ddo/interfaces/MetadataAlgorithm' import { ComputeJob } from '@oceanprotocol/lib/dist/node/ocean/interfaces/ComputeJob' -import { checkAndBuyDT } from 'utils/dtUtils' interface UseCompute { compute: ( @@ -13,7 +12,7 @@ interface UseCompute { dataTokenAddress: string, algorithmRawCode: string, computeContainer: ComputeValue, - marketFeeAddress: string + marketFeeAddress?: string ) => Promise computeStep?: number computeStepText?: string @@ -62,7 +61,7 @@ function useCompute(): UseCompute { dataTokenAddress: string, algorithmRawCode: string, computeContainer: ComputeValue, - marketFeeAddress: string + marketFeeAddress?: string ): Promise { if (!ocean || !account) return @@ -72,50 +71,47 @@ function useCompute(): UseCompute { setIsLoading(true) setStep(0) - await checkAndBuyDT(ocean, dataTokenAddress, account, config) - rawAlgorithmMeta.container = computeContainer - rawAlgorithmMeta.rawcode = algorithmRawCode - - const output = {} - Logger.log( - 'compute order', - accountId, - did, - computeService, - rawAlgorithmMeta, - marketFeeAddress - ) - const tokenTransfer = await ocean.compute.order( - accountId, - did, - computeService.index, - undefined, - rawAlgorithmMeta, - marketFeeAddress - ) - - setStep(1) - // const computeOrder = JSON.parse(order) - // Logger.log('compute order', computeOrder) - // const tokenTransfer = await ocean.datatokens.transferWei( - // computeOrder.dataToken, - // computeOrder.to, - // String(computeOrder.numTokens), - // computeOrder.from - // ) - setStep(2) - const response = await ocean.compute.start( - did, - tokenTransfer, + const userOwnedTokens = await ocean.accounts.getTokenBalance( dataTokenAddress, - account, - undefined, - rawAlgorithmMeta, - output, - `${computeService.index}`, - computeService.type + account ) - return response + if (parseFloat(userOwnedTokens) < 1) { + setComputeError('Not enough datatokens') + } else { + rawAlgorithmMeta.container = computeContainer + rawAlgorithmMeta.rawcode = algorithmRawCode + const output = {} + Logger.log( + 'compute order', + accountId, + did, + computeService, + rawAlgorithmMeta, + marketFeeAddress + ) + const tokenTransfer = await ocean.compute.order( + accountId, + did, + computeService.index, + undefined, + rawAlgorithmMeta, + marketFeeAddress + ) + setStep(1) + setStep(2) + const response = await ocean.compute.start( + did, + tokenTransfer, + dataTokenAddress, + account, + undefined, + rawAlgorithmMeta, + output, + `${computeService.index}`, + computeService.type + ) + return response + } } catch (error) { Logger.error(error) setComputeError(error.message) diff --git a/src/hooks/useConsume/useConsume.ts b/src/hooks/useConsume/useConsume.ts index 1450924..6ec61d4 100644 --- a/src/hooks/useConsume/useConsume.ts +++ b/src/hooks/useConsume/useConsume.ts @@ -2,7 +2,6 @@ import { useState } from 'react' import { useOcean } from 'providers' import { feedback } from 'utils' import { DID, Logger, ServiceType } from '@oceanprotocol/lib' -import { checkAndBuyDT } from 'utils/dtUtils' interface UseConsume { consume: ( @@ -49,38 +48,33 @@ function useConsume(): UseConsume { try { setStep(0) - await checkAndBuyDT(ocean, dataTokenAddress, account, config) - - setStep(1) - const tokenTransfer = await ocean.assets.order( - did as string, - serviceType, - accountId, - undefined, - marketFeeAddress - ) - Logger.log('order created', tokenTransfer) - setStep(2) - // const res = JSON.parse(order) - // Logger.log('order parsed', res) - // Logger.log('ocean.datatokens before transfer', ocean.datatokens) - // const tokenTransfer = await ocean.datatokens.transferWei( - // res.dataToken, - // res.to, - // String(res.numTokens), - // res.from - // ) - // Logger.log('token transfered', tokenTransfer) - setStep(3) - await ocean.assets.download( - did as string, - tokenTransfer, + const userOwnedTokens = await ocean.accounts.getTokenBalance( dataTokenAddress, - account, - '' + account ) - - setStep(4) + if (parseFloat(userOwnedTokens) < 1) { + setConsumeError('Not enough datatokens') + } else { + setStep(1) + const tokenTransfer = await ocean.assets.order( + did as string, + serviceType, + accountId, + undefined, + marketFeeAddress + ) + Logger.log('order created', tokenTransfer) + setStep(2) + setStep(3) + await ocean.assets.download( + did as string, + tokenTransfer, + dataTokenAddress, + account, + '' + ) + setStep(4) + } } catch (error) { setConsumeError(error.message) Logger.error(error) diff --git a/src/hooks/usePublish/PriceOptions.ts b/src/hooks/usePostForSale/usePublish/PriceOptions.ts similarity index 85% rename from src/hooks/usePublish/PriceOptions.ts rename to src/hooks/usePostForSale/usePublish/PriceOptions.ts index c0b6eb8..a30b665 100644 --- a/src/hooks/usePublish/PriceOptions.ts +++ b/src/hooks/usePostForSale/usePublish/PriceOptions.ts @@ -1,6 +1,6 @@ export interface PriceOptions { price: number - tokensToMint: number + dtAmount: number type: 'fixed' | 'dynamic' | string weightOnDataToken: string swapFee: string diff --git a/src/hooks/usePostForSale/usePublish/README.md b/src/hooks/usePostForSale/usePublish/README.md new file mode 100644 index 0000000..cb27151 --- /dev/null +++ b/src/hooks/usePostForSale/usePublish/README.md @@ -0,0 +1,39 @@ +# `usePublish` + +Post asset for sale by creating liquidity pools or fixed rate exchange + +## Usage + +```tsx +import React from 'react' +import { useOcean, usePostforSale } from '@oceanprotocol/react' +import { Metadata } from '@oceanprotocol/lib' + +export default function MyComponent() { + const { accountId } = useOcean() + + // Publish helpers + const { publish, publishStep } = usePostforSale() + + const priceOptions = { + price: 10, + dtAmount: 10, + type: 'fixed', + weightOnDataToken: '', + swapFee: '' + } + + async function handlePostforSale() { + const ddo = await createPricing(dataTokenAddress, priceOptions) + } + + return ( +
+

Post for sale

+ +

Your account: {accountId}

+ +
+ ) +} +``` diff --git a/src/hooks/usePostForSale/usePublish/index.ts b/src/hooks/usePostForSale/usePublish/index.ts new file mode 100644 index 0000000..d3e69d5 --- /dev/null +++ b/src/hooks/usePostForSale/usePublish/index.ts @@ -0,0 +1,2 @@ +export * from './usePostforSale' +export * from './PriceOptions' diff --git a/src/hooks/usePostForSale/usePublish/usePostforSale.ts b/src/hooks/usePostForSale/usePublish/usePostforSale.ts new file mode 100644 index 0000000..3c85737 --- /dev/null +++ b/src/hooks/usePostForSale/usePublish/usePostforSale.ts @@ -0,0 +1,84 @@ +import { DID, DDO, Logger, Metadata } from '@oceanprotocol/lib' +import { + Service, + ServiceComputePrivacy, + ServiceType +} from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service' +import { useState } from 'react' +import { useOcean } from 'providers' +import ProviderStatus from 'providers/OceanProvider/ProviderStatus' +import { publishFeedback } from 'utils' +import { PriceOptions } from './PriceOptions' + +interface UsePostforSale { + createPricing: ( + dataTokenAddress: string, + priceOptions: PriceOptions, + ) => Promise + publishStep?: number + publishStepText?: string + publishError?: string + isLoading: boolean +} + +function usePostforSale(): UsePostforSale { + const { ocean, status, account, accountId, config } = useOcean() + const [isLoading, setIsLoading] = useState(false) + const [publishStep, setPublishStep] = useState() + const [publishStepText, setPublishStepText] = useState() + const [publishError, setPublishError] = useState() + + function setStep(index?: number) { + setPublishStep(index) + index && setPublishStepText(publishFeedback[index]) + } + + async function createPricing( + dataTokenAddress: string, + priceOptions: PriceOptions + ): Promise { + switch (priceOptions.type) { + case 'dynamic': { + await ocean.pool.createDTPool( + accountId, + dataTokenAddress, + priceOptions.dtAmount.toString(), + priceOptions.weightOnDataToken, + priceOptions.swapFee + ) + break + } + case 'fixed': { + if (!config.fixedRateExchangeAddress) { + Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`) + return null + } + + await ocean.fixedRateExchange.create( + dataTokenAddress, + priceOptions.price.toString(), + accountId + ) + await ocean.datatokens.approve( + dataTokenAddress, + config.fixedRateExchangeAddress, + priceOptions.dtAmount, + accountId + ) + break + } + } + } + + + return { + createPricing, + publishStep, + publishStepText, + isLoading, + publishError + } +} + +export { usePostforSale, UsePostforSale } +export default usePostforSale diff --git a/src/hooks/usePublish/DataTokenOptions.ts b/src/hooks/usePublish/DataTokenOptions.ts index 9bb28fb..2579a9c 100644 --- a/src/hooks/usePublish/DataTokenOptions.ts +++ b/src/hooks/usePublish/DataTokenOptions.ts @@ -1,4 +1,5 @@ export interface DataTokenOptions { + tokensToMint: number cap?: string name?: string symbol?: string diff --git a/src/hooks/usePublish/README.md b/src/hooks/usePublish/README.md index 654c2ca..c1e789f 100644 --- a/src/hooks/usePublish/README.md +++ b/src/hooks/usePublish/README.md @@ -1,6 +1,6 @@ # `usePublish` -Publish data sets, and create data tokens and liquidity pools for them. +Create data tokens, Mint and Publish data sets ## Usage @@ -24,16 +24,12 @@ export default function MyComponent() { } } - const priceOptions = { - price: 10, - tokensToMint: 10, - type: 'fixed', - weightOnDataToken: '', - swapFee: '' + const dataTokenOptions = { + tokensToMint: 10 } async function handlePublish() { - const ddo = await publish(metadata, priceOptions, 'access') + const ddo = await publish(metadata, 'access', dataTokenOptions) } return ( diff --git a/src/hooks/usePublish/index.ts b/src/hooks/usePublish/index.ts index 582f913..968ef5e 100644 --- a/src/hooks/usePublish/index.ts +++ b/src/hooks/usePublish/index.ts @@ -1,3 +1,2 @@ export * from './usePublish' -export * from './PriceOptions' export * from './DataTokenOptions' diff --git a/src/hooks/usePublish/usePublish.ts b/src/hooks/usePublish/usePublish.ts index e89b090..21ce9c6 100644 --- a/src/hooks/usePublish/usePublish.ts +++ b/src/hooks/usePublish/usePublish.ts @@ -5,18 +5,16 @@ import { ServiceType } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service' import { useState } from 'react' -import { DataTokenOptions } from '.' +import { DataTokenOptions } from './DataTokenOptions' import { useOcean } from 'providers' import ProviderStatus from 'providers/OceanProvider/ProviderStatus' import { publishFeedback } from 'utils' -import { PriceOptions } from './PriceOptions' interface UsePublish { publish: ( asset: Metadata, - priceOptions: PriceOptions, serviceConfigs: ServiceType, - dataTokenOptions?: DataTokenOptions, + dataTokenOptions: DataTokenOptions, providerUri?: string ) => Promise mint: (tokenAddress: string, tokensToMint: string) => void @@ -43,44 +41,6 @@ function usePublish(): UsePublish { await ocean.datatokens.mint(tokenAddress, accountId, tokensToMint) } - async function createPricing( - priceOptions: PriceOptions, - dataTokenAddress: string, - mintedTokens: string - ): Promise { - switch (priceOptions.type) { - case 'dynamic': { - await ocean.pool.createDTPool( - accountId, - dataTokenAddress, - priceOptions.tokensToMint.toString(), - priceOptions.weightOnDataToken, - priceOptions.swapFee - ) - break - } - case 'fixed': { - if (!config.fixedRateExchangeAddress) { - Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`) - return null - } - - await ocean.fixedRateExchange.create( - dataTokenAddress, - priceOptions.price.toString(), - accountId - ) - await ocean.datatokens.approve( - dataTokenAddress, - config.fixedRateExchangeAddress, - mintedTokens, - accountId - ) - break - } - } - } - /** * Publish an asset.It also creates the datatoken, mints tokens and gives the market allowance * @param {Metadata} asset The metadata of the asset. @@ -91,9 +51,8 @@ function usePublish(): UsePublish { */ async function publish( asset: Metadata, - priceOptions: PriceOptions, serviceType: ServiceType, - dataTokenOptions?: DataTokenOptions, + dataTokenOptions: DataTokenOptions, providerUri?: string ): Promise { if (status !== ProviderStatus.CONNECTED || !ocean || !account) return null @@ -102,7 +61,7 @@ function usePublish(): UsePublish { setPublishError(undefined) try { - const tokensToMint = priceOptions.tokensToMint.toString() + const tokensToMint = dataTokenOptions.tokensToMint.toString() const publishedDate = new Date(Date.now()).toISOString().split('.')[0] + 'Z' @@ -189,8 +148,8 @@ function usePublish(): UsePublish { await mint(ddo.dataToken, tokensToMint) Logger.log(`minted ${tokensToMint} tokens`) - await createPricing(priceOptions, ddo.dataToken, tokensToMint) - setStep(8) + // await createPricing(priceOptions, ddo.dataToken, tokensToMint) + // setStep(8) return ddo } catch (error) { setPublishError(error.message) diff --git a/src/utils/dtUtils.ts b/src/utils/dtUtils.ts index c875f9b..cbb8621 100644 --- a/src/utils/dtUtils.ts +++ b/src/utils/dtUtils.ts @@ -44,6 +44,33 @@ export async function getCheapestPool( } } +export async function getFirstPool( + ocean: Ocean, + dataTokenAddress: string +): Promise { + if (!ocean || !dataTokenAddress) return null + + const tokenPools = await ocean.pool.searchPoolforDT(dataTokenAddress) + + if (tokenPools === undefined || tokenPools.length === 0) { + return { + address: '', + price: 0 + } + } + const firstPoolAddress = tokenPools[0] + const firstPoolPrice = await ocean.pool.getOceanNeeded(firstPoolAddress, '1') + const oceanReserve = await ocean.pool.getOceanReserve(firstPoolAddress) + const dtReserve = await ocean.pool.getDTReserve(firstPoolAddress) + + return { + address: firstPoolAddress, + price: Number(firstPoolPrice), + ocean: Number(oceanReserve), + datatoken: Number(dtReserve) + } +} + export async function getCheapestExchange( ocean: Ocean, dataTokenAddress: string @@ -90,7 +117,7 @@ export async function getBestDataTokenPrice( ocean: Ocean, dataTokenAddress: string ): Promise { - const cheapestPool = await getCheapestPool(ocean, dataTokenAddress) + const cheapestPool = await getFirstPool(ocean, dataTokenAddress) const cheapestExchange = await getCheapestExchange(ocean, dataTokenAddress) Decimal.set({ precision: 5 }) @@ -119,62 +146,3 @@ export async function getBestDataTokenPrice( } as BestPrice } } - -export async function checkAndBuyDT( - ocean: Ocean, - dataTokenAddress: string, - account: Account, - config: Config -): Promise { - const userOwnedTokens = await ocean.accounts.getTokenBalance( - dataTokenAddress, - account - ) - Logger.log(`User has ${userOwnedTokens} tokens`) - if (userOwnedTokens === '0') { - const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) - - 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': { - if (!config.oceanTokenAddress) { - Logger.error(`'oceanTokenAddress' not set in config`) - return - } - - if (!config.fixedRateExchangeAddress) { - Logger.error(`'fixedRateExchangeAddress' not set in config`) - return - } - - Logger.log('Buying token from exchange', bestPrice, account.getId()) - await ocean.datatokens.approve( - config.oceanTokenAddress, - config.fixedRateExchangeAddress, - bestPrice.value.toString(), - account.getId() - ) - const exchange = await ocean.fixedRateExchange.buyDT( - bestPrice.address, - '1', - account.getId() - ) - Logger.log('DT exchange buy response', exchange) - return exchange - } - } - } -} diff --git a/src/utils/index.ts b/src/utils/index.ts index ccc4435..d3114b6 100644 --- a/src/utils/index.ts +++ b/src/utils/index.ts @@ -31,12 +31,11 @@ export const feedback: { [key in number]: string } = { } export const publishFeedback: { [key in number]: string } = { - 0: '1/6 Creating datatoken ...', - 2: '2/6 Encrypting files ...', - 4: '3/6 Generating proof ...', - 6: '4/6 Storing ddo ...', - 7: '5/6 Minting tokens ...', - 8: '6/6 Asset published succesfully' + 0: '1/5 Creating datatoken ...', + 2: '2/5 Encrypting files ...', + 4: '3/5 Storing ddo ...', + 6: '4/5 Minting tokens ...', + 8: '5/5 Asset published succesfully' } export * from './web3' From ad270f8a394748481c9a9d71e15db7be325bc210 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 04:55:18 -0700 Subject: [PATCH 02/31] refactor --- src/hooks/useBuy/README.md | 38 --- src/hooks/useBuy/index.ts | 1 - src/hooks/useBuy/useBuy.ts | 110 -------- src/hooks/usePostForSale/usePublish/index.ts | 2 - .../usePublish/usePostforSale.ts | 84 ------- .../usePublish => usePricing}/PriceOptions.ts | 0 .../usePublish => usePricing}/README.md | 19 +- src/hooks/usePricing/index.ts | 2 + src/hooks/usePricing/usePricing.ts | 238 ++++++++++++++++++ 9 files changed, 255 insertions(+), 239 deletions(-) delete mode 100644 src/hooks/useBuy/README.md delete mode 100644 src/hooks/useBuy/index.ts delete mode 100644 src/hooks/useBuy/useBuy.ts delete mode 100644 src/hooks/usePostForSale/usePublish/index.ts delete mode 100644 src/hooks/usePostForSale/usePublish/usePostforSale.ts rename src/hooks/{usePostForSale/usePublish => usePricing}/PriceOptions.ts (100%) rename src/hooks/{usePostForSale/usePublish => usePricing}/README.md (57%) create mode 100644 src/hooks/usePricing/index.ts create mode 100644 src/hooks/usePricing/usePricing.ts diff --git a/src/hooks/useBuy/README.md b/src/hooks/useBuy/README.md deleted file mode 100644 index 8680615..0000000 --- a/src/hooks/useBuy/README.md +++ /dev/null @@ -1,38 +0,0 @@ -# `useBuy` - -Buy datatoken. - -## Usage - -```tsx -import React from 'react' -import { useOcean, useConsume } from '@oceanprotocol/react' - -const did = 'did:op:0x000000000' - -export default function MyComponent() { - const { accountId } = useOcean() - - // Get metadata for this asset - const { title, price, ddo } = useMetadata(did) - - // Consume helpers - const { consume, consumeStep } = useConsume() - - async function handleDownload() { - await consume(did, ddo.dataToken, 'access') - } - - return ( -
-

{title}

-

Price: {price}

- -

Your account: {accountId}

- -
- ) -} -``` diff --git a/src/hooks/useBuy/index.ts b/src/hooks/useBuy/index.ts deleted file mode 100644 index 0518fcf..0000000 --- a/src/hooks/useBuy/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useBuy' diff --git a/src/hooks/useBuy/useBuy.ts b/src/hooks/useBuy/useBuy.ts deleted file mode 100644 index 1c3592a..0000000 --- a/src/hooks/useBuy/useBuy.ts +++ /dev/null @@ -1,110 +0,0 @@ -import { useState } from 'react' -import { useOcean } from 'providers' -import { feedback } from 'utils' -import { DID, Logger, ServiceType } from '@oceanprotocol/lib' -import { getBestDataTokenPrice } from 'utils/dtUtils' -import { TransactionReceipt } from 'web3-core' -import { Decimal } from 'decimal.js' - -interface UseBuy { - buyDT: ( - dataTokenAddress: string, - dtAmount: number | string, - ) => Promise - consumeStep?: number - consumeStepText?: string - consumeError?: string - isLoading: boolean -} - -export const buyFeedback: { [key in number]: string } = { - 0: '1/2 Approving OCEAN Tokens', - 1: '2/3 Buying Datatoken', - 2: '3/3 Bought Datatoken' -} - -function useBuy(): UseBuy { - const { ocean, account, accountId, config } = useOcean() - const [isLoading, setIsLoading] = useState(false) - const [consumeStep, setConsumeStep] = useState() - const [consumeStepText, setConsumeStepText] = useState() - const [consumeError, setConsumeError] = useState() - - function setStep(index: number) { - setConsumeStep(index) - setConsumeStepText(buyFeedback[index]) - } - - async function buyDT( - dataTokenAddress: string, - dtAmount: number | string, - ): Promise { - if (!ocean || !account || !accountId) return - - setIsLoading(true) - setConsumeError(undefined) - setStep(0) - - try { - const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) - 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, - String(dtAmount), - price, - maxPrice - ) - setStep(2) - Logger.log('DT buy response', buyResponse) - return buyResponse - } - case 'exchange': { - if (!config.oceanTokenAddress) { - Logger.error(`'oceanTokenAddress' not set in config`) - return - } - if (!config.fixedRateExchangeAddress) { - Logger.error(`'fixedRateExchangeAddress' not set in config`) - return - } - Logger.log('Buying token from exchange', bestPrice, account.getId()) - await ocean.datatokens.approve( - config.oceanTokenAddress, - config.fixedRateExchangeAddress, - bestPrice.value.toString(), - account.getId() - ) - setStep(1) - const exchange = await ocean.fixedRateExchange.buyDT( - bestPrice.address, - String(dtAmount), - account.getId() - ) - setStep(2) - Logger.log('DT exchange buy response', exchange) - return exchange - } - } - } catch (error) { - setConsumeError(error.message) - Logger.error(error) - } finally { - setConsumeStep(undefined) - setConsumeStepText(undefined) - setIsLoading(false) - } - } - - return { buyDT, consumeStep, consumeStepText, consumeError, isLoading } -} - -export { useBuy, UseBuy } -export default useBuy - - - diff --git a/src/hooks/usePostForSale/usePublish/index.ts b/src/hooks/usePostForSale/usePublish/index.ts deleted file mode 100644 index d3e69d5..0000000 --- a/src/hooks/usePostForSale/usePublish/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './usePostforSale' -export * from './PriceOptions' diff --git a/src/hooks/usePostForSale/usePublish/usePostforSale.ts b/src/hooks/usePostForSale/usePublish/usePostforSale.ts deleted file mode 100644 index 3c85737..0000000 --- a/src/hooks/usePostForSale/usePublish/usePostforSale.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { DID, DDO, Logger, Metadata } from '@oceanprotocol/lib' -import { - Service, - ServiceComputePrivacy, - ServiceType -} from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service' -import { useState } from 'react' -import { useOcean } from 'providers' -import ProviderStatus from 'providers/OceanProvider/ProviderStatus' -import { publishFeedback } from 'utils' -import { PriceOptions } from './PriceOptions' - -interface UsePostforSale { - createPricing: ( - dataTokenAddress: string, - priceOptions: PriceOptions, - ) => Promise - publishStep?: number - publishStepText?: string - publishError?: string - isLoading: boolean -} - -function usePostforSale(): UsePostforSale { - const { ocean, status, account, accountId, config } = useOcean() - const [isLoading, setIsLoading] = useState(false) - const [publishStep, setPublishStep] = useState() - const [publishStepText, setPublishStepText] = useState() - const [publishError, setPublishError] = useState() - - function setStep(index?: number) { - setPublishStep(index) - index && setPublishStepText(publishFeedback[index]) - } - - async function createPricing( - dataTokenAddress: string, - priceOptions: PriceOptions - ): Promise { - switch (priceOptions.type) { - case 'dynamic': { - await ocean.pool.createDTPool( - accountId, - dataTokenAddress, - priceOptions.dtAmount.toString(), - priceOptions.weightOnDataToken, - priceOptions.swapFee - ) - break - } - case 'fixed': { - if (!config.fixedRateExchangeAddress) { - Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`) - return null - } - - await ocean.fixedRateExchange.create( - dataTokenAddress, - priceOptions.price.toString(), - accountId - ) - await ocean.datatokens.approve( - dataTokenAddress, - config.fixedRateExchangeAddress, - priceOptions.dtAmount, - accountId - ) - break - } - } - } - - - return { - createPricing, - publishStep, - publishStepText, - isLoading, - publishError - } -} - -export { usePostforSale, UsePostforSale } -export default usePostforSale diff --git a/src/hooks/usePostForSale/usePublish/PriceOptions.ts b/src/hooks/usePricing/PriceOptions.ts similarity index 100% rename from src/hooks/usePostForSale/usePublish/PriceOptions.ts rename to src/hooks/usePricing/PriceOptions.ts diff --git a/src/hooks/usePostForSale/usePublish/README.md b/src/hooks/usePricing/README.md similarity index 57% rename from src/hooks/usePostForSale/usePublish/README.md rename to src/hooks/usePricing/README.md index cb27151..dea0700 100644 --- a/src/hooks/usePostForSale/usePublish/README.md +++ b/src/hooks/usePricing/README.md @@ -1,6 +1,8 @@ -# `usePublish` +# `usePricing` Post asset for sale by creating liquidity pools or fixed rate exchange +Buy DT +Sell DT ## Usage @@ -13,7 +15,7 @@ export default function MyComponent() { const { accountId } = useOcean() // Publish helpers - const { publish, publishStep } = usePostforSale() + const { createPricing, buyDT, sellDT } = usePricing() const priceOptions = { price: 10, @@ -23,16 +25,25 @@ export default function MyComponent() { swapFee: '' } - async function handlePostforSale() { + async function handleCreatePricing() { const ddo = await createPricing(dataTokenAddress, priceOptions) } + async function handleBuyDT() { + const ddo = await buyDT(dataTokenAddress, 1) + } + async function handleSellDT() { + const ddo = await sellDT(dataTokenAddress, 1) + } + return (

Post for sale

Your account: {accountId}

- + + +
) } diff --git a/src/hooks/usePricing/index.ts b/src/hooks/usePricing/index.ts new file mode 100644 index 0000000..3b43af5 --- /dev/null +++ b/src/hooks/usePricing/index.ts @@ -0,0 +1,2 @@ +export * from './usePricing' +export * from './PriceOptions' diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts new file mode 100644 index 0000000..ea438a3 --- /dev/null +++ b/src/hooks/usePricing/usePricing.ts @@ -0,0 +1,238 @@ +import { DID, DDO, Logger, Metadata } from '@oceanprotocol/lib' +import { + Service, + ServiceComputePrivacy, + ServiceType +} from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service' +import { useState } from 'react' +import { useOcean } from 'providers' +import ProviderStatus from 'providers/OceanProvider/ProviderStatus' +import { publishFeedback } from 'utils' +import { PriceOptions } from './PriceOptions' +import { TransactionReceipt } from 'web3-core' +import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils' +import { Decimal } from 'decimal.js' + +interface UsePricing { + createPricing: ( + dataTokenAddress: string, + priceOptions: PriceOptions, + ) => Promise + buyDT: ( + dataTokenAddress: string, + dtAmount: number | string, + ) => Promise + sellDT: ( + dataTokenAddress: string, + dtAmount: number | string, + ) => Promise + pricingStep?: number + pricingStepText?: string + pricingError?: string + isLoading: boolean +} + +export const buyDTFeedback: { [key in number]: string } = { + 0: '1/3 Approving OCEAN ...', + 1: '2/3 Buying DT ...', + 2: '3/3 DT Bought' +} +export const sellDTFeedback: { [key in number]: string } = { + 0: '1/3 Approving DT ...', + 1: '2/3 Selling DT ...', + 2: '3/3 DT sold' +} + +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 usePricing(): UsePricing { + const { ocean, status, account, accountId, config } = useOcean() + const [isLoading, setIsLoading] = useState(false) + const [pricingStep, setPricingStep] = useState() + const [pricingStepText, setPricingStepText] = useState() + const [pricingError, setPricingError] = useState() + + function setStepBuyDT(index?: number) { + setPricingStep(index) + index && setPricingStepText(buyDTFeedback[index]) + } + function setStepSellDT(index?: number) { + setPricingStep(index) + index && setPricingStepText(sellDTFeedback[index]) + } + function setStepCreatePricing(index?: number) { + setPricingStep(index) + index && setPricingStepText(createPricingFeedback[index]) + } + + async function createPricing( + dataTokenAddress: string, + priceOptions: PriceOptions + ): Promise { + setStepCreatePricing(0) + let response = null + try{ + 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, + priceOptions.dtAmount, + accountId + ) + setStepCreatePricing(3) + return response + } + } + } + catch (error) { + setPricingError(error.message) + Logger.error(error) + } finally { + setPricingStep(undefined) + setPricingStepText(undefined) + setIsLoading(false) + } +} + + async function buyDT( + dataTokenAddress: string, + dtAmount: number | string, + ): Promise { + if (!ocean || !account || !accountId) return + + setIsLoading(true) + setPricingError(undefined) + setStepBuyDT(0) + + try { + const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) + switch (bestPrice?.type) { + case 'pool': { + const price = new Decimal(bestPrice.value).times(1.05).toString() + const maxPrice = new Decimal(bestPrice.value).times(2).toString() + setStepBuyDT(1) + Logger.log('Buying token from pool', bestPrice, account.getId(), price) + const buyResponse = await ocean.pool.buyDT( + account.getId(), + bestPrice.address, + String(dtAmount), + price, + maxPrice + ) + setStepBuyDT(2) + Logger.log('DT buy response', buyResponse) + return buyResponse + } + case 'exchange': { + if (!config.oceanTokenAddress) { + Logger.error(`'oceanTokenAddress' not set in config`) + return + } + if (!config.fixedRateExchangeAddress) { + Logger.error(`'fixedRateExchangeAddress' not set in config`) + return + } + Logger.log('Buying token from exchange', bestPrice, account.getId()) + await ocean.datatokens.approve( + config.oceanTokenAddress, + config.fixedRateExchangeAddress, + bestPrice.value.toString(), + account.getId() + ) + setStepBuyDT(1) + const exchange = await ocean.fixedRateExchange.buyDT( + bestPrice.address, + String(dtAmount), + account.getId() + ) + setStepBuyDT(2) + Logger.log('DT exchange buy response', exchange) + return exchange + } + } + } catch (error) { + setPricingError(error.message) + Logger.error(error) + } finally { + setPricingStep(undefined) + setPricingStepText(undefined) + setIsLoading(false) + } + } + + async function sellDT( + dataTokenAddress: string, + dtAmount: number | string, + ): Promise { + if (!ocean || !account || !accountId) return + + setIsLoading(true) + setPricingError(undefined) + setStepSellDT(0) + + try { + const pool=await getFirstPool(ocean, dataTokenAddress) + const price = new Decimal(pool.value).times(0.95).toString() + setStepSellDT(1) + Logger.log('Selling token to pool', pool, account.getId(), price) + const sellResponse = await ocean.pool.sellDT( + account.getId(), + pool.address, + String(dtAmount), + price + ) + setStepSellDT(2) + Logger.log('DT sell response', sellResponse) + return sellResponse + } catch (error) { + setPricingError(error.message) + Logger.error(error) + } finally { + setStepSellDT(undefined) + setPricingStepText(undefined) + setIsLoading(false) + } + } + + return { + createPricing, + buyDT, + sellDT, + pricingStep, + pricingStepText, + isLoading, + pricingError + } +} + +export { usePricing, UsePricing } +export default usePricing From 8896e776b3537e24c312579f703c33e3d962cdee Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 05:05:45 -0700 Subject: [PATCH 03/31] fix lint --- src/hooks/usePricing/usePricing.ts | 50 ++++++++++--------- src/providers/OceanProvider/OceanProvider.tsx | 2 +- tsconfig.json | 2 +- 3 files changed, 29 insertions(+), 25 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index ea438a3..888f5d8 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -16,15 +16,15 @@ import { Decimal } from 'decimal.js' interface UsePricing { createPricing: ( dataTokenAddress: string, - priceOptions: PriceOptions, + priceOptions: PriceOptions ) => Promise buyDT: ( dataTokenAddress: string, - dtAmount: number | string, + dtAmount: number | string ) => Promise sellDT: ( dataTokenAddress: string, - dtAmount: number | string, + dtAmount: number | string ) => Promise pricingStep?: number pricingStepText?: string @@ -35,19 +35,19 @@ interface UsePricing { export const buyDTFeedback: { [key in number]: string } = { 0: '1/3 Approving OCEAN ...', 1: '2/3 Buying DT ...', - 2: '3/3 DT Bought' + 2: '3/3 DT Bought' } export const sellDTFeedback: { [key in number]: string } = { 0: '1/3 Approving DT ...', 1: '2/3 Selling DT ...', - 2: '3/3 DT sold' + 2: '3/3 DT sold' } -export const createPricingFeedback:{ [key in number]: string } = { +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', + 3: '4/4 Pricing created' } function usePricing(): UsePricing { @@ -76,11 +76,11 @@ function usePricing(): UsePricing { ): Promise { setStepCreatePricing(0) let response = null - try{ + try { switch (priceOptions.type) { case 'dynamic': { setStepCreatePricing(2) - response=await ocean.pool.createDTPool( + response = await ocean.pool.createDTPool( accountId, dataTokenAddress, priceOptions.dtAmount.toString(), @@ -96,7 +96,7 @@ function usePricing(): UsePricing { return null } setStepCreatePricing(2) - response=await ocean.fixedRateExchange.create( + response = await ocean.fixedRateExchange.create( dataTokenAddress, priceOptions.price.toString(), accountId @@ -112,20 +112,19 @@ function usePricing(): UsePricing { return response } } - } - catch (error) { + } catch (error) { setPricingError(error.message) Logger.error(error) } finally { setPricingStep(undefined) setPricingStepText(undefined) setIsLoading(false) + } } -} async function buyDT( dataTokenAddress: string, - dtAmount: number | string, + dtAmount: number | string ): Promise { if (!ocean || !account || !accountId) return @@ -140,7 +139,12 @@ function usePricing(): UsePricing { const price = new Decimal(bestPrice.value).times(1.05).toString() const maxPrice = new Decimal(bestPrice.value).times(2).toString() setStepBuyDT(1) - Logger.log('Buying token from pool', bestPrice, account.getId(), price) + Logger.log( + 'Buying token from pool', + bestPrice, + account.getId(), + price + ) const buyResponse = await ocean.pool.buyDT( account.getId(), bestPrice.address, @@ -191,7 +195,7 @@ function usePricing(): UsePricing { async function sellDT( dataTokenAddress: string, - dtAmount: number | string, + dtAmount: number | string ): Promise { if (!ocean || !account || !accountId) return @@ -200,16 +204,16 @@ function usePricing(): UsePricing { setStepSellDT(0) try { - const pool=await getFirstPool(ocean, dataTokenAddress) + const pool = await getFirstPool(ocean, dataTokenAddress) const price = new Decimal(pool.value).times(0.95).toString() setStepSellDT(1) Logger.log('Selling token to pool', pool, account.getId(), price) const sellResponse = await ocean.pool.sellDT( - account.getId(), - pool.address, - String(dtAmount), - price - ) + account.getId(), + pool.address, + String(dtAmount), + price + ) setStepSellDT(2) Logger.log('DT sell response', sellResponse) return sellResponse @@ -222,7 +226,7 @@ function usePricing(): UsePricing { setIsLoading(false) } } - + return { createPricing, buyDT, diff --git a/src/providers/OceanProvider/OceanProvider.tsx b/src/providers/OceanProvider/OceanProvider.tsx index 871c60f..5d3f0a6 100644 --- a/src/providers/OceanProvider/OceanProvider.tsx +++ b/src/providers/OceanProvider/OceanProvider.tsx @@ -137,7 +137,7 @@ function OceanProvider({ } async function logout() { // TODO: #67 check how is the proper way to logout - web3Modal?.clearCachedProvider() + if (web3Modal) web3Modal.clearCachedProvider() } // TODO: #68 Refetch balance periodically, or figure out some event to subscribe to diff --git a/tsconfig.json b/tsconfig.json index f3c9f7c..9ca5a13 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -14,5 +14,5 @@ "importHelpers": true, "strict": true }, - "include": ["./src/@types", "./src/index.ts"] + "include": ["./src/@types", "./src/hooks", "./src/index.ts"] } From c5cce9e7cf546281c2b52092dd4e4ae2a81571f9 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 09:19:22 -0700 Subject: [PATCH 04/31] fix tsc --- src/hooks/usePricing/usePricing.ts | 35 +++++++++++++++--------------- src/hooks/usePublish/usePublish.ts | 10 ++++++--- 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 888f5d8..11b5a7f 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -1,13 +1,6 @@ -import { DID, DDO, Logger, Metadata } from '@oceanprotocol/lib' -import { - Service, - ServiceComputePrivacy, - ServiceType -} from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service' +import { Logger } from '@oceanprotocol/lib' import { useState } from 'react' import { useOcean } from 'providers' -import ProviderStatus from 'providers/OceanProvider/ProviderStatus' -import { publishFeedback } from 'utils' import { PriceOptions } from './PriceOptions' import { TransactionReceipt } from 'web3-core' import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils' @@ -17,7 +10,7 @@ interface UsePricing { createPricing: ( dataTokenAddress: string, priceOptions: PriceOptions - ) => Promise + ) => Promise buyDT: ( dataTokenAddress: string, dtAmount: number | string @@ -73,7 +66,8 @@ function usePricing(): UsePricing { async function createPricing( dataTokenAddress: string, priceOptions: PriceOptions - ): Promise { + ): Promise { + if (!ocean || !account || !accountId) return null setStepCreatePricing(0) let response = null try { @@ -105,7 +99,7 @@ function usePricing(): UsePricing { await ocean.datatokens.approve( dataTokenAddress, config.fixedRateExchangeAddress, - priceOptions.dtAmount, + String(priceOptions.dtAmount), accountId ) setStepCreatePricing(3) @@ -120,13 +114,14 @@ function usePricing(): UsePricing { setPricingStepText(undefined) setIsLoading(false) } + return null } async function buyDT( dataTokenAddress: string, dtAmount: number | string ): Promise { - if (!ocean || !account || !accountId) return + if (!ocean || !account || !accountId) return null setIsLoading(true) setPricingError(undefined) @@ -159,11 +154,11 @@ function usePricing(): UsePricing { case 'exchange': { if (!config.oceanTokenAddress) { Logger.error(`'oceanTokenAddress' not set in config`) - return + return null } if (!config.fixedRateExchangeAddress) { Logger.error(`'fixedRateExchangeAddress' not set in config`) - return + return null } Logger.log('Buying token from exchange', bestPrice, account.getId()) await ocean.datatokens.approve( @@ -191,21 +186,26 @@ function usePricing(): UsePricing { setPricingStepText(undefined) setIsLoading(false) } + return null } async function sellDT( dataTokenAddress: string, dtAmount: number | string ): Promise { - if (!ocean || !account || !accountId) return - + if (!ocean || !account || !accountId) return null + if (!config.oceanTokenAddress) { + Logger.error(`'oceanTokenAddress' not set in config`) + return null + } setIsLoading(true) setPricingError(undefined) setStepSellDT(0) try { const pool = await getFirstPool(ocean, dataTokenAddress) - const price = new Decimal(pool.value).times(0.95).toString() + if (!pool || pool.price === 0) return null + const price = new Decimal(pool.price).times(0.95).toString() setStepSellDT(1) Logger.log('Selling token to pool', pool, account.getId(), price) const sellResponse = await ocean.pool.sellDT( @@ -225,6 +225,7 @@ function usePricing(): UsePricing { setPricingStepText(undefined) setIsLoading(false) } + return null } return { diff --git a/src/hooks/usePublish/usePublish.ts b/src/hooks/usePublish/usePublish.ts index 21ce9c6..5abfe80 100644 --- a/src/hooks/usePublish/usePublish.ts +++ b/src/hooks/usePublish/usePublish.ts @@ -65,7 +65,7 @@ function usePublish(): UsePublish { const publishedDate = new Date(Date.now()).toISOString().split('.')[0] + 'Z' - const timeout = 0 + let timeout = 0 const services: Service[] = [] const price = '1' @@ -75,13 +75,15 @@ function usePublish(): UsePublish { account, price, publishedDate, - timeout + timeout, + providerUri ) Logger.log('access service created', accessService) services.push(accessService) break } case 'compute': { + timeout = 3600 const cluster = ocean.compute.createClusterAttributes( 'Kubernetes', 'http://10.0.0.17/xxx' @@ -122,7 +124,9 @@ function usePublish(): UsePublish { price, publishedDate, provider, - origComputePrivacy as ServiceComputePrivacy + origComputePrivacy as ServiceComputePrivacy, + timeout, + providerUri ) services.push(computeService) break From c64160729d408fe3255e04fc77603fba16c78042 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 09:45:11 -0700 Subject: [PATCH 05/31] export usePricing --- src/hooks/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 968161c..d4c70a6 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -2,3 +2,4 @@ export * from './useConsume' export * from './useMetadata' export * from './usePublish' export * from './useCompute' +export * from './usePricing' From 65d43f80a36d69b06c76ee0c6693e030990fbeb0 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 09:45:41 -0700 Subject: [PATCH 06/31] update examples --- example/src/App.tsx | 4 ++++ example/src/Publish.tsx | 35 +++++++++++++++++++++++++---- example/src/Trade.tsx | 49 +++++++++++++++++++++++++++++++++++++++++ 3 files changed, 84 insertions(+), 4 deletions(-) create mode 100644 example/src/Trade.tsx diff --git a/example/src/App.tsx b/example/src/App.tsx index cfe4efa..80dd955 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -8,6 +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' const configRinkeby = new ConfigHelper().getConfig('rinkeby') const providerOptions = {} @@ -39,6 +40,9 @@ function App() {
+
+ +
diff --git a/example/src/Publish.tsx b/example/src/Publish.tsx index 326b61f..736fe47 100644 --- a/example/src/Publish.tsx +++ b/example/src/Publish.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { usePublish } from '@oceanprotocol/react' +import { usePublish, usePricing } from '@oceanprotocol/react' // import { useOcean, usePublish } from '@oceanprotocol/react' import { DDO } from '@oceanprotocol/lib' import { useState } from 'react' @@ -7,6 +7,7 @@ import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata' export function Publish() { const { publish, publishStepText, isLoading } = usePublish() + const { createPricing, buyDT, sellDT, pricingStep, pricingStepText, isLoading: pricingIsLoading, pricingError} = usePricing() const [ddo, setDdo] = useState() const asset = { @@ -33,16 +34,35 @@ export function Publish() { const publishAsset = async () => { const priceOptions = { price: 7, - tokensToMint: 10, + dtAmount: 10, type: 'fixed', weightOnDataToken: '', swapFee: '' } - - const ddo = await publish(asset as Metadata, priceOptions, 'access') + const datatokenOptions = { + tokensToMint:10 + } + const ddo = await publish(asset as Metadata, 'access', datatokenOptions) console.log(ddo) setDdo(ddo) } + + const PostForSale = 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 ( <>
Publish
@@ -53,6 +73,13 @@ export function Publish() { IsLoading: {isLoading.toString()} || Status: {publishStepText}
DID: {ddo && ddo.id}
+
+ +
+
+ IsLoading: {pricingIsLoading.toString()} || pricingStatus: {pricingStepText} +
+ ) } diff --git a/example/src/Trade.tsx b/example/src/Trade.tsx new file mode 100644 index 0000000..8b305b3 --- /dev/null +++ b/example/src/Trade.tsx @@ -0,0 +1,49 @@ +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, pricingStep, pricingStepText, isLoading: pricingIsLoading, pricingError} = usePricing() + const [did, setDid] = useState() + const ActionBuy = async () => { + if (!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 ActionSell = async () => { + if (!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") + } + } + return ( + <> +
Trade Datatoken
+
+ +
+
+ +
+
+ IsLoading: {pricingIsLoading.toString()} || Status: {pricingStepText} +
+ + + ) +} From 678d9a0b80bdf4cf4a56d2c08400062d7f01210f Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 09:56:36 -0700 Subject: [PATCH 07/31] allow timeout pass through --- src/hooks/usePublish/usePublish.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/hooks/usePublish/usePublish.ts b/src/hooks/usePublish/usePublish.ts index 5abfe80..844ef36 100644 --- a/src/hooks/usePublish/usePublish.ts +++ b/src/hooks/usePublish/usePublish.ts @@ -15,6 +15,7 @@ interface UsePublish { asset: Metadata, serviceConfigs: ServiceType, dataTokenOptions: DataTokenOptions, + timeout?: number, providerUri?: string ) => Promise mint: (tokenAddress: string, tokensToMint: string) => void @@ -53,10 +54,10 @@ function usePublish(): UsePublish { asset: Metadata, serviceType: ServiceType, dataTokenOptions: DataTokenOptions, + timeout?: number, providerUri?: string ): Promise { if (status !== ProviderStatus.CONNECTED || !ocean || !account) return null - setIsLoading(true) setPublishError(undefined) @@ -71,6 +72,7 @@ function usePublish(): UsePublish { const price = '1' switch (serviceType) { case 'access': { + if (!timeout) timeout = 0 const accessService = await ocean.assets.createAccessServiceAttributes( account, price, @@ -83,7 +85,7 @@ function usePublish(): UsePublish { break } case 'compute': { - timeout = 3600 + if (!timeout) timeout = 3600 const cluster = ocean.compute.createClusterAttributes( 'Kubernetes', 'http://10.0.0.17/xxx' From faec8343bb89fef04aaeedd2e7f3c14894974358 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 11:41:34 -0700 Subject: [PATCH 08/31] update docs --- src/hooks/usePricing/README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/hooks/usePricing/README.md b/src/hooks/usePricing/README.md index dea0700..89fabda 100644 --- a/src/hooks/usePricing/README.md +++ b/src/hooks/usePricing/README.md @@ -13,7 +13,7 @@ import { Metadata } from '@oceanprotocol/lib' export default function MyComponent() { const { accountId } = useOcean() - + const dataTokenAddress = '0x00000' // Publish helpers const { createPricing, buyDT, sellDT } = usePricing() @@ -26,14 +26,14 @@ export default function MyComponent() { } async function handleCreatePricing() { - const ddo = await createPricing(dataTokenAddress, priceOptions) + await createPricing(dataTokenAddress, priceOptions) } async function handleBuyDT() { - const ddo = await buyDT(dataTokenAddress, 1) + await buyDT(dataTokenAddress, 1) } async function handleSellDT() { - const ddo = await sellDT(dataTokenAddress, 1) + await sellDT(dataTokenAddress, 1) } return ( From 822cf9aabca20e37d56edc9ad8b9d4047bb442b3 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Wed, 14 Oct 2020 11:49:22 -0700 Subject: [PATCH 09/31] update docs --- src/hooks/usePricing/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/hooks/usePricing/README.md b/src/hooks/usePricing/README.md index 89fabda..a325807 100644 --- a/src/hooks/usePricing/README.md +++ b/src/hooks/usePricing/README.md @@ -30,10 +30,10 @@ export default function MyComponent() { } async function handleBuyDT() { - await buyDT(dataTokenAddress, 1) + await buyDT(dataTokenAddress, '1') } async function handleSellDT() { - await sellDT(dataTokenAddress, 1) + await sellDT(dataTokenAddress, '1') } return ( From b6ddcf069f11731187f4c0746c4d7660a4dec3a2 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 00:48:17 -0700 Subject: [PATCH 10/31] update example --- example/src/Trade.tsx | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/example/src/Trade.tsx b/example/src/Trade.tsx index 8b305b3..3fb4533 100644 --- a/example/src/Trade.tsx +++ b/example/src/Trade.tsx @@ -10,7 +10,7 @@ export function Trade() { const { createPricing, buyDT, sellDT, pricingStep, pricingStepText, isLoading: pricingIsLoading, pricingError} = usePricing() const [did, setDid] = useState() const ActionBuy = async () => { - if (!did) return + if (!did) { console.error("No DID"); return} const ddo = await ocean.assets.resolve(did) if(ddo){ const tx = await buyDT(ddo.dataToken,'1') @@ -21,7 +21,7 @@ export function Trade() { } } const ActionSell = async () => { - if (!did) return + if (!did) { console.error("No DID"); return} const ddo = await ocean.assets.resolve(did) if(ddo){ const tx = await buyDT(ddo.dataToken,'1') @@ -31,9 +31,15 @@ export function Trade() { console.error("Publish the asset first and create a pricing") } } + const handleChange = (e: any) => { + setDid(e.target.value) + } return ( <>
Trade Datatoken
+
+ DID +
From 1b5c5caad9d882267cde53a82fc872c130e7981f Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 03:31:58 -0700 Subject: [PATCH 11/31] bump ocean.js --- package-lock.json | 14 +++++++------- package.json | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/package-lock.json b/package-lock.json index 17564c7..4d6823a 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1516,17 +1516,17 @@ } }, "@oceanprotocol/contracts": { - "version": "0.5.5", - "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-0.5.5.tgz", - "integrity": "sha512-Omwlh3KxPm2JOuLd6DW4teAQhGaIv0fRTopCvctey0XGsf3DcbJpwS0A0YfgLQnvCyyVMKsiq90YCqpJ3SO/cw==" + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/@oceanprotocol/contracts/-/contracts-0.5.6.tgz", + "integrity": "sha512-LING+GvW37I0L40rZdPCZ1SvcZurDSGGhT0WOVPNO8oyh2C3bXModDBNE4+gCFa8pTbQBOc4ot1/Zoj9PfT/zA==" }, "@oceanprotocol/lib": { - "version": "0.6.0", - "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-0.6.0.tgz", - "integrity": "sha512-5Kv6oVV7nneeVoT79fAQh93Ksb4Zg0TjjbVutMIYDt9kB8/Iwc/5NYU88unaz4XHX5zBl5rqnwfWoZMRDaI7hA==", + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-0.6.4.tgz", + "integrity": "sha512-yNaeoTXjRmhXrDgRMchxmS49zqWI23e50W49OsOyEt+RqDKpbBBBlqzyeNcI0KU3vwnwhV+CH7nqSDUbOothow==", "requires": { "@ethereum-navigator/navigator": "^0.5.0", - "@oceanprotocol/contracts": "^0.5.5", + "@oceanprotocol/contracts": "^0.5.6", "decimal.js": "^10.2.0", "fs": "0.0.1-security", "lzma": "^2.3.2", diff --git a/package.json b/package.json index f88535e..f6ead11 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "dist/" ], "dependencies": { - "@oceanprotocol/lib": "^0.6.0", + "@oceanprotocol/lib": "^0.6.4", "axios": "^0.20.0", "decimal.js": "^10.2.1", "web3": "^1.3.0", From d2e5a8114d43792a9f00855f51ea8855a719a4c7 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 03:32:10 -0700 Subject: [PATCH 12/31] fix handlers --- example/src/Publish.tsx | 4 ++-- example/src/Trade.tsx | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/example/src/Publish.tsx b/example/src/Publish.tsx index 736fe47..be8b0f6 100644 --- a/example/src/Publish.tsx +++ b/example/src/Publish.tsx @@ -47,7 +47,7 @@ export function Publish() { setDdo(ddo) } - const PostForSale = async () => { + const handlePostForSale = async () => { if(ddo){ const priceOptions = { price: 7, @@ -74,7 +74,7 @@ export function Publish() {
DID: {ddo && ddo.id}
- +
IsLoading: {pricingIsLoading.toString()} || pricingStatus: {pricingStepText} diff --git a/example/src/Trade.tsx b/example/src/Trade.tsx index 3fb4533..9fa0e3f 100644 --- a/example/src/Trade.tsx +++ b/example/src/Trade.tsx @@ -9,7 +9,7 @@ export function Trade() { const { ocean, accountId } = useOcean() const { createPricing, buyDT, sellDT, pricingStep, pricingStepText, isLoading: pricingIsLoading, pricingError} = usePricing() const [did, setDid] = useState() - const ActionBuy = async () => { + const handleBuy = async () => { if (!did) { console.error("No DID"); return} const ddo = await ocean.assets.resolve(did) if(ddo){ @@ -20,7 +20,7 @@ export function Trade() { console.error("Publish the asset first and create a pricing") } } - const ActionSell = async () => { + const handleSell = async () => { if (!did) { console.error("No DID"); return} const ddo = await ocean.assets.resolve(did) if(ddo){ @@ -41,10 +41,10 @@ export function Trade() { DID
- +
- +
IsLoading: {pricingIsLoading.toString()} || Status: {pricingStepText} From acf7b68560cf5ec1a4dfc01884c836bd9315896b Mon Sep 17 00:00:00 2001 From: Alex Coseru Date: Fri, 16 Oct 2020 13:33:03 +0300 Subject: [PATCH 13/31] Update src/hooks/usePricing/README.md Co-authored-by: Matthias Kretschmann --- src/hooks/usePricing/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/hooks/usePricing/README.md b/src/hooks/usePricing/README.md index a325807..251662b 100644 --- a/src/hooks/usePricing/README.md +++ b/src/hooks/usePricing/README.md @@ -8,7 +8,7 @@ Sell DT ```tsx import React from 'react' -import { useOcean, usePostforSale } from '@oceanprotocol/react' +import { useOcean, usePricing } from '@oceanprotocol/react' import { Metadata } from '@oceanprotocol/lib' export default function MyComponent() { From 06ef2746f49b2aaa306d9a79b9a6cb5a9504b9fe Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 03:33:59 -0700 Subject: [PATCH 14/31] fix usePricing Readme --- src/hooks/usePricing/README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/hooks/usePricing/README.md b/src/hooks/usePricing/README.md index 251662b..707b67f 100644 --- a/src/hooks/usePricing/README.md +++ b/src/hooks/usePricing/README.md @@ -1,8 +1,6 @@ # `usePricing` -Post asset for sale by creating liquidity pools or fixed rate exchange -Buy DT -Sell DT +Hook with helper utilities to create fixed price exchanges or liquidity pools for your data set and buy/sell datatokens ## Usage From 40929faedf7949e3ba844f1480504873d3b5f7a2 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 03:59:10 -0700 Subject: [PATCH 15/31] use token name instead of DT --- example/src/Publish.tsx | 2 +- src/hooks/usePricing/usePricing.ts | 70 ++++++++++++++++++++---------- 2 files changed, 47 insertions(+), 25 deletions(-) diff --git a/example/src/Publish.tsx b/example/src/Publish.tsx index be8b0f6..a4a69a5 100644 --- a/example/src/Publish.tsx +++ b/example/src/Publish.tsx @@ -7,7 +7,7 @@ import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata' export function Publish() { const { publish, publishStepText, isLoading } = usePublish() - const { createPricing, buyDT, sellDT, pricingStep, pricingStepText, isLoading: pricingIsLoading, pricingError} = usePricing() + const { createPricing, buyDT, sellDT, pricingStep, pricingStepText, pricingIsLoading, pricingError} = usePricing() const [ddo, setDdo] = useState() const asset = { diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 11b5a7f..75712ab 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -22,7 +22,7 @@ interface UsePricing { pricingStep?: number pricingStepText?: string pricingError?: string - isLoading: boolean + pricingIsLoading: boolean } export const buyDTFeedback: { [key in number]: string } = { @@ -45,22 +45,40 @@ export const createPricingFeedback: { [key in number]: string } = { function usePricing(): UsePricing { const { ocean, status, account, accountId, config } = useOcean() - const [isLoading, setIsLoading] = useState(false) + const [pricingIsLoading, setPricingIsLoading] = useState(false) const [pricingStep, setPricingStep] = useState() const [pricingStepText, setPricingStepText] = useState() const [pricingError, setPricingError] = useState() - function setStepBuyDT(index?: number) { + function setStepBuyDT(index?: number, datatokenName?: string) { setPricingStep(index) - index && setPricingStepText(buyDTFeedback[index]) + let message + if (index) { + if (datatokenName) + message = buyDTFeedback[index].replace(/DT/g, datatokenName) + else message = buyDTFeedback[index] + setPricingStepText(message) + } } - function setStepSellDT(index?: number) { + function setStepSellDT(index?: number, datatokenName?: string) { setPricingStep(index) - index && setPricingStepText(sellDTFeedback[index]) + let message + if (index) { + if (datatokenName) + message = sellDTFeedback[index].replace(/DT/g, datatokenName) + else message = sellDTFeedback[index] + setPricingStepText(message) + } } - function setStepCreatePricing(index?: number) { + function setStepCreatePricing(index?: number, datatokenName?: string) { setPricingStep(index) - index && setPricingStepText(createPricingFeedback[index]) + let message + if (index) { + if (datatokenName) + message = createPricingFeedback[index].replace(/DT/g, datatokenName) + else message = createPricingFeedback[index] + setPricingStepText(message) + } } async function createPricing( @@ -68,9 +86,13 @@ function usePricing(): UsePricing { priceOptions: PriceOptions ): Promise { if (!ocean || !account || !accountId) return null - setStepCreatePricing(0) + let response = null try { + setPricingIsLoading(true) + setPricingError(undefined) + const datatokenName = await ocean.datatokens.getName(dataTokenAddress) + setStepCreatePricing(0, datatokenName) switch (priceOptions.type) { case 'dynamic': { setStepCreatePricing(2) @@ -112,7 +134,7 @@ function usePricing(): UsePricing { } finally { setPricingStep(undefined) setPricingStepText(undefined) - setIsLoading(false) + setPricingIsLoading(false) } return null } @@ -123,17 +145,17 @@ function usePricing(): UsePricing { ): Promise { if (!ocean || !account || !accountId) return null - setIsLoading(true) - setPricingError(undefined) - setStepBuyDT(0) - try { + const datatokenName = await ocean.datatokens.getName(dataTokenAddress) + setPricingIsLoading(true) + setPricingError(undefined) + setStepBuyDT(0) const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) switch (bestPrice?.type) { case 'pool': { const price = new Decimal(bestPrice.value).times(1.05).toString() const maxPrice = new Decimal(bestPrice.value).times(2).toString() - setStepBuyDT(1) + setStepBuyDT(1, datatokenName) Logger.log( 'Buying token from pool', bestPrice, @@ -167,7 +189,7 @@ function usePricing(): UsePricing { bestPrice.value.toString(), account.getId() ) - setStepBuyDT(1) + setStepBuyDT(1, datatokenName) const exchange = await ocean.fixedRateExchange.buyDT( bestPrice.address, String(dtAmount), @@ -184,7 +206,7 @@ function usePricing(): UsePricing { } finally { setPricingStep(undefined) setPricingStepText(undefined) - setIsLoading(false) + setPricingIsLoading(false) } return null } @@ -198,15 +220,15 @@ function usePricing(): UsePricing { Logger.error(`'oceanTokenAddress' not set in config`) return null } - setIsLoading(true) - setPricingError(undefined) - setStepSellDT(0) - try { + const datatokenName = await ocean.datatokens.getName(dataTokenAddress) + setPricingIsLoading(true) + setPricingError(undefined) + setStepSellDT(0, datatokenName) const pool = await getFirstPool(ocean, dataTokenAddress) if (!pool || pool.price === 0) return null const price = new Decimal(pool.price).times(0.95).toString() - setStepSellDT(1) + setStepSellDT(1, datatokenName) Logger.log('Selling token to pool', pool, account.getId(), price) const sellResponse = await ocean.pool.sellDT( account.getId(), @@ -223,7 +245,7 @@ function usePricing(): UsePricing { } finally { setStepSellDT(undefined) setPricingStepText(undefined) - setIsLoading(false) + setPricingIsLoading(false) } return null } @@ -234,7 +256,7 @@ function usePricing(): UsePricing { sellDT, pricingStep, pricingStepText, - isLoading, + pricingIsLoading, pricingError } } From efdfdb86876cc0a73c9bac916eedd85c2749c627 Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 04:08:06 -0700 Subject: [PATCH 16/31] use dtSymbol --- src/hooks/usePricing/usePricing.ts | 33 +++++++++++++++--------------- 1 file changed, 16 insertions(+), 17 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 75712ab..7797b64 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -49,33 +49,32 @@ function usePricing(): UsePricing { const [pricingStep, setPricingStep] = useState() const [pricingStepText, setPricingStepText] = useState() const [pricingError, setPricingError] = useState() + const [dtSymbol, setDtSymbol] = useState() - function setStepBuyDT(index?: number, datatokenName?: string) { + function setStepBuyDT(index?: number) { setPricingStep(index) let message if (index) { - if (datatokenName) - message = buyDTFeedback[index].replace(/DT/g, datatokenName) + if (dtSymbol) message = buyDTFeedback[index].replace(/DT/g, dtSymbol) else message = buyDTFeedback[index] setPricingStepText(message) } } - function setStepSellDT(index?: number, datatokenName?: string) { + function setStepSellDT(index?: number) { setPricingStep(index) let message if (index) { - if (datatokenName) - message = sellDTFeedback[index].replace(/DT/g, datatokenName) + if (dtSymbol) message = sellDTFeedback[index].replace(/DT/g, dtSymbol) else message = sellDTFeedback[index] setPricingStepText(message) } } - function setStepCreatePricing(index?: number, datatokenName?: string) { + function setStepCreatePricing(index?: number) { setPricingStep(index) let message if (index) { - if (datatokenName) - message = createPricingFeedback[index].replace(/DT/g, datatokenName) + if (dtSymbol) + message = createPricingFeedback[index].replace(/DT/g, dtSymbol) else message = createPricingFeedback[index] setPricingStepText(message) } @@ -91,8 +90,8 @@ function usePricing(): UsePricing { try { setPricingIsLoading(true) setPricingError(undefined) - const datatokenName = await ocean.datatokens.getName(dataTokenAddress) - setStepCreatePricing(0, datatokenName) + setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) + setStepCreatePricing(0) switch (priceOptions.type) { case 'dynamic': { setStepCreatePricing(2) @@ -146,7 +145,7 @@ function usePricing(): UsePricing { if (!ocean || !account || !accountId) return null try { - const datatokenName = await ocean.datatokens.getName(dataTokenAddress) + setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) setPricingIsLoading(true) setPricingError(undefined) setStepBuyDT(0) @@ -155,7 +154,7 @@ function usePricing(): UsePricing { case 'pool': { const price = new Decimal(bestPrice.value).times(1.05).toString() const maxPrice = new Decimal(bestPrice.value).times(2).toString() - setStepBuyDT(1, datatokenName) + setStepBuyDT(1) Logger.log( 'Buying token from pool', bestPrice, @@ -189,7 +188,7 @@ function usePricing(): UsePricing { bestPrice.value.toString(), account.getId() ) - setStepBuyDT(1, datatokenName) + setStepBuyDT(1) const exchange = await ocean.fixedRateExchange.buyDT( bestPrice.address, String(dtAmount), @@ -221,14 +220,14 @@ function usePricing(): UsePricing { return null } try { - const datatokenName = await ocean.datatokens.getName(dataTokenAddress) + setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) setPricingIsLoading(true) setPricingError(undefined) - setStepSellDT(0, datatokenName) + setStepSellDT(0) const pool = await getFirstPool(ocean, dataTokenAddress) if (!pool || pool.price === 0) return null const price = new Decimal(pool.price).times(0.95).toString() - setStepSellDT(1, datatokenName) + setStepSellDT(1) Logger.log('Selling token to pool', pool, account.getId(), price) const sellResponse = await ocean.pool.sellDT( account.getId(), From 6167d88fd93a0afc96cd4feb85d011b27914494a Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 05:06:34 -0700 Subject: [PATCH 17/31] split usePricing --- example/src/Publish.tsx | 4 +- example/src/Trade.tsx | 6 +- src/hooks/index.ts | 3 +- .../PriceOptions.ts | 0 .../README.md | 16 +- src/hooks/useCreatePricing/index.ts | 2 + .../useCreatePricing/useCreatePricing.ts | 114 ++++++++++++++ src/hooks/usePricing/index.ts | 2 - src/hooks/useTrade/README.md | 35 +++++ src/hooks/useTrade/index.ts | 1 + .../usePricing.ts => useTrade/useTrade.ts} | 143 ++++-------------- 11 files changed, 194 insertions(+), 132 deletions(-) rename src/hooks/{usePricing => useCreatePricing}/PriceOptions.ts (100%) rename src/hooks/{usePricing => useCreatePricing}/README.md (62%) create mode 100644 src/hooks/useCreatePricing/index.ts create mode 100644 src/hooks/useCreatePricing/useCreatePricing.ts delete mode 100644 src/hooks/usePricing/index.ts create mode 100644 src/hooks/useTrade/README.md create mode 100644 src/hooks/useTrade/index.ts rename src/hooks/{usePricing/usePricing.ts => useTrade/useTrade.ts} (56%) diff --git a/example/src/Publish.tsx b/example/src/Publish.tsx index a4a69a5..57066d1 100644 --- a/example/src/Publish.tsx +++ b/example/src/Publish.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { usePublish, usePricing } from '@oceanprotocol/react' +import { usePublish, useCreatePricing } from '@oceanprotocol/react' // import { useOcean, usePublish } from '@oceanprotocol/react' import { DDO } from '@oceanprotocol/lib' import { useState } from 'react' @@ -7,7 +7,7 @@ import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata' export function Publish() { const { publish, publishStepText, isLoading } = usePublish() - const { createPricing, buyDT, sellDT, pricingStep, pricingStepText, pricingIsLoading, pricingError} = usePricing() + const { createPricing, pricingStep, pricingStepText, pricingIsLoading, pricingError} = useCreatePricing() const [ddo, setDdo] = useState() const asset = { diff --git a/example/src/Trade.tsx b/example/src/Trade.tsx index 9fa0e3f..f880c01 100644 --- a/example/src/Trade.tsx +++ b/example/src/Trade.tsx @@ -1,5 +1,5 @@ import React from 'react' -import { useOcean, usePricing } from '@oceanprotocol/react' +import { useOcean, useTrade } from '@oceanprotocol/react' // import { useOcean, usePublish } from '@oceanprotocol/react' import { DDO } from '@oceanprotocol/lib' import { useState } from 'react' @@ -7,7 +7,7 @@ import { Metadata } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Metadata' export function Trade() { const { ocean, accountId } = useOcean() - const { createPricing, buyDT, sellDT, pricingStep, pricingStepText, isLoading: pricingIsLoading, pricingError} = usePricing() + const { buyDT, sellDT, tradeStep, tradeStepText, tradeIsLoading, tradeError} = useTrade() const [did, setDid] = useState() const handleBuy = async () => { if (!did) { console.error("No DID"); return} @@ -47,7 +47,7 @@ export function Trade() {
- IsLoading: {pricingIsLoading.toString()} || Status: {pricingStepText} + IsLoading: {tradeIsLoading.toString()} || Status: {tradeStepText}
diff --git a/src/hooks/index.ts b/src/hooks/index.ts index d4c70a6..519a8c1 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -2,4 +2,5 @@ export * from './useConsume' export * from './useMetadata' export * from './usePublish' export * from './useCompute' -export * from './usePricing' +export * from './useCreatePricing' +export * from './useTrade' diff --git a/src/hooks/usePricing/PriceOptions.ts b/src/hooks/useCreatePricing/PriceOptions.ts similarity index 100% rename from src/hooks/usePricing/PriceOptions.ts rename to src/hooks/useCreatePricing/PriceOptions.ts diff --git a/src/hooks/usePricing/README.md b/src/hooks/useCreatePricing/README.md similarity index 62% rename from src/hooks/usePricing/README.md rename to src/hooks/useCreatePricing/README.md index 707b67f..563d572 100644 --- a/src/hooks/usePricing/README.md +++ b/src/hooks/useCreatePricing/README.md @@ -1,19 +1,19 @@ # `usePricing` -Hook with helper utilities to create fixed price exchanges or liquidity pools for your data set and buy/sell datatokens +Hook with helper utilities to create fixed price exchanges or liquidity pools for your data set ## Usage ```tsx import React from 'react' -import { useOcean, usePricing } from '@oceanprotocol/react' +import { useOcean, useCreatePricing } from '@oceanprotocol/react' import { Metadata } from '@oceanprotocol/lib' export default function MyComponent() { const { accountId } = useOcean() const dataTokenAddress = '0x00000' // Publish helpers - const { createPricing, buyDT, sellDT } = usePricing() + const { createPricing } = useCreatePricing() const priceOptions = { price: 10, @@ -27,21 +27,13 @@ export default function MyComponent() { await createPricing(dataTokenAddress, priceOptions) } - async function handleBuyDT() { - await buyDT(dataTokenAddress, '1') - } - async function handleSellDT() { - await sellDT(dataTokenAddress, '1') - } - + return (

Post for sale

Your account: {accountId}

- -
) } diff --git a/src/hooks/useCreatePricing/index.ts b/src/hooks/useCreatePricing/index.ts new file mode 100644 index 0000000..0982522 --- /dev/null +++ b/src/hooks/useCreatePricing/index.ts @@ -0,0 +1,2 @@ +export * from './useCreatePricing' +export * from './PriceOptions' diff --git a/src/hooks/useCreatePricing/useCreatePricing.ts b/src/hooks/useCreatePricing/useCreatePricing.ts new file mode 100644 index 0000000..9169470 --- /dev/null +++ b/src/hooks/useCreatePricing/useCreatePricing.ts @@ -0,0 +1,114 @@ +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 + 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() + const [pricingStepText, setPricingStepText] = useState() + const [pricingError, setPricingError] = useState() + const [dtSymbol, setDtSymbol] = useState() + + 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 { + 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 diff --git a/src/hooks/usePricing/index.ts b/src/hooks/usePricing/index.ts deleted file mode 100644 index 3b43af5..0000000 --- a/src/hooks/usePricing/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './usePricing' -export * from './PriceOptions' diff --git a/src/hooks/useTrade/README.md b/src/hooks/useTrade/README.md new file mode 100644 index 0000000..e6f0e85 --- /dev/null +++ b/src/hooks/useTrade/README.md @@ -0,0 +1,35 @@ +# `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 ( +
+

Trade

+ + + +
+ ) +} +``` diff --git a/src/hooks/useTrade/index.ts b/src/hooks/useTrade/index.ts new file mode 100644 index 0000000..ba87662 --- /dev/null +++ b/src/hooks/useTrade/index.ts @@ -0,0 +1 @@ +export * from './useTrade' diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/useTrade/useTrade.ts similarity index 56% rename from src/hooks/usePricing/usePricing.ts rename to src/hooks/useTrade/useTrade.ts index 7797b64..8d1380c 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/useTrade/useTrade.ts @@ -1,16 +1,11 @@ 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 UsePricing { - createPricing: ( - dataTokenAddress: string, - priceOptions: PriceOptions - ) => Promise +interface UseTrade { buyDT: ( dataTokenAddress: string, dtAmount: number | string @@ -19,10 +14,10 @@ interface UsePricing { dataTokenAddress: string, dtAmount: number | string ) => Promise - pricingStep?: number - pricingStepText?: string - pricingError?: string - pricingIsLoading: boolean + tradeStep?: number + tradeStepText?: string + tradeError?: string + tradeIsLoading: boolean } export const buyDTFeedback: { [key in number]: string } = { @@ -36,107 +31,32 @@ export const sellDTFeedback: { [key in number]: string } = { 2: '3/3 DT sold' } -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 usePricing(): UsePricing { +function useTrade(): UseTrade { const { ocean, status, account, accountId, config } = useOcean() - const [pricingIsLoading, setPricingIsLoading] = useState(false) - const [pricingStep, setPricingStep] = useState() - const [pricingStepText, setPricingStepText] = useState() - const [pricingError, setPricingError] = useState() + const [tradeIsLoading, setTradeIsLoading] = useState(false) + const [tradeStep, setTradeStep] = useState() + const [tradeStepText, setTradeStepText] = useState() + const [tradeError, setTradeError] = useState() const [dtSymbol, setDtSymbol] = useState() function setStepBuyDT(index?: number) { - setPricingStep(index) + setTradeStep(index) let message if (index) { if (dtSymbol) message = buyDTFeedback[index].replace(/DT/g, dtSymbol) else message = buyDTFeedback[index] - setPricingStepText(message) + setTradeStepText(message) } } function setStepSellDT(index?: number) { - setPricingStep(index) + setTradeStep(index) let message if (index) { if (dtSymbol) message = sellDTFeedback[index].replace(/DT/g, dtSymbol) else message = sellDTFeedback[index] - setPricingStepText(message) + setTradeStepText(message) } } - 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 { - 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 - } async function buyDT( dataTokenAddress: string, @@ -146,8 +66,8 @@ function usePricing(): UsePricing { try { setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) - setPricingIsLoading(true) - setPricingError(undefined) + setTradeIsLoading(true) + setTradeError(undefined) setStepBuyDT(0) const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) switch (bestPrice?.type) { @@ -200,12 +120,12 @@ function usePricing(): UsePricing { } } } catch (error) { - setPricingError(error.message) + setTradeError(error.message) Logger.error(error) } finally { - setPricingStep(undefined) - setPricingStepText(undefined) - setPricingIsLoading(false) + setTradeStep(undefined) + setTradeStepText(undefined) + setTradeIsLoading(false) } return null } @@ -221,8 +141,8 @@ function usePricing(): UsePricing { } try { setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) - setPricingIsLoading(true) - setPricingError(undefined) + setTradeIsLoading(true) + setTradeError(undefined) setStepSellDT(0) const pool = await getFirstPool(ocean, dataTokenAddress) if (!pool || pool.price === 0) return null @@ -239,26 +159,25 @@ function usePricing(): UsePricing { Logger.log('DT sell response', sellResponse) return sellResponse } catch (error) { - setPricingError(error.message) + setTradeError(error.message) Logger.error(error) } finally { setStepSellDT(undefined) - setPricingStepText(undefined) - setPricingIsLoading(false) + setTradeStepText(undefined) + setTradeIsLoading(false) } return null } return { - createPricing, buyDT, sellDT, - pricingStep, - pricingStepText, - pricingIsLoading, - pricingError + tradeStep, + tradeStepText, + tradeIsLoading, + tradeError } } -export { usePricing, UsePricing } -export default usePricing +export { useTrade, UseTrade } +export default useTrade From e39f41403d07a56ebb442414033474e7452f291d Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Fri, 16 Oct 2020 05:31:45 -0700 Subject: [PATCH 18/31] merge dtUtils --- src/utils/dtUtils.ts | 113 ++++++++++++++++++++++++++++++++----------- 1 file changed, 86 insertions(+), 27 deletions(-) diff --git a/src/utils/dtUtils.ts b/src/utils/dtUtils.ts index cbb8621..9c8b638 100644 --- a/src/utils/dtUtils.ts +++ b/src/utils/dtUtils.ts @@ -44,33 +44,6 @@ export async function getCheapestPool( } } -export async function getFirstPool( - ocean: Ocean, - dataTokenAddress: string -): Promise { - if (!ocean || !dataTokenAddress) return null - - const tokenPools = await ocean.pool.searchPoolforDT(dataTokenAddress) - - if (tokenPools === undefined || tokenPools.length === 0) { - return { - address: '', - price: 0 - } - } - const firstPoolAddress = tokenPools[0] - const firstPoolPrice = await ocean.pool.getOceanNeeded(firstPoolAddress, '1') - const oceanReserve = await ocean.pool.getOceanReserve(firstPoolAddress) - const dtReserve = await ocean.pool.getDTReserve(firstPoolAddress) - - return { - address: firstPoolAddress, - price: Number(firstPoolPrice), - ocean: Number(oceanReserve), - datatoken: Number(dtReserve) - } -} - export async function getCheapestExchange( ocean: Ocean, dataTokenAddress: string @@ -113,6 +86,33 @@ export async function getCheapestExchange( } } +export async function getFirstPool( + ocean: Ocean, + dataTokenAddress: string +): Promise { + if (!ocean || !dataTokenAddress) return null + + const tokenPools = await ocean.pool.searchPoolforDT(dataTokenAddress) + + if (tokenPools === undefined || tokenPools.length === 0) { + return { + address: '', + price: 0 + } + } + const firstPoolAddress = tokenPools[0] + const firstPoolPrice = await ocean.pool.getOceanNeeded(firstPoolAddress, '1') + const oceanReserve = await ocean.pool.getOceanReserve(firstPoolAddress) + const dtReserve = await ocean.pool.getDTReserve(firstPoolAddress) + + return { + address: firstPoolAddress, + price: Number(firstPoolPrice), + ocean: Number(oceanReserve), + datatoken: Number(dtReserve) + } +} + export async function getBestDataTokenPrice( ocean: Ocean, dataTokenAddress: string @@ -146,3 +146,62 @@ export async function getBestDataTokenPrice( } as BestPrice } } + +export async function checkAndBuyDT( + ocean: Ocean, + dataTokenAddress: string, + account: Account, + config: Config +): Promise { + const userOwnedTokens = await ocean.accounts.getTokenBalance( + dataTokenAddress, + account + ) + Logger.log(`User has ${userOwnedTokens} tokens`) + if (userOwnedTokens === '0') { + const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) + + 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': { + if (!config.oceanTokenAddress) { + Logger.error(`'oceanTokenAddress' not set in config`) + return + } + + if (!config.fixedRateExchangeAddress) { + Logger.error(`'fixedRateExchangeAddress' not set in config`) + return + } + + Logger.log('Buying token from exchange', bestPrice, account.getId()) + await ocean.datatokens.approve( + config.oceanTokenAddress, + config.fixedRateExchangeAddress, + bestPrice.value.toString(), + account.getId() + ) + const exchange = await ocean.fixedRateExchange.buyDT( + bestPrice.address, + '1', + account.getId() + ) + Logger.log('DT exchange buy response', exchange) + return exchange + } + } + } +} From 6e5ae7b2ce9d0de782a13b5d1c86427d4c34614f Mon Sep 17 00:00:00 2001 From: alexcos20 Date: Mon, 19 Oct 2020 02:47:12 -0700 Subject: [PATCH 19/31] move to usePricing --- example/src/App.tsx | 4 +- example/src/Pricing.tsx | 57 +++++++ example/src/Publish.tsx | 40 +---- example/src/Trade.tsx | 55 ------- src/hooks/index.ts | 3 +- src/hooks/useCreatePricing/index.ts | 2 - .../useCreatePricing/useCreatePricing.ts | 114 ------------- .../PriceOptions.ts | 0 .../README.md | 16 +- src/hooks/usePricing/index.ts | 2 + .../useTrade.ts => usePricing/usePricing.ts} | 150 ++++++++++++++---- src/hooks/usePublish/DataTokenOptions.ts | 1 - src/hooks/usePublish/README.md | 4 +- src/hooks/usePublish/usePublish.ts | 13 -- src/hooks/useTrade/README.md | 35 ---- src/hooks/useTrade/index.ts | 1 - 16 files changed, 202 insertions(+), 295 deletions(-) create mode 100644 example/src/Pricing.tsx delete mode 100644 example/src/Trade.tsx delete mode 100644 src/hooks/useCreatePricing/index.ts delete mode 100644 src/hooks/useCreatePricing/useCreatePricing.ts rename src/hooks/{useCreatePricing => usePricing}/PriceOptions.ts (100%) rename src/hooks/{useCreatePricing => usePricing}/README.md (60%) create mode 100644 src/hooks/usePricing/index.ts rename src/hooks/{useTrade/useTrade.ts => usePricing/usePricing.ts} (54%) delete mode 100644 src/hooks/useTrade/README.md delete mode 100644 src/hooks/useTrade/index.ts diff --git a/example/src/App.tsx b/example/src/App.tsx index 80dd955..ace802b 100644 --- a/example/src/App.tsx +++ b/example/src/App.tsx @@ -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() {
- +
diff --git a/example/src/Pricing.tsx b/example/src/Pricing.tsx new file mode 100644 index 0000000..c4d63f8 --- /dev/null +++ b/example/src/Pricing.tsx @@ -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() + 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 ( + <> +
Trade Datatoken
+
+ Datatoken +
+
+ +
+
+ +
+
+ +
+
+ IsLoading: {pricingIsLoading.toString()} || Status: {pricingStepText} +
+ + + ) +} diff --git a/example/src/Publish.tsx b/example/src/Publish.tsx index 57066d1..6e7e46c 100644 --- a/example/src/Publish.tsx +++ b/example/src/Publish.tsx @@ -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() 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 ( <>
Publish
@@ -73,13 +51,7 @@ export function Publish() { IsLoading: {isLoading.toString()} || Status: {publishStepText}
DID: {ddo && ddo.id}
-
- -
-
- IsLoading: {pricingIsLoading.toString()} || pricingStatus: {pricingStepText} -
- + ) } diff --git a/example/src/Trade.tsx b/example/src/Trade.tsx deleted file mode 100644 index f880c01..0000000 --- a/example/src/Trade.tsx +++ /dev/null @@ -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() - 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 ( - <> -
Trade Datatoken
-
- DID -
-
- -
-
- -
-
- IsLoading: {tradeIsLoading.toString()} || Status: {tradeStepText} -
- - - ) -} diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 519a8c1..d4c70a6 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -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' diff --git a/src/hooks/useCreatePricing/index.ts b/src/hooks/useCreatePricing/index.ts deleted file mode 100644 index 0982522..0000000 --- a/src/hooks/useCreatePricing/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './useCreatePricing' -export * from './PriceOptions' diff --git a/src/hooks/useCreatePricing/useCreatePricing.ts b/src/hooks/useCreatePricing/useCreatePricing.ts deleted file mode 100644 index 9169470..0000000 --- a/src/hooks/useCreatePricing/useCreatePricing.ts +++ /dev/null @@ -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 - 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() - const [pricingStepText, setPricingStepText] = useState() - const [pricingError, setPricingError] = useState() - const [dtSymbol, setDtSymbol] = useState() - - 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 { - 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 diff --git a/src/hooks/useCreatePricing/PriceOptions.ts b/src/hooks/usePricing/PriceOptions.ts similarity index 100% rename from src/hooks/useCreatePricing/PriceOptions.ts rename to src/hooks/usePricing/PriceOptions.ts diff --git a/src/hooks/useCreatePricing/README.md b/src/hooks/usePricing/README.md similarity index 60% rename from src/hooks/useCreatePricing/README.md rename to src/hooks/usePricing/README.md index 563d572..5ca406f 100644 --- a/src/hooks/useCreatePricing/README.md +++ b/src/hooks/usePricing/README.md @@ -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 (

Post for sale

Your account: {accountId}

+ + +
) } diff --git a/src/hooks/usePricing/index.ts b/src/hooks/usePricing/index.ts new file mode 100644 index 0000000..3b43af5 --- /dev/null +++ b/src/hooks/usePricing/index.ts @@ -0,0 +1,2 @@ +export * from './usePricing' +export * from './PriceOptions' diff --git a/src/hooks/useTrade/useTrade.ts b/src/hooks/usePricing/usePricing.ts similarity index 54% rename from src/hooks/useTrade/useTrade.ts rename to src/hooks/usePricing/usePricing.ts index 8d1380c..a5b1874 100644 --- a/src/hooks/useTrade/useTrade.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -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 buyDT: ( dataTokenAddress: string, dtAmount: number | string @@ -14,12 +19,19 @@ interface UseTrade { dataTokenAddress: string, dtAmount: number | string ) => Promise - 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() - const [tradeStepText, setTradeStepText] = useState() - const [tradeError, setTradeError] = useState() + const [pricingIsLoading, setPricingIsLoading] = useState(false) + const [pricingStep, setPricingStep] = useState() + const [pricingStepText, setPricingStepText] = useState() + const [pricingError, setPricingError] = useState() const [dtSymbol, setDtSymbol] = useState() + 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 { + 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 diff --git a/src/hooks/usePublish/DataTokenOptions.ts b/src/hooks/usePublish/DataTokenOptions.ts index 2579a9c..9bb28fb 100644 --- a/src/hooks/usePublish/DataTokenOptions.ts +++ b/src/hooks/usePublish/DataTokenOptions.ts @@ -1,5 +1,4 @@ export interface DataTokenOptions { - tokensToMint: number cap?: string name?: string symbol?: string diff --git a/src/hooks/usePublish/README.md b/src/hooks/usePublish/README.md index c1e789f..1acab0b 100644 --- a/src/hooks/usePublish/README.md +++ b/src/hooks/usePublish/README.md @@ -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() { diff --git a/src/hooks/usePublish/usePublish.ts b/src/hooks/usePublish/usePublish.ts index 844ef36..2f37b7f 100644 --- a/src/hooks/usePublish/usePublish.ts +++ b/src/hooks/usePublish/usePublish.ts @@ -18,7 +18,6 @@ interface UsePublish { timeout?: number, providerUri?: string ) => Promise - 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, diff --git a/src/hooks/useTrade/README.md b/src/hooks/useTrade/README.md deleted file mode 100644 index e6f0e85..0000000 --- a/src/hooks/useTrade/README.md +++ /dev/null @@ -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 ( -
-

Trade

- - - -
- ) -} -``` diff --git a/src/hooks/useTrade/index.ts b/src/hooks/useTrade/index.ts deleted file mode 100644 index ba87662..0000000 --- a/src/hooks/useTrade/index.ts +++ /dev/null @@ -1 +0,0 @@ -export * from './useTrade' From 95b7849ca6c40c354fc0bdfb0a4f64a20583b211 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Mon, 19 Oct 2020 12:30:58 +0200 Subject: [PATCH 20/31] small refactor, pass DDO, set datatoken symbol --- src/hooks/usePricing/usePricing.ts | 111 ++++++++++++++++------------- 1 file changed, 61 insertions(+), 50 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index a5b1874..aa81d49 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -1,5 +1,5 @@ -import { Logger } from '@oceanprotocol/lib' -import { useState } from 'react' +import { DDO, Logger } from '@oceanprotocol/lib' +import { useEffect, useState } from 'react' import { useOcean } from 'providers' import { PriceOptions } from './PriceOptions' import { TransactionReceipt } from 'web3-core' @@ -8,18 +8,11 @@ import { Decimal } from 'decimal.js' interface UsePricing { createPricing: ( - dataTokenAddress: string, priceOptions: PriceOptions ) => Promise - buyDT: ( - dataTokenAddress: string, - dtAmount: number | string - ) => Promise - sellDT: ( - dataTokenAddress: string, - dtAmount: number | string - ) => Promise - mint: (tokenAddress: string, tokensToMint: string) => void + buyDT: (dtAmount: number | string) => Promise + sellDT: (dtAmount: number | string) => Promise + mint: (tokensToMint: string) => void pricingStep?: number pricingStepText?: string pricingError?: string @@ -32,70 +25,87 @@ export const createPricingFeedback: { [key in number]: string } = { 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 ...', 2: '3/3 DT Bought' } + export const sellDTFeedback: { [key in number]: string } = { 0: '1/3 Approving DT ...', 1: '2/3 Selling DT ...', 2: '3/3 DT sold' } -function usePricing(): UsePricing { - const { ocean, status, account, accountId, config } = useOcean() + +function usePricing(ddo: DDO): UsePricing { + const { ocean, account, accountId, config } = useOcean() const [pricingIsLoading, setPricingIsLoading] = useState(false) - const [pricingStep, setPricingStep] = useState() - const [pricingStepText, setPricingStepText] = useState() - const [pricingError, setPricingError] = useState() + const [pricingStep, setPricingStep] = useState() + const [pricingStepText, setPricingStepText] = useState() + const [pricingError, setPricingError] = useState() const [dtSymbol, setDtSymbol] = useState() + const { dataToken, dataTokenInfo } = ddo + + // Get Datatoken symbol, from DDO first, then from chain + useEffect(() => { + if (!dataToken) return + + async function init() { + const dtSymbol = + dataTokenInfo?.symbol || (await ocean?.datatokens.getSymbol(dataToken)) + setDtSymbol(dtSymbol) + } + init() + }, [ocean, dataToken, dataTokenInfo?.symbol]) + 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) - } + if (!index) return + + const message = dtSymbol + ? createPricingFeedback[index].replace(/DT/g, dtSymbol) + : createPricingFeedback[index] + setPricingStepText(message) } function setStepBuyDT(index?: number) { setPricingStep(index) - let message - if (index) { - if (dtSymbol) message = buyDTFeedback[index].replace(/DT/g, dtSymbol) - else message = buyDTFeedback[index] - setPricingStepText(message) - } + if (!index) return + + const message = dtSymbol + ? buyDTFeedback[index].replace(/DT/g, dtSymbol) + : buyDTFeedback[index] + setPricingStepText(message) } function setStepSellDT(index?: number) { setPricingStep(index) - let message - if (index) { - if (dtSymbol) message = sellDTFeedback[index].replace(/DT/g, dtSymbol) - else message = sellDTFeedback[index] - setPricingStepText(message) - } + if (!index) return + + const message = dtSymbol + ? sellDTFeedback[index].replace(/DT/g, dtSymbol) + : sellDTFeedback[index] + setPricingStepText(message) } - async function mint(tokenAddress: string, tokensToMint: string) { - Logger.log('mint function', tokenAddress, accountId) - await ocean.datatokens.mint(tokenAddress, accountId, tokensToMint) + async function mint(tokensToMint: string) { + Logger.log('mint function', dataToken, accountId) + await ocean.datatokens.mint(dataToken, accountId, tokensToMint) } + async function buyDT( - dataTokenAddress: string, dtAmount: number | string ): Promise { if (!ocean || !account || !accountId) return null try { - setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) + setDtSymbol(await ocean.datatokens.getSymbol(dataToken)) setPricingIsLoading(true) setPricingError(undefined) setStepBuyDT(0) - const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) + const bestPrice = await getBestDataTokenPrice(ocean, dataToken) + switch (bestPrice?.type) { case 'pool': { const price = new Decimal(bestPrice.value).times(1.05).toString() @@ -157,20 +167,21 @@ function usePricing(): UsePricing { } async function sellDT( - dataTokenAddress: string, dtAmount: number | string ): Promise { if (!ocean || !account || !accountId) return null + if (!config.oceanTokenAddress) { Logger.error(`'oceanTokenAddress' not set in config`) return null } + try { - setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) + setDtSymbol(await ocean.datatokens.getSymbol(dataToken)) setPricingIsLoading(true) setPricingError(undefined) setStepSellDT(0) - const pool = await getFirstPool(ocean, dataTokenAddress) + const pool = await getFirstPool(ocean, dataToken) if (!pool || pool.price === 0) return null const price = new Decimal(pool.price).times(0.95).toString() setStepSellDT(1) @@ -196,7 +207,6 @@ function usePricing(): UsePricing { } async function createPricing( - dataTokenAddress: string, priceOptions: PriceOptions ): Promise { if (!ocean || !account || !accountId) return null @@ -205,14 +215,15 @@ function usePricing(): UsePricing { try { setPricingIsLoading(true) setPricingError(undefined) - setDtSymbol(await ocean.datatokens.getSymbol(dataTokenAddress)) + setDtSymbol(await ocean.datatokens.getSymbol(dataToken)) setStepCreatePricing(0) + switch (priceOptions.type) { case 'dynamic': { setStepCreatePricing(2) response = await ocean.pool.createDTPool( accountId, - dataTokenAddress, + dataToken, priceOptions.dtAmount.toString(), priceOptions.weightOnDataToken, priceOptions.swapFee @@ -227,13 +238,13 @@ function usePricing(): UsePricing { } setStepCreatePricing(2) response = await ocean.fixedRateExchange.create( - dataTokenAddress, + dataToken, priceOptions.price.toString(), accountId ) setStepCreatePricing(1) await ocean.datatokens.approve( - dataTokenAddress, + dataToken, config.fixedRateExchangeAddress, String(priceOptions.dtAmount), accountId From c7a355e6fa4e617a7304b33c6114b8a8f4876e33 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Mon, 19 Oct 2020 12:44:31 +0200 Subject: [PATCH 21/31] output datatoken name & symbol --- src/hooks/usePricing/usePricing.ts | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index aa81d49..7c33299 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -7,6 +7,8 @@ import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils' import { Decimal } from 'decimal.js' interface UsePricing { + dtSymbol: string | undefined + dtName: string | undefined createPricing: ( priceOptions: PriceOptions ) => Promise @@ -45,20 +47,27 @@ function usePricing(ddo: DDO): UsePricing { const [pricingStepText, setPricingStepText] = useState() const [pricingError, setPricingError] = useState() const [dtSymbol, setDtSymbol] = useState() + const [dtName, setDtName] = useState() const { dataToken, dataTokenInfo } = ddo - // Get Datatoken symbol, from DDO first, then from chain + // Get Datatoken info, from DDO first, then from chain useEffect(() => { if (!dataToken) return async function init() { - const dtSymbol = - dataTokenInfo?.symbol || (await ocean?.datatokens.getSymbol(dataToken)) + const dtSymbol = dataTokenInfo + ? dataTokenInfo.symbol + : await ocean?.datatokens.getSymbol(dataToken) setDtSymbol(dtSymbol) + + const dtName = dataTokenInfo + ? dataTokenInfo.name + : await ocean?.datatokens.getName(dataToken) + setDtName(dtName) } init() - }, [ocean, dataToken, dataTokenInfo?.symbol]) + }, [ocean, dataToken, dataTokenInfo]) function setStepCreatePricing(index?: number) { setPricingStep(index) @@ -265,6 +274,8 @@ function usePricing(ddo: DDO): UsePricing { } return { + dtSymbol, + dtName, createPricing, buyDT, sellDT, From a565e83220e488abaecc9a99ec6dc951fd60243f Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Mon, 19 Oct 2020 13:03:36 +0200 Subject: [PATCH 22/31] usePricing docs update --- src/hooks/usePricing/README.md | 24 ++++++++++++------------ 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/hooks/usePricing/README.md b/src/hooks/usePricing/README.md index 5ca406f..d7ce3f5 100644 --- a/src/hooks/usePricing/README.md +++ b/src/hooks/usePricing/README.md @@ -1,20 +1,20 @@ # `usePricing` -Hook with helper utilities to create fixed price exchanges or liquidity pools for your data set, mint datatokens , buy and sell datatokens +Hook with helper utilities to create fixed price exchanges or liquidity pools for your data set, mint datatokens, and buy and sell datatokens. ## Usage ```tsx import React from 'react' import { useOcean, useCreatePricing } from '@oceanprotocol/react' -import { Metadata } from '@oceanprotocol/lib' +import { Metadata, DDO } from '@oceanprotocol/lib' -export default function MyComponent() { +export default function MyComponent({ ddo }: { ddo: DDO }) { const { accountId } = useOcean() - const dataTokenAddress = '0x00000' + // Publish helpers - const { createPricing } = usePricing() - + const { createPricing } = usePricing(ddo) + const priceOptions = { price: 10, dtAmount: 10, @@ -24,19 +24,19 @@ export default function MyComponent() { } async function handleCreatePricing() { - await createPricing(dataTokenAddress, priceOptions) + await createPricing(priceOptions) } async function handleMint() { - await mint(dataTokenAddress, '1') + await mint('1') } async function handleBuyDT() { - await buyDT(dataTokenAddress, '1') + await buyDT('1') } async function handleSellDT() { - await sellDT(dataTokenAddress, '1') + await sellDT('1') } - + return (

Post for sale

@@ -44,7 +44,7 @@ export default function MyComponent() {

Your account: {accountId}

- +
) From bf689e7c02077ce261b2c2bde619b96dc3a5b09c Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Mon, 19 Oct 2020 13:11:53 +0200 Subject: [PATCH 23/31] remove redundant symbol calls --- src/hooks/usePricing/usePricing.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 7c33299..94c8f9f 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -7,8 +7,8 @@ import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils' import { Decimal } from 'decimal.js' interface UsePricing { - dtSymbol: string | undefined - dtName: string | undefined + dtSymbol?: string + dtName?: string createPricing: ( priceOptions: PriceOptions ) => Promise @@ -109,7 +109,6 @@ function usePricing(ddo: DDO): UsePricing { if (!ocean || !account || !accountId) return null try { - setDtSymbol(await ocean.datatokens.getSymbol(dataToken)) setPricingIsLoading(true) setPricingError(undefined) setStepBuyDT(0) @@ -186,7 +185,6 @@ function usePricing(ddo: DDO): UsePricing { } try { - setDtSymbol(await ocean.datatokens.getSymbol(dataToken)) setPricingIsLoading(true) setPricingError(undefined) setStepSellDT(0) @@ -224,7 +222,6 @@ function usePricing(ddo: DDO): UsePricing { try { setPricingIsLoading(true) setPricingError(undefined) - setDtSymbol(await ocean.datatokens.getSymbol(dataToken)) setStepCreatePricing(0) switch (priceOptions.type) { From bc62cbc22e7aa27a4ee4f7c72db2d57e141bd10d Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Mon, 19 Oct 2020 13:18:18 +0200 Subject: [PATCH 24/31] docs updates --- src/hooks/useConsume/README.md | 7 +++++++ src/hooks/useConsume/useConsume.ts | 3 ++- src/hooks/usePricing/README.md | 10 ++++++++-- src/providers/OceanProvider/OceanProvider.tsx | 2 +- 4 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/hooks/useConsume/README.md b/src/hooks/useConsume/README.md index 516a200..8de4a67 100644 --- a/src/hooks/useConsume/README.md +++ b/src/hooks/useConsume/README.md @@ -9,6 +9,7 @@ import React from 'react' import { useOcean, useConsume } from '@oceanprotocol/react' const did = 'did:op:0x000000000' +const dtBalance = 20 export default function MyComponent() { const { accountId } = useOcean() @@ -16,10 +17,16 @@ export default function MyComponent() { // Get metadata for this asset const { title, price, ddo } = useMetadata(did) + // Pricing helpers + const { buyDT } = usePricing(ddo) + // Consume helpers const { consume, consumeStep } = useConsume() + const hasDatatoken = dtBalance >= 1 + async function handleDownload() { + !hasDatatoken && (await buyDT('1')) await consume(did, ddo.dataToken, 'access') } diff --git a/src/hooks/useConsume/useConsume.ts b/src/hooks/useConsume/useConsume.ts index 6ec61d4..c46215a 100644 --- a/src/hooks/useConsume/useConsume.ts +++ b/src/hooks/useConsume/useConsume.ts @@ -25,7 +25,7 @@ export const consumeFeedback: { [key in number]: string } = { } function useConsume(): UseConsume { - const { ocean, account, accountId, config } = useOcean() + const { ocean, account, accountId } = useOcean() const [isLoading, setIsLoading] = useState(false) const [consumeStep, setConsumeStep] = useState() const [consumeStepText, setConsumeStepText] = useState() @@ -43,6 +43,7 @@ function useConsume(): UseConsume { marketFeeAddress: string ): Promise { if (!ocean || !account || !accountId) return + setIsLoading(true) setConsumeError(undefined) diff --git a/src/hooks/usePricing/README.md b/src/hooks/usePricing/README.md index d7ce3f5..4dd0e84 100644 --- a/src/hooks/usePricing/README.md +++ b/src/hooks/usePricing/README.md @@ -12,8 +12,14 @@ import { Metadata, DDO } from '@oceanprotocol/lib' export default function MyComponent({ ddo }: { ddo: DDO }) { const { accountId } = useOcean() - // Publish helpers - const { createPricing } = usePricing(ddo) + // Pricing helpers + const { + createPricing, + buyDT, + sellDT, + pricingStepText, + pricingError + } = usePricing(ddo) const priceOptions = { price: 10, diff --git a/src/providers/OceanProvider/OceanProvider.tsx b/src/providers/OceanProvider/OceanProvider.tsx index 5d3f0a6..871c60f 100644 --- a/src/providers/OceanProvider/OceanProvider.tsx +++ b/src/providers/OceanProvider/OceanProvider.tsx @@ -137,7 +137,7 @@ function OceanProvider({ } async function logout() { // TODO: #67 check how is the proper way to logout - if (web3Modal) web3Modal.clearCachedProvider() + web3Modal?.clearCachedProvider() } // TODO: #68 Refetch balance periodically, or figure out some event to subscribe to From 1cd3c6055da34e1ce97d5a623595aa22cf497a43 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Mon, 19 Oct 2020 13:39:14 +0200 Subject: [PATCH 25/31] publish tweaks --- src/hooks/useConsume/useConsume.ts | 1 + src/hooks/usePublish/README.md | 12 +++++------- src/hooks/usePublish/usePublish.ts | 11 ++++------- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/hooks/useConsume/useConsume.ts b/src/hooks/useConsume/useConsume.ts index c46215a..8e2677a 100644 --- a/src/hooks/useConsume/useConsume.ts +++ b/src/hooks/useConsume/useConsume.ts @@ -57,6 +57,7 @@ function useConsume(): UseConsume { setConsumeError('Not enough datatokens') } else { setStep(1) + ocean.datatokens.generateDtName() const tokenTransfer = await ocean.assets.order( did as string, serviceType, diff --git a/src/hooks/usePublish/README.md b/src/hooks/usePublish/README.md index 1acab0b..b985aae 100644 --- a/src/hooks/usePublish/README.md +++ b/src/hooks/usePublish/README.md @@ -1,6 +1,6 @@ # `usePublish` -Create datatoken and publish data sets +Publish data sets and create datatokens for them. ## Usage @@ -10,7 +10,7 @@ import { useOcean, usePublish } from '@oceanprotocol/react' import { Metadata } from '@oceanprotocol/lib' export default function MyComponent() { - const { accountId } = useOcean() + const { ocean, accountId } = useOcean() // Publish helpers const { publish, publishStep } = usePublish() @@ -24,12 +24,10 @@ export default function MyComponent() { } } - const dataTokenOptions = { - - } - async function handlePublish() { - const ddo = await publish(metadata, 'access', dataTokenOptions) + const ddo = await publish(metadata, 'access') + // Heads Up! You should now create pricing for your data set + // with the `usePricing()` hook in another step. } return ( diff --git a/src/hooks/usePublish/usePublish.ts b/src/hooks/usePublish/usePublish.ts index 2f37b7f..e87c76a 100644 --- a/src/hooks/usePublish/usePublish.ts +++ b/src/hooks/usePublish/usePublish.ts @@ -14,7 +14,7 @@ interface UsePublish { publish: ( asset: Metadata, serviceConfigs: ServiceType, - dataTokenOptions: DataTokenOptions, + dataTokenOptions?: DataTokenOptions, timeout?: number, providerUri?: string ) => Promise @@ -25,7 +25,7 @@ interface UsePublish { } function usePublish(): UsePublish { - const { ocean, status, account, accountId, config } = useOcean() + const { ocean, status, account } = useOcean() const [isLoading, setIsLoading] = useState(false) const [publishStep, setPublishStep] = useState() const [publishStepText, setPublishStepText] = useState() @@ -46,7 +46,7 @@ function usePublish(): UsePublish { async function publish( asset: Metadata, serviceType: ServiceType, - dataTokenOptions: DataTokenOptions, + dataTokenOptions?: DataTokenOptions, timeout?: number, providerUri?: string ): Promise { @@ -57,10 +57,9 @@ function usePublish(): UsePublish { try { const publishedDate = new Date(Date.now()).toISOString().split('.')[0] + 'Z' - let timeout = 0 const services: Service[] = [] - const price = '1' + switch (serviceType) { case 'access': { if (!timeout) timeout = 0 @@ -142,8 +141,6 @@ function usePublish(): UsePublish { .next(setStep) Logger.log('ddo created', ddo) setStep(7) - // await createPricing(priceOptions, ddo.dataToken, tokensToMint) - // setStep(8) return ddo } catch (error) { setPublishError(error.message) From 7c5eba07c35a7833cda15473adff20626014666d Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 21 Oct 2020 00:31:32 +0200 Subject: [PATCH 26/31] refactor createPricing --- src/hooks/usePricing/usePricing.ts | 112 ++++++++++++++--------------- 1 file changed, 56 insertions(+), 56 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 94c8f9f..f5a18fd 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -11,10 +11,10 @@ interface UsePricing { dtName?: string createPricing: ( priceOptions: PriceOptions - ) => Promise - buyDT: (dtAmount: number | string) => Promise - sellDT: (dtAmount: number | string) => Promise - mint: (tokensToMint: string) => void + ) => Promise + buyDT: (dtAmount: number | string) => Promise + sellDT: (dtAmount: number | string) => Promise + mint: (tokensToMint: string) => Promise pricingStep?: number pricingStepText?: string pricingError?: string @@ -22,10 +22,11 @@ interface UsePricing { } 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' + 0: 'Minting DT ...', + 1: 'Approving DT ...', + 2: 'Approving Ocean ...', + 3: 'Creating ...', + 4: 'Pricing created.' } export const buyDTFeedback: { [key in number]: string } = { @@ -98,15 +99,16 @@ function usePricing(ddo: DDO): UsePricing { setPricingStepText(message) } - async function mint(tokensToMint: string) { + async function mint(tokensToMint: string): Promise { Logger.log('mint function', dataToken, accountId) - await ocean.datatokens.mint(dataToken, accountId, tokensToMint) + const tx = await ocean.datatokens.mint(dataToken, accountId, tokensToMint) + return tx } async function buyDT( dtAmount: number | string - ): Promise { - if (!ocean || !account || !accountId) return null + ): Promise { + if (!ocean || !account || !accountId) return try { setPricingIsLoading(true) @@ -139,11 +141,11 @@ function usePricing(ddo: DDO): UsePricing { case 'exchange': { if (!config.oceanTokenAddress) { Logger.error(`'oceanTokenAddress' not set in config`) - return null + return } if (!config.fixedRateExchangeAddress) { Logger.error(`'fixedRateExchangeAddress' not set in config`) - return null + return } Logger.log('Buying token from exchange', bestPrice, account.getId()) await ocean.datatokens.approve( @@ -171,17 +173,16 @@ function usePricing(ddo: DDO): UsePricing { setPricingStepText(undefined) setPricingIsLoading(false) } - return null } async function sellDT( dtAmount: number | string - ): Promise { - if (!ocean || !account || !accountId) return null + ): Promise { + if (!ocean || !account || !accountId) return if (!config.oceanTokenAddress) { Logger.error(`'oceanTokenAddress' not set in config`) - return null + return } try { @@ -189,7 +190,7 @@ function usePricing(ddo: DDO): UsePricing { setPricingError(undefined) setStepSellDT(0) const pool = await getFirstPool(ocean, dataToken) - if (!pool || pool.price === 0) return null + if (!pool || pool.price === 0) return const price = new Decimal(pool.price).times(0.95).toString() setStepSellDT(1) Logger.log('Selling token to pool', pool, account.getId(), price) @@ -210,55 +211,55 @@ function usePricing(ddo: DDO): UsePricing { setPricingStepText(undefined) setPricingIsLoading(false) } - return null } async function createPricing( priceOptions: PriceOptions - ): Promise { - if (!ocean || !account || !accountId) return null + ): Promise { + if (!ocean || !account || !accountId) return + + const { type, dtAmount, price, weightOnDataToken, swapFee } = priceOptions + const isPool = type === 'dynamic' + + if (!isPool && !config.fixedRateExchangeAddress) { + Logger.error(`'fixedRateExchangeAddress' not set in ccnfig.`) + return + } - let response = null try { setPricingIsLoading(true) setPricingError(undefined) - setStepCreatePricing(0) - switch (priceOptions.type) { - case 'dynamic': { - setStepCreatePricing(2) - response = await ocean.pool.createDTPool( + setStepCreatePricing(0) + await mint(`${dtAmount}`) + + setStepCreatePricing(3) + const response = isPool + ? // TODO: in ocean.js: ocean.pool.createDTPool should be ocean.pool.create + // And if it involves mutliple wallet interacts the method itself should emit step events. + await ocean.pool.createDTPool( accountId, dataToken, - priceOptions.dtAmount.toString(), - priceOptions.weightOnDataToken, - priceOptions.swapFee + `${dtAmount}`, + weightOnDataToken, + 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( - dataToken, - priceOptions.price.toString(), - accountId - ) - setStepCreatePricing(1) - await ocean.datatokens.approve( - dataToken, - config.fixedRateExchangeAddress, - String(priceOptions.dtAmount), - accountId - ) - setStepCreatePricing(3) - return response - } + : // TODO: in ocean.js: ocean.fixedRateExchange.create should return tx receipt + await ocean.fixedRateExchange.create(dataToken, `${price}`, accountId) + + // TODO: why is approve after the creation? + if (!isPool && config.fixedRateExchangeAddress) { + setStepCreatePricing(1) + await ocean.datatokens.approve( + dataToken, + config.fixedRateExchangeAddress, + `${dtAmount}`, + accountId + ) } + + setStepCreatePricing(4) + return response } catch (error) { setPricingError(error.message) Logger.error(error) @@ -267,7 +268,6 @@ function usePricing(ddo: DDO): UsePricing { setPricingStepText(undefined) setPricingIsLoading(false) } - return null } return { From 30fd0b22581d9a697c6b812084d225da6c0a4dbe Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 21 Oct 2020 11:36:34 +0200 Subject: [PATCH 27/31] bump ocean.js --- package-lock.json | 6 +++--- package.json | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/package-lock.json b/package-lock.json index 8b29263..2728109 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1521,9 +1521,9 @@ "integrity": "sha512-LING+GvW37I0L40rZdPCZ1SvcZurDSGGhT0WOVPNO8oyh2C3bXModDBNE4+gCFa8pTbQBOc4ot1/Zoj9PfT/zA==" }, "@oceanprotocol/lib": { - "version": "0.6.5", - "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-0.6.5.tgz", - "integrity": "sha512-GH7ZujwmV997kZT4GJy7cZF0TBitM/RVm+xBLtqpr5qmrP/4Pq38WODbOol3dGEHsyT62qzDTvCGoBYSRSCU1g==", + "version": "0.6.7", + "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-0.6.7.tgz", + "integrity": "sha512-6Il5PJfaZXXkXO8ECZCsH13OOGlPaN9vK3pLW9EQ6Zj9NlESeLdh0lmvvYSyvloYU999rOY4+X9ujhN6P18clw==", "requires": { "@ethereum-navigator/navigator": "^0.5.0", "@oceanprotocol/contracts": "^0.5.6", diff --git a/package.json b/package.json index 23e07c4..e392bbf 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "dist/" ], "dependencies": { - "@oceanprotocol/lib": "^0.6.5", + "@oceanprotocol/lib": "^0.6.7", "axios": "^0.20.0", "decimal.js": "^10.2.1", "web3": "^1.3.0", From 1caa9e1b69c2814691c60d9d100f38762f9a8237 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 21 Oct 2020 12:32:43 +0200 Subject: [PATCH 28/31] refactor messages --- src/hooks/usePricing/usePricing.ts | 100 ++++++++++++++--------------- 1 file changed, 49 insertions(+), 51 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index f5a18fd..5cbdd24 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -21,24 +21,30 @@ interface UsePricing { pricingIsLoading: boolean } -export const createPricingFeedback: { [key in number]: string } = { - 0: 'Minting DT ...', - 1: 'Approving DT ...', - 2: 'Approving Ocean ...', - 3: 'Creating ...', - 4: 'Pricing created.' +function getCreatePricingFeedback(dtSymbol: string): { [key: number]: string } { + return { + 1: `Minting ${dtSymbol} ...`, + 2: `Approving ${dtSymbol} ...`, + 3: 'Approving OCEAN ...', + 4: 'Creating ...', + 5: 'Pricing created.' + } } -export const buyDTFeedback: { [key in number]: string } = { - 0: '1/3 Approving OCEAN ...', - 1: '2/3 Buying DT ...', - 2: '3/3 DT Bought' +function getBuyDTFeedback(dtSymbol: string): { [key: number]: string } { + return { + 1: '1/3 Approving OCEAN ...', + 2: `2/3 Buying ${dtSymbol} ...`, + 3: `3/3 ${dtSymbol} bought.` + } } -export const sellDTFeedback: { [key in number]: string } = { - 0: '1/3 Approving DT ...', - 1: '2/3 Selling DT ...', - 2: '3/3 DT sold' +function getSellDTFeedback(dtSymbol: string): { [key: number]: string } { + return { + 1: '1/3 Approving OCEAN ...', + 2: `2/3 Selling ${dtSymbol} ...`, + 3: `3/3 ${dtSymbol} sold.` + } } function usePricing(ddo: DDO): UsePricing { @@ -70,33 +76,25 @@ function usePricing(ddo: DDO): UsePricing { init() }, [ocean, dataToken, dataTokenInfo]) - function setStepCreatePricing(index?: number) { + function setStepCreatePricing(index: number) { setPricingStep(index) - if (!index) return - - const message = dtSymbol - ? createPricingFeedback[index].replace(/DT/g, dtSymbol) - : createPricingFeedback[index] - setPricingStepText(message) + if (!dtSymbol) return + const messages = getCreatePricingFeedback(dtSymbol) + setPricingStepText(messages[index]) } - function setStepBuyDT(index?: number) { + function setStepBuyDT(index: number) { setPricingStep(index) - if (!index) return - - const message = dtSymbol - ? buyDTFeedback[index].replace(/DT/g, dtSymbol) - : buyDTFeedback[index] - setPricingStepText(message) + if (!dtSymbol) return + const messages = getBuyDTFeedback(dtSymbol) + setPricingStepText(messages[index]) } - function setStepSellDT(index?: number) { - setPricingStep(index) - if (!index) return - const message = dtSymbol - ? sellDTFeedback[index].replace(/DT/g, dtSymbol) - : sellDTFeedback[index] - setPricingStepText(message) + function setStepSellDT(index: number) { + setPricingStep(index) + if (!dtSymbol) return + const messages = getSellDTFeedback(dtSymbol) + setPricingStepText(messages[index]) } async function mint(tokensToMint: string): Promise { @@ -113,14 +111,14 @@ function usePricing(ddo: DDO): UsePricing { try { setPricingIsLoading(true) setPricingError(undefined) - setStepBuyDT(0) + setStepBuyDT(1) const bestPrice = await getBestDataTokenPrice(ocean, dataToken) switch (bestPrice?.type) { case 'pool': { const price = new Decimal(bestPrice.value).times(1.05).toString() const maxPrice = new Decimal(bestPrice.value).times(2).toString() - setStepBuyDT(1) + setStepBuyDT(2) Logger.log( 'Buying token from pool', bestPrice, @@ -134,7 +132,7 @@ function usePricing(ddo: DDO): UsePricing { price, maxPrice ) - setStepBuyDT(2) + setStepBuyDT(3) Logger.log('DT buy response', buyResponse) return buyResponse } @@ -154,13 +152,13 @@ function usePricing(ddo: DDO): UsePricing { bestPrice.value.toString(), account.getId() ) - setStepBuyDT(1) + setStepBuyDT(2) const exchange = await ocean.fixedRateExchange.buyDT( bestPrice.address, String(dtAmount), account.getId() ) - setStepBuyDT(2) + setStepBuyDT(3) Logger.log('DT exchange buy response', exchange) return exchange } @@ -169,7 +167,7 @@ function usePricing(ddo: DDO): UsePricing { setPricingError(error.message) Logger.error(error) } finally { - setStepBuyDT(undefined) + setStepBuyDT(0) setPricingStepText(undefined) setPricingIsLoading(false) } @@ -188,11 +186,11 @@ function usePricing(ddo: DDO): UsePricing { try { setPricingIsLoading(true) setPricingError(undefined) - setStepSellDT(0) + setStepSellDT(1) const pool = await getFirstPool(ocean, dataToken) if (!pool || pool.price === 0) return const price = new Decimal(pool.price).times(0.95).toString() - setStepSellDT(1) + setStepSellDT(2) Logger.log('Selling token to pool', pool, account.getId(), price) const sellResponse = await ocean.pool.sellDT( account.getId(), @@ -200,14 +198,14 @@ function usePricing(ddo: DDO): UsePricing { String(dtAmount), price ) - setStepSellDT(2) + setStepSellDT(3) Logger.log('DT sell response', sellResponse) return sellResponse } catch (error) { setPricingError(error.message) Logger.error(error) } finally { - setStepSellDT(undefined) + setStepSellDT(0) setPricingStepText(undefined) setPricingIsLoading(false) } @@ -216,7 +214,7 @@ function usePricing(ddo: DDO): UsePricing { async function createPricing( priceOptions: PriceOptions ): Promise { - if (!ocean || !account || !accountId) return + if (!ocean || !account || !accountId || !dtSymbol) return const { type, dtAmount, price, weightOnDataToken, swapFee } = priceOptions const isPool = type === 'dynamic' @@ -226,11 +224,11 @@ function usePricing(ddo: DDO): UsePricing { return } - try { - setPricingIsLoading(true) - setPricingError(undefined) + setPricingIsLoading(true) + setPricingError(undefined) + setStepCreatePricing(1) - setStepCreatePricing(0) + try { await mint(`${dtAmount}`) setStepCreatePricing(3) @@ -264,7 +262,7 @@ function usePricing(ddo: DDO): UsePricing { setPricingError(error.message) Logger.error(error) } finally { - setPricingStep(undefined) + setPricingStep(0) setPricingStepText(undefined) setPricingIsLoading(false) } From a9e8c10c58dbbe23cf1b13242b669c868e24bc6a Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 21 Oct 2020 13:37:01 +0200 Subject: [PATCH 29/31] refactor for event subscription --- src/hooks/usePricing/usePricing.ts | 127 +++++++++++++---------------- src/hooks/usePricing/utils.ts | 40 +++++++++ 2 files changed, 97 insertions(+), 70 deletions(-) create mode 100644 src/hooks/usePricing/utils.ts diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 5cbdd24..69f1ed2 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -5,6 +5,12 @@ import { PriceOptions } from './PriceOptions' import { TransactionReceipt } from 'web3-core' import { getBestDataTokenPrice, getFirstPool } from 'utils/dtUtils' import { Decimal } from 'decimal.js' +import { + getCreatePricingPoolFeedback, + getCreatePricingExchangeFeedback, + getBuyDTFeedback, + getSellDTFeedback +} from './utils' interface UsePricing { dtSymbol?: string @@ -21,32 +27,6 @@ interface UsePricing { pricingIsLoading: boolean } -function getCreatePricingFeedback(dtSymbol: string): { [key: number]: string } { - return { - 1: `Minting ${dtSymbol} ...`, - 2: `Approving ${dtSymbol} ...`, - 3: 'Approving OCEAN ...', - 4: 'Creating ...', - 5: 'Pricing created.' - } -} - -function getBuyDTFeedback(dtSymbol: string): { [key: number]: string } { - return { - 1: '1/3 Approving OCEAN ...', - 2: `2/3 Buying ${dtSymbol} ...`, - 3: `3/3 ${dtSymbol} bought.` - } -} - -function getSellDTFeedback(dtSymbol: string): { [key: number]: string } { - return { - 1: '1/3 Approving OCEAN ...', - 2: `2/3 Selling ${dtSymbol} ...`, - 3: `3/3 ${dtSymbol} sold.` - } -} - function usePricing(ddo: DDO): UsePricing { const { ocean, account, accountId, config } = useOcean() const [pricingIsLoading, setPricingIsLoading] = useState(false) @@ -76,24 +56,28 @@ function usePricing(ddo: DDO): UsePricing { init() }, [ocean, dataToken, dataTokenInfo]) - function setStepCreatePricing(index: number) { + // Helper for setting steps & feedback for all flows + function setStep(index: number, type: 'pool' | 'exchange' | 'buy' | 'sell') { setPricingStep(index) if (!dtSymbol) return - const messages = getCreatePricingFeedback(dtSymbol) - setPricingStepText(messages[index]) - } - function setStepBuyDT(index: number) { - setPricingStep(index) - if (!dtSymbol) return - const messages = getBuyDTFeedback(dtSymbol) - setPricingStepText(messages[index]) - } + let messages + + switch (type) { + case 'pool': + messages = getCreatePricingPoolFeedback(dtSymbol) + break + case 'exchange': + messages = getCreatePricingExchangeFeedback(dtSymbol) + break + case 'buy': + messages = getBuyDTFeedback(dtSymbol) + break + case 'sell': + messages = getSellDTFeedback(dtSymbol) + break + } - function setStepSellDT(index: number) { - setPricingStep(index) - if (!dtSymbol) return - const messages = getSellDTFeedback(dtSymbol) setPricingStepText(messages[index]) } @@ -111,14 +95,14 @@ function usePricing(ddo: DDO): UsePricing { try { setPricingIsLoading(true) setPricingError(undefined) - setStepBuyDT(1) + setStep(1, 'buy') const bestPrice = await getBestDataTokenPrice(ocean, dataToken) switch (bestPrice?.type) { case 'pool': { const price = new Decimal(bestPrice.value).times(1.05).toString() const maxPrice = new Decimal(bestPrice.value).times(2).toString() - setStepBuyDT(2) + setStep(2, 'buy') Logger.log( 'Buying token from pool', bestPrice, @@ -132,7 +116,7 @@ function usePricing(ddo: DDO): UsePricing { price, maxPrice ) - setStepBuyDT(3) + setStep(3, 'buy') Logger.log('DT buy response', buyResponse) return buyResponse } @@ -152,13 +136,13 @@ function usePricing(ddo: DDO): UsePricing { bestPrice.value.toString(), account.getId() ) - setStepBuyDT(2) + setStep(2, 'buy') const exchange = await ocean.fixedRateExchange.buyDT( bestPrice.address, String(dtAmount), account.getId() ) - setStepBuyDT(3) + setStep(3, 'buy') Logger.log('DT exchange buy response', exchange) return exchange } @@ -167,7 +151,7 @@ function usePricing(ddo: DDO): UsePricing { setPricingError(error.message) Logger.error(error) } finally { - setStepBuyDT(0) + setStep(0, 'buy') setPricingStepText(undefined) setPricingIsLoading(false) } @@ -186,11 +170,11 @@ function usePricing(ddo: DDO): UsePricing { try { setPricingIsLoading(true) setPricingError(undefined) - setStepSellDT(1) + setStep(1, 'sell') const pool = await getFirstPool(ocean, dataToken) if (!pool || pool.price === 0) return const price = new Decimal(pool.price).times(0.95).toString() - setStepSellDT(2) + setStep(2, 'sell') Logger.log('Selling token to pool', pool, account.getId(), price) const sellResponse = await ocean.pool.sellDT( account.getId(), @@ -198,14 +182,14 @@ function usePricing(ddo: DDO): UsePricing { String(dtAmount), price ) - setStepSellDT(3) + setStep(3, 'sell') Logger.log('DT sell response', sellResponse) return sellResponse } catch (error) { setPricingError(error.message) Logger.error(error) } finally { - setStepSellDT(0) + setStep(0, 'sell') setPricingStepText(undefined) setPricingIsLoading(false) } @@ -226,38 +210,39 @@ function usePricing(ddo: DDO): UsePricing { setPricingIsLoading(true) setPricingError(undefined) - setStepCreatePricing(1) + + let tx try { + setStep(9, 'pool') await mint(`${dtAmount}`) - setStepCreatePricing(3) - const response = isPool - ? // TODO: in ocean.js: ocean.pool.createDTPool should be ocean.pool.create - // And if it involves mutliple wallet interacts the method itself should emit step events. - await ocean.pool.createDTPool( + if (isPool) { + setStep(1, 'pool') + tx = await ocean.pool + .create( accountId, dataToken, `${dtAmount}`, weightOnDataToken, swapFee ) - : // TODO: in ocean.js: ocean.fixedRateExchange.create should return tx receipt - await ocean.fixedRateExchange.create(dataToken, `${price}`, accountId) + .next((step: number) => setStep(step, 'pool')) + } else { + setStep(1, 'exchange') + tx = await ocean.fixedRateExchange + .create(dataToken, `${price}`, accountId) + .next((step: number) => setStep(step, 'exchange')) - // TODO: why is approve after the creation? - if (!isPool && config.fixedRateExchangeAddress) { - setStepCreatePricing(1) - await ocean.datatokens.approve( - dataToken, - config.fixedRateExchangeAddress, - `${dtAmount}`, - accountId - ) + setStep(1, 'exchange') + config.fixedRateExchangeAddress && + (await ocean.datatokens.approve( + dataToken, + config.fixedRateExchangeAddress, + `${dtAmount}`, + accountId + )) } - - setStepCreatePricing(4) - return response } catch (error) { setPricingError(error.message) Logger.error(error) @@ -266,6 +251,8 @@ function usePricing(ddo: DDO): UsePricing { setPricingStepText(undefined) setPricingIsLoading(false) } + + return tx } return { diff --git a/src/hooks/usePricing/utils.ts b/src/hooks/usePricing/utils.ts new file mode 100644 index 0000000..358accc --- /dev/null +++ b/src/hooks/usePricing/utils.ts @@ -0,0 +1,40 @@ +export function getCreatePricingPoolFeedback( + dtSymbol: string +): { [key: number]: string } { + return { + 99: `Minting ${dtSymbol} ...`, + 1: 'Creating pool ...', + 2: `Approving ${dtSymbol} ...`, + 3: 'Approving OCEAN ...', + 4: 'Creating ...', + 5: 'Pool created.' + } +} + +export function getCreatePricingExchangeFeedback( + dtSymbol: string +): { [key: number]: string } { + return { + 99: `Minting ${dtSymbol} ...`, + 1: `Approving ${dtSymbol} ...`, + 2: 'Approving OCEAN ...', + 3: 'Creating ...', + 4: 'Fixed exchange created.' + } +} + +export function getBuyDTFeedback(dtSymbol: string): { [key: number]: string } { + return { + 1: '1/3 Approving OCEAN ...', + 2: `2/3 Buying ${dtSymbol} ...`, + 3: `3/3 ${dtSymbol} bought.` + } +} + +export function getSellDTFeedback(dtSymbol: string): { [key: number]: string } { + return { + 1: '1/3 Approving OCEAN ...', + 2: `2/3 Selling ${dtSymbol} ...`, + 3: `3/3 ${dtSymbol} sold.` + } +} From 21f044e91ed42eb28299fce80b1ea93ddc49326a Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 21 Oct 2020 13:48:59 +0200 Subject: [PATCH 30/31] refactor --- src/hooks/usePricing/usePricing.ts | 55 +++++++++++++------------- src/utils/dtUtils.ts | 62 +----------------------------- 2 files changed, 28 insertions(+), 89 deletions(-) diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 69f1ed2..580243e 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -28,7 +28,7 @@ interface UsePricing { } function usePricing(ddo: DDO): UsePricing { - const { ocean, account, accountId, config } = useOcean() + const { ocean, accountId, config } = useOcean() const [pricingIsLoading, setPricingIsLoading] = useState(false) const [pricingStep, setPricingStep] = useState() const [pricingStepText, setPricingStepText] = useState() @@ -90,7 +90,9 @@ function usePricing(ddo: DDO): UsePricing { async function buyDT( dtAmount: number | string ): Promise { - if (!ocean || !account || !accountId) return + if (!ocean || !accountId) return + + let tx try { setPricingIsLoading(true) @@ -103,22 +105,17 @@ function usePricing(ddo: DDO): UsePricing { const price = new Decimal(bestPrice.value).times(1.05).toString() const maxPrice = new Decimal(bestPrice.value).times(2).toString() setStep(2, 'buy') - Logger.log( - 'Buying token from pool', - bestPrice, - account.getId(), - price - ) - const buyResponse = await ocean.pool.buyDT( - account.getId(), + Logger.log('Buying token from pool', bestPrice, accountId, price) + tx = await ocean.pool.buyDT( + accountId, bestPrice.address, String(dtAmount), price, maxPrice ) setStep(3, 'buy') - Logger.log('DT buy response', buyResponse) - return buyResponse + Logger.log('DT buy response', tx) + break } case 'exchange': { if (!config.oceanTokenAddress) { @@ -129,22 +126,22 @@ function usePricing(ddo: DDO): UsePricing { Logger.error(`'fixedRateExchangeAddress' not set in config`) return } - Logger.log('Buying token from exchange', bestPrice, account.getId()) + Logger.log('Buying token from exchange', bestPrice, accountId) await ocean.datatokens.approve( config.oceanTokenAddress, config.fixedRateExchangeAddress, - bestPrice.value.toString(), - account.getId() + `${bestPrice.value}`, + accountId ) setStep(2, 'buy') - const exchange = await ocean.fixedRateExchange.buyDT( + tx = await ocean.fixedRateExchange.buyDT( bestPrice.address, - String(dtAmount), - account.getId() + `${dtAmount}`, + accountId ) setStep(3, 'buy') - Logger.log('DT exchange buy response', exchange) - return exchange + Logger.log('DT exchange buy response', tx) + break } } } catch (error) { @@ -155,12 +152,14 @@ function usePricing(ddo: DDO): UsePricing { setPricingStepText(undefined) setPricingIsLoading(false) } + + return tx } async function sellDT( dtAmount: number | string ): Promise { - if (!ocean || !account || !accountId) return + if (!ocean || !accountId) return if (!config.oceanTokenAddress) { Logger.error(`'oceanTokenAddress' not set in config`) @@ -175,16 +174,16 @@ function usePricing(ddo: DDO): UsePricing { if (!pool || pool.price === 0) return const price = new Decimal(pool.price).times(0.95).toString() setStep(2, 'sell') - Logger.log('Selling token to pool', pool, account.getId(), price) - const sellResponse = await ocean.pool.sellDT( - account.getId(), + Logger.log('Selling token to pool', pool, accountId, price) + const tx = await ocean.pool.sellDT( + accountId, pool.address, - String(dtAmount), + `${dtAmount}`, price ) setStep(3, 'sell') - Logger.log('DT sell response', sellResponse) - return sellResponse + Logger.log('DT sell response', tx) + return tx } catch (error) { setPricingError(error.message) Logger.error(error) @@ -198,7 +197,7 @@ function usePricing(ddo: DDO): UsePricing { async function createPricing( priceOptions: PriceOptions ): Promise { - if (!ocean || !account || !accountId || !dtSymbol) return + if (!ocean || !accountId || !dtSymbol) return const { type, dtAmount, price, weightOnDataToken, swapFee } = priceOptions const isPool = type === 'dynamic' diff --git a/src/utils/dtUtils.ts b/src/utils/dtUtils.ts index 9c8b638..38ec580 100644 --- a/src/utils/dtUtils.ts +++ b/src/utils/dtUtils.ts @@ -1,5 +1,4 @@ -import { Logger, Ocean, Account, Config, BestPrice } from '@oceanprotocol/lib' -import { TransactionReceipt } from 'web3-core' +import { Logger, Ocean, BestPrice } from '@oceanprotocol/lib' import { Decimal } from 'decimal.js' import Pool from 'hooks/useMetadata/Pool' import Web3 from 'web3' @@ -146,62 +145,3 @@ export async function getBestDataTokenPrice( } as BestPrice } } - -export async function checkAndBuyDT( - ocean: Ocean, - dataTokenAddress: string, - account: Account, - config: Config -): Promise { - const userOwnedTokens = await ocean.accounts.getTokenBalance( - dataTokenAddress, - account - ) - Logger.log(`User has ${userOwnedTokens} tokens`) - if (userOwnedTokens === '0') { - const bestPrice = await getBestDataTokenPrice(ocean, dataTokenAddress) - - 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': { - if (!config.oceanTokenAddress) { - Logger.error(`'oceanTokenAddress' not set in config`) - return - } - - if (!config.fixedRateExchangeAddress) { - Logger.error(`'fixedRateExchangeAddress' not set in config`) - return - } - - Logger.log('Buying token from exchange', bestPrice, account.getId()) - await ocean.datatokens.approve( - config.oceanTokenAddress, - config.fixedRateExchangeAddress, - bestPrice.value.toString(), - account.getId() - ) - const exchange = await ocean.fixedRateExchange.buyDT( - bestPrice.address, - '1', - account.getId() - ) - Logger.log('DT exchange buy response', exchange) - return exchange - } - } - } -} From 266bf8474ed5780537801a138973bbba3ef79220 Mon Sep 17 00:00:00 2001 From: Matthias Kretschmann Date: Wed, 21 Oct 2020 14:24:37 +0200 Subject: [PATCH 31/31] bump ocean.js, fix feedback --- package-lock.json | 6 ++-- package.json | 2 +- src/hooks/usePricing/usePricing.ts | 47 ++++++++++-------------------- src/hooks/usePricing/utils.ts | 15 +++++----- 4 files changed, 27 insertions(+), 43 deletions(-) diff --git a/package-lock.json b/package-lock.json index 2728109..fea95c4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1521,9 +1521,9 @@ "integrity": "sha512-LING+GvW37I0L40rZdPCZ1SvcZurDSGGhT0WOVPNO8oyh2C3bXModDBNE4+gCFa8pTbQBOc4ot1/Zoj9PfT/zA==" }, "@oceanprotocol/lib": { - "version": "0.6.7", - "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-0.6.7.tgz", - "integrity": "sha512-6Il5PJfaZXXkXO8ECZCsH13OOGlPaN9vK3pLW9EQ6Zj9NlESeLdh0lmvvYSyvloYU999rOY4+X9ujhN6P18clw==", + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@oceanprotocol/lib/-/lib-0.7.0.tgz", + "integrity": "sha512-XRQ58wWbohtz/buug0498EbpBchxrPwYBh8f/Iln1Vwh6h3IfLWvznmg4gNg/H1AE3qdPsuVcBJwYb0Bos/yGQ==", "requires": { "@ethereum-navigator/navigator": "^0.5.0", "@oceanprotocol/contracts": "^0.5.6", diff --git a/package.json b/package.json index e392bbf..e52a199 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "dist/" ], "dependencies": { - "@oceanprotocol/lib": "^0.6.7", + "@oceanprotocol/lib": "^0.7.0", "axios": "^0.20.0", "decimal.js": "^10.2.1", "web3": "^1.3.0", diff --git a/src/hooks/usePricing/usePricing.ts b/src/hooks/usePricing/usePricing.ts index 580243e..75cbd57 100644 --- a/src/hooks/usePricing/usePricing.ts +++ b/src/hooks/usePricing/usePricing.ts @@ -196,7 +196,7 @@ function usePricing(ddo: DDO): UsePricing { async function createPricing( priceOptions: PriceOptions - ): Promise { + ): Promise { if (!ocean || !accountId || !dtSymbol) return const { type, dtAmount, price, weightOnDataToken, swapFee } = priceOptions @@ -210,38 +210,25 @@ function usePricing(ddo: DDO): UsePricing { setPricingIsLoading(true) setPricingError(undefined) - let tx + setStep(99, 'pool') try { - setStep(9, 'pool') await mint(`${dtAmount}`) - if (isPool) { - setStep(1, 'pool') - tx = await ocean.pool - .create( - accountId, - dataToken, - `${dtAmount}`, - weightOnDataToken, - swapFee - ) - .next((step: number) => setStep(step, 'pool')) - } else { - setStep(1, 'exchange') - tx = await ocean.fixedRateExchange - .create(dataToken, `${price}`, accountId) - .next((step: number) => setStep(step, 'exchange')) - - setStep(1, 'exchange') - config.fixedRateExchangeAddress && - (await ocean.datatokens.approve( - dataToken, - config.fixedRateExchangeAddress, - `${dtAmount}`, - accountId - )) - } + const tx = isPool + ? await ocean.pool + .create( + accountId, + dataToken, + `${dtAmount}`, + weightOnDataToken, + swapFee + ) + .next((step: number) => setStep(step, 'pool')) + : await ocean.fixedRateExchange + .create(dataToken, `${price}`, accountId) + .next((step: number) => setStep(step, 'exchange')) + return tx } catch (error) { setPricingError(error.message) Logger.error(error) @@ -250,8 +237,6 @@ function usePricing(ddo: DDO): UsePricing { setPricingStepText(undefined) setPricingIsLoading(false) } - - return tx } return { diff --git a/src/hooks/usePricing/utils.ts b/src/hooks/usePricing/utils.ts index 358accc..5589665 100644 --- a/src/hooks/usePricing/utils.ts +++ b/src/hooks/usePricing/utils.ts @@ -3,11 +3,11 @@ export function getCreatePricingPoolFeedback( ): { [key: number]: string } { return { 99: `Minting ${dtSymbol} ...`, - 1: 'Creating pool ...', - 2: `Approving ${dtSymbol} ...`, - 3: 'Approving OCEAN ...', - 4: 'Creating ...', - 5: 'Pool created.' + 0: 'Creating pool ...', + 1: `Approving ${dtSymbol} ...`, + 2: 'Approving OCEAN ...', + 3: 'Setup pool ...', + 4: 'Pool created.' } } @@ -16,10 +16,9 @@ export function getCreatePricingExchangeFeedback( ): { [key: number]: string } { return { 99: `Minting ${dtSymbol} ...`, + 0: 'Creating exchange ...', 1: `Approving ${dtSymbol} ...`, - 2: 'Approving OCEAN ...', - 3: 'Creating ...', - 4: 'Fixed exchange created.' + 2: 'Fixed exchange created.' } }