chore(js-client): Update and restructure examples [fixes DXJ-454] (#464)

* Update examples

* Update js-client examples

* Add cli to example

* Fixes

* Update js-client

* Update js-client version in js-client examples

* PR fixes

* Remove marine-js

* Update locks

* Fix aqua

* Remove unused import

* Adjust import

* Change code comment

* Update example structures

* Fix quickstart examples

* Add aqua command to README

* Add marine example

* Fix image links

* Fixes

* Misc fixes
This commit is contained in:
Akim
2023-12-12 18:46:57 +07:00
committed by GitHub
parent f2b057ba4a
commit fbfc344abf
180 changed files with 61741 additions and 184592 deletions

View File

@ -0,0 +1,24 @@
aqua Deals declares *
data Deal:
definition: string
timestamp: string
dealIdOriginal: string
dealId: string
chainNetwork: string
chainNetworkId: u64
data Deals:
defaultWorker: ?Deal
func get() -> Deals:
<- Deals(
defaultWorker=?[Deal(
definition="bafkreifzhzgakizgfyyf2cqkmrhj5p73aw3lovhaji6sad54veo5dm4nxi",
timestamp="2023-11-30T23:34:44.833Z",
dealIdOriginal="0x6CA51618eC0C1cc34f6D5ead6AD1BA8e57b950D0",
dealId="6ca51618ec0c1cc34f6d5ead6ad1ba8e57b950d0",
chainNetwork="kras",
chainNetworkId=80001
)]
)

View File

@ -0,0 +1,4 @@
aqua Hosts declares *
func get() -> ?u8:
<- nil

View File

@ -0,0 +1,2 @@
service Adder("adder"):
add_one(value: u64) -> u64

View File

@ -0,0 +1,9 @@
# yaml-language-server: $schema=schemas/env.json
# Defines user project preferences
# Documentation: https://github.com/fluencelabs/cli/tree/main/docs/configs/env.md
version: 0
fluenceEnv: kras

View File

@ -0,0 +1,28 @@
{
"$id": "https://fluence.dev/schemas/env.yaml",
"title": "env.yaml",
"type": "object",
"description": "Defines user project preferences",
"properties": {
"fluenceEnv": {
"title": "Fluence environment",
"description": "Fluence environment to connect to",
"type": "string",
"enum": [
"kras",
"testnet",
"stage",
"local",
"custom"
],
"nullable": true
},
"version": {
"type": "number",
"const": 0
}
},
"required": [
"version"
]
}

View File

@ -0,0 +1,779 @@
{
"type": "object",
"properties": {
"services": {
"title": "Services",
"description": "A map with service names as keys and Service configs as values. You can have any number of services listed here as long as service name keys start with a lowercase letter and contain only letters numbers and underscores. You can use `fluence service add` command to add a service to this config",
"type": "object",
"additionalProperties": {
"title": "Service config",
"description": "Service config. Defines where the service is and how to deploy it",
"type": "object",
"properties": {
"get": {
"type": "string",
"description": "Path to service directory or URL to the tar.gz archive with the service"
},
"overrideModules": {
"type": "object",
"title": "Overrides",
"description": "A map of modules to override",
"additionalProperties": {
"type": "object",
"title": "Module overrides",
"description": "Overrides for the module config",
"properties": {
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
}
},
"required": [],
"nullable": true
},
"properties": {
"Module_name": {
"type": "object",
"title": "Module overrides",
"description": "Overrides for the module config",
"properties": {
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
}
},
"required": [],
"nullable": true
}
},
"nullable": true,
"required": []
}
},
"required": [
"get"
]
},
"properties": {
"Service_name": {
"title": "Service config",
"description": "Service config. Defines where the service is and how to deploy it",
"type": "object",
"properties": {
"get": {
"type": "string",
"description": "Path to service directory or URL to the tar.gz archive with the service"
},
"overrideModules": {
"type": "object",
"title": "Overrides",
"description": "A map of modules to override",
"additionalProperties": {
"type": "object",
"title": "Module overrides",
"description": "Overrides for the module config",
"properties": {
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
}
},
"required": [],
"nullable": true
},
"properties": {
"Module_name": {
"type": "object",
"title": "Module overrides",
"description": "Overrides for the module config",
"properties": {
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
}
},
"required": [],
"nullable": true
}
},
"nullable": true,
"required": []
}
},
"required": [
"get"
]
}
},
"required": [],
"nullable": true
},
"version": {
"type": "number",
"const": 5
},
"dependencies": {
"type": "object",
"title": "Dependencies",
"nullable": true,
"description": "(For advanced users) Overrides for the project dependencies",
"properties": {
"npm": {
"type": "object",
"title": "npm dependencies",
"nullable": true,
"description": "A map of npm aqua dependency versions. Fluence CLI ensures dependencies are installed each time you run aqua",
"additionalProperties": {
"type": "string"
},
"properties": {
"npm_dependency_name": {
"type": "string",
"description": "npm dependency version"
}
},
"required": []
},
"cargo": {
"type": "object",
"title": "Cargo dependencies",
"nullable": true,
"description": "A map of cargo dependency versions. Fluence CLI ensures dependencies are installed each time you run commands that depend on Marine or Marine REPL",
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Cargo_dependency_name": {
"type": "string",
"description": "cargo dependency version"
}
}
}
},
"required": []
},
"aquaInputPath": {
"type": "string",
"nullable": true,
"description": "Path to the aqua file or directory with aqua files that you want to compile by default. Must be relative to the project root dir"
},
"aquaOutputTSPath": {
"type": "string",
"nullable": true,
"description": "Path to the default compilation target dir from aqua to ts. Must be relative to the project root dir"
},
"aquaOutputJSPath": {
"type": "string",
"nullable": true,
"description": "Path to the default compilation target dir from aqua to js. Must be relative to the project root dir. Overrides 'aquaOutputTSPath' property"
},
"hosts": {
"description": "A map of objects with worker names as keys, each object defines a list of peer IDs to host the worker on. Intended to be used by providers to deploy directly without using the blockchain",
"type": "object",
"nullable": true,
"additionalProperties": {
"type": "object",
"description": "Worker config",
"properties": {
"services": {
"description": "An array of service names to include in this worker. Service names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"spells": {
"description": "An array of spell names to include in this worker. Spell names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"peerIds": {
"type": "array",
"description": "An array of peer IDs to deploy on",
"items": {
"type": "string"
},
"minItems": 1
}
},
"required": []
},
"properties": {
"workerName": {
"type": "object",
"description": "Worker config",
"properties": {
"services": {
"description": "An array of service names to include in this worker. Service names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"spells": {
"description": "An array of spell names to include in this worker. Spell names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"peerIds": {
"type": "array",
"description": "An array of peer IDs to deploy on",
"items": {
"type": "string"
},
"minItems": 1
}
},
"required": []
}
},
"required": []
},
"deals": {
"description": "A map of objects with worker names as keys, each object defines a deal",
"type": "object",
"nullable": true,
"additionalProperties": {
"type": "object",
"description": "Worker config",
"properties": {
"services": {
"description": "An array of service names to include in this worker. Service names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"spells": {
"description": "An array of spell names to include in this worker. Spell names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"minWorkers": {
"type": "number",
"description": "Required workers to activate the deal",
"default": 1,
"nullable": true,
"minimum": 1
},
"targetWorkers": {
"type": "number",
"description": "Max workers in the deal",
"default": 3,
"nullable": true,
"minimum": 1
}
},
"required": []
},
"properties": {
"dealName": {
"type": "object",
"description": "Worker config",
"properties": {
"services": {
"description": "An array of service names to include in this worker. Service names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"spells": {
"description": "An array of spell names to include in this worker. Spell names must be listed in fluence.yaml",
"type": "array",
"items": {
"type": "string"
},
"nullable": true
},
"minWorkers": {
"type": "number",
"description": "Required workers to activate the deal",
"default": 1,
"nullable": true,
"minimum": 1
},
"targetWorkers": {
"type": "number",
"description": "Max workers in the deal",
"default": 3,
"nullable": true,
"minimum": 1
}
},
"required": []
}
},
"required": []
},
"spells": {
"type": "object",
"nullable": true,
"description": "A map with spell names as keys and spell configs as values",
"additionalProperties": {
"type": "object",
"description": "Spell config",
"properties": {
"get": {
"type": "string",
"description": "Path to spell"
},
"version": {
"type": "number",
"const": 0
},
"aquaFilePath": {
"type": "string",
"description": "Path to Aqua file which contains an Aqua function that you want to use as a spell",
"nullable": true
},
"function": {
"type": "string",
"description": "Name of the Aqua function that you want to use as a spell",
"nullable": true
},
"initArgs": {
"type": "object",
"description": "A map of Aqua function arguments names as keys and arguments values as values. They will be passed to the spell function and will be stored in the key-value storage for this particular spell.",
"nullable": true
},
"clock": {
"type": "object",
"nullable": true,
"description": "Trigger the spell execution periodically. If you want to disable this property by overriding it in fluence.yaml - pass empty config for it like this: `clock: {}`",
"properties": {
"periodSec": {
"type": "number",
"description": "How often the spell will be executed. If set to 0, the spell will be executed only once. If this value not provided at all - the spell will never be executed",
"minimum": 0,
"maximum": 3153600000,
"nullable": true
},
"startTimestamp": {
"type": "string",
"description": "An ISO timestamp when the periodic execution should start. If this property or `startDelaySec` not specified, periodic execution will start immediately. If it is set to 0 - the spell will never be executed",
"nullable": true
},
"endTimestamp": {
"type": "string",
"description": "An ISO timestamp when the periodic execution should end. If this property or `endDelaySec` not specified, periodic execution will never end. If it is in the past at the moment of spell creation on Rust peer - the spell will never be executed",
"nullable": true
},
"startDelaySec": {
"type": "number",
"description": "How long to wait before the first execution in seconds. If this property or `startTimestamp` not specified, periodic execution will start immediately. WARNING! Currently your computer's clock is used to determine a final timestamp that is sent to the server. This property conflicts with `startTimestamp`. You can specify only one of them",
"nullable": true,
"minimum": 0,
"maximum": 4294967295
},
"endDelaySec": {
"type": "number",
"description": "How long to wait before the last execution in seconds. If this property or `endTimestamp` not specified, periodic execution will never end. WARNING! Currently your computer's clock is used to determine a final timestamp that is sent to the server. If it is in the past at the moment of spell creation - the spell will never be executed. This property conflicts with `endTimestamp`. You can specify only one of them",
"nullable": true,
"minimum": 0,
"maximum": 4294967295
}
},
"required": []
}
},
"required": [
"get"
]
},
"properties": {
"Spell_name": {
"type": "object",
"description": "Spell config",
"properties": {
"get": {
"type": "string",
"description": "Path to spell"
},
"version": {
"type": "number",
"const": 0
},
"aquaFilePath": {
"type": "string",
"description": "Path to Aqua file which contains an Aqua function that you want to use as a spell",
"nullable": true
},
"function": {
"type": "string",
"description": "Name of the Aqua function that you want to use as a spell",
"nullable": true
},
"initArgs": {
"type": "object",
"description": "A map of Aqua function arguments names as keys and arguments values as values. They will be passed to the spell function and will be stored in the key-value storage for this particular spell.",
"nullable": true
},
"clock": {
"type": "object",
"nullable": true,
"description": "Trigger the spell execution periodically. If you want to disable this property by overriding it in fluence.yaml - pass empty config for it like this: `clock: {}`",
"properties": {
"periodSec": {
"type": "number",
"description": "How often the spell will be executed. If set to 0, the spell will be executed only once. If this value not provided at all - the spell will never be executed",
"minimum": 0,
"maximum": 3153600000,
"nullable": true
},
"startTimestamp": {
"type": "string",
"description": "An ISO timestamp when the periodic execution should start. If this property or `startDelaySec` not specified, periodic execution will start immediately. If it is set to 0 - the spell will never be executed",
"nullable": true
},
"endTimestamp": {
"type": "string",
"description": "An ISO timestamp when the periodic execution should end. If this property or `endDelaySec` not specified, periodic execution will never end. If it is in the past at the moment of spell creation on Rust peer - the spell will never be executed",
"nullable": true
},
"startDelaySec": {
"type": "number",
"description": "How long to wait before the first execution in seconds. If this property or `startTimestamp` not specified, periodic execution will start immediately. WARNING! Currently your computer's clock is used to determine a final timestamp that is sent to the server. This property conflicts with `startTimestamp`. You can specify only one of them",
"nullable": true,
"minimum": 0,
"maximum": 4294967295
},
"endDelaySec": {
"type": "number",
"description": "How long to wait before the last execution in seconds. If this property or `endTimestamp` not specified, periodic execution will never end. WARNING! Currently your computer's clock is used to determine a final timestamp that is sent to the server. If it is in the past at the moment of spell creation - the spell will never be executed. This property conflicts with `endTimestamp`. You can specify only one of them",
"nullable": true,
"minimum": 0,
"maximum": 4294967295
}
},
"required": []
}
},
"required": [
"get"
]
}
},
"required": []
},
"aquaImports": {
"type": "array",
"description": "A list of path to be considered by aqua compiler to be used as imports. First dependency in the list has the highest priority. Priority of imports is considered in the following order: imports from --import flags, imports from aquaImports property in fluence.yaml, project's .fluence/aqua dir, npm dependencies from fluence.yaml, npm dependencies from user's .fluence/config.yaml, npm dependencies recommended by fluence",
"items": {
"type": "string"
},
"nullable": true
},
"marineBuildArgs": {
"type": "string",
"description": "Space separated `cargo build` flags and args to pass to marine build. Can be overridden using --marine-build-args flag Default: --release",
"nullable": true
},
"cliVersion": {
"type": "string",
"description": "The version of the Fluence CLI that is compatible with this project. Set this to enforce a particular set of versions of all fluence components",
"nullable": true
},
"ipfsAddr": {
"type": "string",
"description": "IPFS multiaddress to use when uploading workers with 'deal deploy'. Default: /dns4/ipfs.fluence.dev/tcp/5001 or /ip4/127.0.0.1/tcp/5001 if using local local env (for 'workers deploy' IPFS address provided by relay that you are connected to is used)",
"nullable": true,
"default": "/dns4/ipfs.fluence.dev/tcp/5001"
},
"customFluenceEnv": {
"type": "object",
"description": "Custom Fluence environment to use when connecting to Fluence network",
"nullable": true,
"properties": {
"contractsEnv": {
"type": "string",
"description": "Contracts environment to use for this fluence network to sign contracts on the blockchain",
"enum": [
"kras",
"testnet",
"stage",
"local"
]
},
"relays": {
"type": "array",
"description": "List of custom relay multiaddresses to use when connecting to Fluence network",
"items": {
"type": "string"
},
"minItems": 1
}
},
"required": [
"contractsEnv",
"relays"
]
},
"defaultSecretKeyName": {
"description": "Secret key with this name will be used by default by js-client inside CLI to run Aqua code",
"type": "string",
"nullable": true
},
"relaysPath": {
"description": "Path to the directory where you want relays.json file to be generated. Must be relative to the project root dir. This file contains a list of relays to use when connecting to Fluence network and depends on the default environment that you use in your project",
"type": "string",
"nullable": true
}
},
"required": [
"version"
],
"$id": "https://fluence.dev/schemas/fluence.yaml",
"title": "fluence.yaml",
"description": "Defines Fluence Project, most importantly - what exactly you want to deploy and how. You can use `fluence init` command to generate a template for new Fluence project"
}

View File

@ -0,0 +1,93 @@
{
"type": "object",
"$id": "https://fluence.dev/schemas/module.yaml",
"title": "module.yaml",
"description": "Defines [Marine Module](https://fluence.dev/docs/build/concepts/#modules). You can use `fluence module new` command to generate a template for new module",
"properties": {
"name": {
"type": "string",
"description": "\"name\" property from the Cargo.toml (for module type \"rust\") or name of the precompiled .wasm file (for module type \"compiled\")"
},
"type": {
"type": "string",
"enum": [
"rust",
"compiled"
],
"nullable": true,
"default": "compiled",
"description": "Module type \"compiled\" is for the precompiled modules. Module type \"rust\" is for the source code written in rust which can be compiled into a Marine module"
},
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
},
"version": {
"type": "number",
"const": 0
}
},
"required": [
"version",
"name"
]
}

View File

@ -0,0 +1,259 @@
{
"type": "object",
"$id": "https://fluence.dev/schemas/service.yaml",
"title": "service.yaml",
"description": "Defines a [Marine service](https://fluence.dev/docs/build/concepts/#services), most importantly the modules that the service consists of. You can use `fluence service new` command to generate a template for new service",
"properties": {
"name": {
"type": "string",
"description": "Service name. Currently it is used for the service name only when you add service to fluence.yaml using \"add\" command. But this name can be overridden to any other with the --name flag or manually in fluence.yaml"
},
"modules": {
"title": "Modules",
"description": "Service must have a facade module. Each module properties can be overridden by the same properties in the service config",
"type": "object",
"additionalProperties": {
"type": "object",
"title": "Module",
"properties": {
"get": {
"type": "string",
"description": "Either path to the module directory or URL to the tar.gz archive which contains the content of the module directory"
},
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
}
},
"required": [
"get"
]
},
"properties": {
"facade": {
"type": "object",
"title": "Module",
"properties": {
"get": {
"type": "string",
"description": "Either path to the module directory or URL to the tar.gz archive which contains the content of the module directory"
},
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
}
},
"required": [
"get"
]
},
"Other_module_name": {
"type": "object",
"title": "Module",
"properties": {
"get": {
"type": "string",
"description": "Either path to the module directory or URL to the tar.gz archive which contains the content of the module directory"
},
"maxHeapSize": {
"type": "string",
"nullable": true,
"description": "Max size of the heap that a module can allocate in format: [number][whitespace?][specificator?] where ? is an optional field and specificator is one from the following (case-insensitive):\nK, Kb - kilobyte\nKi, KiB - kibibyte\nM, Mb - megabyte\nMi, MiB - mebibyte\nG, Gb - gigabyte\nGi, GiB - gibibyte\nCurrent limit is 4 GiB"
},
"loggerEnabled": {
"type": "boolean",
"nullable": true,
"description": "Set true to allow module to use the Marine SDK logger"
},
"loggingMask": {
"type": "number",
"nullable": true,
"description": "manages the logging targets, described in detail: https://fluence.dev/docs/marine-book/marine-rust-sdk/developing/logging#using-target-map"
},
"volumes": {
"type": "object",
"nullable": true,
"required": [],
"title": "Volumes",
"additionalProperties": {
"type": "string"
},
"properties": {
"Alias": {
"type": "string",
"description": "path"
}
},
"description": "A map of accessible files and their aliases. Aliases should be used in Marine module development because it's hard to know the full path to a file"
},
"envs": {
"type": "object",
"title": "Environment variables",
"nullable": true,
"required": [],
"additionalProperties": {
"type": "string"
},
"properties": {
"Environment_variable_name": {
"type": "string",
"description": "Environment variable value"
}
},
"description": "environment variables accessible by a particular module with standard Rust env API like this: std::env::var(IPFS_ADDR_ENV_NAME). Please note that Marine adds three additional environment variables. Module environment variables could be examined with repl"
},
"mountedBinaries": {
"title": "Mounted binaries",
"type": "object",
"additionalProperties": {
"type": "string"
},
"properties": {
"Mounted_binary_name": {
"type": "string",
"description": "Path to a mounted binary"
}
},
"nullable": true,
"required": [],
"description": "A map of binary executable files that module is allowed to call. Example: curl: /usr/bin/curl"
}
},
"required": [
"get"
]
}
},
"required": [
"facade"
]
},
"version": {
"type": "number",
"const": 0
}
},
"required": [
"version",
"name",
"modules"
]
}

View File

@ -0,0 +1,203 @@
{
"$id": "https://fluence.dev/schemas/workers.yaml",
"title": "workers.yaml",
"type": "object",
"description": "A result of app deployment. This file is created automatically after successful deployment using `fluence workers deploy` command",
"properties": {
"version": {
"type": "number",
"const": 0
},
"deals": {
"type": "object",
"description": "A map of created deals",
"additionalProperties": {
"type": "object",
"properties": {
"definition": {
"type": "string"
},
"timestamp": {
"type": "string",
"description": "ISO timestamp of the time when the worker was deployed"
},
"dealId": {
"type": "string"
},
"dealIdOriginal": {
"type": "string"
},
"chainNetwork": {
"type": "string",
"enum": [
"kras",
"testnet",
"stage",
"local"
]
},
"chainNetworkId": {
"type": "number"
}
},
"required": [
"timestamp",
"definition",
"dealId",
"dealIdOriginal",
"chainNetwork",
"chainNetworkId"
]
},
"properties": {
"Worker_deployed_using_deals": {
"type": "object",
"properties": {
"definition": {
"type": "string"
},
"timestamp": {
"type": "string",
"description": "ISO timestamp of the time when the worker was deployed"
},
"dealId": {
"type": "string"
},
"dealIdOriginal": {
"type": "string"
},
"chainNetwork": {
"type": "string",
"enum": [
"kras",
"testnet",
"stage",
"local"
]
},
"chainNetworkId": {
"type": "number"
}
},
"required": [
"timestamp",
"definition",
"dealId",
"dealIdOriginal",
"chainNetwork",
"chainNetworkId"
]
}
},
"required": [],
"nullable": true
},
"hosts": {
"type": "object",
"description": "A map of deployed workers",
"additionalProperties": {
"type": "object",
"properties": {
"definition": {
"type": "string"
},
"timestamp": {
"type": "string",
"description": "ISO timestamp of the time when the worker was deployed"
},
"dummyDealId": {
"type": "string"
},
"installation_spells": {
"type": "array",
"description": "A list of installation spells",
"items": {
"type": "object",
"properties": {
"host_id": {
"type": "string"
},
"spell_id": {
"type": "string"
},
"worker_id": {
"type": "string"
}
},
"required": [
"host_id",
"spell_id",
"worker_id"
]
}
},
"relayId": {
"type": "string"
}
},
"required": [
"timestamp",
"definition",
"installation_spells",
"relayId",
"dummyDealId"
]
},
"properties": {
"Worker_deployed_using_direct_hosting": {
"type": "object",
"properties": {
"definition": {
"type": "string"
},
"timestamp": {
"type": "string",
"description": "ISO timestamp of the time when the worker was deployed"
},
"dummyDealId": {
"type": "string"
},
"installation_spells": {
"type": "array",
"description": "A list of installation spells",
"items": {
"type": "object",
"properties": {
"host_id": {
"type": "string"
},
"spell_id": {
"type": "string"
},
"worker_id": {
"type": "string"
}
},
"required": [
"host_id",
"spell_id",
"worker_id"
]
}
},
"relayId": {
"type": "string"
}
},
"required": [
"timestamp",
"definition",
"installation_spells",
"relayId",
"dummyDealId"
]
}
},
"required": [],
"nullable": true
}
},
"required": [
"version"
]
}

View File

@ -0,0 +1,16 @@
# yaml-language-server: $schema=schemas/workers.json
# A result of app deployment. This file is created automatically after successful deployment using `fluence workers deploy` command
# Documentation: https://github.com/fluencelabs/cli/tree/main/docs/configs/workers.md
version: 0
deals:
defaultWorker:
definition: bafkreifzhzgakizgfyyf2cqkmrhj5p73aw3lovhaji6sad54veo5dm4nxi
timestamp: 2023-11-30T23:34:44.833Z
dealIdOriginal: "0x6CA51618eC0C1cc34f6D5ead6AD1BA8e57b950D0"
dealId: 6ca51618ec0c1cc34f6d5ead6ad1ba8e57b950d0
chainNetwork: kras
chainNetworkId: 80001

View File

@ -0,0 +1,2 @@
[workspace]
members = [ "src/services/adder/modules/adder" ]

View File

@ -0,0 +1,128 @@
# 2. Browser-Parallel-Computation
> It's recommended to complete [CLI quickstart](https://fluence.dev/docs/build/get-started) before exploring this example as the example contains concepts build upon deployed service
In the first section, we explored browser-to-browser messaging using local, i.e. browser-native, services and the Fluence network for message transport. Now we have already deployed a simple service `Adder` for you, and we will try to experiment with this.
The service code:
```rust
use marine_rs_sdk::marine;
pub fn main() {}
#[marine]
pub fn add_one(value: u64) -> u64 {
value + 1
}
```
You can deploy it yourself by following [CLI quickstart](https://fluence.dev/docs/build/get-started) guide, replacing `HelloWorld` module with following code and renaming `HelloWorld` service to `Adder` service there.
First, let's have a look at the Aqua file. Navigate to the `2-browser-parallel-computation/src/aqua/getting_started.aqua` file in your IDE or terminal:
> If you have trouble reading aqua, feel free to refer to [aqua book](https://fluence.dev/docs/aqua-book/introduction)
> Read carefully through comments, starting with `--`.
```aqua
import Subnet, Worker from "@fluencelabs/aqua-lib/subnet.aqua"
-- 'use' clause brings Deal service into the scope
use "deals.aqua"
-- this 'import' brings every aqua service declaration into the scope
import "services.aqua"
-- Function to get all workers from subnet
func resolveSubnet() -> []Worker:
-- Getting deal id of deployed deal to resolve subnet
deals <- Deals.get()
dealId = deals.defaultWorker!.dealIdOriginal
-- Subnets cannot be resolved on local (client) peers, e.g., the CLI client or the browser. Instead, a subnet needs to be resolved on a relay.
on HOST_PEER_ID:
-- Resolving subnets using Deal id of deployed service
subnet <- Subnet.resolve(dealId)
<- subnet.workers
-- This data structure represents the aqua function that is calling the worker via the frontend.
data ComputationRequest:
worker_id: string
host_id: string
value: u64
-- Executes single computation request
func add_one_single(request: ComputationRequest) -> u64:
-- Extracting worker and host for execution service request
on request.worker_id via request.host_id:
-- Service execution
res <- Adder.add_one(request.value)
-- Returning result from function
<- res
func add_one_sequential(requests: []ComputationRequest) -> *u64:
-- Stream for keeping all computation results
results: *u64
-- Iterating over every computation request, one by one
for request <- requests:
on request.worker_id via request.host_id:
res <- Adder.add_one(request.value)
results <<- res
<- results
func add_one_parallel(requests: []ComputationRequest) -> *u64:
results: *u64
-- Starting a parallel computation. Cycle body called in parallel
for request <- requests par:
on request.worker_id via request.host_id:
res <- Adder.add_one(request.value)
results <<- res
-- waiting for all parallel calls to finish
join results[requests.length - 1]
<- results
```
Let's navigate to the `2-browser-parallel-computation/src/frontend` directory in the VSCode terminal and install the dependencies:
```sh
npm install
```
Run aqua compiler:
```bash
fluence aqua
```
And run the application with:
```sh
npm start
```
Which will open a new browser tab at `http://localhost:3000` . Following the instructions, we connect to any one of the displayed relay ids.
![Browser To Service Implementation](./assets/Browser-Parallel-Computation.png)
First, try to input some numbers there. They're args for aqua functions.
After this you can try to click on the buttons below
> **Compute Single** - Takes only first number and adds 1 to the number. Returns the result of computation below.
> **Compute Sequential** - Each of the numbers provided is incremented one after the other. That is, we have three sequential function calls.
> **Compute Parallel** - Each of the three numbers provide is increment in parallel. That is, we fork the call into three arms, execute the Adder function for each arm, join the the arms and present the result, which may be either the value for each arm or a timeout.
> Note: the joined results vary in order, which is determined by the latency of each of the Adder calls; fastest responses fill the array first.
A little more involved than our first example, but we are again getting a lot done with very little code. Of course, there could be more than one hosted service in play and we could implement, for example, hosted spell checking, text formatting and so much more without much extra effort to express additional workflow logic in our Aqua script.
This brings us to the end of this quick start tutorial. We hope you are as excited as we are to put Aqua and the Fluence stack to work. To continue your Fluence journey, have a look at the remainder of this book, take a deep dive into Aqua with the [Aqua book](https://fluence.dev/docs/aqua-book/introduction) or dig into Marine and Aqua examples in the [repo](https://github.com/fluencelabs/examples).

Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 185 KiB

View File

@ -0,0 +1,24 @@
# yaml-language-server: $schema=.fluence/schemas/fluence.json
# Defines Fluence Project, most importantly - what exactly you want to deploy and how. You can use `fluence init` command to generate a template for new Fluence project
# Documentation: https://github.com/fluencelabs/cli/tree/main/docs/configs/fluence.md
version: 5
aquaInputPath: src/aqua/getting-started.aqua
deals:
defaultWorker:
targetWorkers: 3
services:
- adder
spells: []
services:
adder:
get: src/services/adder
relaysPath: src/frontend/src
aquaOutputTSPath: src/frontend/src/compiled-aqua

View File

@ -0,0 +1,60 @@
import Subnet, Worker from "@fluencelabs/aqua-lib/subnet.aqua"
-- 'use' clause brings Deal service into the scope
use "deals.aqua"
-- this 'import' brings every aqua service declaration into the scope
import "services.aqua"
-- Function to get all workers from subnet
func resolveSubnet() -> []Worker:
-- Getting deal id of deployed deal to resolve subnet
deals <- Deals.get()
dealId = deals.defaultWorker!.dealIdOriginal
-- Subnets cannot be resolved on local (client) peers, e.g., the CLI client or the browser. Instead, a subnet needs to be resolved on a relay.
on HOST_PEER_ID:
-- Resolving subnets using Deal id of deployed service
subnet <- Subnet.resolve(dealId)
<- subnet.workers
-- This data structure represents the aqua function that is calling the worker via the frontend.
data ComputationRequest:
worker_id: string
host_id: string
value: u64
-- Executes single computation request
func add_one_single(request: ComputationRequest) -> u64:
-- Extracting worker and host for execution service request
on request.worker_id via request.host_id:
-- Service execution
res <- Adder.add_one(request.value)
-- Returning result from function
<- res
func add_one_sequential(requests: []ComputationRequest) -> *u64:
-- Stream for keeping all computation results
results: *u64
-- Iterating over every computation request, one by one
for request <- requests:
on request.worker_id via request.host_id:
res <- Adder.add_one(request.value)
results <<- res
<- results
func add_one_parallel(requests: []ComputationRequest) -> *u64:
results: *u64
-- Starting a parallel computation. Cycle body called in parallel
for request <- requests par:
on request.worker_id via request.host_id:
res <- Adder.add_one(request.value)
results <<- res
-- waiting for all parallel calls to finish
join results[requests.length - 1]
<- results

View File

@ -0,0 +1,10 @@
.idea
.DS_Store
/.fluence/project-secrets.yaml
/.fluence/schemas
**/node_modules
**/target/
.repl_history
.vscode/settings.json
src/compiled-aqua/

View File

@ -0,0 +1,8 @@
module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 120,
tabWidth: 4,
useTabs: false,
};

View File

@ -0,0 +1,8 @@
module.exports = {
preset: 'jest-puppeteer',
testMatch: ['**/?(*.)+(spec|test).[t]s'],
testPathIgnorePatterns: ['/node_modules/', 'dist'],
transform: {
'^.+\\.ts?$': 'ts-jest',
},
};

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,56 @@
{
"name": "getting-started-browser",
"version": "0.1.0",
"private": true,
"dependencies": {
"@fluencelabs/js-client": "^0.5.4",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"web-vitals": "^1.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest --config=jest.config.js",
"_test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all",
"not ie 11",
"not android 4.4.3-4.4.4"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"@testing-library/jest-dom": "^6.1.4",
"@testing-library/react": "^11.2.7",
"@testing-library/user-event": "^14.5.1",
"@types/jest": "^29.5.6",
"@types/jest-environment-puppeteer": "^4.4.1",
"@types/node": "^20.8.9",
"@types/puppeteer": "^5.4.4",
"@types/react": "^18.2.33",
"@types/react-dom": "^18.2.14",
"@types/serve-handler": "^6.1.3",
"jest-puppeteer": "^6.0.2",
"react-scripts": "^5.0.1",
"sass": "^1.58.3",
"serve": "^13.0.2",
"ts-jest": "^28.0.8",
"typescript": "^4.9.5"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,44 @@
<!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>
<script src='https://cdn.jsdelivr.net/npm/@fluencelabs/js-client.web.standalone@0.13.3/dist/js-client.min.js'
async></script>
</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"
}

File diff suppressed because one or more lines are too long

View File

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

View File

@ -0,0 +1,160 @@
$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;
}
ul,
li {
list-style-type: none;
margin: 0;
padding: 0;
}
.p {
width: 550px;
}
.btn-clipboard {
border: none;
background-color: transparent;
cursor: pointer;
&:hover,
&:focus {
color: $accent-color;
}
&:focus {
outline: none;
}
}
.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;
}
}
.btn-hello {
width: 200px;
display: inline;
float: right;
}
table {
text-align: right;
}
.label {
width: 120px;
display: inline-block;
}
.input {
width: 500px;
height: 26px;
box-sizing: border-box;
margin: 5px;
border: 1px solid;
border-color: $color2;
color: $color1;
&::placeholder {
color: $color2;
}
&:hover,
&:focus {
outline: 1px solid white;
border-color: $accent-color;
}
}
.gg-clipboard {
box-sizing: border-box;
position: relative;
display: block;
transform: scale(var(--ggs, 1));
width: 18px;
height: 18px;
border: 2px solid;
border-radius: 2px;
}
.gg-clipboard::after,
.gg-clipboard::before {
content: "";
display: block;
box-sizing: border-box;
position: absolute;
border-radius: 2px;
width: 10px;
left: 2px;
}
.gg-clipboard::before {
border: 2px solid;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
top: -2px;
height: 6px;
}
.gg-clipboard::after {
height: 2px;
background: currentColor;
box-shadow: 0 -4px 0 0;
bottom: 2px;
}

View File

@ -0,0 +1,233 @@
import React, { useEffect, useRef, useState } from 'react';
import logo from './logo.svg';
import './App.scss';
import { Fluence, type ConnectionState } from '@fluencelabs/js-client';
import { resolveSubnet, add_one_parallel, add_one_sequential, add_one_single } from './compiled-aqua/getting-started';
import relays from "./relays.json";
const relayNodes = [relays[0], relays[1], relays[2]];
interface ComputationResult {
host_id: string;
value: number;
worker_id: string;
}
function App() {
const [connectionState, setConnectionState] = useState<ConnectionState>('disconnected');
const [peerInfo, setPeerInfo] = useState<{ peerId: string; relayPeerId: string } | null>(null);
const [numbers, setNumbers] = useState([1, 2, 3]);
const [computedNumbers, setComputedNumbers] = useState<number[]>();
const [computationInProgress, setComputationInProgress] = useState(false);
const onNumberChange = (input: string, index: number) => {
setNumbers([...numbers.slice(0, index), Number(input) || 0, ...numbers.slice(index + 1)]);
}
const numberContainers = [useRef<HTMLInputElement>(null), useRef<HTMLInputElement>(null), useRef<HTMLInputElement>(null)];
useEffect(() => {
if (connectionState === 'connected') {
const client = Fluence.getClient();
const peerId = client.getPeerId();
const relayPeerId = client.getRelayPeerId();
setPeerInfo({ peerId, relayPeerId });
}
}, [connectionState]);
const connect = async (relayPeerId: string) => {
try {
setConnectionState('connecting');
await Fluence.connect(relayPeerId);
setConnectionState('connected');
} catch (err) {
console.log('Client could not connect', err);
}
};
const getComputationResuls = async () => {
const subnets = await resolveSubnet();
const size = Math.max(subnets.length, numbers.length);
const computationResults: ComputationResult[] = [];
for (let i = 0; i < size; i++) {
const workerId = subnets[i].worker_id;
if (workerId === null) {
continue;
}
computationResults.push({
value: numbers[i],
worker_id: workerId,
host_id: subnets[i].host_id,
})
}
return computationResults;
};
const computeSingleBtnOnClick = async () => {
if (connectionState !== 'connected') {
return;
}
setComputationInProgress(true);
const computationResults = await getComputationResuls();
const result = await add_one_single(computationResults[0]);
setComputedNumbers([result]);
setComputationInProgress(false);
};
const computeSequentialBtnOnClick = async () => {
if (connectionState !== 'connected') {
return;
}
setComputationInProgress(true);
const computationResults = await getComputationResuls();
const results = await add_one_sequential(computationResults);
setComputedNumbers(results);
setComputationInProgress(false);
};
const computeParallelBtnOnClick = async () => {
if (connectionState !== 'connected') {
return;
}
setComputationInProgress(true);
const computationResults = await getComputationResuls();
const results = await add_one_parallel(computationResults);
setComputedNumbers(results);
setComputationInProgress(false);
};
const isConnected = connectionState === 'connected';
return (
<div className="App">
<header>
<img src={logo} className="logo" alt="logo" />
</header>
<div className="content">
<h1>{connectionState}</h1>
{isConnected ? (
<>
<table>
<tbody>
<tr>
<td className="bold">Peer id:</td>
<td className="mono">
<span id="peerId">{peerInfo?.peerId}</span>
</td>
<td>
<button
className="btn-clipboard"
onClick={() => copyToClipboard(peerInfo?.peerId)}
>
<i className="gg-clipboard"></i>
</button>
</td>
</tr>
<tr>
<td className="bold">Relay peer id:</td>
<td className="mono">
<span id="relayId">{peerInfo?.relayPeerId}</span>
</td>
<td>
<button
className="btn-clipboard"
onClick={() => copyToClipboard(peerInfo?.relayPeerId)}
>
<i className="gg-clipboard"></i>
</button>
</td>
</tr>
</tbody>
</table>
<div>
<h2>Input numbers for computation</h2>
<p className="p">
Input 3 numbers for parallel computation
</p>
{
numberContainers.map((ref, i) => (
<div className="row" key={i}>
<label className="label bold">Number {i}</label>
<input
ref={ref}
style={{width: 'auto'}}
id="targetPeerId"
className="input"
type="text"
onChange={(e) => onNumberChange(e.target.value, i)}
value={numbers[i]}
/>
</div>
))
}
<div className="row">
<button className="btn btn-hello" style={{float: 'initial'}} onClick={computeSingleBtnOnClick}>
Compute single
</button>
</div>
<div className="row">
<button className="btn btn-hello" style={{float: 'initial'}} onClick={computeSequentialBtnOnClick}>
Compute sequential
</button>
</div>
<div className="row">
<button className="btn btn-hello" style={{float: 'initial'}} onClick={computeParallelBtnOnClick}>
Compute parallel
</button>
</div>
</div>
</>
) : (
<>
<h1>Intro 2: Computing on the network</h1>
<h2>Pick a relay</h2>
<ul>
{relayNodes.map((x) => (
<li key={x.peerId}>
<span className="mono">{x.peerId}</span>
<button className="btn" onClick={() => connect(x.multiaddr)}>
Connect
</button>
</li>
))}
</ul>
</>
)}
{(computedNumbers || computationInProgress) && (
<>
<h2>Computation result</h2>
<div id="message"> {computationInProgress ? '...' : JSON.stringify(computedNumbers)} </div>
</>
)}
</div>
</div>
);
}
const copyToClipboard = (text?: string) => {
if (text) {
navigator.clipboard.writeText(text);
}
};
export default App;

View File

@ -0,0 +1,103 @@
import { Page } from 'puppeteer';
import handler from 'serve-handler';
import http from 'http';
import path from 'path';
const port = 3000;
const uri = `http://localhost:${port}/`;
const publicPath = path.join(__dirname, '../../build/');
console.log(publicPath);
const server = http.createServer((request, response) => {
return handler(request, response, {
public: publicPath,
});
});
const startServer = async () => {
return new Promise((resolve: any) => {
server.listen(port, resolve);
});
};
const stopServer = async () => {
return new Promise((resolve: any) => {
server.close(resolve);
});
};
const peerIdLength = '12D3KooWM2CYSHefG6KPKbYFAgsbPh8p6b8HYHc6VNkge2rPtYv5'.length;
const loadApp = async (page: Page) => {
console.log('opening page...');
await page.goto('http://localhost:3000/');
console.log('clicking connect button...');
await page.click('.btn');
console.log('waiting for fluence to connect...');
await page.waitForTimeout(1000);
console.log('waiting for "say hello" button to appear...');
await page.waitForSelector('.btn-hello');
console.log('getting self peer id and relay...');
const peerId = await page.$eval('#peerId', (x) => x.textContent);
const relayId = await page.$eval('#relayId', (x) => x.textContent);
expect(peerId?.length).toBe(peerIdLength);
expect(relayId?.length).toBe(peerIdLength);
return {
peerId,
relayId,
};
};
const waitForSelectorAndGetText = async (page: Page, selector: string) => {
const page1Message = await page.waitForSelector('#message');
return await page1Message?.evaluate((x) => x.textContent?.trim().replace('\n', ''));
};
describe('smoke test', () => {
beforeAll(startServer);
afterAll(stopServer);
it('should work', async () => {
const page1 = await browser.newPage();
const page2 = await browser.newPage();
console.log('=== browser 1 ===');
const peerRelay1 = await loadApp(page1);
console.log('=== browser 2 ===');
const peerRelay2 = await loadApp(page2);
console.log('=== browser 1 ===');
console.log('filling form...');
await page1.focus('#targetPeerId');
await page1.keyboard.type(peerRelay2.peerId!);
await page1.focus('#targetRelayId');
await page1.keyboard.type(peerRelay2.relayId!);
console.log('clicking "say hello"...');
await page1.click('.btn-hello');
console.log('waiting for particle to execute...');
await page1.waitForTimeout(1000);
console.log('=== finale ===');
console.log('getting message from page1...');
const page1Message = await waitForSelectorAndGetText(page1, '#message');
console.log('getting message from page2...');
const page2Message = await waitForSelectorAndGetText(page2, '#message');
expect(page1Message).toBe('Hello back to you, ' + peerRelay1.peerId);
expect(page2Message).toBe('Hello from: ' + peerRelay1.peerId);
}, 15000);
});

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,46 @@
[
{
"multiaddr": "/dns4/0-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e",
"peerId": "12D3KooWSD5PToNiLQwKDXsu8JSysCwUt8BVUJEqCHcDe7P5h45e"
},
{
"multiaddr": "/dns4/1-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWR4cv1a8tv7pps4HH6wePNaK6gf1Hww5wcCMzeWxyNw51",
"peerId": "12D3KooWR4cv1a8tv7pps4HH6wePNaK6gf1Hww5wcCMzeWxyNw51"
},
{
"multiaddr": "/dns4/2-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWKnEqMfYo9zvfHmqTLpLdiHXPe4SVqUWcWHDJdFGrSmcA",
"peerId": "12D3KooWKnEqMfYo9zvfHmqTLpLdiHXPe4SVqUWcWHDJdFGrSmcA"
},
{
"multiaddr": "/dns4/3-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWHLxVhUQyAuZe6AHMB29P7wkvTNMn7eDMcsqimJYLKREf",
"peerId": "12D3KooWHLxVhUQyAuZe6AHMB29P7wkvTNMn7eDMcsqimJYLKREf"
},
{
"multiaddr": "/dns4/4-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWJd3HaMJ1rpLY1kQvcjRPEvnDwcXrH8mJvk7ypcZXqXGE",
"peerId": "12D3KooWJd3HaMJ1rpLY1kQvcjRPEvnDwcXrH8mJvk7ypcZXqXGE"
},
{
"multiaddr": "/dns4/5-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWFEwNWcHqi9rtsmDhsYcDbRUCDXH84RC4FW6UfsFWaoHi",
"peerId": "12D3KooWFEwNWcHqi9rtsmDhsYcDbRUCDXH84RC4FW6UfsFWaoHi"
},
{
"multiaddr": "/dns4/6-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWCMr9mU894i8JXAFqpgoFtx6qnV1LFPSfVc3Y34N4h4LS",
"peerId": "12D3KooWCMr9mU894i8JXAFqpgoFtx6qnV1LFPSfVc3Y34N4h4LS"
},
{
"multiaddr": "/dns4/7-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWDUszU2NeWyUVjCXhGEt1MoZrhvdmaQQwtZUriuGN1jTr",
"peerId": "12D3KooWDUszU2NeWyUVjCXhGEt1MoZrhvdmaQQwtZUriuGN1jTr"
},
{
"multiaddr": "/dns4/8-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWEFFCZnar1cUJQ3rMWjvPQg6yMV2aXWs2DkJNSRbduBWn",
"peerId": "12D3KooWEFFCZnar1cUJQ3rMWjvPQg6yMV2aXWs2DkJNSRbduBWn"
},
{
"multiaddr": "/dns4/9-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWFtf3rfCDAfWwt6oLZYZbDfn9Vn7bv7g6QjjQxUUEFVBt",
"peerId": "12D3KooWFtf3rfCDAfWwt6oLZYZbDfn9Vn7bv7g6QjjQxUUEFVBt"
},
{
"multiaddr": "/dns4/10-kras.fluence.dev/tcp/9000/wss/p2p/12D3KooWD7CvsYcpF9HE9CCV9aY3SJ317tkXVykjtZnht2EbzDPm",
"peerId": "12D3KooWD7CvsYcpF9HE9CCV9aY3SJ317tkXVykjtZnht2EbzDPm"
}
]

View File

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

View File

@ -0,0 +1,14 @@
[package]
name = "adder"
version = "0.1.0"
edition = "2018"
[[bin]]
name = "adder"
path = "src/main.rs"
[dependencies]
marine-rs-sdk = "0.10.0"
[dev-dependencies]
marine-rs-sdk-test = "0.10.0"

View File

@ -0,0 +1,11 @@
# yaml-language-server: $schema=../../../../../.fluence/schemas/module.json
# Defines [Marine Module](https://fluence.dev/docs/build/concepts/#modules). You can use `fluence module new` command to generate a template for new module
# Documentation: https://github.com/fluencelabs/cli/tree/main/docs/configs/module.md
version: 0
type: rust
name: adder

View File

@ -0,0 +1,8 @@
use marine_rs_sdk::marine;
pub fn main() {}
#[marine]
pub fn add_one(value: u64) -> u64 {
value + 1
}

View File

@ -0,0 +1,13 @@
# yaml-language-server: $schema=../../../.fluence/schemas/service.json
# Defines a [Marine service](https://fluence.dev/docs/build/concepts/#services), most importantly the modules that the service consists of. You can use `fluence service new` command to generate a template for new service
# Documentation: https://github.com/fluencelabs/cli/tree/main/docs/configs/service.md
version: 0
name: adder
modules:
facade:
get: modules/adder