1
0
mirror of https://github.com/oceanprotocol/market.git synced 2024-12-02 05:57:29 +01:00
This commit is contained in:
mihaisc 2021-12-20 16:38:54 +02:00
parent 4caf72d0c9
commit b86ac219f3
11 changed files with 5352 additions and 13990 deletions

1
next-env.d.ts vendored
View File

@ -1,5 +1,4 @@
/// <reference types="next" /> /// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" /> /// <reference types="next/image-types/global" />
// NOTE: This file should not be edited // NOTE: This file should not be edited

View File

@ -4,6 +4,11 @@ module.exports = (phase, { defaultConfig }) => {
*/ */
const nextConfig = { const nextConfig = {
webpack: (config, options) => { webpack: (config, options) => {
config.plugins.push(
new options.webpack.IgnorePlugin({
resourceRegExp: /^electron$/
})
)
config.module.rules.push( config.module.rules.push(
{ {
test: /\.svg$/, test: /\.svg$/,

18989
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -71,8 +71,8 @@
"swr": "^1.0.1", "swr": "^1.0.1",
"urql": "^2.0.5", "urql": "^2.0.5",
"use-dark-mode": "^2.3.1", "use-dark-mode": "^2.3.1",
"web3": "^1.6.0", "web3": "^1.6.1",
"web3-utils": "^1.5.3", "web3-utils": "^1.6.1",
"web3modal": "^1.9.4", "web3modal": "^1.9.4",
"yup": "^0.32.11" "yup": "^0.32.11"
}, },

View File

@ -149,11 +149,11 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement {
if (!accountId || !networkId || !web3) return if (!accountId || !networkId || !web3) return
try { try {
const balance = { // const balance = {
eth: web3.utils.fromWei(await web3.eth.getBalance(accountId, 'latest')), // eth: web3.utils.fromWei(await web3.eth.getBalance(accountId, 'latest')),
ocean: await getOceanBalance(accountId, networkId, web3) // ocean: await getOceanBalance(accountId, networkId, web3)
} // }
setBalance(balance) // setBalance(balance)
LoggerInstance.log('[web3] Balance: ', balance) LoggerInstance.log('[web3] Balance: ', balance)
} catch (error) { } catch (error) {
LoggerInstance.error('[web3] Error: ', error.message) LoggerInstance.error('[web3] Error: ', error.message)
@ -262,7 +262,7 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement {
// Figure out if we're on a chain's testnet, or not // Figure out if we're on a chain's testnet, or not
setIsTestnet( setIsTestnet(
networkData?.network !== 'mainnet' && networkData.network !== 'moonriver' networkData?.network !== 'mainnet' && networkData?.network !== 'moonriver'
) )
LoggerInstance.log( LoggerInstance.log(

View File

@ -0,0 +1,22 @@
import { useEffect, useState } from 'react'
import { NftFactory } from '@oceanprotocol/lib'
import { useWeb3 } from '@context/Web3'
function useNftFactory(): NftFactory {
const { web3, chainId } = useWeb3()
const [nftFactory, setNftFactory] = useState<NftFactory>()
useEffect(() => {
if (!web3 || !chainId) return
const factory = new NftFactory(
'0xa15024b732A8f2146423D14209eFd074e61964F3',
web3
)
setNftFactory(factory)
}, [web3, chainId])
return nftFactory
}
export default useNftFactory

View File

@ -18,6 +18,7 @@ interface ServiceComputeOptions {
} }
interface Service { interface Service {
id: string
type: 'access' | 'compute' | string type: 'access' | 'compute' | string
files: string files: string
datatokenAddress: string datatokenAddress: string

View File

@ -1,47 +1,57 @@
import axios, { CancelToken, AxiosResponse } from 'axios' import axios, { CancelToken, AxiosResponse } from 'axios'
import { DID, LoggerInstance } from '@oceanprotocol/lib' import {
FileMetadata,
LoggerInstance,
ProviderInstance
} from '@oceanprotocol/lib'
export interface FileMetadata { export interface FileInfo {
index: number index: number
valid: boolean valid: boolean
contentType: string contentType: string
contentLength: string contentLength: string
} }
export async function getEncryptedFileUrls( export async function getEncryptedFiles(
files: string[], files: FileMetadata[],
providerUrl: string, providerUrl: string,
did: string, did: string,
accountId: string accountId: string
): Promise<string> { ): Promise<string> {
try { try {
// https://github.com/oceanprotocol/provider/blob/v4main/API.md#encrypt-endpoint // https://github.com/oceanprotocol/provider/blob/v4main/API.md#encrypt-endpoint
const url = `${providerUrl}/api/v1/services/encrypt` console.log('start encr')
const response: AxiosResponse<{ encryptedDocument: string }> = const response = await ProviderInstance.encrypt(
await axios.post(url, { did,
documentId: did, accountId,
signature: '', // TODO: add signature files,
publisherAddress: accountId, providerUrl,
document: files (url: string, body: string) => {
}) return axios.post(url, body, {
return response?.data?.encryptedDocument headers: { 'Content-Type': 'application/octet-stream' }
})
}
)
console.log('encr eres', response)
return response.data
} catch (error) { } catch (error) {
console.error('Error parsing json: ' + error.message) console.error('Error parsing json: ' + error.message)
} }
} }
export async function getFileInfo( export async function getFileInfo(
url: string | DID, url: string,
providerUrl: string, providerUrl: string,
cancelToken: CancelToken cancelToken: CancelToken
): Promise<FileMetadata[]> { ): Promise<FileInfo[]> {
let postBody let postBody
try { try {
if (url instanceof DID) postBody = { did: url.getDid() } // TODO: what was the point of this?
else postBody = { url } // if (url instanceof DID) postBody = { did: url.getDid() }
// else postBody = { url }
const response: AxiosResponse<FileMetadata[]> = await axios.post( postBody = { url: url, type: 'url' }
`${providerUrl}/api/v1/services/fileinfo`, const response: AxiosResponse<FileInfo[]> = await axios.post(
`${providerUrl}/api/services/fileinfo`,
postBody, postBody,
{ cancelToken } { cancelToken }
) )

View File

@ -39,7 +39,7 @@ export default function Actions({
<Button <Button
type="submit" type="submit"
style="primary" style="primary"
disabled={values.user.accountId === '' || !isValid} disabled={values.user.accountId === ''}
> >
Submit Submit
</Button> </Button>

View File

@ -1,6 +1,6 @@
import { generateDid } from '@oceanprotocol/lib'
import { mapTimeoutStringToSeconds } from '@utils/ddo' import { mapTimeoutStringToSeconds } from '@utils/ddo'
import { getEncryptedFileUrls } from '@utils/provider' import { getEncryptedFiles } from '@utils/provider'
import { sha256 } from 'js-sha256'
import slugify from 'slugify' import slugify from 'slugify'
import { algorithmContainerPresets } from './_constants' import { algorithmContainerPresets } from './_constants'
import { FormPublishData } from './_types' import { FormPublishData } from './_types'
@ -62,9 +62,10 @@ export async function transformPublishFormToDdo(
} = metadata } = metadata
const { access, files, links, providerUrl, timeout } = services[0] const { access, files, links, providerUrl, timeout } = services[0]
const did = nftAddress ? `0x${sha256(`${nftAddress}${chainId}`)}` : '0x...' const did = nftAddress ? generateDid(nftAddress, chainId) : '0x...'
const currentTime = dateToStringNoMS(new Date()) const currentTime = dateToStringNoMS(new Date())
const isPreview = !datatokenAddress && !nftAddress
console.log('did', did, isPreview)
// Transform from files[0].url to string[] assuming only 1 file // Transform from files[0].url to string[] assuming only 1 file
const filesTransformed = files?.length && files[0].valid && [files[0].url] const filesTransformed = files?.length && files[0].valid && [files[0].url]
const linksTransformed = links?.length && links[0].valid && [links[0].url] const linksTransformed = links?.length && links[0].valid && [links[0].url]
@ -110,19 +111,24 @@ export async function transformPublishFormToDdo(
} }
}) })
} }
console.log('new meta', newMetadata)
// Encrypt just created string[] of urls // this is the default format hardcoded
const file = [
{
type: 'url',
url: files[0].url,
method: 'GET'
}
]
const filesEncrypted = const filesEncrypted =
!isPreview &&
files?.length && files?.length &&
files[0].valid && files[0].valid &&
(await getEncryptedFileUrls( (await getEncryptedFiles(file, providerUrl.url, did, accountId))
filesTransformed,
providerUrl.url,
did,
accountId
))
const newService: Service = { const newService: Service = {
id: 'notAnId',
type: access, type: access,
files: filesEncrypted || '', files: filesEncrypted || '',
datatokenAddress, datatokenAddress,
@ -139,19 +145,19 @@ export async function transformPublishFormToDdo(
version: '4.0.0', version: '4.0.0',
chainId, chainId,
metadata: newMetadata, metadata: newMetadata,
services: [newService], services: [newService]
// Only added for DDO preview, reflecting Asset response, // Only added for DDO preview, reflecting Asset response,
// again, we can assume if `datatokenAddress` is not passed, // again, we can assume if `datatokenAddress` is not passed,
// we are on preview. // we are on preview.
...(!datatokenAddress && { // ...(!datatokenAddress && {
dataTokenInfo: { // dataTokenInfo: {
name: values.services[0].dataTokenOptions.name, // name: values.services[0].dataTokenOptions.name,
symbol: values.services[0].dataTokenOptions.symbol // symbol: values.services[0].dataTokenOptions.symbol
}, // },
nft: { // nft: {
owner: accountId // owner: accountId
} // }
}) // })
} }
return newDdo return newDdo

View File

@ -1,7 +1,6 @@
import React, { ReactElement, useState, useRef } from 'react' import React, { ReactElement, useState, useRef } from 'react'
import { Form, Formik, validateYupSchema } from 'formik' import { Form, Formik } from 'formik'
import { initialValues } from './_constants' import { initialValues } from './_constants'
import { validationSchema } from './_validation'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory' import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
import { useWeb3 } from '@context/Web3' import { useWeb3 } from '@context/Web3'
import { transformPublishFormToDdo } from './_utils' import { transformPublishFormToDdo } from './_utils'
@ -13,20 +12,40 @@ import Debug from './Debug'
import Navigation from './Navigation' import Navigation from './Navigation'
import { Steps } from './Steps' import { Steps } from './Steps'
import { FormPublishData } from './_types' import { FormPublishData } from './_types'
import { sha256 } from 'js-sha256'
import { generateNftCreateData } from '@utils/nft'
import { useUserPreferences } from '@context/UserPreferences' import { useUserPreferences } from '@context/UserPreferences'
import useNftFactory from '@hooks/contracts/useNftFactory'
import {
Datatoken,
Nft,
NftCreateData,
getHash,
Erc20CreateParams,
FreCreationParams,
PoolCreationParams,
ProviderInstance
} from '@oceanprotocol/lib'
import { useSiteMetadata } from '@hooks/useSiteMetadata'
import Web3 from 'web3'
import axios from 'axios'
import { useCancelToken } from '@hooks/useCancelToken'
// TODO: restore FormikPersist, add back clear form action // TODO: restore FormikPersist, add back clear form action
const formName = 'ocean-publish-form' const formName = 'ocean-publish-form'
async function fetchMethod(url: string): Promise<Response> {
const result = await fetch(url)
if (!result) {
throw result.json()
}
return result
}
export default function PublishPage({ export default function PublishPage({
content content
}: { }: {
content: { title: string; description: string; warning: string } content: { title: string; description: string; warning: string }
}): ReactElement { }): ReactElement {
const { debug } = useUserPreferences() const { debug } = useUserPreferences()
const { accountId, chainId } = useWeb3() const { accountId, web3, chainId } = useWeb3()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId) const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId)
// TODO: success & error states need to be handled for each step we want to display // TODO: success & error states need to be handled for each step we want to display
@ -34,9 +53,185 @@ export default function PublishPage({
const [success, setSuccess] = useState<string>() const [success, setSuccess] = useState<string>()
const [error, setError] = useState<string>() const [error, setError] = useState<string>()
const scrollToRef = useRef() const scrollToRef = useRef()
const { appConfig } = useSiteMetadata()
const nftFactory = useNftFactory()
const newCancelToken = useCancelToken()
async function handleSubmit(values: FormPublishData) { async function handleSubmit(values: FormPublishData) {
try { try {
const ocean = '0x8967BCF84170c91B0d24D4302C2376283b0B3a07'
const nftCreateData: NftCreateData = {
name: values.metadata.nft.name,
symbol: values.metadata.nft.symbol,
// tokenURI: values.metadata.nft.image,
tokenURI: '',
templateIndex: 1
}
const ercParams: Erc20CreateParams = {
templateIndex: 1,
minter: accountId,
feeManager: accountId,
mpFeeAddress: accountId,
feeToken: ocean,
feeAmount: `0`,
cap: '1000',
name: values.services[0].dataTokenOptions.name,
symbol: values.services[0].dataTokenOptions.symbol
}
let erc721Address = ''
let datatokenAddress = ''
switch (values.pricing.type) {
case 'dynamic': {
const poolParams: PoolCreationParams = {
// ssContract: '0xeD8CA02627867f459593DD35bC2B0C465B9E9518',
ssContract: '0xeD8CA02627867f459593DD35bC2B0C465B9E9518',
basetokenAddress: ocean,
basetokenSender: '0xa15024b732A8f2146423D14209eFd074e61964F3',
publisherAddress: accountId,
marketFeeCollector: accountId,
poolTemplateAddress: '0x3B942aCcb370e92A07C3227f9fdAc058F62e68C0',
rate: '1',
basetokenDecimals: 18,
vestingAmount: '0',
vestedBlocks: 2726000,
initialBasetokenLiquidity: '20',
swapFeeLiquidityProvider: 1e15,
swapFeeMarketPlaceRunner: 1e15
}
const token = new Datatoken(web3)
token.approve(
ocean,
'0xa15024b732A8f2146423D14209eFd074e61964F3',
'1000',
accountId
)
const result = await nftFactory.createNftErcWithPool(
accountId,
nftCreateData,
ercParams,
poolParams
)
console.log('pool cre', result)
;[erc721Address] = result.events.NFTCreated.returnValues
break
}
case 'fixed': {
const freParams: FreCreationParams = {
fixedRateAddress: `0x235C9bE4D23dCbd16c1Bf89ec839cb7C452FD9e9`,
baseTokenAddress: ocean,
owner: accountId,
marketFeeCollector: appConfig.marketFeeAddress,
baseTokenDecimals: 18,
dataTokenDecimals: 18,
fixedRate: '1',
marketFee: 1,
withMint: false
}
const result = await nftFactory.createNftErcWithFixedRate(
accountId,
nftCreateData,
ercParams,
freParams
)
console.log('create nft', result)
console.log(
'events',
result.events.NFTCreated.returnValues,
result.events.TokenCreated.returnValues
)
erc721Address = result.events.NFTCreated.returnValues[0]
datatokenAddress = result.events.TokenCreated.returnValues[0]
console.log('create address', erc721Address, datatokenAddress)
break
}
case 'free': {
// TODO: create dispenser here
// console.log('params ', ercParams)
// const result = await nftFactory.createNftWithErc(
// accountId,
// nftCreateData,
// ercParams
// )
// console.log('result', result.events.NFTCreated.returnValues[0])
// const encrypted = await ProviderInstance.encrypt(
// '0xasdasda',
// accountId,
// values.metadata,
// 'https://providerv4.rinkeby.oceanprotocol.com/',
// async (url: string) => {
// return (await axios.post(url, { cancelToken: newCancelToken() }))
// .data
// }
// )
// console.log('encrypted', encrypted)
// const published =
// const nft = new Nft(web3)
// const est = await nft.estSetTokenURI(
// result.events.NFTCreated.address,
// accountId,
// values.metadata.nft.image
// )
// console.log('est ', est)
// const resss = await nft.setTokenURI(
// result.events.NFTCreated.address,
// accountId,
// values.metadata.nft.image
// )
break
}
}
erc721Address = '0x7f9696ebfa882db0ac9f83fb0d2dca5b2edb4532'
datatokenAddress = '0xa15024b732A8f2146423D14209eFd074e61964F3'
const ddo = await transformPublishFormToDdo(
values,
datatokenAddress,
erc721Address
)
console.log('formated ddo', JSON.stringify(ddo))
const encryptedResponse = await ProviderInstance.encrypt(
ddo.id,
accountId,
ddo,
'https://providerv4.rinkeby.oceanprotocol.com/',
(url: string, body: string) => {
return axios.post(url, body, {
headers: { 'Content-Type': 'application/octet-stream' },
cancelToken: newCancelToken()
})
}
)
const encryptedDddo = encryptedResponse.data
console.log('encrypted ddo', encryptedDddo)
const metadataHash = getHash(JSON.stringify(ddo))
const nft = new Nft(web3)
const flags = Web3.utils.stringToHex('0')
// const data = web3.utils.stringToHex(encryptedDddo)
// const dataHash = web3.utils.stringToHex(metadataHash)
// console.log('hex data', data)
console.log('hex hash', metadataHash)
console.log('hex flags', flags)
const res = await nft.setMetadata(
erc721Address,
accountId,
0,
'https://providerv4.rinkeby.oceanprotocol.com/',
'',
'0x2',
encryptedDddo,
'0x' + metadataHash
)
console.log('res meta', res)
// -------------------------------------------------- // --------------------------------------------------
// 1. Mint NFT & datatokens & put in pool // 1. Mint NFT & datatokens & put in pool
// -------------------------------------------------- // --------------------------------------------------
@ -77,13 +272,14 @@ export default function PublishPage({
setSuccess('Your DDO was published successfully!') setSuccess('Your DDO was published successfully!')
} catch (error) { } catch (error) {
setError(error.message) setError(error.message)
console.log('err', error)
} }
} }
return isInPurgatory && purgatoryData ? null : ( return isInPurgatory && purgatoryData ? null : (
<Formik <Formik
initialValues={initialValues} initialValues={initialValues}
validationSchema={validationSchema} // validationSchema={validationSchema}
onSubmit={async (values, { resetForm }) => { onSubmit={async (values, { resetForm }) => {
// kick off publishing // kick off publishing
await handleSubmit(values) await handleSubmit(values)