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

Commit

Permalink
publish events
Browse files Browse the repository at this point in the history
  • Loading branch information
mihaisc committed Jul 17, 2020
1 parent 984248a commit 3a8b12a
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 81 deletions.
2 changes: 1 addition & 1 deletion example/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function App() {

return (
<div className="app">
<OceanProvider config={configRinkeby}>
<OceanProvider config={config}>
<div className="container">
<div>
<Wallet />
Expand Down
3 changes: 2 additions & 1 deletion example/src/Publish.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useState } from 'react'

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

const asset = {
Expand Down Expand Up @@ -44,6 +44,7 @@ export function Publish() {
<div>
<button onClick={publishAsset}>Publish</button>
</div>
<div>Status: {publishStepText}</div>
<div>DID: {ddo && ddo.id} </div>
</>
)
Expand Down
157 changes: 95 additions & 62 deletions src/hooks/usePublish/usePublish.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import { useEffect } from 'react'
import { useEffect, useState } from 'react'
import { DDO, Metadata, DataTokens, Logger } from '@oceanprotocol/lib'
import { useOcean } from '../../providers'
import ProviderStatus from '../../providers/OceanProvider/ProviderStatus'
import {
Service,
ServiceType
} from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service'
import { Service } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service'
import { ServiceConfig } from './ServiceConfig'
import { publishFeedback } from '../../utils'

interface UsePublish {
publish: (
Expand All @@ -16,79 +14,109 @@ interface UsePublish {
serviceConfigs: ServiceConfig[]
) => Promise<DDO>
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 {
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() {
return new DataTokens(
ocean.datatokens.factoryAddress,
ocean.datatokens.factoryABI.abi,
ocean.datatokens.datatokensABI.abi,
web3
)
function setStep(index: number) {
setPublishStep(index)
setPublishStepText(publishFeedback[index])
}

/**
* 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(
asset: Metadata,
tokensToMint: string,
marketAddress: string,
serviceConfigs: ServiceConfig[]
): Promise<DDO> {
if (status !== ProviderStatus.CONNECTED) return

Logger.log('ocean dt', ocean.datatokens)
const data = { t: 1, url: config.metadataStoreUri }
const blob = JSON.stringify(data)
const tokenAddress = await ocean.datatokens.create(blob, accountId)
Logger.log('datatoken created', tokenAddress)
Logger.log('tokens to mint', tokensToMint)
if (status !== ProviderStatus.CONNECTED || !ocean || !account) return
setIsLoading(true)
setPublishError(undefined)
try {
setStep(0)
const data = { t: 1, url: config.metadataStoreUri }
const blob = JSON.stringify(data)
const tokenAddress = await ocean.datatokens.create(blob, accountId)
Logger.log('datatoken created', tokenAddress)

await mint(tokenAddress, tokensToMint)
setStep(1)
await mint(tokenAddress, tokensToMint)
Logger.log(`minted ${tokensToMint} tokens`)

Logger.log('giving allowance to ', marketAddress)
await giveMarketAllowance(tokenAddress, marketAddress, tokensToMint)
Logger.log('tokenAddress created', tokenAddress)
const publishedDate = new Date(Date.now()).toISOString().split('.')[0] + 'Z'
const timeout = 0
const services: Service[] = []

serviceConfigs.forEach(async (serviceConfig) => {
const price = ocean.datatokens.toWei(serviceConfig.cost)
switch (serviceConfig.serviceType) {
case 'access': {
const accessService = await ocean.assets.createAccessServiceAttributes(
account,
price,
publishedDate,
timeout
)
Logger.log('access service created', accessService)
services.push(accessService)
break
}
case 'compute': {
const computeService = await ocean.assets.createAccessServiceAttributes(
account,
price,
publishedDate,
0
)
services.push(computeService)
break
setStep(2)
await giveMarketAllowance(tokenAddress, marketAddress, tokensToMint)
Logger.log('allowance to market', marketAddress)
const publishedDate =
new Date(Date.now()).toISOString().split('.')[0] + 'Z'
const timeout = 0
const services: Service[] = []
setStep(3)
serviceConfigs.forEach(async (serviceConfig) => {
const price = ocean.datatokens.toWei(serviceConfig.cost)
switch (serviceConfig.serviceType) {
case 'access': {
const accessService = await ocean.assets.createAccessServiceAttributes(
account,
price,
publishedDate,
timeout
)
Logger.log('access service created', accessService)
services.push(accessService)
break
}
case 'compute': {
const computeService = await ocean.assets.createAccessServiceAttributes(
account,
price,
publishedDate,
0
)
services.push(computeService)
break
}
}
}
})

const ddo = await ocean.assets.create(
asset,
account,
services,
tokenAddress
)
})
Logger.log('services created', services)
setStep(4)
const ddo = await ocean.assets.create(
asset,
account,
services,
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) {
Expand All @@ -111,7 +139,12 @@ function usePublish(): UsePublish {

return {
publish,
mint
mint,
giveMarketAllowance,
publishStep,
publishStepText,
isLoading,
publishError
}
}

Expand Down
40 changes: 23 additions & 17 deletions src/providers/OceanProvider/OceanProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,10 @@ function OceanProvider({
const [account, setAccount] = useState<Account | undefined>()
const [accountId, setAccountId] = 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() {
Logger.log('Ocean Provider init')
Expand Down Expand Up @@ -64,10 +67,6 @@ function OceanProvider({
const web3 = new Web3(provider)
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
const ocean = await Ocean.getInstance(config)

Expand Down Expand Up @@ -115,22 +114,29 @@ function OceanProvider({

const handleAccountsChanged = async (accounts: string[]) => {
console.debug("Handling 'accountsChanged' event with payload", accounts)
if (accounts.length > 0) {
setAccountId(accounts[0])

if (web3) {
const balance = await getBalance(web3, accounts[0])
setBalance(balance)
}
if (status === ProviderStatus.CONNECTED) {
connect(web3ModalOpts)
}
// if (accounts.length > 0) {
// setAccountId(accounts[0])

// if (web3) {
// const balance = await getBalance(web3, accounts[0])
// setBalance(balance)
// }
// }
}

// ToDo need to handle this, it's not implemented, need to update chainId and reinitialize ocean lib
const handleNetworkChanged = async (networkId: string | number) => {
console.debug("Handling 'networkChanged' event with payload", networkId)
web3Provider.autoRefreshOnNetworkChange = false
// init(networkId)
// handleConnect(ethProvider)
console.debug(
"Handling 'networkChanged' event with payload",
networkId,
status
)
if (status === ProviderStatus.CONNECTED) {
connect(web3ModalOpts)
}
}

useEffect(() => {
Expand All @@ -145,7 +151,7 @@ function OceanProvider({
web3Provider.removeListener('networkChanged', handleNetworkChanged)
}
}
}, [web3, web3Modal, web3Provider])
}, [web3Modal, web3Provider])

return (
<OceanContext.Provider
Expand Down
8 changes: 8 additions & 0 deletions src/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,11 @@ export const feedback: { [key in number]: string } = {
1: '1/3 Transfering data token.',
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'
}

0 comments on commit 3a8b12a

Please sign in to comment.