1
0
mirror of https://github.com/oceanprotocol/react.git synced 2025-02-14 21:10:38 +01:00

publish events

This commit is contained in:
mihaisc 2020-07-17 13:24:46 +03:00
parent 984248abdf
commit 3a8b12a2a5
5 changed files with 129 additions and 81 deletions

View File

@ -29,7 +29,7 @@ function App() {
return ( return (
<div className="app"> <div className="app">
<OceanProvider config={configRinkeby}> <OceanProvider config={config}>
<div className="container"> <div className="container">
<div> <div>
<Wallet /> <Wallet />

View File

@ -5,7 +5,7 @@ import { useState } from 'react'
export function Publish() { export function Publish() {
const { accountId } = useOcean() const { accountId } = useOcean()
const { publish } = usePublish() const { publish, publishStepText } = usePublish()
const [ddo, setDdo] = useState<DDO | undefined>() const [ddo, setDdo] = useState<DDO | undefined>()
const asset = { const asset = {
@ -44,6 +44,7 @@ export function Publish() {
<div> <div>
<button onClick={publishAsset}>Publish</button> <button onClick={publishAsset}>Publish</button>
</div> </div>
<div>Status: {publishStepText}</div>
<div>DID: {ddo && ddo.id} </div> <div>DID: {ddo && ddo.id} </div>
</> </>
) )

View File

@ -1,12 +1,10 @@
import { useEffect } from 'react' import { useEffect, useState } from 'react'
import { DDO, Metadata, DataTokens, Logger } from '@oceanprotocol/lib' import { DDO, Metadata, DataTokens, Logger } from '@oceanprotocol/lib'
import { useOcean } from '../../providers' import { useOcean } from '../../providers'
import ProviderStatus from '../../providers/OceanProvider/ProviderStatus' import ProviderStatus from '../../providers/OceanProvider/ProviderStatus'
import { import { Service } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service'
Service,
ServiceType
} from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service'
import { ServiceConfig } from './ServiceConfig' import { ServiceConfig } from './ServiceConfig'
import { publishFeedback } from '../../utils'
interface UsePublish { interface UsePublish {
publish: ( publish: (
@ -16,44 +14,65 @@ interface UsePublish {
serviceConfigs: ServiceConfig[] serviceConfigs: ServiceConfig[]
) => Promise<DDO> ) => Promise<DDO>
mint: (tokenAddress: string, tokensToMint: string) => void mint: (tokenAddress: string, tokensToMint: string) => void
giveMarketAllowance: (
tokenAddress: string,
marketAddress: string,
tokens: string
) => void
publishStep?: number
publishStepText?: string
publishError?: string
isLoading: boolean
} }
function usePublish(): UsePublish { function usePublish(): UsePublish {
const { web3, ocean, status, account, accountId, config } = useOcean() const { web3, ocean, status, account, accountId, config } = useOcean()
const [isLoading, setIsLoading] = useState(false)
const [publishStep, setPublishStep] = useState<number | undefined>()
const [publishStepText, setPublishStepText] = useState<string | undefined>()
const [publishError, setPublishError] = useState<string | undefined>()
function createDataToken() { function setStep(index: number) {
return new DataTokens( setPublishStep(index)
ocean.datatokens.factoryAddress, setPublishStepText(publishFeedback[index])
ocean.datatokens.factoryABI.abi,
ocean.datatokens.datatokensABI.abi,
web3
)
} }
/**
* Publish an asset.It also creates the datatoken, mints tokens and gives the market allowance
* @param {Metadata} asset The metadata of the asset.
* @param {string} tokensToMint Numer of tokens to mint and give allowance to market
* @param {string} marketAddress The address of the market
* @param {ServiceConfig[]} serviceConfigs Desired services of the asset, ex: [{serviceType: 'access', cost:'1'}]
* @return {Promise<DDO>} Returns the newly published ddo
*/
async function publish( async function publish(
asset: Metadata, asset: Metadata,
tokensToMint: string, tokensToMint: string,
marketAddress: string, marketAddress: string,
serviceConfigs: ServiceConfig[] serviceConfigs: ServiceConfig[]
): Promise<DDO> { ): Promise<DDO> {
if (status !== ProviderStatus.CONNECTED) return if (status !== ProviderStatus.CONNECTED || !ocean || !account) return
setIsLoading(true)
Logger.log('ocean dt', ocean.datatokens) setPublishError(undefined)
try {
setStep(0)
const data = { t: 1, url: config.metadataStoreUri } const data = { t: 1, url: config.metadataStoreUri }
const blob = JSON.stringify(data) const blob = JSON.stringify(data)
const tokenAddress = await ocean.datatokens.create(blob, accountId) const tokenAddress = await ocean.datatokens.create(blob, accountId)
Logger.log('datatoken created', tokenAddress) Logger.log('datatoken created', tokenAddress)
Logger.log('tokens to mint', tokensToMint)
setStep(1)
await mint(tokenAddress, tokensToMint) await mint(tokenAddress, tokensToMint)
Logger.log(`minted ${tokensToMint} tokens`)
Logger.log('giving allowance to ', marketAddress) setStep(2)
await giveMarketAllowance(tokenAddress, marketAddress, tokensToMint) await giveMarketAllowance(tokenAddress, marketAddress, tokensToMint)
Logger.log('tokenAddress created', tokenAddress) Logger.log('allowance to market', marketAddress)
const publishedDate = new Date(Date.now()).toISOString().split('.')[0] + 'Z' const publishedDate =
new Date(Date.now()).toISOString().split('.')[0] + 'Z'
const timeout = 0 const timeout = 0
const services: Service[] = [] const services: Service[] = []
setStep(3)
serviceConfigs.forEach(async (serviceConfig) => { serviceConfigs.forEach(async (serviceConfig) => {
const price = ocean.datatokens.toWei(serviceConfig.cost) const price = ocean.datatokens.toWei(serviceConfig.cost)
switch (serviceConfig.serviceType) { switch (serviceConfig.serviceType) {
@ -80,15 +99,24 @@ function usePublish(): UsePublish {
} }
} }
}) })
Logger.log('services created', services)
setStep(4)
const ddo = await ocean.assets.create( const ddo = await ocean.assets.create(
asset, asset,
account, account,
services, services,
tokenAddress tokenAddress
) )
setStep(5)
return ddo return ddo
} catch (error) {
setPublishError(error.message)
Logger.error(error)
setStep(undefined)
} finally {
setIsLoading(false)
}
} }
async function mint(tokenAddress: string, tokensToMint: string) { async function mint(tokenAddress: string, tokensToMint: string) {
@ -111,7 +139,12 @@ function usePublish(): UsePublish {
return { return {
publish, publish,
mint mint,
giveMarketAllowance,
publishStep,
publishStepText,
isLoading,
publishError
} }
} }

View File

@ -36,7 +36,10 @@ function OceanProvider({
const [account, setAccount] = useState<Account | undefined>() const [account, setAccount] = useState<Account | undefined>()
const [accountId, setAccountId] = useState<string | undefined>() const [accountId, setAccountId] = useState<string | undefined>()
const [balance, setBalance] = useState<string | undefined>() const [balance, setBalance] = useState<string | undefined>()
const [status, setStatus] = useState(ProviderStatus.NOT_AVAILABLE) const [status, setStatus] = useState<ProviderStatus>(
ProviderStatus.NOT_AVAILABLE
)
const [web3ModalOpts, setWeb3ModalOpts] = useState<Partial<ICoreOptions>>()
function init() { function init() {
Logger.log('Ocean Provider init') Logger.log('Ocean Provider init')
@ -64,10 +67,6 @@ function OceanProvider({
const web3 = new Web3(provider) const web3 = new Web3(provider)
setWeb3(web3) setWeb3(web3)
// const factory = require('@oceanprotocol/contracts/artifacts/development/Factory.json')
// const datatokensTemplate = require('@oceanprotocol/contracts/artifacts/development/DataTokenTemplate.json')
// config.factoryABI = factory.abi
// config.datatokensABI = datatokensTemplate.abi
config.web3Provider = web3 config.web3Provider = web3
const ocean = await Ocean.getInstance(config) const ocean = await Ocean.getInstance(config)
@ -115,22 +114,29 @@ function OceanProvider({
const handleAccountsChanged = async (accounts: string[]) => { const handleAccountsChanged = async (accounts: string[]) => {
console.debug("Handling 'accountsChanged' event with payload", accounts) console.debug("Handling 'accountsChanged' event with payload", accounts)
if (accounts.length > 0) { if (status === ProviderStatus.CONNECTED) {
setAccountId(accounts[0]) connect(web3ModalOpts)
}
// if (accounts.length > 0) {
// setAccountId(accounts[0])
if (web3) { // if (web3) {
const balance = await getBalance(web3, accounts[0]) // const balance = await getBalance(web3, accounts[0])
setBalance(balance) // setBalance(balance)
} // }
} // }
} }
// ToDo need to handle this, it's not implemented, need to update chainId and reinitialize ocean lib // ToDo need to handle this, it's not implemented, need to update chainId and reinitialize ocean lib
const handleNetworkChanged = async (networkId: string | number) => { const handleNetworkChanged = async (networkId: string | number) => {
console.debug("Handling 'networkChanged' event with payload", networkId) console.debug(
web3Provider.autoRefreshOnNetworkChange = false "Handling 'networkChanged' event with payload",
// init(networkId) networkId,
// handleConnect(ethProvider) status
)
if (status === ProviderStatus.CONNECTED) {
connect(web3ModalOpts)
}
} }
useEffect(() => { useEffect(() => {
@ -145,7 +151,7 @@ function OceanProvider({
web3Provider.removeListener('networkChanged', handleNetworkChanged) web3Provider.removeListener('networkChanged', handleNetworkChanged)
} }
} }
}, [web3, web3Modal, web3Provider]) }, [web3Modal, web3Provider])
return ( return (
<OceanContext.Provider <OceanContext.Provider

View File

@ -18,3 +18,11 @@ export const feedback: { [key in number]: string } = {
1: '1/3 Transfering data token.', 1: '1/3 Transfering data token.',
2: '2/3 Payment confirmed. Requesting access...' 2: '2/3 Payment confirmed. Requesting access...'
} }
export const publishFeedback: { [key in number]: string } = {
0: '1/5 Creating datatoken ...',
1: '2/5 Minting tokens ...',
2: '3/5 Giving allowance to market to sell your tokens ...',
3: '4/5 Publishing asset ...',
4: '5/5 Asset published succesfully'
}