Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

migrate from RChain-API to rnode web APIs #15

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 0 additions & 16 deletions .dir-locals.el

This file was deleted.

13 changes: 0 additions & 13 deletions .flowconfig

This file was deleted.

11 changes: 11 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Contributing to RChain-Status

## Coding style

- airbnb style (use `npm run lint`)
- @ts-check (see https://properjs.org/)

vs-code supports these nicely.



47 changes: 4 additions & 43 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -103,55 +103,16 @@ <h2>Setup</h2>
</div>
<script type="module">
import statusPage from './page.js';
window.addEventListener("DOMContentLoaded", () => {
const byId = id => document.getElementById(id);
const def = obj => Object.freeze(obj);

const ui = def({
nameBox: byId("name"),
registerButton: byId("register"),
newStatusBox: byId("new-status"),
nonceBox: byId("nonce"),
setStatusButton: byId("set-status"),
friendBox: byId("friend-name"),
checkButton: byId("check-status"),
friendStatusP: byId("friend-status"),
proposeButton: byId("propose"),
problem: byId("problem"),
signature: byId("signature"),
window.addEventListener("DOMContentLoaded", () => {
statusPage({
getElementById: id => document.getElementById(id),
hide: (elt) => { elt.hidden = false; },
showText: (elt, txt) => { elt.textContent = txt; elt.hidden = false; },
enable: (button) => { button.disabled = false; },
disable: (button) => { button.disabled = true; },
});
const port = def({
listen: (handler) => { window.onmessage = event => handler(event.data); },
postMessage: (data) => window.postMessage(data, '*'),
});
statusPage(ui, port, fetch);
}, { fetch });
});
</script>
<script>
function typingPause(field, go, ms) {
let timer;
field.addEventListener('keyup', (event) => {
clearTimeout(timer);
if (field.value) {
timer = setTimeout(go(field.value), ms);
}
});
}

const byId = id => document.getElementById(id);
const anImg = byId('regAvatar');
function updateAvatar(name) {
const src = `https://robohash.org/${name}?size=48x48&amp;set=set3`;
anImg.setAttribute('src', src);
anImg.hidden = false;
}

typingPause(byId('name'), updateAvatar, 500);

</script>
</body>
</html>
10 changes: 10 additions & 0 deletions jsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
// This file can contain .js-specific Typescript compiler config.
{
"compilerOptions": {
"noEmit": false,
"declaration": true,
"emitDeclarationOnly": true,
},
"include": ["**/*.js", "*.js"],
}

105 changes: 29 additions & 76 deletions main.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,11 @@
const { RNode, RHOCore } = require('rchain-api');
const docopt = require('docopt').docopt;
const { rhol } = RHOCore;
const TODO = undefined;
const RHOCore = TODO;

const usage = `

const host = argv[2] ? argv[2] : 'localhost';
const port = argv[3] ? parseInt(argv[3], 10) : 40401;
const uiPort = argv[4] ? parseInt(process.argv[4], 10) : 8080;


Start a fresh node, deploy the contract, note the uri and then start this middleware.

Usage:
main.js [options]

Options:
--host INT The hostname or IPv4 address of the node
[default: localhost]
--port INT The tcp port of the nodes gRPC service
[default: 40401]
--ui-port INT The tcp port for the dApp UI to connect on
[default: 8080]
-c --register URI The dApp's register contract's URI in the registry
-h --help show usage

`;

function main(argv, { grpc, express, clock, random }) {
const cli = docopt(usage, { argv: argv.slice(2) });
console.log('DEBUG: cli:', cli);

const myNode = RNode(grpc, { host: cli["--host"], port: cli["--port"] });
const app = express();

// Serve static assets like index.html and page.js from root directory
app.use(express.static(__dirname));

app.post('/users/:name', registerHandler(myNode, clock, cli["--register"]));
/*
app.post('/users/:name', registerHandler(myNode, clock, cli['--register']));
app.post('/users/:name/status', setHandler(myNode, clock));
app.get('/users/:name/status', checkHandler(myNode, clock, random));

app.listen(cli["--ui-port"], () => {
console.log('RChain status dapp started.');
console.log(`Using ${cli["--host"]}:${cli["--port"]} to contact RNode.`);
console.log(`User interface on port ${cli["--ui-port"]}`);
});
}

*/

/**
* Helper for when communication with the node goes wrong. Logs the problem
Expand All @@ -56,15 +15,14 @@ function main(argv, { grpc, express, clock, random }) {
* @param oops The failure ...
*
*/
function bail(response, oops) {
function bail(res, oops) {
console.log(oops);
res.status(500).send({ message: oops.message });
}


function registerHandler(myNode, clock, uri) {
export function registerHandler(myNode, clock, uri) {
return (req, res) => {

const rholangCode = rhol`
new lookup(\`rho:registry:lookup\`), registerCh in {
lookup!(\`URI\`, *registerCh)|
Expand All @@ -73,15 +31,15 @@ function registerHandler(myNode, clock, uri) {
registerForStatus!(${req.params.name}, ${req.query.sig}, ${req.query.pubKey}, "bogusReturn")
}
}
`.replace("URI", uri) //TODO Do this better
`.replace('URI', uri); //TODO Do this better

const deployData = {
term: rholangCode,
timestamp: clock().valueOf(),
phloPrice: { value: 1}, //TODO These are placeholder values.
phloLimit: { value: 1000000},
phloPrice: { value: 1 }, //TODO These are placeholder values.
phloLimit: { value: 1000000 },
from: '0x01',
}
};

// TODO: use a non-trivial return channel and wait for results there.
myNode.doDeploy(deployData, true)
Expand All @@ -92,18 +50,17 @@ function registerHandler(myNode, clock, uri) {
}


function setHandler(myNode, clock) {
export function setHandler(myNode, clock) {
return (req, res) => {

const rholangCode = rhol`@[${req.params.name}, "newStatus"]!(${req.query.status}, ${req.query.signature}, "notUsingAck")`
const rholangCode = rhol`@[${req.params.name}, "newStatus"]!(${req.query.status}, ${req.query.signature}, "notUsingAck")`;

const deployData = {
term: rholangCode,
timestamp: clock.valueOf(),
phloPrice: { value: 1}, //TODO These are placeholder values.
phloLimit: { value: 1000000},
phloPrice: { value: 1 }, //TODO These are placeholder values.
phloLimit: { value: 1000000 },
from: '0x01',
}
};

myNode.doDeploy(deployData, true)
.then(() => {
Expand All @@ -113,9 +70,8 @@ function setHandler(myNode, clock) {
}


function checkHandler(myNode, clock, random) {
export function checkHandler(myNode, clock, random) {
return (req, res) => {

// Generate a public ack channel
// TODO this should be unforgeable.
const ack = random().toString(36).substring(7);
Expand All @@ -124,10 +80,10 @@ function checkHandler(myNode, clock, random) {
const deployData = {
term: rholangCode,
timestamp: clock.valueOf(),
phloPrice: { value: 1}, //TODO These are placeholder values.
phloLimit: { value: 1000000},
phloPrice: { value: 1 }, //TODO These are placeholder values.
phloLimit: { value: 1000000 },
from: '0x01',
}
};
// Check the status, sending it to the ack channel
myNode.doDeploy(deployData, true)
.then(_ => myNode.listenForDataAtPublicName(ack))
Expand All @@ -143,18 +99,15 @@ function checkHandler(myNode, clock, random) {
};
}

function rhol(template, ...subs) {
const literal = val => JSON.stringify(val);
const encoded = subs.map(literal);


if (require.main === module) {
/* eslint-disable global-require */

// Import primitive effects only when invoked as main module.
main(process.argv, {
// If express followed ocap discipine, we would pass it
// access to files and the network and such.
express: require('express'),
grpc: require('grpc'),
clock: () => new Date(),
random: Math.random,
const out = [];
template.forEach((part, ix) => {
out.push(part);
out.push(encoded[ix]);
});

return out.join('');
}
18 changes: 6 additions & 12 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "RChain-Status-Dapp",
"version": "1.0.2",
"name": "rchain-status",
"version": "1.1.0",
"description": "Build your first RChain dapp",
"main": "main.js",
"scripts": {
Expand All @@ -12,22 +12,16 @@
},
"repository": {
"type": "git",
"url": "git+https://github.com/JoshOrndorff/Rchain-Status"
"url": "git+https://github.com/rchain-community/Rchain-Status"
},
"author": "Joshy Orndorff",
"contributors": ["Dan Connolly", "Joshy Orndorff"],
"license": "Unlicense",
"devDependencies": {
"eslint": "^5.4.0",
"eslint-config-airbnb-base": "^13.1.0",
"eslint-plugin-import": "^2.14.0",
"flow-bin": "^0.80.0",
"flow-interfaces-chrome": "^0.5.1"
"eslint-plugin-import": "^2.14.0"
},
"dependencies": {
"@grpc/proto-loader": "^0.3.0",
"docopt": "^0.6.2",
"express": "^4.16.3",
"grpc": "^1.14.1",
"rchain-api": "^0.7.1-beta.2"
"docopt": "^0.6.2"
}
}
Loading