Merge pull request #43 from status-im/react-example1-test

React example1
This commit is contained in:
Iuri Matias 2019-10-02 22:21:13 -04:00 committed by GitHub
commit 05d3d11e70
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
23 changed files with 23052 additions and 145 deletions

3
.gitignore vendored
View File

@ -5,4 +5,5 @@ subspace.db
TODO
test.js
/dist/
/react/
/react/
/examples/react-example1/src/contract.json

View File

@ -0,0 +1,41 @@
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 deploy
```
And then:
```
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.

151
examples/react-example1/deploy.js vendored Normal file
View File

@ -0,0 +1,151 @@
const Web3 = require("web3");
const web3 = new Web3("ws://localhost:8545");
const fs = require("fs-extra");
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": true,
"inputs": [
{
"internalType": "uint256",
"name": "",
"type": "uint256"
}
],
"name": "products",
"outputs": [
{
"internalType": "string",
"name": "title",
"type": "string"
},
{
"internalType": "uint256",
"name": "latestRating",
"type": "uint256"
}
],
"payable": false,
"stateMutability": "view",
"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"
}
];
const data = "0x608060405234801561001057600080fd5b506100556040518060400160405280600681526020017f6c6170746f70000000000000000000000000000000000000000000000000000081525061005a60201b60201c565b610244565b600080805480919060010161006f91906100ee565b9050600080828154811061007f57fe5b90600052602060002090600202019050828160000190805190602001906100a7929190610120565b50600281600101819055507f5dc23a654c93455cd36741580d5c1fafc8f35c429bb831bc768008bd655a1219826040518082815260200191505060405180910390a1505050565b81548183558181111561011b5760020281600202836000526020600020918201910161011a91906101a0565b5b505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061016157805160ff191683800117855561018f565b8280016001018555821561018f579182015b8281111561018e578251825591602001919060010190610173565b5b50905061019c91906101d7565b5090565b6101d491905b808211156101d057600080820160006101bf91906101fc565b6001820160009055506002016101a6565b5090565b90565b6101f991905b808211156101f55760008160009055506001016101dd565b5090565b90565b50805460018160011615610100020316600290046000825580601f106102225750610241565b601f01602090049060005260206000209081019061024091906101d7565b5b50565b610659806102536000396000f3fe60806040526004361061003f5760003560e01c806302ec06be1461004157806311eaa75a146101095780637acc0b20146101db578063f4ef9e3614610296575b005b34801561004d57600080fd5b506101076004803603602081101561006457600080fd5b810190808035906020019064010000000081111561008157600080fd5b82018360208201111561009357600080fd5b803590602001918460018302840111640100000000831117156100b557600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f8201169050808301925050505050505091929192905050506102db565b005b34801561011557600080fd5b506101d96004803603604081101561012c57600080fd5b81019080803590602001909291908035906020019064010000000081111561015357600080fd5b82018360208201111561016557600080fd5b8035906020019184600183028401116401000000008311171561018757600080fd5b91908080601f016020809104026020016040519081016040528093929190818152602001838380828437600081840152601f19601f82011690508083019250505050505050919291929050505061036f565b005b3480156101e757600080fd5b50610214600480360360208110156101fe57600080fd5b81019080803590602001909291905050506103a6565b6040518080602001838152602001828103825284818151815260200191508051906020019080838360005b8381101561025a57808201518184015260208101905061023f565b50505050905090810190601f1680156102875780820380516001836020036101000a031916815260200191505b50935050505060405180910390f35b3480156102a257600080fd5b506102d9600480360360408110156102b957600080fd5b81019080803590602001909291908035906020019092919050505061046f565b005b60008080548091906001016102f091906104ce565b9050600080828154811061030057fe5b9060005260206000209060020201905082816000019080519060200190610328929190610500565b50600281600101819055507f5dc23a654c93455cd36741580d5c1fafc8f35c429bb831bc768008bd655a1219826040518082815260200191505060405180910390a1505050565b806000838154811061037d57fe5b906000526020600020906002020160000190805190602001906103a1929190610500565b505050565b600081815481106103b357fe5b9060005260206000209060020201600091509050806000018054600181600116156101000203166002900480601f01602080910402602001604051908101604052809291908181526020018280546001816001161561010002031660029004801561045f5780601f106104345761010080835404028352916020019161045f565b820191906000526020600020905b81548152906001019060200180831161044257829003601f168201915b5050505050908060010154905082565b817ffdefdf8d82459f7b1eb157e5c44cbe6ee73d8ddd387511fe3622a3ee663b4697826040518082815260200191505060405180910390a280600083815481106104b557fe5b9060005260206000209060020201600101819055505050565b8154818355818111156104fb576002028160020283600052602060002091820191016104fa9190610580565b5b505050565b828054600181600116156101000203166002900490600052602060002090601f016020900481019282601f1061054157805160ff191683800117855561056f565b8280016001018555821561056f579182015b8281111561056e578251825591602001919060010190610553565b5b50905061057c91906105b7565b5090565b6105b491905b808211156105b0576000808201600061059f91906105dc565b600182016000905550600201610586565b5090565b90565b6105d991905b808211156105d55760008160009055506001016105bd565b5090565b90565b50805460018160011615610100020316600290046000825580601f106106025750610621565b601f01602090049060005260206000209081019061062091906105b7565b5b5056fea265627a7a72315820283a23649d3076ca075a3d9190d7b69b6665e8b1d83e5240c8cfbe34dc9d9b3364736f6c634300050b0032";
const MyContract = new web3.eth.Contract(abi, {data, gas: "800000"});
(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 });
let address = instance.options.address;
console.dir("deployment done!");
fs.writeJsonSync("./src/contract.json", { address, abi });
console.dir("artifact written to src/contract.json")
process.exit(0)
})()

View File

@ -0,0 +1,35 @@
{
"name": "observables",
"version": "0.1.0",
"private": true,
"dependencies": {
"fs-extra": "^8.1.0",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "3.1.1",
"rxjs": "^6.5.2",
"web3": "^1.2.1"
},
"scripts": {
"start": "react-scripts start",
"deploy": "node deploy.js",
"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>

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

@ -0,0 +1,77 @@
import React from "react";
import Subspace from "@status-im/subspace";
import { $average, $max, $min, $latest } from "@status-im/subspace";
import { map } from 'rxjs/operators';
import ProductComponent from "./ProductComponent";
import web3 from './web3';
import ProductContract from './MyContract';
let Product;
class App extends React.Component {
state = {
userTitle: "",
userRating: 0,
minRating: 0,
maxRating: 0,
averageRating: 0
};
async componentDidMount() {
const subspace = new Subspace(web3.currentProvider);
await subspace.init();
Product = await ProductContract.getInstance();
const rating$ = subspace.trackEvent(Product, "Rating").pipe(map(x => parseInt(x.rating)));
window.Product = Product;
window.web3 = web3;
this.setState({
title: subspace.trackProperty(Product, "products", [0]).pipe(map(x => x.title)),
averageRating: rating$.pipe($average()),
minRating: rating$.pipe($min()),
maxRating: rating$.pipe($max()),
last5Ratings: rating$.pipe($latest(5)),
balance: subspace.trackBalance(Product.options.address)
});
}
rateProduct = async () => {
await Product.methods.rateProduct(0, this.state.userRating).send();
};
updateTitle = async () => {
await Product.methods.editProduct(0, this.state.userTitle).send();
};
sendFunds = async () => {
await web3.eth.sendTransaction({value: this.state.contractFunds, to: Product.options.address});
};
render() {
return (
<div>
<button onClick={this.rateProduct}>Rate Product</button>
<input type="number" value={this.state.userRating} onChange={(evt) => this.setState({userRating: parseInt(evt.target.value)}) } />
<button onClick={this.updateTitle}>Update Title</button>
<input type="string" value={this.state.userTitle} onChange={(evt) => this.setState({userTitle: evt.target.value}) } />
<button onClick={this.sendFunds}>Send Funds</button>
<input type="string" value={this.state.contractFunds} onChange={(evt) => this.setState({contractFunds: parseInt(evt.target.value)}) } />
<ProductComponent
title={this.state.title}
maxRating={this.state.maxRating}
minRating={this.state.minRating}
averageRating={this.state.averageRating}
balance={this.state.balance}
last5Ratings={this.state.last5Ratings}
/>
</div>
);
}
}
export default App;

View File

@ -0,0 +1,16 @@
import web3 from './web3';
import {abi, address} from './contract.json'
const MyContract = new web3.eth.Contract(abi, {from: web3.eth.default, gas: "800000"});
MyContract.options.address = address;
MyContract.getInstance = async () => {
if (!web3.eth.defaultAccount) {
const accounts = await web3.eth.getAccounts();
web3.eth.defaultAccount = accounts[0];
}
MyContract.options.from = web3.eth.defaultAccount;
return MyContract;
}
export default MyContract;

View File

@ -0,0 +1,25 @@
import React from "react";
import { observe } from "@status-im/subspace/react";
const ProductComponent = ({ maxRating, minRating, averageRating, title, balance, last5Ratings }) => {
// Handle initial state when no data is available
// if (!maxRating && !minRating && !averageRating) {
// return <p>No data</p>;
// }
console.dir("last5Ratings")
console.dir(last5Ratings)
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>
<li><b>last 5 ratings: </b> {(last5Ratings || []).join(', ')}</li>
<li><b>balance in contract:</b> {balance}</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:
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"
resolved "https://registry.yarnpkg.com/css-color-names/-/css-color-names-0.0.4.tgz#808adc2e79cf84738069b646cb20ec27beb629e0"
integrity sha1-gIrcLnnPhHOAabZGyyDsJ762KeA=
@ -4793,11 +4793,6 @@ he@1.2.x:
resolved "https://registry.yarnpkg.com/he/-/he-1.2.0.tgz#84ae65fa7eafb165fddb61566ae14baf05664f0f"
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:
version "1.0.1"
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"
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:
version "1.1.2"
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"
resolved "https://registry.yarnpkg.com/is-color-stop/-/is-color-stop-1.1.0.tgz#cfff471aee4dd5c9e158598fbe12967b5cdad345"
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:
version "0.1.4"
@ -8936,16 +8928,6 @@ rework@1.0.1:
convert-source-map "^0.3.3"
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:
version "2.6.3"
resolved "https://registry.yarnpkg.com/rimraf/-/rimraf-2.6.3.tgz#b2d104fe0d8fb27cf9e0a1cda8262dd3833c6cab"

View File

@ -21,12 +21,10 @@ const getENV = function () {
}
return 'BROWSER';
}
return 'CORDOVA';
};
class Database {
constructor(dbFilename, events, cb) {
@ -56,20 +54,19 @@ class Database {
let firstKnownBlock = 0;
let lastKnownBlock = 0;
if(collection && collection.count()){
if (collection && collection.count()){
firstKnownBlock = collection.min('blockNumber');
lastKnownBlock = collection.max('blockNumber');
} else {
this.db.addCollection(eventKey);
}
return {
firstKnownBlock: firstKnownBlock || 0,
lastKnownBlock: lastKnownBlock || 0
};
}
getEventsFor(eventKey) {
let children = this.db.getCollection(eventKey);
return children.find();

View File

@ -2,15 +2,15 @@ import { fromEvent, ReplaySubject } from 'rxjs';
import hash from 'object-hash';
class EventSyncer {
constructor(web3, events, db) {
this.events = events;
this.web3 = web3;
this.db = db;
this.subscriptions = [];
}
track(contractInstance, eventName, filterConditionsOrCb, gteBlockNum){
track(contractInstance, eventName, filterConditionsOrCb, gteBlockNum) {
const isFilterFunction = typeof filterConditionsOrCb === 'function';
const eventKey = hash(Object.assign({address: contractInstance.options.address}, (isFilterFunction ? {filterConditionsOrCb} : (filterConditionsOrCb || {}))));
@ -30,10 +30,10 @@ class EventSyncer {
let contractObserver = fromEvent(this.events, eventKey)
contractObserver.subscribe((e) => {
if(!e) return;
if (!e) return;
const id = hash({eventName, blockNumber: e.blockNumber, transactionIndex: e.transactionIndex, logIndex: e.logIndex});
// TODO: would be nice if this was smart enough to understand the type of returnValues and do the needed conversions
const eventData = {
id,
@ -47,8 +47,8 @@ class EventSyncer {
// TODO: test reorgs
sub.next({blockNumber: e.blockNumber, ...e.returnValues});
if(e.removed){
if (e.removed){
this.db.deleteEvent(eventKey, id);
return;
}
@ -83,7 +83,7 @@ class EventSyncer {
_retrieveEvents(eventKey, firstKnownBlock, lastKnownBlock, filterConditions, filterConditionsCb, contractInstance, eventName) {
// TODO: this should be moved to a 'smart' module
// it should be able to do events X at the time to avoid slow downs as well as the 10k limit
if (firstKnownBlock == 0 || (firstKnownBlock > 0 && firstKnownBlock <= filterConditions.fromBlock)) {
if (filterConditions.toBlock === 'latest') {
// emit DB Events [fromBlock, lastKnownBlock]
@ -129,7 +129,7 @@ class EventSyncer {
}
}
}
_serveDBEvents(eventKey, firstKnownBlock, lastKnownBlock, filterConditions, filterConditionsCb) {
const cb = this._parseEventCBFactory(filterConditions, filterConditionsCb, eventKey);
const storedEvents = this.db.getEventsFor(eventKey).filter(x => x.blockNumber >= firstKnownBlock && x.blockNumber <= lastKnownBlock);
@ -137,7 +137,7 @@ class EventSyncer {
cb(null, ev);
});
}
_getPastEvents(contract, eventName, filterConditions, filterConditionsCb, eventKey) {
const cb = this._parseEventCBFactory(filterConditions, filterConditionsCb, eventKey);
contract.getPastEvents.apply(contract, [eventName, filterConditions, (err, events) => {
@ -146,15 +146,15 @@ class EventSyncer {
});
}]);
}
_subscribeToEvent(event, filterConditions, filterConditionsCb, eventKey) {
const s = event.apply(event, [filterConditions, this._parseEventCBFactory(filterConditions, filterConditionsCb, eventKey) ]);
this.subscriptions.push(s);
return s;
}
_parseEventCBFactory = (filterConditions, filterConditionsCb, eventKey) => (err, ev) => {
if(err) {
if (err) {
console.error(err);
return;
}

View File

@ -21,8 +21,8 @@ class LogSyncer {
const logObserver = fromEvent(this.events, eventKey)
logObserver.subscribe((e) => {
if(!e) return;
if (!e) return;
const id = hash({eventName: eventKey, blockNumber: e.blockNumber, transactionIndex: e.transactionIndex, logIndex: e.logIndex});
// TODO: would be nice if this was smart enough to understand the type of returnValues and do the needed conversions
@ -50,7 +50,7 @@ class LogSyncer {
this.events.emit("updateDB");
});
const eth_subscribe = this._retrieveEvents(eventKey,
const eth_subscribe = this._retrieveEvents(eventKey,
eventSummary.firstKnownBlock,
eventSummary.lastKnownBlock,
filterConditions
@ -60,7 +60,7 @@ class LogSyncer {
sub.subscribe = (next, error, complete) => {
const s = og_subscribe.apply(sub, [next, error, complete]);
s.add(() => { // Removing web3js subscription when rxJS unsubscribe is executed
if(eth_subscribe) eth_subscribe.unsubscribe();
if (eth_subscribe) eth_subscribe.unsubscribe();
});
return s;
}
@ -75,7 +75,7 @@ class LogSyncer {
if (filterConditions.toBlock === 'latest') {
// emit DB Events [fromBlock, lastKnownBlock]
this._serveDBEvents(eventKey, filterConditions.fromBlock, lastKnownBlock, filterConditions);
// create a event subscription [lastKnownBlock + 1, ...]
// create a event subscription [lastKnownBlock + 1, ...]
let filters = Object.assign({}, filterConditions, { fromBlock: filterConditions.fromBlock > lastKnownBlock ? filterConditions.fromBlock : lastKnownBlock + 1 });
return this._subscribeToEvent(filters, eventKey);
}
@ -116,7 +116,7 @@ class LogSyncer {
}
}
}
_serveDBEvents(eventKey, firstKnownBlock, lastKnownBlock, filterConditions) {
const cb = this._parseEventCBFactory(filterConditions, eventKey);
const storedEvents = this.db.getEventsFor(eventKey).filter(x => x.blockNumber >= firstKnownBlock && x.blockNumber <= lastKnownBlock);
@ -124,44 +124,44 @@ class LogSyncer {
cb(null, ev);
});
}
_getPastEvents(filterConditions, eventKey) {
const cb = this._parseEventCBFactory(filterConditions, eventKey);
this.web3.getPastLogs(options, (err, logs) => {
if(err) {
throw new Error(err);
}
logs.forEach(l => {
cb(null, l);
})
});
}
_subscribeToEvent(filterConditions, eventKey) {
const s = this.web3.subscribe('logs', filterConditions, this._parseEventCBFactory(filterConditions, eventKey));
this.subscriptions.push(s);
return s;
}
_parseEventCBFactory = (filterConditions, eventKey) => (err, ev) => {
if(err) {
if (err) {
throw new Error(err);
}
if (filterConditions) {
if(filterConditions.address && ev.address.toLowerCase() !== filterConditions.address.toLowerCase()) return;
if(filterConditions.topics){
if (filterConditions.address && ev.address.toLowerCase() !== filterConditions.address.toLowerCase()) return;
if (filterConditions.topics){
let shouldSkip = false;
filterConditions.topics.forEach((topic, i) => {
if(topic != null && (!ev.topics[i] || ev.topics[i].toLowerCase() !== topic.toLowerCase())){
if (topic != null && (!ev.topics[i] || ev.topics[i].toLowerCase() !== topic.toLowerCase())){
shouldSkip = true;
}
});
if(shouldSkip) return;
}
}
this.events.emit(eventKey, ev);
}

View File

@ -42,6 +42,57 @@ 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;
}
if (currentValue < acc) return currentValue;
return acc;
})
);
}
export function $latest(num) {
return pipe(
scan((acc, curr) => {
let currentValue = curr;
acc.push(currentValue)
if (acc.length > num) {
acc.shift()
}
return acc;
}, [])
);
}
/*
of(10, 3, 4)
.pipe($average())

View File

@ -1,30 +0,0 @@
// var Web3 = require('web3')
const Events = require('events')
const { map, scan } = require('rxjs/operators');
const Simulator = require('./simulator.js')
const EventSyncer = require('./eventSyncer.js')
const events = new Events()
const eventSyncer = new EventSyncer(events);
eventSyncer.init(run);
function run() {
let myscan = scan((acc, curr) => {
acc.push(curr);
if (acc.length > 4) {
acc.shift();
}
return acc;
}, [])
let mymap = map(arr => arr.reduce((acc, current) => acc + current, 0) / arr.length)
eventSyncer.trackEvent('contractEvent', ((x) => x.from === "0x123")).pipe(map(x => x.rating), myscan, mymap).subscribe((v) => {
console.dir("current average is " + v)
})
const simulator = new Simulator(events);
simulator.emitEvents()
}

View File

@ -54,7 +54,7 @@ export function observe(WrappedComponent) {
componentDidUpdate(prevProps) {
Object.keys(prevProps).forEach(prop => {
if(!prevProps[prop] && this.props[prop]){
if (!prevProps[prop] && this.props[prop]){
this.subscribeToProp(prop);
} else if(prevProps[prop] !== this.props[prop]){
this.unsubscribe(prop);
@ -67,7 +67,7 @@ export function observe(WrappedComponent) {
render() {
const props = Object.keys(this.props).reduce((accum, curr) => {
if(!isObservable(this.props[curr])){
if (!isObservable(this.props[curr])){
accum[curr] = this.props[curr];
return accum;
}

View File

@ -1,27 +0,0 @@
class Simulator {
constructor(events) {
this.events = events;
this.contractEvents = [
{ id: 1, from: "0x123", type: "Rating", rating: 3 },
{ id: 2, from: "0x123", type: "Rating", rating: 1 },
{ id: 3, from: "0x234", type: "Rating", rating: 5 },
{ id: 4, from: "0x123", type: "Rating", rating: 4 },
{ id: 5, from: "0x123", type: "Rating", rating: 2 },
{ id: 6, from: "0x342", type: "Rating", rating: 2 }
]
}
emitEvents() {
let i = 0
// emit contract event each 1 second
setInterval(() => {
if (i >= this.contractEvents.length) return
this.events.emit("contractEvent", this.contractEvents[i])
i += 1
}, 1 * 1000)
}
}
module.exports = Simulator;

View File

@ -13,8 +13,7 @@ import LogSyncer from './logSyncer';
export default class Subspace {
constructor(provider, options = {}) {
if(provider.constructor.name !== "WebsocketProvider"){
if (provider.constructor.name !== "WebsocketProvider") {
console.warn("subspace: it's recommended to use a websocket provider to react to new events");
}
@ -26,7 +25,7 @@ export default class Subspace {
this.options.callInterval = options.callInterval || 0;
this.options.dbFilename = options.dbFilename || 'subspace.db';
this.latestBlockNumber = undefined;
this.newBlocksSubscription = null;
this.intervalTracker = null;
this.callables = [];
@ -41,6 +40,10 @@ export default class Subspace {
this.web3.getBlock('latest').then(block => {
this.latestBlockNumber = block.number;
this._initNewBlocksSubscription();
this._initCallInterval();
resolve();
})
})
@ -52,7 +55,7 @@ export default class Subspace {
}
clearDB(collection) {
if(collection){
if (collection){
// TODO: delete specific collection
} else {
// TODO: delete everything
@ -63,16 +66,15 @@ export default class Subspace {
return this.logSyncer.track(options);
}
_initNewBlocksSubscription() {
if(this.newBlocksSubscription != null || this.options.callInterval !== 0) return;
if (this.newBlocksSubscription != null || this.options.callInterval !== 0) return;
this.newBlocksSubscription = this.web3.subscribe('newBlockHeaders', (err, result) => {
if(err) {
if (err) {
sub.error(err);
return;
}
this.callables.forEach(fn => {
fn();
});
@ -80,14 +82,13 @@ export default class Subspace {
}
_initCallInterval() {
if(this.intervalTracker != null || this.options.callInterval === 0) return;
if (this.intervalTracker != null || this.options.callInterval === 0) return;
this.intervalTracker = setInterval(() => {
this.callables.forEach(fn => {
fn();
});
}, this.options.callInterval);
}
// TODO: should save value in database?
@ -97,19 +98,16 @@ export default class Subspace {
const method = contractInstance.methods[propName].apply(contractInstance.methods[propName], methodArgs)
const callContractMethod = () => {
method.call.apply(method.call, [callArgs, (err, result) => {
if(err) {
if (err) {
sub.error(err);
return;
}
sub.next(result);
}]);
};
callContractMethod();
this._initNewBlocksSubscription();
this._initCallInterval();
this.callables.push(callContractMethod);
return sub.pipe(distinctUntilChanged((a, b) => equal(a, b)));
@ -118,11 +116,11 @@ export default class Subspace {
trackBalance(address, erc20Address) {
const sub = new ReplaySubject();
if(!isAddress(address)) throw "invalid address"
if(erc20Address && !isAddress(erc20Address)) throw "invalid ERC20 contract address"
if (!isAddress(address)) throw "invalid address"
if (erc20Address && !isAddress(erc20Address)) throw "invalid ERC20 contract address"
let callFn;
if(!erc20Address){
if (!erc20Address){
callFn = () => {
const fn = this.web3.getBalance;
@ -140,7 +138,7 @@ export default class Subspace {
// balanceOf
const data = "0x70a08231" + "000000000000000000000000" + stripHexPrefix(erc20Address);
fn.apply(fn, [{to: erc20Address, data}, (err, result) => {
if(err) {
if (err) {
sub.error(err);
return;
}
@ -149,11 +147,13 @@ export default class Subspace {
};
}
callFn();
// FIX ME: has issues immediatly getting the value
// this.web3.getBlock('latest').then(block => {
setTimeout(() => {
callFn();
}, 500);
// });
this._initNewBlocksSubscription();
this._initCallInterval();
this.callables.push(callFn);
return sub.pipe(distinctUntilChanged((a, b) => equal(a, b)));
@ -161,7 +161,7 @@ export default class Subspace {
close(){
clearInterval(this.intervalTracker);
if(this.newBlocksSubscription) this.newBlocksSubscription.unsubscribe();
if (this.newBlocksSubscription) this.newBlocksSubscription.unsubscribe();
this.eventSyncer.close();
this.intervalTracker = null;
this.callables = [];

View File

@ -3,7 +3,6 @@ export function randomString() {
return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
}
export function isAddress(address) {
return /^(0x)?[0-9a-fA-F]{40}$/i.test(address)
};