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/types/global" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited

View File

@ -4,6 +4,11 @@ module.exports = (phase, { defaultConfig }) => {
*/
const nextConfig = {
webpack: (config, options) => {
config.plugins.push(
new options.webpack.IgnorePlugin({
resourceRegExp: /^electron$/
})
)
config.module.rules.push(
{
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",
"urql": "^2.0.5",
"use-dark-mode": "^2.3.1",
"web3": "^1.6.0",
"web3-utils": "^1.5.3",
"web3": "^1.6.1",
"web3-utils": "^1.6.1",
"web3modal": "^1.9.4",
"yup": "^0.32.11"
},

View File

@ -149,11 +149,11 @@ function Web3Provider({ children }: { children: ReactNode }): ReactElement {
if (!accountId || !networkId || !web3) return
try {
const balance = {
eth: web3.utils.fromWei(await web3.eth.getBalance(accountId, 'latest')),
ocean: await getOceanBalance(accountId, networkId, web3)
}
setBalance(balance)
// const balance = {
// eth: web3.utils.fromWei(await web3.eth.getBalance(accountId, 'latest')),
// ocean: await getOceanBalance(accountId, networkId, web3)
// }
// setBalance(balance)
LoggerInstance.log('[web3] Balance: ', balance)
} catch (error) {
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
setIsTestnet(
networkData?.network !== 'mainnet' && networkData.network !== 'moonriver'
networkData?.network !== 'mainnet' && networkData?.network !== 'moonriver'
)
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 {
id: string
type: 'access' | 'compute' | string
files: string
datatokenAddress: string

View File

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

View File

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

View File

@ -1,6 +1,6 @@
import { generateDid } from '@oceanprotocol/lib'
import { mapTimeoutStringToSeconds } from '@utils/ddo'
import { getEncryptedFileUrls } from '@utils/provider'
import { sha256 } from 'js-sha256'
import { getEncryptedFiles } from '@utils/provider'
import slugify from 'slugify'
import { algorithmContainerPresets } from './_constants'
import { FormPublishData } from './_types'
@ -62,9 +62,10 @@ export async function transformPublishFormToDdo(
} = metadata
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 isPreview = !datatokenAddress && !nftAddress
console.log('did', did, isPreview)
// Transform from files[0].url to string[] assuming only 1 file
const filesTransformed = files?.length && files[0].valid && [files[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 =
!isPreview &&
files?.length &&
files[0].valid &&
(await getEncryptedFileUrls(
filesTransformed,
providerUrl.url,
did,
accountId
))
(await getEncryptedFiles(file, providerUrl.url, did, accountId))
const newService: Service = {
id: 'notAnId',
type: access,
files: filesEncrypted || '',
datatokenAddress,
@ -139,19 +145,19 @@ export async function transformPublishFormToDdo(
version: '4.0.0',
chainId,
metadata: newMetadata,
services: [newService],
services: [newService]
// Only added for DDO preview, reflecting Asset response,
// again, we can assume if `datatokenAddress` is not passed,
// we are on preview.
...(!datatokenAddress && {
dataTokenInfo: {
name: values.services[0].dataTokenOptions.name,
symbol: values.services[0].dataTokenOptions.symbol
},
nft: {
owner: accountId
}
})
// ...(!datatokenAddress && {
// dataTokenInfo: {
// name: values.services[0].dataTokenOptions.name,
// symbol: values.services[0].dataTokenOptions.symbol
// },
// nft: {
// owner: accountId
// }
// })
}
return newDdo

View File

@ -1,7 +1,6 @@
import React, { ReactElement, useState, useRef } from 'react'
import { Form, Formik, validateYupSchema } from 'formik'
import { Form, Formik } from 'formik'
import { initialValues } from './_constants'
import { validationSchema } from './_validation'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
import { useWeb3 } from '@context/Web3'
import { transformPublishFormToDdo } from './_utils'
@ -13,20 +12,40 @@ import Debug from './Debug'
import Navigation from './Navigation'
import { Steps } from './Steps'
import { FormPublishData } from './_types'
import { sha256 } from 'js-sha256'
import { generateNftCreateData } from '@utils/nft'
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
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({
content
}: {
content: { title: string; description: string; warning: string }
}): ReactElement {
const { debug } = useUserPreferences()
const { accountId, chainId } = useWeb3()
const { accountId, web3, chainId } = useWeb3()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId)
// 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 [error, setError] = useState<string>()
const scrollToRef = useRef()
const { appConfig } = useSiteMetadata()
const nftFactory = useNftFactory()
const newCancelToken = useCancelToken()
async function handleSubmit(values: FormPublishData) {
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
// --------------------------------------------------
@ -77,13 +272,14 @@ export default function PublishPage({
setSuccess('Your DDO was published successfully!')
} catch (error) {
setError(error.message)
console.log('err', error)
}
}
return isInPurgatory && purgatoryData ? null : (
<Formik
initialValues={initialValues}
validationSchema={validationSchema}
// validationSchema={validationSchema}
onSubmit={async (values, { resetForm }) => {
// kick off publishing
await handleSubmit(values)