gitbook-docs/fluence-js/2_basics.md

6.1 KiB

Basics

Intro

In this section we will show you how Fluence JS can be used to create a hello world application with Fluence stack.

Aqua code

Let's start with the aqua code first:

service HelloWorld("hello-world"):
    hello(str: string)

func sayHello():
    HelloWorld.hello("Hello, world!")

func getRelayTime() -> u64:
    on HOST_PEER:
        ts <- Peer.timestamp_ms()
    <- ts

This file has three definitions.

The first one is a service named HelloWorld. A Service interfaces functions executable on a peer. We will register a handler for this interface in our typescript application.

The second definition is the function sayHello. The only thing the function is doing is calling the hello method of HelloWorld service located on the current peer. We will show you how to call this function from the typescript application.

Finally we have a functions which demonstrate how to work with the network. It asks the current time from the relay peer and return back the our peer.

Installing dependencies

Initialize an empty npm package:

npm init

We will need these two packages for the application runtime

npm install @fluencelabs/fluence @fluencelabs/fluence-network-environment

The first one is the SDK itself and the second is a maintained list of Fluence networks and nodes to connect to.

Aqua compiler cli has to be installed, but is not needed at runtime.

npm install --save-dev @fluencelabs/aqua

Aqua comes with the standard library which can accessed from "@fluencelabs/aqua-lib" package. All the aqua packages are only needed at compiler time, so we install it as a development dependency

npm install --save-dev @fluencelabs/aqua-lib

Also we might want to have aqua source files automatically recompiled on every save. We will take advantage of chokidar for that:

npm install --save-dev @fluencelabs/chokidar-cli

And last, but no least we will need TypeScript

npm install --save-dev typescript
npx tsc --init

Setting up aqua compiler

Let's put aqua described earlier into aqua/hello-world.aqua file. You probably want to keep the generated TypeScript in the same directory with other typescript files, usually src. Let's create the src/_aqua directory for that.

The overall project structure looks like this:

 ┣ aqua
 ┃ ┗ hello-world.aqua
 ┣ src
 ┃ ┣ _aqua
 ┃ ┃ ┗ hello-world.ts
 ┃ ┗ index.ts
 ┣ package-lock.json
 ┣ package.json
 ┗ tsconfig.json

The Aqua compiler can be run with npm:

npx aqua -i ./aqua/ -o ./src/_aqua

We recommend to store this logic inside a script in packages.json file:

{
  ...
  "scripts": {
    ...
    "compile-aqua": "aqua -i ./aqua/ -o ./src/_aqua", // (1)
    "watch-aqua": "chokidar \"**/*.aqua\" -c \"npm run compile-aqua\"" // (2)
  },
  ...
}

compile-aqua (1) runs the compilation once, producing src/_aqua/hello-world.ts in our case watch-aqua (2) starts watching for any changes in .aqua files recompiling them on the fly

Using the compiled code in typescript application

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. It also generate a function for service callback registration. Note that all the type information and therefore type checking and code completion facilities are there!

Let's see how use generated code in our application. index.ts:

import { Fluence } from "@fluencelabs/fluence";
import { krasnodar } from "@fluencelabs/fluence-network-environment"; // (1)
import {
  registerHelloWorld,
  sayHello,
  getRelayTime,
} from "./_aqua/hello-world"; // (2)

async function main() {
  await Fluence.start({ connectTo: krasnodar[0] }); // (3)

  // (3)
  registerHelloWorld({
    hello: async (str) => {
      console.log(str);
    },
  });

  await sayHello(); // (4)

  const relayTime = await getRelayTime(); // (5)

  console.log("The relay time is: ", new Date(relayTime).toLocaleString());

  await Fluence.stop(); // (6)
}

main();

(1) Import list of possible relay nodes (network environment)

(2) Aqua compiler provides functions which can be directly imported like any normal typescript function.

(3) A Fluence peer has to be started before running any application in Fluence Network. For the vast majority of use cases you should use Fluence facade to start and stop the peer. The start method accepts a parameters object which. The most common parameter is the address of the relay node the peer should connect to. In this example we are using the first node of the krasnodar network. If you do not specify the connectTo options will only be able to execute air on the local machine only. Please keep in mind that the init function is asynchronous

For every exported service XXX definition in aqua code, the compiler provides a registerXXX counterpart. These functions provide a type-safe way of registering callback handlers for the services. The callbacks are executed when the appropriate service is called in aqua on the current peer. The handlers take form of the object where keys are the name of functions and the values are async functions used as the corresponding callbacks. For example in (3) we are registering handler for HelloWorld service which outputs it's parameter to the console

For every exported func XXX definition in aqua code, the compiler provides an async function which can be directly called from typescript. In (4, 5) we are calling exported aqua function with no arguments. Note that every function is asynchronous.

(6) You should call stop when the peer is no longer needed. As a rule of thumb all the peers should be uninitialized before destroying the application.

Let's try running the example:

node -r ts-node/register src/index.ts

If everything has been done correctly yuo should see Hello, world! in the console.

The next section will cover in-depth and advanced usage of Fluence JS

The code from this section is available in on github