Rename js-sdk-examples to fluence-js-examples

This commit is contained in:
Pavel Murygin
2021-10-20 22:03:31 +03:00
parent 921938082b
commit 59af5c4e0f
33 changed files with 0 additions and 0 deletions

View File

@ -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*

View File

@ -0,0 +1,147 @@
# Getting Started with Fluence
This sample project demonstrates how fluence network can be accessed from the browser. As an example it retrieves the timestamp of the current time from the relay node. The project is based on an create-react-app template with slight modifications to integrate Fluence. The primary focus is the integration itself, i.e React could be swapped with a framework of your choice.
## Getting started
Run aqua compiler in watch mode:
```bash
npm run watch-aqua
```
Start the application
```bash
npm start
```
The browser window with `localhost:3000` should open
## How it works
The application can be split into two main building blocks: the runtime provided by the `@fluencelabs/fluence` package and the compiler for the `Aqua` language. The workflow is as follows:
1. You write aqua code
2. Aqua gets compiled into the typescript file
3. The typescript is build by the webpack (or any other tool of you choice) into js bunlde.
## Project structure
```
aqua (1)
┗ getting-started.aqua (3)
node_modules
public
src
┣ _aqua (2)
┃ ┗ getting-started.ts (4)
┣ App.scss
┣ App.tsx
┣ index.css
┣ index.tsx
┣ logo.svg
┗ react-app-env.d.ts
package-lock.json
package.json
tsconfig.json
```
The project structure is based on the create-react-app template with some minor differences:
* `aqua` (1) contains the Aqua source code files. The complier picks them up and generate corresponding typescript file. See `getting-started.aqua` (3) and `getting-started.ts` respectively
* `src/_aqua` (2) is where the generated target files are places. The target directory is conveniently placed inside the sources directory which makes it easy to import typescript functions from the application source code
## npm packages and scripts
The following npm packages are used:
* `@fluencelabs/fluence` - is the client for Fluence Network running inside the browser. See https://github.com/fluencelabs/fluence-js for additional information
* `@fluencelabs/fluence-network-environment` - is the maintained list of Fluence networks and nodes to connect to.
* `@fluencelabs/aqua` - is the command line interface for Aqua compiler. See https://github.com/fluencelabs/aqua for more information
* `@fluencelabs/aqua-lib` - Aqua language standard library
* `chokidar-cli` - A tool to watch for aqua file changes and compile them on the fly
The compilation of aqua code is implemented with these scripts:
```
scripts: {
...
"compile-aqua": "aqua -i ./aqua/ -o ./src/_aqua",
"watch-aqua": "chokidar \"**/*.aqua\" -c \"npm run compile-aqua\""
}
...
```
The interface is pretty straightforward: you just specify the input and output directories for the compiler.
## Aqua code
```
import "@fluencelabs/aqua-lib/builtin.aqua"
func getRelayTime(relayPeerId: PeerId) -> u64: (1)
on relayPeerId: (2)
ts <- Peer.timestamp_ms() (3)
<- ts (4)
```
The code above defines a function which retrieves the current timestamp from the relay node. The function works as following:
1. The function definition, specifying arguments and return value types
2. Shift the execution to the peer with id equal to `relayPeerId`
3. Calls built-in function on the current peer and stores the result into a variable
4. Returns the result
The function gets compiled into typescript and can be called from the application code (see next section)
## Application code
Let's take a look at how we can use Fluence from typecript.
First, we need to import the relevant packages:
```typescript
import { createClient, FluenceClient } from "@fluencelabs/fluence";
import { krasnodar } from "@fluencelabs/fluence-network-environment";
import { getRelayTime } from "./_aqua/getting-started";
```
Please notice that the function defined in Aqua has been compiled into typescript and can be directly imported. Using the code generated by the compiler is as easy as calling a function. The compiler generates all the boilerplate needed to send a particle into the network and wraps it into a single call. Note that all the type information and therefore type checking and code completion facilities are there!
Next we initialize the client:
```typescript
const relayNode = krasnodar[0];
function App() {
const [client, setClient] = useState<FluenceClient | null>(null);
...
useEffect(() => {
createClient(relayNode)
.then((client) => setClient(client))
.catch((err) => console.log("Client initialization failed", err));
}, [client]);
```
Every peer running in the browser must connect to the network through a relay node. We use the first node of the krasnodar network there. In our example we store the client using React `useState` facilities. Feel free to store wherever you store other application state.
Executing Aqua is as easy as calling a function in typesctipt:
```typescript
const doGetRelayTime = async () => {
if (!client) {
return;
}
const time = await getRelayTime(client, relayNode.peerId);
setRelayTime(new Date(time));
};
```

View File

@ -0,0 +1,6 @@
import "@fluencelabs/aqua-lib/builtin.aqua"
func getRelayTime(relayPeerId: PeerId) -> u64:
on relayPeerId:
ts <- Peer.timestamp_ms()
<- ts

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,53 @@
{
"name": "getting-started-browser",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fluencelabs/fluence": "0.12.0",
"@fluencelabs/fluence-network-environment": "1.0.10",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^12.8.3",
"@types/jest": "^26.0.24",
"@types/node": "^12.20.16",
"@types/react": "^17.0.14",
"@types/react-dom": "^17.0.9",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"typescript": "^4.3.5",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"compile-aqua": "aqua -i ./aqua/ -o ./src/_aqua",
"watch-aqua": "chokidar \"**/*.aqua\" -c \"npm run compile-aqua\""
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@fluencelabs/aqua": "^0.3.0-226",
"@fluencelabs/aqua-lib": "0.1.9",
"chokidar-cli": "^2.1.0",
"node-sass": "^6.0.1"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,42 @@
<!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" />
<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>Fluence getting started</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: 4.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -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"
}

View File

@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:

View File

@ -0,0 +1,63 @@
$color1: black;
$color2: rgb(214, 214, 214);
$accent-color: rgb(225, 30, 90);
.logo {
height: 15vmin;
pointer-events: none;
}
.mono {
font-family: monospace, monospace;
}
.bold {
font-weight: bold;
}
header {
margin-top: 10vmin;
}
header,
h1,
h2,
h3 {
text-align: center;
}
.content {
width: 800px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
align-content: center;
margin-left: auto;
margin-right: auto;
}
.btn {
height: 26px;
border: 1px solid;
border-color: $color2;
background-color: transparent;
margin: 5px;
font-size: 16px;
color: $color1;
&::placeholder {
color: $color2;
}
&:hover,
&:focus {
outline: 1px solid white;
border-color: $accent-color;
color: $accent-color;
}
}

View File

@ -0,0 +1,52 @@
import React, { useEffect, useState } from "react";
import logo from "./logo.svg";
import "./App.scss";
import { Fluence } from "@fluencelabs/fluence";
import { krasnodar } from "@fluencelabs/fluence-network-environment";
import { getRelayTime } from "./_aqua/getting-started";
const relayNode = krasnodar[0];
function App() {
const [relayTime, setRelayTime] = useState<Date | null>(null);
useEffect(() => {
Fluence.start({ connectTo: relayNode })
.catch((err) => console.log("Client initialization failed", err));
}, []);
const onGetRelayTimeBtnClick = async () => {
if (!Fluence.getStatus().isConnected) {
return;
}
const time = await getRelayTime(relayNode.peerId);
setRelayTime(new Date(time));
};
return (
<div className="App">
<header>
<img src={logo} className="logo" alt="logo" />
</header>
<div className="content">
<h1>Status: {Fluence.getStatus().isConnected ? "Connected" : "Disconnected"}</h1>
<button className="btn" onClick={onGetRelayTimeBtnClick}>
Get relay time
</button>
{relayTime && (
<>
<h2>Relay time:</h2>
<div>{relayTime?.toLocaleString() || ""}</div>
</>
)}
</div>
</div>
);
}
export default App;

View File

@ -0,0 +1,103 @@
/**
*
* This file is auto-generated. Do not edit manually: changes may be erased.
* Generated by Aqua compiler: https://github.com/fluencelabs/aqua/.
* If you find any bugs, please write an issue on GitHub: https://github.com/fluencelabs/aqua/issues
* Aqua version: 0.3.0-226
*
*/
import { Fluence, FluencePeer } from '@fluencelabs/fluence';
import {
ResultCodes,
RequestFlow,
RequestFlowBuilder,
CallParams,
} from '@fluencelabs/fluence/dist/internal/compilerSupport/v1';
// Services
// Functions
export function getRelayTime(relayPeerId: string, config?: {ttl?: number}) : Promise<number>;
export function getRelayTime(peer: FluencePeer, relayPeerId: string, config?: {ttl?: number}) : Promise<number>;
export function getRelayTime(...args: any) {
let peer: FluencePeer;
let relayPeerId: any;
let config: any;
if (FluencePeer.isInstance(args[0])) {
peer = args[0];
relayPeerId = args[1];
config = args[2];
} else {
peer = Fluence.getPeer();
relayPeerId = args[0];
config = args[1];
}
let request: RequestFlow;
const promise = new Promise<number>((resolve, reject) => {
const r = new RequestFlowBuilder()
.disableInjections()
.withRawScript(
`
(xor
(seq
(seq
(seq
(seq
(seq
(call %init_peer_id% ("getDataSrv" "-relay-") [] -relay-)
(call %init_peer_id% ("getDataSrv" "relayPeerId") [] relayPeerId)
)
(call -relay- ("op" "noop") [])
)
(xor
(call relayPeerId ("peer" "timestamp_ms") [] ts)
(seq
(call -relay- ("op" "noop") [])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 1])
)
)
)
(call -relay- ("op" "noop") [])
)
(xor
(call %init_peer_id% ("callbackSrv" "response") [ts])
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 2])
)
)
(call %init_peer_id% ("errorHandlingSrv" "error") [%last_error% 3])
)
`,
)
.configHandler((h) => {
h.on('getDataSrv', '-relay-', () => {
return peer.getStatus().relayPeerId;
});
h.on('getDataSrv', 'relayPeerId', () => {return relayPeerId;});
h.onEvent('callbackSrv', 'response', (args) => {
const [res] = args;
resolve(res);
});
h.onEvent('errorHandlingSrv', 'error', (args) => {
const [err] = args;
reject(err);
});
})
.handleScriptError(reject)
.handleTimeout(() => {
reject('Request timed out for getRelayTime');
})
if(config && config.ttl) {
r.withTTL(config.ttl)
}
request = r.build();
});
peer.internals.initiateFlow(request!);
return promise;
}

View File

@ -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;
}

View File

@ -0,0 +1,12 @@
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 11 KiB

View File

@ -0,0 +1 @@
/// <reference types="react-scripts" />

View File

@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"esModuleInterop": true,
"noImplicitAny": false,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noFallthroughCasesInSwitch": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": [
"src"
]
}