5387b9a3dd
* add balance check and check is consumable * add isOrderable and other helpers * finish start compute job * removed unused methods * add more comments * add pool logic for order * move asset selection to compute helper * small fix * fixed get algo list * refactor start compute job and more fixes * update order params * use compute env and compute consumer address * fix prices * fix algorithms selection list on allowAllPublisher case * fix edit compute settings * update compute resources valid until logic * fixes and cleanups * wip compute jobs * fix compute timeout value * fixed compute jobs logic * fix algo selection list name * fixed compute jobs from profile loading * update start compute flow messages * update set algo access details * update compute message logic * added logs * update package lock * remove logs * fix edit compute checksums for files and container * Fix compute dataset algorithm list (#1194) * fix query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * remove comment Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * Fix previous order tx (#1197) * rename nft update query Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix previous order Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix build * handle order price, NaN and default 0 * optional value for all fee, prevent breaking when no value * fix aquarius call and added logs * update provider compute status call * remove percentage fee from price sum, depends smart contract calculation (#1249) Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> * fix display of compute datasets with free price * removed to lowerCase on eth address * fix compute jobs section and your jobs * bumo ocean lib to 1.0.0-next.32 * c2d show price with fee, exclude provider fee * wip get results * include loading when calculating data + algo price, tooltip show order price * update get compute url and use oceanjs helper for download * update computeStatus signature to fix build and CI * added logs * refactor setting price and fees for assets * update compute details and compute results UI and style * update flex value * update download buttons style * update download buttons text * bump ocean lib version and lint fixes * get provier uri for compute results based on job input did * use zero adress for price and fees order * some fixes * Add reuse order in start compute flow (#1352) * wip add reuse order logic * add reuse order in start job * added missing check if no jobs found * update lib Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix lint Signed-off-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> * fix fixed rate * fix build * fix your compute jobs section when asset network not selected * disable edit compute settings for algorithms * fix compute jobs infinite loading when no jobs found * fix compute form * show token symbol for free assets also on compute price output * removed swp file * some decimal fixes * partial fix for asset with pool fees, algo not working yet * more decimal fixes * fix algo with pool price and fees fetching * fix selecting algorithms when on different network * fix compute jobs table auto refresh and details modal closing * wip compute initialize * order fixes * fix lint * fix conditions and cleanups * fix compute status text display * init prices and fees after starting a compute job * start/order button tweaks * kick in loader earlier * update compute status feedback messages * fixed initial price * compute jobs refetch and reuse order * remove logs * removed logs and added some explanations * use compute env max duration value in seconds * error handling on intializeCompute and order * removed console logs and added one new check * use optional on initialized provider check * remove toast from provider helper * fix compute env issue on start order * disable job selection during actions execution * temporary fix publish algo with custom docker image * fix provider fee display * remove unnecessary condition * fix alignment based button on action type (#1491) * fix alignment based on action type * moving to CSS modules * send providerFeeAmount as string * remove cast on providerFeeAmount * removed some logs and added few comments * update price output tooltip and total price logic * set providerFee amount only when avaialable * bump oceanlib to 1.1.2 * replace FIleMetadata to fix build * used approveWei for approving provider fees * fix free algo price selection and display * fix provider fee load at first algo selection * update compute help text * fix provider fee approve for free assets * cleanup * remove commented out code * remove unused state * removed unused imports * typos in comments, variables, props * more typos * shorten getAccessDetailsFromTokenPrice() a bit * state & hooks access reordering * Update src/@utils/ddo.ts remove metadata from service type Co-authored-by: Matthias Kretschmann <m@kretschmann.io> * effect dependency fixes * state renaming * effect dependency fixes * compute jobs profile visual fixes * effect dependency fixes * more comments removal * add accountId as a dependency in effect * move isOwner to asset provider * refactor handleComputeOrder for less complexity and more useful error reporting * more proper error throwing * provider fee statement tweak * more obvious edit action * empty array for `publisherTrustedAlgorithms` & `publisherTrustedAlgorithmPublishers` by default * ref #1538 * ref #1539 * don t use initial tx values as valid order use subgraph value * fix algo list fetching * closes #1537 * addresses #1538 * fix disable compute button if algo is consumable * move isOwner check to single effect * Correctly display trusted algorithms in compute asset (#1541) * fix allowed algo * fix trusted algo filter Co-authored-by: mihaisc <mihai.scarlat@smartcontrol.ro> Co-authored-by: Soon Huat <soon_huat.phan@daimler.com> Co-authored-by: Soon Huat <soonhuat.phan@hotmail.com> Co-authored-by: Enzo Vezzaro <enzo-vezzaro@live.it> Co-authored-by: Matthias Kretschmann <m@kretschmann.io> Co-authored-by: mihaisc <mihai@oceanprotocol.com> |
||
---|---|---|
.github | ||
.husky | ||
.jest | ||
.storybook | ||
.vscode | ||
content | ||
public | ||
scripts | ||
src | ||
.codeclimate.yml | ||
.env.example | ||
.eslintrc | ||
.gitignore | ||
.nvmrc | ||
.prettierrc | ||
app.config.js | ||
LICENSE | ||
next-env.d.ts | ||
next.config.js | ||
package-lock.json | ||
package.json | ||
README.md | ||
tsconfig.json |
Ocean Marketplace
Table of Contents
- 🏄 Get Started
- 🦑 Environment variables
- 🦀 Data Sources
- 👩🎤 Storybook
- 🤖 Testing
- ✨ Code Style
- 🛳 Production
- ⬆️ Deployment
- 💖 Contributing
- 🍴 Forking
- 💰 Pricing Options
- ✅ GDPR Compliance
- 🏛 License
🏄 Get Started
The app is a React app built with Next.js + TypeScript + CSS modules and will connect to Ocean remote components by default.
To start local development:
git clone git@github.com:oceanprotocol/market.git
cd market
# when using nvm to manage Node.js versions
nvm use
npm install
npm start
This will start the development server under
http://localhost:8000
.
Local components with Barge
If you prefer to connect to locally running components instead of remote connections, you can spin up barge
and use a local Ganache network in another terminal before running npm start
:
git clone git@github.com:oceanprotocol/barge.git
cd barge
# startup with local Ganache node
./start_ocean.sh
Barge will deploy contracts to the local Ganache node which will take some time. At the end the compiled artifacts need to be copied over to this project into node_modules/@oceanprotocol/contracts/artifacts
. This script will do that for you:
./scripts/copy-contracts.sh
Finally, set environment variables to use this local connection in .env
in the app:
# modify env variables
cp .env.example .env
npm start
To use the app together with MetaMask, importing one of the accounts auto-generated by the Ganache container is the easiest way to have test ETH available. All of them have 100 ETH by default. Upon start, the ocean_ganache_1
container will print out the private keys of multiple accounts in its logs. Pick one of them and import into MetaMask.
To fully test all The Graph integrations, you have to run your own local Graph node with our ocean-subgraph
deployed to it. Barge does not include a local subgraph so by default, the subgraphUri
is hardcoded to the Rinkeby subgraph in our getDevelopmentConfig
function.
Cleaning all Docker images so they are fetched freshly is often a good idea to make sure no issues are caused by old or stale images:
docker system prune --all --volumes
🦑 Environment variables
The app.config.js
file is setup to prioritize environment variables for setting each Ocean component endpoint. By setting environment variables, you can easily switch between Ocean networks the app connects to, without directly modifying app.config.js
.
For local development, you can use a .env
file:
# modify env variables, Rinkeby is enabled by default when using those files
cp .env.example .env
🦀 Data Sources
All displayed data in the app is presented around the concept of one data set, which is a combination of:
- metadata about a data set
- the actual data set files
- the NFT which represents the data set
- the datatokens representing access rights to the data set files
- financial data connected to these datatokens, either a pool or a fixed rate exchange contract
- calculations and conversions based on financial data
- metadata about publisher accounts
All this data then comes from multiple sources:
Aquarius
All initial data sets and their metadata (DDO) is retrieved client-side on run-time from the Aquarius instance, defined in app.config.js
. All app calls to Aquarius are done with 2 internal methods which mimic the same methods in ocean.js, but allow us:
- to cancel requests when components get unmounted in combination with axios
- hit Aquarius as early as possible without relying on any ocean.js initialization
Aquarius runs Elasticsearch under the hood so its stored metadata can be queried with Elasticsearch queries like so:
import { QueryResult } from '@oceanprotocol/lib/dist/node/metadatacache/MetadataCache'
import { queryMetadata } from '@utils/aquarius'
const queryLatest = {
query: {
// https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-query-string-query.html
query_string: { query: `-isInPurgatory:true` }
},
sort: { created: 'desc' }
}
function Component() {
const { appConfig } = useMarketMetadata()
const [result, setResult] = useState<QueryResult>()
useEffect(() => {
if (!appConfig.metadataCacheUri) return
const source = axios.CancelToken.source()
async function init() {
const result = await queryMetadata(query, source.token)
setResult(result)
}
init()
return () => {
source.cancel()
}
}, [appConfig.metadataCacheUri, query])
return <div>{result}</div>
}
For components within a single data set view the useAsset()
hook can be used, which in the background gets the respective metadata from Aquarius.
import { useAsset } from '@context/Asset'
function Component() {
const { ddo } = useAsset()
return <div>{ddo}</div>
}
Ocean Protocol Subgraph
Most financial data in the market is retrieved with GraphQL from our own subgraph, rendered on top of the initial data coming from Aquarius.
The app has Urql Client setup to query the respective subgraph based on network. In any component this client can be used like so:
import { gql, useQuery } from 'urql'
const query = gql`
query PoolLiquidity($id: ID!, $shareId: ID) {
pool(id: $id) {
id
totalShares
}
}
`
function Component() {
const { data } = useQuery(query, {}, pollInterval: 5000 })
return <div>{data}</div>
}
3Box
Publishers can create a profile on 3Box Hub and when found, it will be displayed in the app.
For this our own 3box-proxy is used, within the app the utility method get3BoxProfile()
can be used to get all info:
import get3BoxProfile from '@utils/profile'
function Component() {
const [profile, setProfile] = useState<Profile>()
useEffect(() => {
if (!account) return
const source = axios.CancelToken.source()
async function get3Box() {
const profile = await get3BoxProfile(account, source.token)
if (!profile) return
setProfile(profile)
}
get3Box()
return () => {
source.cancel()
}
}, [account])
return (
<div>
{profile.emoji} {profile.name}
</div>
)
}
Purgatory
Based on list-purgatory some data sets get additional data. Within most components this can be done with the internal useAsset()
hook which fetches data from the market-purgatory endpoint in the background.
For asset purgatory:
import { useAsset } from '@context/Asset'
function Component() {
const { isInPurgatory, purgatoryData } = useAsset()
return isInPurgatory ? <div>{purgatoryData.reason}</div> : null
}
For account purgatory:
import { useWeb3 } from '@context/Web3'
import { useAccountPurgatory } from '@hooks/useAccountPurgatory'
function Component() {
const { accountId } = useWeb3()
const { isInPurgatory, purgatoryData } = useAccountPurgatory(accountId)
return isInPurgatory ? <div>{purgatoryData.reason}</div> : null
}
Network Metadata
All displayed chain & network metadata is retrieved from https://chainid.network
on build time and integrated into NEXT's GraphQL layer. This data source is a community-maintained GitHub repository under ethereum-lists/chains.
Within components this metadata can be queried for under allNetworksMetadataJson
. The useWeb3()
hook does this in the background to expose the final networkDisplayName
for use in components:
export default function NetworkName(): ReactElement {
const { networkId, isTestnet } = useWeb3()
const { networksList } = useNetworkMetadata()
const networkData = getNetworkDataById(networksList, networkId)
const networkName = getNetworkDisplayName(networkData, networkId)
return (
<>
{networkName} {isTestnet && `(Test)`}
</>
)
}
👩🎤 Storybook
Storybook helps us build UI components in isolation from our app's business logic, data, and context. That makes it easy to develop hard-to-reach states and save these UI states as stories to revisit during development, testing, or QA.
To start adding stories, create a index.stories.tsx
inside the component's folder:
src └─── components │ └─── @shared │ └─── │ │ index.tsx │ │ index.module.css │ │ index.stories.tsx │ │ index.test.tsx
Starting up the Storybook server with this command will make it accessible under http://localhost:6006
:
npm run storybook
If you want to build a portable static version under storybook-static/
:
npm run storybook:build
🤖 Testing
Test runs utilize Jest as test runner and Testing Library for writing tests.
All created Storybook stories will automatically run as individual tests by using the StoryShots Addon.
Creating Storybook stories for a component will provide good coverage of a component in many cases. Additional tests for dedicated component functionality which can't be done with Storybook are created as usual Testing Library tests, but you can also import exisiting Storybook stories into those tests.
Executing linting, type checking, and full test run:
npm test
Which is a combination of multiple scripts which can also be run individually:
npm run lint
npm run type-check
npm run jest
A coverage report is automatically shown in console whenever npm run jest
is called. Generated reports are sent to CodeClimate during CI runs.
During local development you can continously get coverage report feedback in your console by running Jest in watch mode:
npm run jest:watch
✨ Code Style
Code style is automatically enforced through ESLint & Prettier rules:
- Git pre-commit hook runs
prettier
on staged files, setup with Husky - VS Code suggested extensions and settings for auto-formatting on file save
- CI runs a linting & TypeScript typings check as part of
npm test
, and fails if errors are found
For running linting and auto-formatting manually, you can use from the root of the project:
# linting check
npm run lint
# auto format all files in the project with prettier, taking all configs into account
npm run format
🛳 Production
To create a production build, run from the root of the project:
npm run build
# serve production build
npm run serve
⬆️ Deployment
Every branch or Pull Request is automatically deployed to multiple hosts for redundancy and emergency reasons:
A link to a preview deployment will appear under each Pull Request.
The latest deployment of the main
branch is automatically aliased to market.oceanprotocol.com
, where the deployment on Netlify is the current live deployment.
💖 Contributing
We welcome contributions in form of bug reports, feature requests, code changes, or documentation improvements. Have a look at our contribution documentation for instructions and workflows:
🍴 Forking
We encourage you to fork this repository and create your own data marketplace. When you publish your forked version of this market there are a few elements that you are required to change for copyright reasons:
- The typeface is copyright protected and needs to be changed unless you purchase a license for it.
- The Ocean Protocol logo is a trademark of the Ocean Protocol Foundation and must be removed from forked versions of the market.
- The name "Ocean Market" is also copyright protected and should be changed to the name of your market.
Additionally, we would also advise that your retain the text saying "Powered by Ocean Protocol" on your forked version of the marketplace in order to give credit for the development work done by the Ocean Protocol team.
Everything else is made open according to the apache2 license. We look forward to seeing your data marketplace!
💰 Pricing Options
Dynamic Pricing
To allow publishers to set pricing as "Dynamic" you need to add the following environmental variable to your .env file: NEXT_PUBLIC_ALLOW_DYNAMIC_PRICING="true"
(default).
Fixed Pricing
To allow publishers to set pricing as "Fixed" you need to add the following environmental variable to your .env file: NEXT_PUBLIC_ALLOW_FIXED_PRICING="true"
(default).
Free Pricing
To allow publishers to set pricing as "Free" you need to add the following environmental variable to your .env file: NEXT_PUBLIC_ALLOW_FREE_PRICING="true"
(default).
This allocates the datatokens to the dispenser contract which dispenses data tokens to users for free. Publishers in your market will now be able to offer their datasets to users for free (excluding gas costs).
✅ GDPR Compliance
Ocean Market comes with prebuilt components for you to customize to cover GDPR requirements. Find additional information on how to use them below.
Multi-Language Privacy Policies
Feel free to adopt our provided privacy policies to your needs. Per default we cover four different languages: English, German, Spanish and French. Please be advised, that you will need to adjust some paragraphs in the policies depending on your market setup (e.g. the use of cookies). You can easily add or remove policies by providing your own markdown files in the content/pages/privacy
directory. For guidelines on how to format your markdown files refer to our provided policies. The pre-linked content tables for these files are automatically generated.
Privacy Preference Center
Additionally, Ocean Market provides a privacy preference center for you to use. This feature is disabled per default since we do not use cookies requiring consent on our deployment of the market. However, if you need to add some functionality depending on cookies, you can simply enable this feature by changing the value of the NEXT_PUBLIC_PRIVACY_PREFERENCE_CENTER
environmental variable to "true"
in your .env
file. This will enable a customizable cookie banner stating the use of your individual cookies. The content of this banner can be adjusted within the content/gdpr.json
file. If no optionalCookies
are provided, the privacy preference center will be set to a simpler version displaying only the title
, text
and close
-button. This can be used to inform the user about the use of essential cookies, where no consent is needed. The privacy preference center supports two different styling options: 'small'
and 'default'
. Setting the style propertie to 'small'
will display a smaller cookie banner to the user at first, only showing the default styled privacy preference center upon the user's customization request.
Now your market users will be provided with additional options to toggle the use of your configured cookie consent categories. You can always retrieve the current consent status per category with the provided useConsent()
hook. See below, how you can set your own custom cookies depending on the market user's consent. Feel free to adjust the provided utility functions for cookie usage provided in the src/utils/cookies.ts
file to your needs.
import { CookieConsentStatus, useConsent } from '@context/CookieConsent'
import { deleteCookie, setCookie } from '@utils/cookies'
// ...
const { cookies, cookieConsentStatus } = useConsent()
cookies.map((cookie) => {
const consent = cookieConsentStatus[cookie.cookieName]
switch (consent) {
case CookieConsentStatus.APPROVED:
// example logic
setCookie(`YOUR_COOKIE_NAME`, 'VALUE')
break
case CookieConsentStatus.REJECTED:
case CookieConsentStatus.NOT_AVAILABLE:
default:
// example logic
deleteCookie(`YOUR_COOKIE_NAME`)
break
}
})
Privacy Preference Center Styling
The privacy preference centre has two styling options default
and small
. The default view shows all of the customization options on a full-height side banner. When the small
setting is used, a much smaller banner is shown which only reveals all of the customization options when the user clicks "Customize".
The style can be changed by altering the style
prop in the PrivacyPreferenceCenter
component in src/components/App.tsx
. For example:
<PrivacyPreferenceCenter style="small" />
🏛 License
Copyright 2022 Ocean Protocol Foundation Ltd.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.