provider, publish, consume
This commit is contained in:
parent
372a46e670
commit
1c1e95fd0b
|
@ -0,0 +1,23 @@
|
|||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# dependencies
|
||||
/node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
.env.local
|
||||
.env.development.local
|
||||
.env.test.local
|
||||
.env.production.local
|
||||
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
|
@ -0,0 +1,44 @@
|
|||
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
|
||||
|
||||
## Available Scripts
|
||||
|
||||
In the project directory, you can run:
|
||||
|
||||
### `npm start`
|
||||
|
||||
Runs the app in the development mode.<br />
|
||||
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
|
||||
|
||||
The page will reload if you make edits.<br />
|
||||
You will also see any lint errors in the console.
|
||||
|
||||
### `npm test`
|
||||
|
||||
Launches the test runner in the interactive watch mode.<br />
|
||||
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
|
||||
|
||||
### `npm run build`
|
||||
|
||||
Builds the app for production to the `build` folder.<br />
|
||||
It correctly bundles React in production mode and optimizes the build for the best performance.
|
||||
|
||||
The build is minified and the filenames include the hashes.<br />
|
||||
Your app is ready to be deployed!
|
||||
|
||||
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
|
||||
|
||||
### `npm run eject`
|
||||
|
||||
**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
|
||||
|
||||
If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
|
||||
|
||||
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
|
||||
|
||||
You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
|
||||
|
||||
## Learn More
|
||||
|
||||
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
|
||||
|
||||
To learn React, check out the [React documentation](https://reactjs.org/).
|
File diff suppressed because it is too large
Load Diff
|
@ -0,0 +1,39 @@
|
|||
{
|
||||
"name": "example",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"dependencies": {
|
||||
"@testing-library/jest-dom": "^4.2.4",
|
||||
"@testing-library/react": "^9.5.0",
|
||||
"@testing-library/user-event": "^7.2.1",
|
||||
"@types/jest": "^24.9.1",
|
||||
"@types/node": "^12.12.47",
|
||||
"@types/react": "^16.9.41",
|
||||
"@types/react-dom": "^16.9.8",
|
||||
"react": "^16.13.1",
|
||||
"react-dom": "^16.13.1",
|
||||
"react-scripts": "3.4.1",
|
||||
"typescript": "^3.7.5"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "react-scripts start",
|
||||
"build": "react-scripts build",
|
||||
"test": "react-scripts test",
|
||||
"eject": "react-scripts eject"
|
||||
},
|
||||
"eslintConfig": {
|
||||
"extends": "react-app"
|
||||
},
|
||||
"browserslist": {
|
||||
"production": [
|
||||
">0.2%",
|
||||
"not dead",
|
||||
"not op_mini all"
|
||||
],
|
||||
"development": [
|
||||
"last 1 chrome version",
|
||||
"last 1 firefox version",
|
||||
"last 1 safari version"
|
||||
]
|
||||
}
|
||||
}
|
Binary file not shown.
After Width: | Height: | Size: 3.1 KiB |
|
@ -0,0 +1,43 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="theme-color" content="#000000" />
|
||||
<meta
|
||||
name="description"
|
||||
content="Web site created using create-react-app"
|
||||
/>
|
||||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
|
||||
<!--
|
||||
manifest.json provides metadata used when your web app is installed on a
|
||||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
|
||||
-->
|
||||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
|
||||
<!--
|
||||
Notice the use of %PUBLIC_URL% in the tags above.
|
||||
It will be replaced with the URL of the `public` folder during the build.
|
||||
Only files inside the `public` folder can be referenced from the HTML.
|
||||
|
||||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
|
||||
work correctly both with client-side routing and a non-root public URL.
|
||||
Learn how to configure a non-root public URL by running `npm run build`.
|
||||
-->
|
||||
<title>React App</title>
|
||||
</head>
|
||||
<body>
|
||||
<noscript>You need to enable JavaScript to run this app.</noscript>
|
||||
<div id="root"></div>
|
||||
<!--
|
||||
This HTML file is a template.
|
||||
If you open it directly in the browser, you will see an empty page.
|
||||
|
||||
You can add webfonts, meta tags, or analytics to this file.
|
||||
The build step will place the bundled scripts into the <body> tag.
|
||||
|
||||
To begin the development, run `npm start` or `yarn start`.
|
||||
To create a production bundle, use `npm run build` or `yarn build`.
|
||||
-->
|
||||
</body>
|
||||
</html>
|
Binary file not shown.
After Width: | Height: | Size: 5.2 KiB |
Binary file not shown.
After Width: | Height: | Size: 9.4 KiB |
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"short_name": "React App",
|
||||
"name": "Create React App Sample",
|
||||
"icons": [
|
||||
{
|
||||
"src": "favicon.ico",
|
||||
"sizes": "64x64 32x32 24x24 16x16",
|
||||
"type": "image/x-icon"
|
||||
},
|
||||
{
|
||||
"src": "logo192.png",
|
||||
"type": "image/png",
|
||||
"sizes": "192x192"
|
||||
},
|
||||
{
|
||||
"src": "logo512.png",
|
||||
"type": "image/png",
|
||||
"sizes": "512x512"
|
||||
}
|
||||
],
|
||||
"start_url": ".",
|
||||
"display": "standalone",
|
||||
"theme_color": "#000000",
|
||||
"background_color": "#ffffff"
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
|
@ -0,0 +1,18 @@
|
|||
.app {
|
||||
width: 100%;
|
||||
|
||||
}
|
||||
.container{
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
margin-left: auto;
|
||||
margin-right: auto;
|
||||
max-width: 860px;
|
||||
|
||||
}
|
||||
|
||||
.container div{
|
||||
display: flex;
|
||||
padding: 10px;
|
||||
margin-top: 40px;
|
||||
}
|
|
@ -0,0 +1,9 @@
|
|||
import React from 'react';
|
||||
import { render } from '@testing-library/react';
|
||||
import App from './App';
|
||||
|
||||
test('renders learn react link', () => {
|
||||
const { getByText } = render(<App />);
|
||||
const linkElement = getByText(/learn react/i);
|
||||
expect(linkElement).toBeInTheDocument();
|
||||
});
|
|
@ -0,0 +1,21 @@
|
|||
import React from 'react';
|
||||
import logo from './logo.svg';
|
||||
import './App.css';
|
||||
|
||||
function App() {
|
||||
return (
|
||||
<div className="app">
|
||||
<div className="container">
|
||||
|
||||
<div>
|
||||
Comp1
|
||||
</div>
|
||||
|
||||
<div>comp2</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default App;
|
|
@ -0,0 +1,13 @@
|
|||
body {
|
||||
margin: 0;
|
||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
|
||||
'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
|
||||
sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
code {
|
||||
font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',
|
||||
monospace;
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import './index.css';
|
||||
import App from './App';
|
||||
import * as serviceWorker from './serviceWorker';
|
||||
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root')
|
||||
);
|
||||
|
||||
// If you want your app to work offline and load faster, you can change
|
||||
// unregister() to register() below. Note this comes with some pitfalls.
|
||||
// Learn more about service workers: https://bit.ly/CRA-PWA
|
||||
serviceWorker.unregister();
|
|
@ -0,0 +1,7 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 841.9 595.3">
|
||||
<g fill="#61DAFB">
|
||||
<path d="M666.3 296.5c0-32.5-40.7-63.3-103.1-82.4 14.4-63.6 8-114.2-20.2-130.4-6.5-3.8-14.1-5.6-22.4-5.6v22.3c4.6 0 8.3.9 11.4 2.6 13.6 7.8 19.5 37.5 14.9 75.7-1.1 9.4-2.9 19.3-5.1 29.4-19.6-4.8-41-8.5-63.5-10.9-13.5-18.5-27.5-35.3-41.6-50 32.6-30.3 63.2-46.9 84-46.9V78c-27.5 0-63.5 19.6-99.9 53.6-36.4-33.8-72.4-53.2-99.9-53.2v22.3c20.7 0 51.4 16.5 84 46.6-14 14.7-28 31.4-41.3 49.9-22.6 2.4-44 6.1-63.6 11-2.3-10-4-19.7-5.2-29-4.7-38.2 1.1-67.9 14.6-75.8 3-1.8 6.9-2.6 11.5-2.6V78.5c-8.4 0-16 1.8-22.6 5.6-28.1 16.2-34.4 66.7-19.9 130.1-62.2 19.2-102.7 49.9-102.7 82.3 0 32.5 40.7 63.3 103.1 82.4-14.4 63.6-8 114.2 20.2 130.4 6.5 3.8 14.1 5.6 22.5 5.6 27.5 0 63.5-19.6 99.9-53.6 36.4 33.8 72.4 53.2 99.9 53.2 8.4 0 16-1.8 22.6-5.6 28.1-16.2 34.4-66.7 19.9-130.1 62-19.1 102.5-49.9 102.5-82.3zm-130.2-66.7c-3.7 12.9-8.3 26.2-13.5 39.5-4.1-8-8.4-16-13.1-24-4.6-8-9.5-15.8-14.4-23.4 14.2 2.1 27.9 4.7 41 7.9zm-45.8 106.5c-7.8 13.5-15.8 26.3-24.1 38.2-14.9 1.3-30 2-45.2 2-15.1 0-30.2-.7-45-1.9-8.3-11.9-16.4-24.6-24.2-38-7.6-13.1-14.5-26.4-20.8-39.8 6.2-13.4 13.2-26.8 20.7-39.9 7.8-13.5 15.8-26.3 24.1-38.2 14.9-1.3 30-2 45.2-2 15.1 0 30.2.7 45 1.9 8.3 11.9 16.4 24.6 24.2 38 7.6 13.1 14.5 26.4 20.8 39.8-6.3 13.4-13.2 26.8-20.7 39.9zm32.3-13c5.4 13.4 10 26.8 13.8 39.8-13.1 3.2-26.9 5.9-41.2 8 4.9-7.7 9.8-15.6 14.4-23.7 4.6-8 8.9-16.1 13-24.1zM421.2 430c-9.3-9.6-18.6-20.3-27.8-32 9 .4 18.2.7 27.5.7 9.4 0 18.7-.2 27.8-.7-9 11.7-18.3 22.4-27.5 32zm-74.4-58.9c-14.2-2.1-27.9-4.7-41-7.9 3.7-12.9 8.3-26.2 13.5-39.5 4.1 8 8.4 16 13.1 24 4.7 8 9.5 15.8 14.4 23.4zM420.7 163c9.3 9.6 18.6 20.3 27.8 32-9-.4-18.2-.7-27.5-.7-9.4 0-18.7.2-27.8.7 9-11.7 18.3-22.4 27.5-32zm-74 58.9c-4.9 7.7-9.8 15.6-14.4 23.7-4.6 8-8.9 16-13 24-5.4-13.4-10-26.8-13.8-39.8 13.1-3.1 26.9-5.8 41.2-7.9zm-90.5 125.2c-35.4-15.1-58.3-34.9-58.3-50.6 0-15.7 22.9-35.6 58.3-50.6 8.6-3.7 18-7 27.7-10.1 5.7 19.6 13.2 40 22.5 60.9-9.2 20.8-16.6 41.1-22.2 60.6-9.9-3.1-19.3-6.5-28-10.2zM310 490c-13.6-7.8-19.5-37.5-14.9-75.7 1.1-9.4 2.9-19.3 5.1-29.4 19.6 4.8 41 8.5 63.5 10.9 13.5 18.5 27.5 35.3 41.6 50-32.6 30.3-63.2 46.9-84 46.9-4.5-.1-8.3-1-11.3-2.7zm237.2-76.2c4.7 38.2-1.1 67.9-14.6 75.8-3 1.8-6.9 2.6-11.5 2.6-20.7 0-51.4-16.5-84-46.6 14-14.7 28-31.4 41.3-49.9 22.6-2.4 44-6.1 63.6-11 2.3 10.1 4.1 19.8 5.2 29.1zm38.5-66.7c-8.6 3.7-18 7-27.7 10.1-5.7-19.6-13.2-40-22.5-60.9 9.2-20.8 16.6-41.1 22.2-60.6 9.9 3.1 19.3 6.5 28.1 10.2 35.4 15.1 58.3 34.9 58.3 50.6-.1 15.7-23 35.6-58.4 50.6zM320.8 78.4z"/>
|
||||
<circle cx="420.9" cy="296.5" r="45.7"/>
|
||||
<path d="M520.5 78.1z"/>
|
||||
</g>
|
||||
</svg>
|
After Width: | Height: | Size: 2.6 KiB |
|
@ -0,0 +1 @@
|
|||
/// <reference types="react-scripts" />
|
|
@ -0,0 +1,149 @@
|
|||
// This optional code is used to register a service worker.
|
||||
// register() is not called by default.
|
||||
|
||||
// This lets the app load faster on subsequent visits in production, and gives
|
||||
// it offline capabilities. However, it also means that developers (and users)
|
||||
// will only see deployed updates on subsequent visits to a page, after all the
|
||||
// existing tabs open on the page have been closed, since previously cached
|
||||
// resources are updated in the background.
|
||||
|
||||
// To learn more about the benefits of this model and instructions on how to
|
||||
// opt-in, read https://bit.ly/CRA-PWA
|
||||
|
||||
const isLocalhost = Boolean(
|
||||
window.location.hostname === 'localhost' ||
|
||||
// [::1] is the IPv6 localhost address.
|
||||
window.location.hostname === '[::1]' ||
|
||||
// 127.0.0.0/8 are considered localhost for IPv4.
|
||||
window.location.hostname.match(
|
||||
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
|
||||
)
|
||||
);
|
||||
|
||||
type Config = {
|
||||
onSuccess?: (registration: ServiceWorkerRegistration) => void;
|
||||
onUpdate?: (registration: ServiceWorkerRegistration) => void;
|
||||
};
|
||||
|
||||
export function register(config?: Config) {
|
||||
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
|
||||
// The URL constructor is available in all browsers that support SW.
|
||||
const publicUrl = new URL(
|
||||
process.env.PUBLIC_URL,
|
||||
window.location.href
|
||||
);
|
||||
if (publicUrl.origin !== window.location.origin) {
|
||||
// Our service worker won't work if PUBLIC_URL is on a different origin
|
||||
// from what our page is served on. This might happen if a CDN is used to
|
||||
// serve assets; see https://github.com/facebook/create-react-app/issues/2374
|
||||
return;
|
||||
}
|
||||
|
||||
window.addEventListener('load', () => {
|
||||
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
|
||||
|
||||
if (isLocalhost) {
|
||||
// This is running on localhost. Let's check if a service worker still exists or not.
|
||||
checkValidServiceWorker(swUrl, config);
|
||||
|
||||
// Add some additional logging to localhost, pointing developers to the
|
||||
// service worker/PWA documentation.
|
||||
navigator.serviceWorker.ready.then(() => {
|
||||
console.log(
|
||||
'This web app is being served cache-first by a service ' +
|
||||
'worker. To learn more, visit https://bit.ly/CRA-PWA'
|
||||
);
|
||||
});
|
||||
} else {
|
||||
// Is not localhost. Just register service worker
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function registerValidSW(swUrl: string, config?: Config) {
|
||||
navigator.serviceWorker
|
||||
.register(swUrl)
|
||||
.then(registration => {
|
||||
registration.onupdatefound = () => {
|
||||
const installingWorker = registration.installing;
|
||||
if (installingWorker == null) {
|
||||
return;
|
||||
}
|
||||
installingWorker.onstatechange = () => {
|
||||
if (installingWorker.state === 'installed') {
|
||||
if (navigator.serviceWorker.controller) {
|
||||
// At this point, the updated precached content has been fetched,
|
||||
// but the previous service worker will still serve the older
|
||||
// content until all client tabs are closed.
|
||||
console.log(
|
||||
'New content is available and will be used when all ' +
|
||||
'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
|
||||
);
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onUpdate) {
|
||||
config.onUpdate(registration);
|
||||
}
|
||||
} else {
|
||||
// At this point, everything has been precached.
|
||||
// It's the perfect time to display a
|
||||
// "Content is cached for offline use." message.
|
||||
console.log('Content is cached for offline use.');
|
||||
|
||||
// Execute callback
|
||||
if (config && config.onSuccess) {
|
||||
config.onSuccess(registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
};
|
||||
})
|
||||
.catch(error => {
|
||||
console.error('Error during service worker registration:', error);
|
||||
});
|
||||
}
|
||||
|
||||
function checkValidServiceWorker(swUrl: string, config?: Config) {
|
||||
// Check if the service worker can be found. If it can't reload the page.
|
||||
fetch(swUrl, {
|
||||
headers: { 'Service-Worker': 'script' }
|
||||
})
|
||||
.then(response => {
|
||||
// Ensure service worker exists, and that we really are getting a JS file.
|
||||
const contentType = response.headers.get('content-type');
|
||||
if (
|
||||
response.status === 404 ||
|
||||
(contentType != null && contentType.indexOf('javascript') === -1)
|
||||
) {
|
||||
// No service worker found. Probably a different app. Reload the page.
|
||||
navigator.serviceWorker.ready.then(registration => {
|
||||
registration.unregister().then(() => {
|
||||
window.location.reload();
|
||||
});
|
||||
});
|
||||
} else {
|
||||
// Service worker found. Proceed as normal.
|
||||
registerValidSW(swUrl, config);
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
console.log(
|
||||
'No internet connection found. App is running in offline mode.'
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export function unregister() {
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker.ready
|
||||
.then(registration => {
|
||||
registration.unregister();
|
||||
})
|
||||
.catch(error => {
|
||||
console.error(error.message);
|
||||
});
|
||||
}
|
||||
}
|
|
@ -0,0 +1,5 @@
|
|||
// jest-dom adds custom jest matchers for asserting on DOM nodes.
|
||||
// allows you to do things like:
|
||||
// expect(element).toHaveTextContent(/react/i)
|
||||
// learn more: https://github.com/testing-library/jest-dom
|
||||
import '@testing-library/jest-dom/extend-expect';
|
|
@ -0,0 +1,25 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "es5",
|
||||
"lib": [
|
||||
"dom",
|
||||
"dom.iterable",
|
||||
"esnext"
|
||||
],
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strict": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"resolveJsonModule": true,
|
||||
"isolatedModules": true,
|
||||
"noEmit": true,
|
||||
"jsx": "react"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
]
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -6,6 +6,7 @@
|
|||
"module": "dist/esm/index.js",
|
||||
"scripts": {
|
||||
"start": "tsc --watch",
|
||||
"start-example": "cd example && npm start",
|
||||
"build": "tsc",
|
||||
"test": "npm run lint",
|
||||
"lint": "eslint --ignore-path .gitignore --ext .js --ext .ts --ext .tsx .",
|
||||
|
@ -20,10 +21,12 @@
|
|||
"dist/"
|
||||
],
|
||||
"dependencies": {
|
||||
"@oceanprotocol/squid": "^2.2.0",
|
||||
"@oceanprotocol/contracts": "^0.2.2",
|
||||
"@oceanprotocol/lib": "../ocean-lib-js",
|
||||
"axios": "^0.19.2",
|
||||
"react": "^16.13.1",
|
||||
"web3connect": "^1.0.0-beta.33"
|
||||
"web3": "^1.2.9",
|
||||
"web3modal": "^1.7.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@release-it/bumper": "^1.1.1",
|
||||
|
|
|
@ -4,10 +4,3 @@ import { HttpProvider } from 'web3-core'
|
|||
interface EthereumProvider extends HttpProvider {
|
||||
enable: () => Promise<void>
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
web3: Web3
|
||||
ethereum: EthereumProvider
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,4 +1,2 @@
|
|||
export * from './useConsume'
|
||||
export * from './useMetadata'
|
||||
export * from './useCompute'
|
||||
export * from './useSearch'
|
||||
|
|
|
@ -1,28 +0,0 @@
|
|||
export interface ComputeValue {
|
||||
entrypoint: string
|
||||
image: string
|
||||
tag: string
|
||||
}
|
||||
export interface ComputeOption {
|
||||
name: string
|
||||
value: ComputeValue
|
||||
}
|
||||
|
||||
export const computeOptions: ComputeOption[] = [
|
||||
{
|
||||
name: 'nodejs',
|
||||
value: {
|
||||
entrypoint: 'node $ALGO',
|
||||
image: 'node',
|
||||
tag: '10'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'python3.7',
|
||||
value: {
|
||||
entrypoint: 'python $ALGO',
|
||||
image: 'oceanprotocol/algo_dockers',
|
||||
tag: 'python-panda'
|
||||
}
|
||||
}
|
||||
]
|
|
@ -1,67 +0,0 @@
|
|||
# `useCompute`
|
||||
|
||||
Start a compute job on a data asset and retrieve its status.
|
||||
|
||||
## Usage
|
||||
|
||||
```tsx
|
||||
import React from 'react'
|
||||
import {
|
||||
useWeb3,
|
||||
useMetadata,
|
||||
useCompute,
|
||||
computeOptions,
|
||||
ComputeValue,
|
||||
readFileContent
|
||||
} from '@oceanprotocol/react'
|
||||
|
||||
const did = 'did:op:0x000000000'
|
||||
|
||||
export default function MyComponent() {
|
||||
// Get web3 from Web3Provider context
|
||||
const { web3, account } = useWeb3()
|
||||
|
||||
// Get metadata for this asset
|
||||
const { title, metadata } = useMetadata(did)
|
||||
|
||||
// compute asset
|
||||
const { compute, computeStep } = useCompute()
|
||||
|
||||
// raw code text
|
||||
const [algorithmRawCode, setAlgorithmRawCode] = useState('')
|
||||
const [computeContainer, setComputeContainer] = useState<ComputeValue>()
|
||||
async function handleCompute() {
|
||||
await consume(did,algorithmRawCode,computeContainer)
|
||||
}
|
||||
|
||||
async function onChangeHandler(event){
|
||||
const fileText = await readFileContent(files[0])
|
||||
setAlgorithmRawCode(fileText)
|
||||
}
|
||||
|
||||
async function handleSelectChange(event: any) {
|
||||
const comType = event.target.value
|
||||
setComputeContainer(comType)
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1>{title}</h1>
|
||||
<p>Price: {web3.utils.fromWei(metadata.main.price)}</p>
|
||||
|
||||
<p>Your account: {account}</p>
|
||||
<label for="computeOptions">Select image to run the algorithm</label>
|
||||
<select id="computeOptions" onChange={handleSelectChange}>
|
||||
{computeOptions.map((x) => (
|
||||
<option value={x.value}>{x.name}</option>
|
||||
)
|
||||
}
|
||||
</select>
|
||||
<input type="file" name="file" onChange={onChangeHandler}/>
|
||||
<button onClick={handleCompute}>
|
||||
{computeStep || 'Start compute job'}
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
```
|
|
@ -1,2 +0,0 @@
|
|||
export * from './useCompute'
|
||||
export * from './ComputeOptions'
|
|
@ -1,94 +0,0 @@
|
|||
import { useState } from 'react'
|
||||
import { DID, MetaDataAlgorithm, Logger } from '@oceanprotocol/squid'
|
||||
import { useOcean } from '../../providers'
|
||||
import { ComputeValue } from './ComputeOptions'
|
||||
import { feedback } from './../../utils'
|
||||
import { LoggerInstance } from '@oceanprotocol/squid/dist/node/utils/Logger'
|
||||
interface UseCompute {
|
||||
compute: (
|
||||
did: DID | string,
|
||||
algorithmRawCode: string,
|
||||
computeContainer: ComputeValue
|
||||
) => Promise<void>
|
||||
computeStep?: number
|
||||
computeStepText?: string
|
||||
computeError?: string
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
// TODO: customize for compute
|
||||
export const computeFeedback: { [key in number]: string } = {
|
||||
...feedback,
|
||||
4: '3/3 Access granted. Starting job...'
|
||||
}
|
||||
const rawAlgorithmMeta: MetaDataAlgorithm = {
|
||||
rawcode: `console.log('Hello world'!)`,
|
||||
format: 'docker-image',
|
||||
version: '0.1',
|
||||
container: {
|
||||
entrypoint: '',
|
||||
image: '',
|
||||
tag: ''
|
||||
}
|
||||
}
|
||||
|
||||
function useCompute(): UseCompute {
|
||||
const { ocean, account, accountId, config } = useOcean()
|
||||
const [computeStep, setComputeStep] = useState<number | undefined>()
|
||||
const [computeStepText, setComputeStepText] = useState<string | undefined>()
|
||||
const [computeError, setComputeError] = useState<string | undefined>()
|
||||
const [isLoading, setIsLoading] = useState(false)
|
||||
|
||||
async function compute(
|
||||
did: DID | string,
|
||||
algorithmRawCode: string,
|
||||
computeContainer: ComputeValue
|
||||
): Promise<void> {
|
||||
if (!ocean || !account) return
|
||||
|
||||
setComputeError(undefined)
|
||||
|
||||
try {
|
||||
setIsLoading(true)
|
||||
const computeOutput = {
|
||||
publishAlgorithmLog: false,
|
||||
publishOutput: false,
|
||||
brizoAddress: config.brizoAddress,
|
||||
brizoUri: config.brizoUri,
|
||||
metadataUri: config.aquariusUri,
|
||||
nodeUri: config.nodeUri,
|
||||
owner: accountId,
|
||||
secretStoreUri: config.secretStoreUri
|
||||
}
|
||||
const agreement = await ocean.compute
|
||||
.order(account, did as string)
|
||||
.next((step: number) => {
|
||||
setComputeStep(step)
|
||||
setComputeStepText(computeFeedback[step])
|
||||
})
|
||||
|
||||
rawAlgorithmMeta.container = computeContainer
|
||||
rawAlgorithmMeta.rawcode = algorithmRawCode
|
||||
setComputeStep(4)
|
||||
setComputeStepText(computeFeedback[4])
|
||||
await ocean.compute.start(
|
||||
account,
|
||||
agreement,
|
||||
undefined,
|
||||
rawAlgorithmMeta,
|
||||
computeOutput
|
||||
)
|
||||
} catch (error) {
|
||||
Logger.error(error)
|
||||
setComputeError(error.message)
|
||||
} finally {
|
||||
setComputeStep(undefined)
|
||||
setIsLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return { compute, computeStep, computeStepText, computeError, isLoading }
|
||||
}
|
||||
|
||||
export { useCompute, UseCompute }
|
||||
export default UseCompute
|
|
@ -1,10 +1,11 @@
|
|||
import { useState } from 'react'
|
||||
import { DID } from '@oceanprotocol/squid'
|
||||
import { useOcean } from '../../providers'
|
||||
import { feedback } from '../../utils'
|
||||
import { DID } from '@oceanprotocol/lib'
|
||||
import { ServiceType } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service'
|
||||
|
||||
interface UseConsume {
|
||||
consume: (did: DID | string) => Promise<void>
|
||||
consume: (did: DID | string, serviceType: ServiceType) => Promise<void>
|
||||
consumeStep?: number
|
||||
consumeStepText?: string
|
||||
consumeError?: string
|
||||
|
@ -16,7 +17,7 @@ interface UseConsume {
|
|||
// instead of just a number
|
||||
export const consumeFeedback: { [key in number]: string } = {
|
||||
...feedback,
|
||||
4: '3/3 Access granted. Consuming file...'
|
||||
3: '3/3 Access granted. Consuming file...'
|
||||
}
|
||||
|
||||
function useConsume(): UseConsume {
|
||||
|
@ -26,30 +27,43 @@ function useConsume(): UseConsume {
|
|||
const [consumeStepText, setConsumeStepText] = useState<string | undefined>()
|
||||
const [consumeError, setConsumeError] = useState<string | undefined>()
|
||||
|
||||
async function consume(did: DID | string): Promise<void> {
|
||||
async function consume(did: string, serviceType: ServiceType): Promise<void> {
|
||||
if (!ocean || !account) return
|
||||
setIsLoading(true)
|
||||
setConsumeError(undefined)
|
||||
|
||||
try {
|
||||
const agreements = await ocean.keeper.conditions.accessSecretStoreCondition.getGrantedDidByConsumer(
|
||||
accountId
|
||||
)
|
||||
const agreement = agreements.find((el: { did: string }) => el.did === did)
|
||||
console.log('existing agre', agreements)
|
||||
const agreementId = agreement
|
||||
? agreement.agreementId
|
||||
: await ocean.assets
|
||||
.order(did as string, account)
|
||||
.next((step: number) => {
|
||||
setConsumeStep(step)
|
||||
setConsumeStepText(consumeFeedback[step])
|
||||
})
|
||||
|
||||
// manually add another step here for better UX
|
||||
setConsumeStep(0)
|
||||
setConsumeStepText(consumeFeedback[0])
|
||||
const ddo = await ocean.metadatastore.retrieveDDO(did)
|
||||
|
||||
setConsumeStep(1)
|
||||
setConsumeStepText(consumeFeedback[1])
|
||||
const order = await ocean.assets
|
||||
.order(did, serviceType, accountId)
|
||||
setConsumeStep(2)
|
||||
setConsumeStepText(consumeFeedback[2])
|
||||
const res = JSON.parse(order)
|
||||
const tokenTransfer = await ocean.datatokens.transfer(
|
||||
res['dataToken'],
|
||||
res['to'],
|
||||
res['numTokens'],
|
||||
res['from']
|
||||
)
|
||||
setConsumeStep(3)
|
||||
setConsumeStepText(consumeFeedback[3])
|
||||
await ocean.assets.download(
|
||||
did,
|
||||
(tokenTransfer as any).transactionHash,
|
||||
ddo.dataToken,
|
||||
account,
|
||||
''
|
||||
)
|
||||
|
||||
setConsumeStep(4)
|
||||
setConsumeStepText(consumeFeedback[4])
|
||||
await ocean.assets.consume(agreementId, did as string, account, '')
|
||||
|
||||
} catch (error) {
|
||||
setConsumeError(error.message)
|
||||
} finally {
|
||||
|
|
|
@ -1,54 +1,44 @@
|
|||
import { useState, useEffect } from 'react'
|
||||
import axios from 'axios'
|
||||
import { DID, DDO, MetaData, Curation } from '@oceanprotocol/squid'
|
||||
import { useOcean, OceanConnectionStatus } from '../../providers'
|
||||
import { DID, DDO, Metadata } from '@oceanprotocol/lib'
|
||||
import { useOcean, } from '../../providers'
|
||||
import ProviderStatus from '../../providers/OceanProvider/ProviderStatus'
|
||||
|
||||
interface UseMetadata {
|
||||
ddo: DDO
|
||||
metadata: MetaData
|
||||
metadata: Metadata
|
||||
title: string
|
||||
getDDO: (did: DID | string) => Promise<DDO>
|
||||
getMetadata: (did: DID | string) => Promise<MetaData>
|
||||
getCuration: (did: DID | string) => Promise<Curation>
|
||||
getMetadata: (did: DID | string) => Promise<Metadata>
|
||||
getTitle: (did: DID | string) => Promise<string>
|
||||
getAllDIDs: () => Promise<DID[]>
|
||||
}
|
||||
|
||||
function useMetadata(did?: DID | string): UseMetadata {
|
||||
const { aquarius, config, status } = useOcean()
|
||||
const { ocean, status } = useOcean()
|
||||
const [ddo, setDDO] = useState<DDO | undefined>()
|
||||
const [metadata, setMetadata] = useState<MetaData | undefined>()
|
||||
const [metadata, setMetadata] = useState<Metadata | undefined>()
|
||||
const [title, setTitle] = useState<string | undefined>()
|
||||
|
||||
async function getDDO(did: DID | string): Promise<DDO> {
|
||||
if (status !== OceanConnectionStatus.CONNECTED) return
|
||||
if (status !== ProviderStatus.CONNECTED) return
|
||||
|
||||
const ddo = await aquarius.retrieveDDO(did)
|
||||
const ddo = await ocean.metadatastore.retrieveDDO(did)
|
||||
return ddo
|
||||
}
|
||||
|
||||
async function getMetadata(did: DID | string): Promise<MetaData> {
|
||||
async function getMetadata(did: DID | string): Promise<Metadata> {
|
||||
const ddo = await getDDO(did)
|
||||
if (!ddo) return
|
||||
const metadata = ddo.findServiceByType('metadata')
|
||||
return metadata.attributes
|
||||
}
|
||||
|
||||
async function getCuration(did: DID | string): Promise<Curation> {
|
||||
const metadata = await getMetadata(did)
|
||||
return metadata.curation
|
||||
}
|
||||
|
||||
async function getTitle(did: DID | string): Promise<string> {
|
||||
const metadata = await getMetadata(did)
|
||||
return metadata.main.name
|
||||
}
|
||||
|
||||
async function getAllDIDs(): Promise<DID[]> {
|
||||
const assets = await axios(`${config.aquariusUri}/api/v1/aquarius/assets`)
|
||||
return assets.data
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
async function init(): Promise<void> {
|
||||
if (!did) return
|
||||
|
@ -68,9 +58,7 @@ function useMetadata(did?: DID | string): UseMetadata {
|
|||
title,
|
||||
getDDO,
|
||||
getMetadata,
|
||||
getCuration,
|
||||
getTitle,
|
||||
getAllDIDs
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -0,0 +1,71 @@
|
|||
import { useEffect } from 'react'
|
||||
import { DDO, Metadata, DataTokens } from '@oceanprotocol/lib'
|
||||
import { useOcean, } from '../../providers'
|
||||
import ProviderStatus from '../../providers/OceanProvider/ProviderStatus'
|
||||
import { Service } from '@oceanprotocol/lib/dist/node/ddo/interfaces/Service'
|
||||
|
||||
interface UsePublish {
|
||||
|
||||
publish: (asset: Metadata, price?: number) => Promise<DDO>
|
||||
|
||||
}
|
||||
|
||||
const factory = require('@oceanprotocol/contracts/artifacts/development/Factory.json')
|
||||
const datatokensTemplate = require('@oceanprotocol/contracts/artifacts/development/DataTokenTemplate.json')
|
||||
|
||||
function usePublish(): UsePublish {
|
||||
const { web3, ocean, status, account, config } = useOcean()
|
||||
|
||||
async function publish(asset: Metadata, price: number = 1): Promise<DDO> {
|
||||
if (status !== ProviderStatus.CONNECTED) return
|
||||
|
||||
const datatoken = new DataTokens(
|
||||
ocean.datatokens.factoryAddress,
|
||||
factory.abi,
|
||||
datatokensTemplate.abi,
|
||||
web3
|
||||
)
|
||||
const data = { t: 1, url: config.metadataStoreUri }
|
||||
const blob = JSON.stringify(data)
|
||||
const tokenAddress = await datatoken.create(blob, account)
|
||||
const publishedDate = new Date(Date.now()).toISOString().split('.')[0] + 'Z'
|
||||
const timeout = 0
|
||||
let services: Service[] = []
|
||||
switch (asset.main.type) {
|
||||
case 'dataset': {
|
||||
const accessService = await ocean.assets.createAccessServiceAttributes(
|
||||
account,
|
||||
price,
|
||||
publishedDate,
|
||||
timeout
|
||||
)
|
||||
services = [accessService]
|
||||
break;
|
||||
}
|
||||
case 'algorithm': {
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
const ddo = await ocean.assets.create(asset, account, services, tokenAddress)
|
||||
|
||||
return ddo
|
||||
}
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
async function init(): Promise<void> {
|
||||
|
||||
}
|
||||
init()
|
||||
}, [])
|
||||
|
||||
return {
|
||||
publish
|
||||
}
|
||||
}
|
||||
|
||||
export { usePublish, UsePublish }
|
||||
export default usePublish
|
|
@ -1,5 +0,0 @@
|
|||
import { DDO, ComputeJob } from '@oceanprotocol/squid'
|
||||
export interface ComputeItem {
|
||||
job: ComputeJob
|
||||
ddo: DDO
|
||||
}
|
|
@ -1,2 +0,0 @@
|
|||
export * from './useSearch'
|
||||
export * from './ComputeItem'
|
|
@ -1,136 +0,0 @@
|
|||
import { useState } from 'react'
|
||||
import { Logger, DDO, ComputeJob } from '@oceanprotocol/squid'
|
||||
import { useOcean } from '../../providers'
|
||||
import {
|
||||
SearchQuery,
|
||||
Aquarius,
|
||||
QueryResult
|
||||
} from '@oceanprotocol/squid/dist/node/aquarius/Aquarius'
|
||||
import { ComputeItem } from './ComputeItem'
|
||||
|
||||
// TODO searchText,
|
||||
interface UseSearch {
|
||||
searchWithQuery: (query: SearchQuery) => Promise<QueryResult>
|
||||
getPublishedList: (page: number, offset: number) => Promise<QueryResult>
|
||||
getConsumedList: () => Promise<DDO[] | undefined>
|
||||
getComputeItems: () => Promise<ComputeItem[] | undefined>
|
||||
searchError?: string
|
||||
}
|
||||
|
||||
function useSearch(): UseSearch {
|
||||
// should we call the useOcean hook in useSearch or in each function?
|
||||
const { ocean, account, config, accountId } = useOcean()
|
||||
const [searchError, setSearchError] = useState<string | undefined>()
|
||||
|
||||
async function searchWithQuery(query: SearchQuery): Promise<QueryResult> {
|
||||
if (!ocean || !account) return
|
||||
|
||||
setSearchError(undefined)
|
||||
|
||||
try {
|
||||
const aquarius = new Aquarius(config.aquariusUri as string, Logger)
|
||||
return await aquarius.queryMetadata(query)
|
||||
} catch (error) {
|
||||
setSearchError(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function getPublishedList(
|
||||
page: number,
|
||||
offset: number
|
||||
): Promise<QueryResult> {
|
||||
if (!ocean || !accountId) return
|
||||
|
||||
setSearchError(undefined)
|
||||
|
||||
try {
|
||||
const query = {
|
||||
page,
|
||||
offset,
|
||||
query: {
|
||||
'publicKey.owner': [accountId]
|
||||
},
|
||||
sort: {
|
||||
created: -1
|
||||
}
|
||||
} as SearchQuery
|
||||
|
||||
return await searchWithQuery(query)
|
||||
} catch (error) {
|
||||
setSearchError(error.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function getConsumedList(): Promise<DDO[] | undefined> {
|
||||
const consumed = await ocean.assets.consumerAssets(accountId)
|
||||
const consumedItems = await Promise.all(
|
||||
consumed.map(async (did) => {
|
||||
try {
|
||||
const ddo = await ocean.assets.resolve(did)
|
||||
if (ddo) {
|
||||
// Since we are getting assets from chain there might be
|
||||
// assets from other marketplaces. So return only those assets
|
||||
// whose serviceEndpoint contains the configured Aquarius URI.
|
||||
const { serviceEndpoint } = ddo.findServiceByType('metadata')
|
||||
if (serviceEndpoint?.includes(config.aquariusUri)) return ddo
|
||||
}
|
||||
} catch (err) {
|
||||
Logger.error(err)
|
||||
}
|
||||
})
|
||||
)
|
||||
const filteredConsumedItems = consumedItems.filter(
|
||||
(value) => typeof value !== 'undefined'
|
||||
)
|
||||
return filteredConsumedItems
|
||||
}
|
||||
|
||||
async function getComputeItems(): Promise<ComputeItem[] | undefined> {
|
||||
if (!ocean || !account) return
|
||||
const jobList = await ocean.compute.status(account)
|
||||
const computeItems = await Promise.all(
|
||||
jobList.map(async (job) => {
|
||||
if (!job) return
|
||||
try {
|
||||
const { did } = await ocean.keeper.agreementStoreManager.getAgreement(
|
||||
job.agreementId
|
||||
)
|
||||
if (
|
||||
did ===
|
||||
'0x0000000000000000000000000000000000000000000000000000000000000000'
|
||||
)
|
||||
return
|
||||
|
||||
const ddo = await ocean.assets.resolve(did)
|
||||
|
||||
if (ddo) {
|
||||
// Since we are getting assets from chain there might be
|
||||
// assets from other marketplaces. So return only those assets
|
||||
// whose serviceEndpoint contains the configured Aquarius URI.
|
||||
const { serviceEndpoint } = ddo.findServiceByType('metadata')
|
||||
if (serviceEndpoint?.includes(config.aquariusUri)) {
|
||||
return { job, ddo }
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
Logger.error(err)
|
||||
}
|
||||
})
|
||||
)
|
||||
const filteredComputeItems = computeItems.filter(
|
||||
(value) => value !== undefined && typeof value.ddo !== 'undefined'
|
||||
)
|
||||
return filteredComputeItems
|
||||
}
|
||||
|
||||
return {
|
||||
searchWithQuery,
|
||||
getPublishedList,
|
||||
getConsumedList,
|
||||
getComputeItems,
|
||||
searchError
|
||||
}
|
||||
}
|
||||
|
||||
export { useSearch, UseSearch }
|
||||
export default useSearch
|
|
@ -2,5 +2,4 @@ export * from './providers'
|
|||
export * from './hooks'
|
||||
// export * from './components'
|
||||
|
||||
export * from './utils/curationUtils'
|
||||
export * from './utils'
|
||||
|
|
|
@ -1,8 +0,0 @@
|
|||
|
||||
enum OceanConnectionStatus {
|
||||
OCEAN_CONNECTION_ERROR = -1,
|
||||
NOT_CONNECTED = 0,
|
||||
CONNECTED = 1
|
||||
}
|
||||
|
||||
export default OceanConnectionStatus
|
|
@ -1,21 +1,32 @@
|
|||
import React, { useContext, useState, useEffect, createContext } from 'react'
|
||||
import { Ocean, Config, Account, Aquarius, Logger } from '@oceanprotocol/squid'
|
||||
import Web3 from 'web3'
|
||||
import Balance from '@oceanprotocol/squid/dist/node/models/Balance'
|
||||
import { connectOcean } from './utils'
|
||||
import { useWeb3, InjectedProviderStatus } from '../Web3Provider'
|
||||
import OceanConnectionStatus from './OceanConnectionStatus'
|
||||
import ProviderStatus from './ProviderStatus'
|
||||
import { Ocean, Logger, Account, Config } from '@oceanprotocol/lib'
|
||||
import Web3Modal, { IProviderOptions } from 'web3modal'
|
||||
import { LogLevel } from '@oceanprotocol/lib/dist/node/utils/Logger'
|
||||
|
||||
const factory = require('@oceanprotocol/contracts/artifacts/development/Factory.json')
|
||||
const datatokensTemplate = require('@oceanprotocol/contracts/artifacts/development/DataTokenTemplate.json')
|
||||
|
||||
interface OceanProviderValue {
|
||||
aquarius: Aquarius
|
||||
web3: Web3 | undefined
|
||||
web3Provider: any
|
||||
web3Modal: Web3Modal
|
||||
ocean: Ocean
|
||||
config: Config
|
||||
account: Account
|
||||
accountId: string
|
||||
balance: Balance
|
||||
balanceInOcean: string
|
||||
status: OceanConnectionStatus
|
||||
config: Config
|
||||
balance: string
|
||||
chainId: number | undefined
|
||||
status: ProviderStatus
|
||||
connect: () => void
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
interface OceanProviderConfig {
|
||||
providerOptions?: IProviderOptions,
|
||||
cacheProvider?: boolean,
|
||||
oceanConfig: Config
|
||||
}
|
||||
|
||||
const OceanContext = createContext(null)
|
||||
|
@ -24,81 +35,144 @@ function OceanProvider({
|
|||
config,
|
||||
children
|
||||
}: {
|
||||
config: Config
|
||||
config: OceanProviderConfig
|
||||
children: any
|
||||
}): any {
|
||||
const [web3, setWeb3] = useState<Web3 | undefined>()
|
||||
const [web3Provider, setWeb3Provider] = useState<any | undefined>()
|
||||
const [ocean, setOcean] = useState<Ocean | undefined>()
|
||||
const [aquarius, setAquarius] = useState<Aquarius | undefined>()
|
||||
const [web3Modal, setWeb3Modal] = useState<Web3Modal>(null)
|
||||
const [chainId, setChainId] = useState<number | undefined>()
|
||||
const [account, setAccount] = useState<Account | undefined>()
|
||||
const [accountId, setAccountId] = useState<string | undefined>()
|
||||
const [balance, setBalance] = useState<Balance | undefined>()
|
||||
const [balanceInOcean, setBalanceInOcean] = useState<string | undefined>()
|
||||
const [status, setStatus] = useState<OceanConnectionStatus>(
|
||||
OceanConnectionStatus.NOT_CONNECTED
|
||||
const [balance, setBalance] = useState<string | undefined>()
|
||||
const [status, setStatus] = useState(
|
||||
ProviderStatus.NOT_AVAILABLE
|
||||
)
|
||||
const { web3, ethProviderStatus } = useWeb3()
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// 1. On mount, connect to Aquarius instance right away
|
||||
// -------------------------------------------------------------
|
||||
|
||||
function init() {
|
||||
const instance = new Web3Modal({
|
||||
cacheProvider: false, // optional,
|
||||
providerOptions: config.providerOptions ? config.providerOptions : {}
|
||||
});
|
||||
setWeb3Modal(instance)
|
||||
|
||||
}
|
||||
|
||||
// On mount setup Web3Modal instance
|
||||
useEffect(() => {
|
||||
const aquarius = new Aquarius(config.aquariusUri, Logger)
|
||||
setAquarius(aquarius)
|
||||
init()
|
||||
}, [])
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// 2. Once `web3` becomes available, connect to the whole network
|
||||
// -------------------------------------------------------------
|
||||
useEffect(() => {
|
||||
if (!web3 || ethProviderStatus !== InjectedProviderStatus.CONNECTED) return
|
||||
async function init(): Promise<void> {
|
||||
const { ocean, account, accountId, balance } = await connectOcean(
|
||||
web3,
|
||||
config
|
||||
)
|
||||
async function connect() {
|
||||
const provider = await web3Modal.connect()
|
||||
setWeb3Provider(provider)
|
||||
|
||||
const web3 = new Web3(provider)
|
||||
setWeb3(web3)
|
||||
|
||||
}
|
||||
|
||||
async function logout() {
|
||||
|
||||
// ToDo check how is the proper way to logout
|
||||
web3Modal.clearCachedProvider()
|
||||
|
||||
}
|
||||
|
||||
async function getAccount(web3: Web3) {
|
||||
const accounts = await web3.eth.getAccounts()
|
||||
return accounts[0]
|
||||
}
|
||||
|
||||
async function getBalance(web3: Web3, address: string) {
|
||||
const balance = await web3.eth.getBalance(address)
|
||||
return Web3.utils.fromWei(balance)
|
||||
}
|
||||
|
||||
//
|
||||
// Listen for provider, account & network changes
|
||||
// and react to it
|
||||
//
|
||||
const handleConnect = async (provider: any) => {
|
||||
Logger.debug("Handling 'connect' event with payload", provider)
|
||||
setStatus(ProviderStatus.CONNECTED)
|
||||
|
||||
config.oceanConfig.factoryABI = config.oceanConfig.factoryABI? config.oceanConfig.factoryABI : factory.abi
|
||||
config.oceanConfig.datatokensABI= config.oceanConfig.datatokensABI? config.oceanConfig.datatokensABI: datatokensTemplate.abi
|
||||
|
||||
const ocean = await Ocean.getInstance(config.oceanConfig)
|
||||
|
||||
setOcean(ocean)
|
||||
setStatus(OceanConnectionStatus.CONNECTED)
|
||||
|
||||
const account = await ocean.accounts[0];
|
||||
setAccount(account)
|
||||
|
||||
const accountId = await getAccount(web3)
|
||||
setAccountId(accountId)
|
||||
|
||||
const balance = await getBalance(web3, account)
|
||||
setBalance(balance)
|
||||
setBalanceInOcean(`${balance?.ocn}`)
|
||||
|
||||
const chainId = web3 && (await web3.eth.getChainId())
|
||||
setChainId(chainId)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ToDo need to handle this, it's not implemented
|
||||
const handleNetworkChanged = async (networkId: string | number) => {
|
||||
console.debug("Handling 'networkChanged' event with payload", networkId)
|
||||
web3Provider.autoRefreshOnNetworkChange = false
|
||||
// init(networkId)
|
||||
// handleConnect(ethProvider)
|
||||
}
|
||||
|
||||
try {
|
||||
init()
|
||||
} catch (error) {
|
||||
console.error(error.message)
|
||||
setStatus(OceanConnectionStatus.OCEAN_CONNECTION_ERROR)
|
||||
throw error.message
|
||||
}
|
||||
}, [web3])
|
||||
|
||||
// -------------------------------------------------------------
|
||||
// 3. Once `ocean` becomes available, spit out some info about it
|
||||
// -------------------------------------------------------------
|
||||
useEffect(() => {
|
||||
async function debug(): Promise<void> {
|
||||
if (!ocean) return
|
||||
Logger.debug(
|
||||
`Ocean instance initiated with:\n ${JSON.stringify(config, null, 2)}`
|
||||
)
|
||||
Logger.debug(await ocean.versions.get())
|
||||
web3Modal && web3Modal.on('connect', handleConnect)
|
||||
|
||||
if (web3Provider !== undefined && web3Provider !== null) {
|
||||
|
||||
web3Provider.on('accountsChanged', handleAccountsChanged)
|
||||
web3Provider.on('networkChanged', handleNetworkChanged)
|
||||
|
||||
return () => {
|
||||
web3Provider.removeListener('accountsChanged', handleAccountsChanged)
|
||||
web3Provider.removeListener('networkChanged', handleNetworkChanged)
|
||||
}
|
||||
debug()
|
||||
}, [ocean])
|
||||
}
|
||||
}, [web3, web3Modal, web3Provider])
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<OceanContext.Provider
|
||||
value={
|
||||
{
|
||||
web3,
|
||||
web3Provider,
|
||||
web3Modal,
|
||||
ocean,
|
||||
aquarius,
|
||||
account,
|
||||
accountId,
|
||||
balance,
|
||||
balanceInOcean,
|
||||
chainId,
|
||||
status,
|
||||
config
|
||||
config: config.oceanConfig,
|
||||
connect,
|
||||
logout,
|
||||
} as OceanProviderValue
|
||||
}
|
||||
>
|
||||
|
|
|
@ -0,0 +1,7 @@
|
|||
enum ProviderStatus {
|
||||
NOT_AVAILABLE = -1,
|
||||
NOT_CONNECTED = 0,
|
||||
CONNECTED = 1
|
||||
}
|
||||
|
||||
export default ProviderStatus
|
|
@ -1,2 +1,2 @@
|
|||
export * from './OceanProvider'
|
||||
export * from './OceanConnectionStatus'
|
||||
export * from './ProviderStatus'
|
|
@ -1,54 +0,0 @@
|
|||
# `Web3Provider`
|
||||
|
||||
To get you started, we added this basic `Web3Provider` which assumes an injected provider (like MetaMask), and will ask for user permissions automatically on first mount.
|
||||
|
||||
Also provides a `useWeb3` helper hook to access its context values from any component.
|
||||
|
||||
We suggest you replace this provider with a more complete solution, since there are many UX considerations not handled in that basic provider, like activate only on user intent, listen for account & network changes, display connection instructions and errors, etc.
|
||||
|
||||
Some great solutions we liked to work with:
|
||||
|
||||
- [web3-react](https://github.com/NoahZinsmeister/web3-react)
|
||||
- [web3modal](https://github.com/web3modal/web3modal)
|
||||
|
||||
## Usage
|
||||
|
||||
Wrap your whole app with the `Web3Provider`:
|
||||
|
||||
```tsx
|
||||
import { Web3Provider } from '@oceanprotocol/react'
|
||||
|
||||
function MyApp() {
|
||||
return (
|
||||
<Web3Provider>
|
||||
{({ web3, chainId, account, balance, enable }) => (
|
||||
<ul>
|
||||
<li>Web3 available: {`${Boolean(web3)}`}</li>
|
||||
<li>Chain ID: {chainId}</li>
|
||||
<li>Account: {account}</li>
|
||||
<li>Balance: {balance}</li>
|
||||
</ul>
|
||||
)}
|
||||
</Web3Provider>
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
You can then access the provider context values with the `useWeb3` hook:
|
||||
|
||||
```tsx
|
||||
import { useWeb3 } from '@oceanprotocol/react'
|
||||
|
||||
function MyComponent() {
|
||||
const { web3, chainId, account, balance, enable } = useWeb3()
|
||||
|
||||
return (
|
||||
<ul>
|
||||
<li>Web3 available: {`${Boolean(web3)}`}</li>
|
||||
<li>Chain ID: {chainId}</li>
|
||||
<li>Account: {account}</li>
|
||||
<li>Balance: {balance}</li>
|
||||
</ul>
|
||||
)
|
||||
}
|
||||
```
|
|
@ -1,166 +0,0 @@
|
|||
import React, { useContext, useState, createContext, useEffect } from 'react'
|
||||
import Web3 from 'web3'
|
||||
import Web3Connect from 'web3connect'
|
||||
import { getWeb3 } from './utils'
|
||||
import Core from 'web3connect/lib/core'
|
||||
|
||||
export enum InjectedProviderStatus {
|
||||
NOT_AVAILABLE = -1,
|
||||
NOT_CONNECTED = 0,
|
||||
CONNECTED = 1
|
||||
}
|
||||
interface Web3ProviderValue {
|
||||
web3: Web3 | undefined
|
||||
web3Connect: Core
|
||||
account: string | undefined
|
||||
balance: string | undefined
|
||||
chainId: number | undefined
|
||||
ethProviderStatus: InjectedProviderStatus
|
||||
enable: () => void
|
||||
}
|
||||
|
||||
const Web3Context = createContext(null)
|
||||
|
||||
// TODO: this will have to be updated to web3modal
|
||||
function Web3Provider({ children }: { children: any }): any {
|
||||
const [web3, setWeb3] = useState<Web3 | undefined>()
|
||||
const [chainId, setChainId] = useState<number | undefined>()
|
||||
const [account, setAccount] = useState<string | undefined>()
|
||||
const [balance, setBalance] = useState<string | undefined>()
|
||||
const [ethProvider, setEthProvider] = useState<any>(null)
|
||||
const [ethProviderStatus, setEthProviderStatus] = useState(
|
||||
InjectedProviderStatus.NOT_AVAILABLE
|
||||
)
|
||||
const [web3Connect, setWeb3Connect] = useState<Core>(null)
|
||||
|
||||
useEffect(() => {
|
||||
async function initWeb3(): Promise<void> {
|
||||
const web3 = await getWeb3()
|
||||
setWeb3(web3)
|
||||
|
||||
const chainId = web3 && (await web3.eth.getChainId())
|
||||
setChainId(chainId)
|
||||
}
|
||||
initWeb3()
|
||||
}, [])
|
||||
|
||||
function init(networkId?: string | number) {
|
||||
const instance = new Web3Connect.Core({
|
||||
network: `${networkId}`,
|
||||
providerOptions: {}
|
||||
})
|
||||
setWeb3Connect(instance)
|
||||
|
||||
if (Web3Connect.checkInjectedProviders().injectedAvailable) {
|
||||
setEthProviderStatus(InjectedProviderStatus.NOT_CONNECTED)
|
||||
}
|
||||
}
|
||||
|
||||
// On mount setup Web3Connect instance & check for injected provider
|
||||
useEffect(() => {
|
||||
init()
|
||||
}, [])
|
||||
|
||||
async function getAccount(web3: Web3) {
|
||||
const accounts = await web3.eth.getAccounts()
|
||||
return accounts[0]
|
||||
}
|
||||
|
||||
async function getBalance(web3: Web3, address: string) {
|
||||
const balance = await web3.eth.getBalance(address)
|
||||
return Web3.utils.fromWei(balance)
|
||||
}
|
||||
|
||||
//
|
||||
// Listen for provider, account & network changes
|
||||
// and react to it
|
||||
//
|
||||
const handleConnect = async (provider: any) => {
|
||||
console.debug("Handling 'connect' event with payload", provider)
|
||||
setEthProvider(provider)
|
||||
setEthProviderStatus(InjectedProviderStatus.CONNECTED)
|
||||
|
||||
const web3 = new Web3(provider)
|
||||
setWeb3(web3)
|
||||
|
||||
const account = await getAccount(web3)
|
||||
setAccount(account)
|
||||
|
||||
const balance = await getBalance(web3, account)
|
||||
setBalance(balance)
|
||||
}
|
||||
|
||||
const handleAccountsChanged = async (accounts: string[]) => {
|
||||
console.debug("Handling 'accountsChanged' event with payload", accounts)
|
||||
if (accounts.length > 0) {
|
||||
setAccount(accounts[0])
|
||||
|
||||
if (web3) {
|
||||
const balance = await getBalance(web3, accounts[0])
|
||||
setBalance(balance)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const handleNetworkChanged = async (networkId: string | number) => {
|
||||
console.debug("Handling 'networkChanged' event with payload", networkId)
|
||||
ethProvider.autoRefreshOnNetworkChange = false
|
||||
init(networkId)
|
||||
handleConnect(ethProvider)
|
||||
}
|
||||
|
||||
//
|
||||
// Setup event listeners.
|
||||
// Web3Connect only supports a 'connect', 'error', and 'close' event,
|
||||
// so we use the injected provider events to handle the rest.
|
||||
//
|
||||
useEffect(() => {
|
||||
web3Connect && web3Connect.on('connect', handleConnect)
|
||||
|
||||
if (ethProvider) {
|
||||
ethProvider.on('accountsChanged', handleAccountsChanged)
|
||||
ethProvider.on('networkChanged', handleNetworkChanged)
|
||||
|
||||
return () => {
|
||||
ethProvider.removeListener('accountsChanged', handleAccountsChanged)
|
||||
ethProvider.removeListener('networkChanged', handleNetworkChanged)
|
||||
}
|
||||
}
|
||||
}, [web3, web3Connect, ethProvider])
|
||||
|
||||
async function enable(): Promise<boolean> {
|
||||
try {
|
||||
// Request account access
|
||||
await window.ethereum.enable()
|
||||
return true
|
||||
} catch (error) {
|
||||
// User denied account access
|
||||
console.error('User denied account access to wallet.')
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Web3Context.Provider
|
||||
value={
|
||||
{
|
||||
web3,
|
||||
web3Connect,
|
||||
chainId,
|
||||
account,
|
||||
balance,
|
||||
ethProviderStatus,
|
||||
enable
|
||||
} as Web3ProviderValue
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</Web3Context.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
// Helper hook to access the provider values
|
||||
const useWeb3 = (): Web3ProviderValue => useContext(Web3Context)
|
||||
|
||||
export { Web3Provider, useWeb3, Web3ProviderValue }
|
||||
export default Web3Provider
|
|
@ -1 +0,0 @@
|
|||
export * from './Web3Provider'
|
|
@ -1,22 +0,0 @@
|
|||
import Web3 from 'web3'
|
||||
|
||||
async function getWeb3(): Promise<Web3> {
|
||||
let web3: Web3
|
||||
|
||||
// modern dapp browser
|
||||
if (window.ethereum) {
|
||||
web3 = new Web3(window.ethereum)
|
||||
}
|
||||
// legacy dapp browser
|
||||
else if (window.web3) {
|
||||
web3 = new Web3(window.web3.currentProvider)
|
||||
}
|
||||
// no dapp browser
|
||||
else {
|
||||
console.debug('Non-Ethereum browser detected.')
|
||||
}
|
||||
|
||||
return web3
|
||||
}
|
||||
|
||||
export { getWeb3 }
|
|
@ -1,2 +1 @@
|
|||
export * from './OceanProvider'
|
||||
export * from './Web3Provider'
|
||||
|
|
|
@ -1,84 +0,0 @@
|
|||
import axios, { AxiosResponse } from 'axios'
|
||||
import Web3 from 'web3'
|
||||
import { DID } from '@oceanprotocol/squid'
|
||||
|
||||
export declare type RatingResponse = [string, number]
|
||||
export declare type GetRatingResponse = {
|
||||
comment: string
|
||||
datePublished: string
|
||||
vote: number
|
||||
}
|
||||
|
||||
export function gethash(message: string) {
|
||||
let hex = ''
|
||||
for (let i = 0; i < message.length; i++) {
|
||||
hex += '' + message.charCodeAt(i).toString(16)
|
||||
}
|
||||
const hexMessage = '0x' + hex
|
||||
return hexMessage
|
||||
}
|
||||
|
||||
export async function rateAsset({
|
||||
did,
|
||||
web3,
|
||||
value,
|
||||
configUrl
|
||||
}: {
|
||||
did: DID | string
|
||||
web3: Web3
|
||||
value: number
|
||||
configUrl: string
|
||||
}): Promise<RatingResponse | string> {
|
||||
try {
|
||||
const timestamp = Math.floor(+new Date() / 1000)
|
||||
const accounts = await web3.eth.getAccounts()
|
||||
const signature = await web3.eth.personal.sign(
|
||||
gethash(`${timestamp}`),
|
||||
accounts ? accounts[0] : '',
|
||||
''
|
||||
)
|
||||
const ratingBody = {
|
||||
did,
|
||||
vote: value,
|
||||
comment: '',
|
||||
address: accounts[0],
|
||||
timestamp: timestamp,
|
||||
signature: signature
|
||||
}
|
||||
|
||||
const response: AxiosResponse = await axios.post(configUrl, ratingBody)
|
||||
if (!response) return 'No Response'
|
||||
return response.data
|
||||
} catch (error) {
|
||||
console.error(error.message)
|
||||
return `Error: ${error.message}`
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAssetRating({
|
||||
did,
|
||||
account,
|
||||
configUrl
|
||||
}: {
|
||||
did: DID | string
|
||||
account: string
|
||||
configUrl: string
|
||||
}): Promise<GetRatingResponse | undefined> {
|
||||
try {
|
||||
if (!account) return
|
||||
|
||||
const response = await axios.get(configUrl, {
|
||||
params: {
|
||||
did: did,
|
||||
address: account
|
||||
}
|
||||
})
|
||||
const votesLength = response.data.length
|
||||
|
||||
if (votesLength > 0) {
|
||||
return response.data[votesLength - 1]
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error.message)
|
||||
}
|
||||
}
|
|
@ -14,8 +14,7 @@ export function readFileContent(file: File): Promise<string> {
|
|||
|
||||
export const feedback: { [key in number]: string } = {
|
||||
99: 'Decrypting file URL...',
|
||||
0: '1/3 Asking for agreement signature...',
|
||||
1: '1/3 Agreement initialized.',
|
||||
2: '2/3 Asking for two payment confirmations...',
|
||||
3: '2/3 Payment confirmed. Requesting access...'
|
||||
0: '1/3 Ordering asset...',
|
||||
1: '1/3 Transfering data token.',
|
||||
2: '2/3 Payment confirmed. Requesting access...'
|
||||
}
|
||||
|
|
|
@ -8,7 +8,9 @@
|
|||
"jsx": "react",
|
||||
"esModuleInterop": true,
|
||||
"sourceMap": true,
|
||||
"declaration": true
|
||||
"declaration": true,
|
||||
"strictNullChecks": false
|
||||
},
|
||||
"include": ["./src/@types", "./src/index.ts"]
|
||||
"include": ["./src/@types", "./src/index.ts"],
|
||||
"exclude": ["node_modules", "dist", "example"]
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue