wip react-example1

This commit is contained in:
Iuri Matias 2019-10-02 14:59:26 -04:00
parent 7666d6f6a2
commit 8eb4129af1
13 changed files with 22916 additions and 26 deletions

View File

@ -0,0 +1,34 @@
subspace - react example
===
Simple application using a react observable component to receive a stream of emitted events. This app will deploy a test contract to **Ganache**.
## Requirements
- `ganache-cli`
- `yarn` or `npm` installed.
## Install
In the parent folder, link the package with `yarn` or `npm`
```
yarn link
```
Then in the current folder link `@status-im/subspace`, and install the packages
```
yarn link "@status-im/subspace"
yarn
```
## Usage
In a terminal execute
```
ganache-cli
```
In a different session, execute
```
yarn run start
```
Browse the DApp in [http://localhost:3000](http://localhost:3000)
*Note*: this is a simple example application that does not include error handling for the web3 connection. Be sure `ganache-cli` is running in `localhost:8545` before browsing the dapp.

View File

@ -0,0 +1,33 @@
{
"name": "observables",
"version": "0.1.0",
"private": true,
"dependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.1",
"rxjs": "^6.5.2",
"web3": "^1.0.0-beta.37"
},
"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"
]
}
}

View File

@ -0,0 +1,21 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<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>

61
examples/react-example1/src/App.js vendored Normal file
View File

@ -0,0 +1,61 @@
import React from "react";
import Subspace from "@status-im/subspace";
import { $average, $max, $min } from "@status-im/subspace";
import { map } from 'rxjs/operators';
import ProductComponent from "./ProductComponent";
import web3 from './web3';
import ProductContract from './MyContract';
import { subscribe } from "graphql";
let Product;
class App extends React.Component {
state = {
title: "",
minRating: 0,
maxRating: 0,
averageRating: 0
};
async componentDidMount() {
Product = await ProductContract.getInstance(); //
const subspace = new Subspace(web3.currentProvider);
await subspace.init();
const rating$ = subspace.trackEvent(Product, "Rating").pipe(map(x => parseInt(x.rating)));
subspace.trackProperty(Product, "products", [0]).pipe().subscribe(console.dir);
this.setState({
averageRating: rating$.pipe($average()),
minRating: rating$.pipe($min()),
maxRating: rating$.pipe($max())
});
}
createTrx = async () => {
const productId = 0;
const rating = parseInt(this.state.rating)
window.Product = Product
await Product.methods.rateProduct(productId, rating).send();
};
render() {
return (
<div>
<button onClick={this.createTrx}>Rate Product</button>
<input type="number" value={this.state.rating} onChange={(evt) => this.setState({rating: evt.target.value}) } />
<ProductComponent
title={this.state.title}
maxRating={this.state.maxRating}
minRating={this.state.minRating}
averageRating={this.state.averageRating}
/>
</div>
);
}
}
export default App;

View File

@ -0,0 +1,139 @@
import web3 from './web3';
const abi = [
{
"constant": false,
"inputs": [
{
"internalType": "string",
"name": "title",
"type": "string"
}
],
"name": "createProduct",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"internalType": "uint256",
"name": "productId",
"type": "uint256"
},
{
"internalType": "string",
"name": "title",
"type": "string"
}
],
"name": "editProduct",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"constant": false,
"inputs": [
{
"internalType": "uint256",
"name": "productId",
"type": "uint256"
},
{
"internalType": "uint256",
"name": "rating",
"type": "uint256"
}
],
"name": "rateProduct",
"outputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "function"
},
{
"inputs": [],
"payable": false,
"stateMutability": "nonpayable",
"type": "constructor"
},
{
"payable": true,
"stateMutability": "payable",
"type": "fallback"
},
{
"anonymous": false,
"inputs": [
{
"indexed": false,
"internalType": "uint256",
"name": "productId",
"type": "uint256"
}
],
"name": "newProduct",
"type": "event"
},
{
"anonymous": false,
"inputs": [
{
"indexed": true,
"internalType": "uint256",
"name": "productId",
"type": "uint256"
},
{
"indexed": false,
"internalType": "uint256",
"name": "rating",
"type": "uint256"
}
],
"name": "Rating",
"type": "event"
},
{
"constant": true,
"inputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"name": "products",
"outputs": [
{
"internalType": "string",
"name": "title",
"type": "string"
}
],
"payable": false,
"stateMutability": "view",
"type": "function"
}
];
const data = "0x608060405234801561001057600080fd5b506100556040518060400160405280600681526020017f6c6170746f70000000000000000000000000000000000000000000000000000081525061005a60201b60201c565b61026e565b60016000818180549050019150816100729190610193565b50600060016000805490500390506100886101bf565b6000828154811061009557fe5b90600052602060002001604051806020016040529081600082018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156101435780601f1061011857610100808354040283529160200191610143565b820191906000526020600020905b81548152906001019060200180831161012657829003601f168201915b50505050508152505090508281600001819052507f5dc23a654c93455cd36741580d5c1fafc8f35c429bb831bc768008bd655a1219826040518082815260200191505060405180910390a1505050565b8154818355818111156101ba578183600052602060002091820191016101b991906101d2565b5b505050565b6040518060200160405280606081525090565b6101fe91905b808211156101fa57600080820160006101f19190610201565b506001016101d8565b5090565b90565b50805460018160011615610100020316600290046000825580601f106102275750610246565b601f0160209004906000526020600020908101906102459190610249565b5b50565b61026b91905b8082111561026757600081600090555060010161024f565b5090565b90565b6106cb8061027d6000396000f3fe60806040526004361061003f5760003560e01c806302ec06be1461004157806311eaa75a146101095780637acc0b20146101db578063f4ef9e361461028f575b005b34801561004d57600080fd5b506101076004803603602081101561006457600080fd5b810190808035906020019064010000000081111561008157600080fd5b82018360208201111561009357600080fd5b803590602001918460018302840111640100000000831117156100b557600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506102d4565b005b34801561011557600080fd5b506101d96004803603604081101561012c57600080fd5b81019080803590602001909291908035906020019064010000000081111561015357600080fd5b82018360208201111561016557600080fd5b8035906020019184600183028401116401000000008311171561018757600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050919291929050505061040d565b005b3480156101e757600080fd5b50610214600480360360208110156101fe57600080fd5b8101908080359060200190929190505050610440565b6040518080602001828103825283818151815260200191508051906020019080838360005b83811015610254578082015181840152602081019050610239565b50505050905090810190601f1680156102815780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b34801561029b57600080fd5b506102d2600480360360408110156102b257600080fd5b8101908080359060200190929190803590602001909291905050506104ff565b005b60016000818180549050019150816102ec919061053b565b5060006001600080549050039050610302610567565b6000828154811061030f57fe5b90600052602060002001604051806020016040529081600082018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156103bd5780601f10610392576101008083540402835291602001916103bd565b820191906000526020600020905b8154815290600101906020018083116103a057829003601f168201915b50505050508152505090508281600001819052507f5dc23a654c93455cd36741580d5c1fafc8f35c429bb831bc768008bd655a1219826040518082815260200191505060405180910390a1505050565b806000838154811061041b57fe5b90600052602060002001600001908051906020019061043b92919061057a565b505050565b6000818154811061044d57fe5b90600052602060002001600091509050806000018054600181600116156101000203166002900480601f0160208091040260200160405190810160405280929190818152602001828054600181600116156101000203166002900480156104f55780601f106104ca576101008083540402835291602001916104f5565b820191906000526020600020905b8154815290600101906020018083116104d857829003601f168201915b5050505050905081565b817ffdefdf8d82459f7b1eb157e5c44cbe6ee73d8ddd387511fe3622a3ee663b4697826040518082815260200191505060405180910390a25050565b8154818355818111156105625781836000526020600020918201910161056191906105fa565b5b505050565b6040518060200160405280606081525090565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f106105bb57805160ff19168380011785556105e9565b828001600101855582156105e9579182015b828111156105e85782518255916020019190600101906105cd565b5b5090506105f69190610629565b5090565b61062691905b808211156106225760008082016000610619919061064e565b50600101610600565b5090565b90565b61064b91905b8082111561064757600081600090555060010161062f565b5090565b90565b50805460018160011615610100020316600290046000825580601f106106745750610693565b601f0160209004906000526020600020908101906106929190610629565b5b5056fea265627a7a723158207edf05422cf9e8fdd43b6bed8a48f8fca2f9c986b2579db7d628dca6781c5ef764736f6c634300050b0032";
const MyContract = new web3.eth.Contract(abi, {data, gas: "800000"});
MyContract.getInstance = async() => {
if (!web3.eth.defaultAccount) {
const accounts = await web3.eth.getAccounts();
web3.eth.defaultAccount = accounts[0];
}
const instance = await MyContract.deploy().send({from: web3.eth.defaultAccount});
instance.options.from = web3.eth.defaultAccount;
return instance;
}
export default MyContract;

View File

@ -0,0 +1,20 @@
import React from "react";
import { observe } from "@status-im/subspace/react";
const ProductComponent = ({ maxRating, minRating, averageRating, title }) => {
// Handle initial state when no data is available
if (!maxRating && !minRating && !averageRating) {
return <p>No data</p>;
}
return <ul>
<li><b>title: </b> {title}</li>
<li><b>minimum rating: </b> {minRating}</li>
<li><b>maximum rating: </b> {maxRating}</li>
<li><b>average rating: </b> {averageRating}</li>
</ul>;
};
// MyComponent will now observe any observable prop it receives
// and update its state whenever the observable emits an event
export default observe(ProductComponent);

11
examples/react-example1/src/index.js vendored Normal file
View File

@ -0,0 +1,11 @@
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, 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();

View File

@ -0,0 +1,135 @@
// 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.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export function register(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, 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, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.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();
});
}
}

5
examples/react-example1/src/web3.js vendored Normal file
View File

@ -0,0 +1,5 @@
import Web3 from 'web3';
const web3 = new Web3("ws://localhost:8545");
export default web3;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -2858,7 +2858,7 @@ css-blank-pseudo@^0.1.4:
dependencies: dependencies:
postcss "^7.0.5" postcss "^7.0.5"
css-color-names@0.0.4, css-color-names@^0.0.4: css-color-names@0.0.4:
version "0.0.4" version "0.0.4"
resolved "https://registry.yarnpkg.com/css-color-names/-/css-color-names-0.0.4.tgz#808adc2e79cf84738069b646cb20ec27beb629e0" resolved "https://registry.yarnpkg.com/css-color-names/-/css-color-names-0.0.4.tgz#808adc2e79cf84738069b646cb20ec27beb629e0"
integrity sha1-gIrcLnnPhHOAabZGyyDsJ762KeA= integrity sha1-gIrcLnnPhHOAabZGyyDsJ762KeA=
@ -4793,11 +4793,6 @@ he@1.2.x:
resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f" resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f"
integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw== integrity sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==
hex-color-regex@^1.1.0:
version "1.1.0"
resolved "https://registry.yarnpkg.com/hex-color-regex/-/hex-color-regex-1.1.0.tgz#4c06fccb4602fe2602b3c93df82d7e7dbf1a8a8e"
integrity sha512-l9sfDFsuqtOqKDsQdqrMRk0U85RZc0RtOR9yPI7mRVOa4FsR/BVnZ0shmQRM96Ji99kYZP/7hn1cedc1+ApsTQ==
hmac-drbg@^1.0.0: hmac-drbg@^1.0.0:
version "1.0.1" version "1.0.1"
resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1" resolved "https://registry.yarnpkg.com/hmac-drbg/-/hmac-drbg-1.0.1.tgz#d2745701025a6c775a6c545793ed502fc0c649a1"
@ -4822,16 +4817,6 @@ hpack.js@^2.1.6:
readable-stream "^2.0.1" readable-stream "^2.0.1"
wbuf "^1.1.0" wbuf "^1.1.0"
hsl-regex@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/hsl-regex/-/hsl-regex-1.0.0.tgz#d49330c789ed819e276a4c0d272dffa30b18fe6e"
integrity sha1-1JMwx4ntgZ4nakwNJy3/owsY/m4=
hsla-regex@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/hsla-regex/-/hsla-regex-1.0.0.tgz#c1ce7a3168c8c6614033a4b5f7877f3b225f9c38"
integrity sha1-wc56MWjIxmFAM6S194d/OyJfnDg=
html-comment-regex@^1.1.0: html-comment-regex@^1.1.0:
version "1.1.2" version "1.1.2"
resolved "https://registry.yarnpkg.com/html-comment-regex/-/html-comment-regex-1.1.2.tgz#97d4688aeb5c81886a364faa0cad1dda14d433a7" resolved "https://registry.yarnpkg.com/html-comment-regex/-/html-comment-regex-1.1.2.tgz#97d4688aeb5c81886a364faa0cad1dda14d433a7"
@ -5257,6 +5242,13 @@ is-color-stop@^1.0.0:
version "1.1.0" version "1.1.0"
resolved "https://registry.yarnpkg.com/is-color-stop/-/is-color-stop-1.1.0.tgz#cfff471aee4dd5c9e158598fbe12967b5cdad345" resolved "https://registry.yarnpkg.com/is-color-stop/-/is-color-stop-1.1.0.tgz#cfff471aee4dd5c9e158598fbe12967b5cdad345"
integrity sha1-z/9HGu5N1cnhWFmPvhKWe1za00U= integrity sha1-z/9HGu5N1cnhWFmPvhKWe1za00U=
dependencies:
css-color-names "^0.0.4"
hex-color-regex "^1.1.0"
hsl-regex "^1.0.0"
hsla-regex "^1.0.0"
rgb-regex "^1.0.1"
rgba-regex "^1.0.0"
is-data-descriptor@^0.1.4: is-data-descriptor@^0.1.4:
version "0.1.4" version "0.1.4"
@ -8936,16 +8928,6 @@ rework@1.0.1:
convert-source-map "^0.3.3" convert-source-map "^0.3.3"
css "^2.0.0" css "^2.0.0"
rgb-regex@^1.0.1:
version "1.0.1"
resolved "https://registry.yarnpkg.com/rgb-regex/-/rgb-regex-1.0.1.tgz#c0e0d6882df0e23be254a475e8edd41915feaeb1"
integrity sha1-wODWiC3w4jviVKR16O3UGRX+rrE=
rgba-regex@^1.0.0:
version "1.0.0"
resolved "https://registry.yarnpkg.com/rgba-regex/-/rgba-regex-1.0.0.tgz#43374e2e2ca0968b0ef1523460b7d730ff22eeb3"
integrity sha1-QzdOLiyglosO8VI0YLfXMP8i7rM=
rimraf@2.6.3: rimraf@2.6.3:
version "2.6.3" version "2.6.3"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab" resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab"

View File

@ -42,6 +42,47 @@ export function $average(cb) {
); );
} }
export function $max(cb) {
return pipe(
scan((acc, curr) => {
let currentValue;
if (typeof cb === 'string' || cb instanceof String){
currentValue = curr[cb];
} else if(typeof cb === "function") {
currentValue = cb(curr);
} else {
currentValue = curr;
}
if (currentValue > acc) return currentValue;
return acc;
})
);
}
export function $min(cb) {
return pipe(
scan((acc, curr) => {
let currentValue;
if (typeof cb === 'string' || cb instanceof String){
currentValue = curr[cb];
} else if(typeof cb === "function") {
currentValue = cb(curr);
} else {
currentValue = curr;
}
console.dir("===========");
console.dir(currentValue);
console.dir(acc);
console.dir(currentValue <= acc);
console.dir("===========");
if (currentValue < acc) return currentValue;
return acc;
})
);
}
/* /*
of(10, 3, 4) of(10, 3, 4)
.pipe($average()) .pipe($average())