diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
new file mode 100644
index 000000000..0e3b264d3
--- /dev/null
+++ b/CONTRIBUTING.md
@@ -0,0 +1,13 @@
+## Contribute Code
+
+You are welcome to contribute to Fluence.
+
+Things you need to know:
+
+1. You need to **agree to the Contributors License Agreement**. This is a common practice in all major Open Source projects. At the current moment we are unable to accept contributions made on behalf of a company. Only individual contributions will be accepted.
+2. **Not all proposed contributions can be accepted**. Some features may e.g. just fit a third-party add-on better. The contribution must fit the overall direction of Fluence and really improve it. The more effort you invest, the better you should clarify in advance whether the contribution fits: the best way would be to just open an issue to discuss the contribution you plan to make.
+
+### Contributor License Agreement
+
+When you contribute, you have to be aware that your contribution is covered by **Apache License 2.0**, but might relicensed under few other software licenses mentioned in the **Contributor License Agreement**.
+In particular you need to agree to the [Contributor License Agreement](https://gist.github.com/fluencelabs-org/3f4cbb3cc14c1c0fb9ad99d8f7316ed7). If you agree to its content, you simply have to click on the link posted by the CLA assistant as a comment to the pull request. Click it to check the CLA, then accept it on the following screen if you agree to it. CLA assistant will save this decision for upcoming contributions and will notify you if there is any change to the CLA in the meantime.
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 000000000..f49a4e16e
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/README.md b/README.md
index dd0f3d0ad..b797f5a57 100644
--- a/README.md
+++ b/README.md
@@ -1,31 +1,128 @@
-# Fluence browser client
+# Fluence JS SDK
-[![npm version](https://badge.fury.io/js/%40fluencelabs%2Ffluence.svg)](https://badge.fury.io/js/%40fluencelabs%2Ffluence)
+[![npm](https://img.shields.io/npm/v/@fluencelabs/fluence)](https://www.npmjs.com/package/@fluencelabs/fluence)
-Browser client for the Fluence network based on the js-libp2p.
+Official SDK for building web-based applications for Fluence
-## How to build
+## About Fluence
-With `npm` installed building could be done as follows:
+Fluence is an open application platform where apps can build on each other, share data and users
+
+| Layer | Tech | Scale | State | Based on |
+| :-------------------: | :-------------------------------------------------------------------------------------------------------------------------------: | :------------------------------: | :-------------------------------: | :-----------------------------------------------------------------------------------------------------------: |
+| Execution | [FCE](https://github.com/fluencelabs/fce) | Single peer | Disk, network, external processes | Wasm, [IT](https://github.com/fluencelabs/interface-types), [Wasmer\*](https://github.com/fluencelabs/wasmer) |
+| Composition | [Aquamarine](https://github.com/fluencelabs/aquamarine) | Involved peers | Results and signatures | ⇅, π-calculus |
+| Topology | [TrustGraph](https://github.com/fluencelabs/fluence/tree/master/trust-graph), [DHT\*](https://github.com/fluencelabs/rust-libp2p) | Distributed with Kademlia\* algo | Actual state of the network | [libp2p](https://github.com/libp2p/rust-libp2p) |
+| Security & Accounting | Blockchain | Whole network | Licenses & payments | substrate? |
+
+
+
+
+## Installation
+
+With npm
+
+```bash
+npm install @fluencelabs/fluence
+```
+
+With yarn
```bash
-npm install fluence
+yarn add @fluencelabs/fluence
+```
+
+## Getting started
+
+Pick a node to connect to the Fluence network. The easiest way to do so is by using [fluence-network-environment](https://github.com/fluencelabs/fluence-network-environment) package
+
+```typescript
+import { dev } from '@fluencelabs/fluence-network-environment';
+
+export const relayNode = dev[0];
+```
+
+Initialize client
+
+
+```typescript
+import { createClient, FluenceClient } from '@fluencelabs/fluence';
+
+const client = await createClient(relayNode);
```
-## Example
+Add response service function calls
-Shows how to register and call new service in Fluence network.
+```typescript
+subscribeToEvent(client, 'helloService', 'helloFunction', (args) => {
+ const [networkInfo] = args;
+ console.log(networkInfo);
+});
+```
+Make a particle
-Generate new peer ids for clients.
```typescript
-let peerId1 = await Fluence.generatePeerId();
-let peerId2 = await Fluence.generatePeerId();
+const particle = new Particle(`
+ (seq
+ (call myRelay ("op" "identify") [] result)
+ (call %init_peer_id% ("helloService" "helloFunction") [result])
+ )`,
+ {
+ myRelay: client.relayPeerId,
+ },
+);
```
-Establish connections to predefined nodes.
+Send it to the network
```typescript
-let client1 = await Fluence.connect("/dns4/134.209.186.43/tcp/9003/ws/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb", peerId1);
-let client2 = await Fluence.connect("/ip4/134.209.186.43/tcp/9002/ws/p2p/12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er", peerId2);
+await sendParticle(client, particle);
```
+
+Observe the result in browser console
+
+```json
+{
+ "external_addresses": [ "/ip4/1.2.3.4/tcp/7777", "/dns4/dev.fluence.dev/tcp/19002" ]
+}
+```
+
+## Documentation
+
+SDK Reference: [readme.io](https://fluence-labs.readme.io/docs/js-sdk)
+
+Detailed guide on building applications: [readme.io](https://fluence-labs.readme.io/docs/build-an-app)
+
+Sample applications:
+
+* [FluentPad](https://github.com/fluencelabs/fluent-pad): a collaborative text editor with users online status synchronization
+* [Other demos](https://github.com/fluencelabs/aqua-demo): (Chat app, Social feed app, Blog platform app)
+
+About [Fluence](https://fluence.network/)
+
+## Developing
+
+### Setting up Dev
+
+Install node packages
+
+```bash
+npm install
+```
+
+### Running tests
+
+To run test execute
+
+```bash
+npm test
+```
+
+## Contributing
+
+While the project is a still in the early stage of development, you are welcome to track progress and contribute. At the current moment we don't have detailed instructions on how to join development or which code guidelines to follow. However, you can expect more info to appear soon enough. In the meanwhile, check out the [basic contributing rules](CONTRIBUTING.md).
+
+## License
+
+[Apache 2.0](LICENSE)
\ No newline at end of file
diff --git a/doc/stack.png b/doc/stack.png
new file mode 100644
index 000000000..7557c5e8c
Binary files /dev/null and b/doc/stack.png differ
diff --git a/package-lock.json b/package-lock.json
index 49d2050db..183629cdd 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,6 +1,6 @@
{
"name": "@fluencelabs/fluence",
- "version": "0.8.0",
+ "version": "0.9.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
@@ -25,9 +25,9 @@
}
},
"@fluencelabs/aquamarine-stepper": {
- "version": "0.0.30",
- "resolved": "https://registry.npmjs.org/@fluencelabs/aquamarine-stepper/-/aquamarine-stepper-0.0.30.tgz",
- "integrity": "sha512-XIgRgyVgPJXvXB3NuYHpSdJ0EFcFZ+K4uduGFf8PfnFii/bFs4F1n3MBB+b4D0y59HR4F9ZQUC4fXxcf6UCYWA=="
+ "version": "0.3.4",
+ "resolved": "https://registry.npmjs.org/@fluencelabs/aquamarine-stepper/-/aquamarine-stepper-0.3.4.tgz",
+ "integrity": "sha512-0NPg9dWvANtc3If8C8O8XjKwzMCq2492lA73faKJdCwUv7m+xHX9G3l6UJULTfV1T4mWVtMQZIKopNOlRYSrKA=="
},
"@sinonjs/commons": {
"version": "1.7.2",
diff --git a/package.json b/package.json
index f2e7236c8..2d1193639 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@fluencelabs/fluence",
- "version": "0.9.0",
+ "version": "0.9.3",
"description": "JS SDK for the Fluence network",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts",
@@ -13,7 +13,7 @@
"author": "Fluence Labs",
"license": "Apache-2.0",
"dependencies": {
- "@fluencelabs/aquamarine-stepper": "0.0.30",
+ "@fluencelabs/aquamarine-stepper": "0.3.4",
"async": "3.2.0",
"base64-js": "1.3.1",
"bs58": "4.0.1",
diff --git a/src/FluenceClient.ts b/src/FluenceClient.ts
index 6a534e52a..288a23f9b 100644
--- a/src/FluenceClient.ts
+++ b/src/FluenceClient.ts
@@ -14,239 +14,22 @@
* limitations under the License.
*/
-import log from 'loglevel';
-import PeerId from 'peer-id';
-import { SecurityTetraplet, StepperOutcome } from './internal/commonTypes';
-import { FluenceClientBase } from './internal/FluenceClientBase';
-import { build, genUUID, ParticleDto } from './internal/particle';
-import { ParticleProcessor } from './internal/ParticleProcessor';
-import { ParticleProcessorStrategy } from './internal/ParticleProcessorStrategy';
+import { PeerIdB58 } from './internal/commonTypes';
+import Multiaddr from 'multiaddr';
-const fetchCallbackServiceName = '__callback';
-const selfRelayVarName = '__relay';
+export interface FluenceClient {
+ readonly relayPeerId: PeerIdB58;
+ readonly selfPeerId: PeerIdB58;
+ readonly isConnected: boolean;
-const wrapRelayBasedCall = (script: string) => {
- return `
- (seq
- (call ${selfRelayVarName} ("op" "identity") [])
- ${script}
- )
- `;
-};
+ disconnect(): Promise;
-const wrapFetchCall = (script: string, particleId: string, resultArgNames: string[]) => {
- // TODO: sanitize
- const resultTogether = resultArgNames.join(' ');
- let res = `
- (seq
- ${script}
- (seq
- (call ${selfRelayVarName} ("op" "identity") [])
- (call %init_peer_id% ("${fetchCallbackServiceName}" "${particleId}") [${resultTogether}])
- )
- )`;
- return wrapRelayBasedCall(res);
-};
+ /**
+ * Establish a connection to the node. If the connection is already established, disconnect and reregister all services in a new connection.
+ *
+ * @param multiaddr
+ */
+ connect(multiaddr: string | Multiaddr): Promise;
-export interface FluenceEvent {
- type: string;
- args: any[];
-}
-
-export type FluenceEventHandler = (event: FluenceEvent) => void;
-
-export class FluenceClient extends FluenceClientBase {
- private eventSubscribers: Map = new Map();
- private eventValidators: Map = new Map();
- private callbacks: Map = new Map();
- private fetchParticles: Map = new Map();
-
- constructor(selfPeerId: PeerId) {
- super(selfPeerId);
- this.processor = new ParticleProcessor(this.strategy, selfPeerId);
- }
-
- async fetch(script: string, resultArgNames: string[], data?: Map, ttl?: number): Promise {
- data = this.addRelayToArgs(data);
- const callBackId = genUUID();
- script = wrapFetchCall(script, callBackId, resultArgNames);
- const particle = await build(this.selfPeerIdFull, script, data, ttl, callBackId);
-
- return new Promise((resolve, reject) => {
- this.fetchParticles.set(callBackId, { resolve, reject });
- this.processor.executeLocalParticle(particle);
- });
- }
-
- // TODO:: better naming probably?
- async fireAndForget(script: string, data?: Map, ttl?: number) {
- data = this.addRelayToArgs(data);
- script = wrapRelayBasedCall(script);
-
- await this.sendScript(script, data, ttl);
- }
-
- registerEvent(
- channel: string,
- eventName: string,
- validate?: (channel: string, eventName: string, args: any[], tetraplets: any[][]) => boolean,
- ) {
- if (!validate) {
- validate = (c, e, a, t) => true;
- }
-
- this.eventValidators.set(`${channel}/${eventName}`, validate);
- }
-
- unregisterEvent(channel: string, eventName: string) {
- this.eventValidators.delete(`${channel}/${eventName}`);
- }
-
- registerCallback(
- serviceId: string,
- fnName: string,
- callback: (args: any[], tetraplets: SecurityTetraplet[][]) => object,
- ) {
- this.callbacks.set(`${serviceId}/${fnName}`, callback);
- }
-
- unregisterCallback(channel: string, eventName: string) {
- this.eventValidators.delete(`${channel}/${eventName}`);
- }
-
- subscribe(channel: string, handler: FluenceEventHandler) {
- if (!this.eventSubscribers.get(channel)) {
- this.eventSubscribers.set(channel, []);
- }
-
- this.eventSubscribers.get(channel).push(handler);
- }
-
- protected strategy: ParticleProcessorStrategy = {
- particleHandler: (serviceId: string, fnName: string, args: any[], tetraplets: SecurityTetraplet[][]) => {
- // missing built-in op
- if (serviceId === 'op' && fnName === 'identity') {
- return {
- ret_code: 0,
- result: JSON.stringify(args),
- };
- }
-
- // async fetch model handling
- if (serviceId === fetchCallbackServiceName) {
- const executingParticlePromiseFns = this.fetchParticles.get(fnName);
- if (executingParticlePromiseFns) {
- // don't block
- setImmediate(() => {
- this.fetchParticles.delete(fnName);
- executingParticlePromiseFns.resolve(args);
- });
- }
-
- return {
- ret_code: 0,
- result: JSON.stringify({}),
- };
- }
-
- // event model handling
- const eventPair = `${serviceId}/${fnName}`;
- const eventValidator = this.eventValidators.get(eventPair);
- if (eventValidator) {
- try {
- if (!eventValidator(serviceId, fnName, args, tetraplets)) {
- return {
- ret_code: 1, // TODO:: error codes
- result: 'validation failed',
- };
- }
- } catch (e) {
- log.error('error running validation function: ' + e);
- return {
- ret_code: 1, // TODO:: error codes
- result: 'validation failed',
- };
- }
-
- // don't block
- setImmediate(() => {
- this.pushEvent(serviceId, {
- type: fnName,
- args: args,
- });
- });
-
- return {
- ret_code: 0,
- result: JSON.stringify({}),
- };
- }
-
- // callback model handling
- const callback = this.callbacks.get(eventPair);
- if (callback) {
- try {
- const res = callback(args, tetraplets);
- return {
- ret_code: 0,
- result: JSON.stringify(res),
- };
- } catch (e) {
- return {
- ret_code: 1, // TODO:: error codes
- result: JSON.stringify(e),
- };
- }
- }
-
- return {
- ret_code: 1,
- result: `Error. There is no service: ${serviceId}`,
- };
- },
-
- sendParticleFurther: async (particle: ParticleDto) => {
- try {
- await this.connection.sendParticle(particle);
- } catch (reason) {
- log.error(`Error on sending particle with id ${particle.id}: ${reason}`);
- }
- },
-
- onParticleTimeout: (particle: ParticleDto, now: number) => {
- log.info(`Particle expired. Now: ${now}, ttl: ${particle.ttl}, ts: ${particle.timestamp}`);
- const executingParticle = this.fetchParticles.get(particle.id);
- if (executingParticle) {
- executingParticle.reject(new Error(`particle ${particle.id} timed out`));
- }
- },
- onLocalParticleRecieved: (particle: ParticleDto) => {},
- onExternalParticleRecieved: (particle: ParticleDto) => {},
- onStepperExecuting: (particle: ParticleDto) => {},
- onStepperExecuted: (stepperOutcome: StepperOutcome) => {
- log.info('inner interpreter outcome:');
- log.info(stepperOutcome);
- },
- };
-
- private pushEvent(channel: string, event: FluenceEvent) {
- const subs = this.eventSubscribers.get(channel);
- if (subs) {
- for (let sub of subs) {
- sub(event);
- }
- }
- }
-
- private addRelayToArgs(data: Map) {
- if (data === undefined) {
- data = new Map();
- }
-
- if (!data.has(selfRelayVarName)) {
- data.set(selfRelayVarName, this.relayPeerId);
- }
-
- return data;
- }
+ sendScript(script: string, data?: Map, ttl?: number): Promise;
}
diff --git a/src/__test__/client.spec.ts b/src/__test__/client.spec.ts
index 41bebbe4e..e1fe24332 100644
--- a/src/__test__/client.spec.ts
+++ b/src/__test__/client.spec.ts
@@ -6,11 +6,15 @@ import { certificateFromString, certificateToString, issue } from '../internal/t
import { TrustGraph } from '../internal/trust/trust_graph';
import { nodeRootCert } from '../internal/trust/misc';
import { generatePeerId, peerIdToSeed, seedToPeerId } from '../internal/peerIdUtils';
-import { FluenceClient } from '../FluenceClient';
+import { FluenceClientImpl } from '../internal/FluenceClientImpl';
import { createConnectedClient, createLocalClient } from './util';
import log from 'loglevel';
import { createClient } from '../api';
import Multiaddr from 'multiaddr';
+import { getModules } from '../internal/builtins';
+
+const devNodeAddress = '/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
+const devNodePeerId = '12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
describe('Typescript usage suite', () => {
it('should create private key from seed and back', async function () {
@@ -49,7 +53,7 @@ describe('Typescript usage suite', () => {
describe.skip('should make connection to network', async function () {
this.timeout(30000);
- const testProcedure = async (client: FluenceClient) => {
+ const testProcedure = async (client: FluenceClientImpl) => {
let resMakingPromise = new Promise((resolve) => {
client.registerCallback('test', 'test', (args, _) => {
resolve(args);
@@ -75,11 +79,10 @@ describe('Typescript usage suite', () => {
it('address as string', async function () {
// arrange
- const addr =
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
+ const addr = devNodeAddress;
// act
- const client = await createClient(addr);
+ const client = (await createClient(addr)) as FluenceClientImpl;
// assert
const res = await testProcedure(client);
@@ -88,12 +91,10 @@ describe('Typescript usage suite', () => {
it('address as multiaddr', async function () {
// arrange
- const addr = new Multiaddr(
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- );
+ const addr = new Multiaddr(devNodeAddress);
// act
- const client = await createClient(addr);
+ const client = (await createClient(addr)) as FluenceClientImpl;
// assert
const res = await testProcedure(client);
@@ -103,13 +104,12 @@ describe('Typescript usage suite', () => {
it('address as node', async function () {
// arrange
const addr = {
- multiaddr:
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- peerId: '12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
+ multiaddr: devNodeAddress,
+ peerId: devNodePeerId,
};
// act
- const client = await createClient(addr);
+ const client = (await createClient(addr)) as FluenceClientImpl;
// assert
const res = await testProcedure(client);
@@ -118,26 +118,24 @@ describe('Typescript usage suite', () => {
it('peerid as peer id', async function () {
// arrange
- const addr =
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
+ const addr = devNodeAddress;
const pid = await generatePeerId();
// act
- const client = await createClient(addr, pid);
+ const client = (await createClient(addr, pid)) as FluenceClientImpl;
// assert
const res = await testProcedure(client);
expect(res).to.deep.equal(['world']);
});
- it('peerid as see', async function () {
+ it('peerid as seed', async function () {
// arrange
- const addr =
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9';
+ const addr = devNodeAddress;
const pid = peerIdToSeed(await generatePeerId());
// act
- const client = await createClient(addr, pid);
+ const client = (await createClient(addr, pid)) as FluenceClientImpl;
// assert
const res = await testProcedure(client);
@@ -148,9 +146,7 @@ describe('Typescript usage suite', () => {
it.skip('should make a call through the network', async function () {
this.timeout(30000);
// arrange
- const client = await createConnectedClient(
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- );
+ const client = await createConnectedClient(devNodeAddress);
client.registerCallback('test', 'test', (args, _) => {
log.trace('should make a call through the network, called "test" "test" with args', args);
@@ -191,9 +187,7 @@ describe('Typescript usage suite', () => {
it.skip('fireAndForget should work', async function () {
this.timeout(30000);
// arrange
- const client = await createConnectedClient(
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- );
+ const client = await createConnectedClient(devNodeAddress);
let resMakingPromise = new Promise((resolve) => {
client.registerCallback('test', 'reverse_args', (args, _) => {
@@ -220,13 +214,23 @@ describe('Typescript usage suite', () => {
expect(res).to.deep.equal(['some d', 'some c', 'some b', 'some a']);
});
- it.skip('fetch should work', async function () {
+ it.skip('add_module', async function () {
this.timeout(30000);
// arrange
const client = await createConnectedClient(
- '/dns4/net01.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
+ '/dns4/dev.fluence.dev/tcp/19003/wss/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb',
);
+ let a = await getModules(client);
+
+ expect(a).not.to.be.undefined;
+ });
+
+ it.skip('fetch should work', async function () {
+ this.timeout(30000);
+ // arrange
+ const client = await createConnectedClient(devNodeAddress);
+
// act
let script = `
(call "${client.relayPeerId}" ("op" "identify") [] result)
@@ -243,16 +247,12 @@ describe('Typescript usage suite', () => {
it.skip('two clients should work inside the same time browser', async function () {
// arrange
const pid1 = await generatePeerId();
- const client1 = new FluenceClient(pid1);
- await client1.connect(
- '/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- );
+ const client1 = new FluenceClientImpl(pid1);
+ await client1.connect(devNodeAddress);
const pid2 = await generatePeerId();
- const client2 = new FluenceClient(pid2);
- await client2.connect(
- '/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- );
+ const client2 = new FluenceClientImpl(pid2);
+ await client2.connect(devNodeAddress);
let resMakingPromise = new Promise((resolve) => {
client2.registerCallback('test', 'test', (args, _) => {
@@ -283,16 +283,12 @@ describe('Typescript usage suite', () => {
it.skip('event registration should work', async function () {
// arrange
const pid1 = await generatePeerId();
- const client1 = new FluenceClient(pid1);
- await client1.connect(
- '/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- );
+ const client1 = new FluenceClientImpl(pid1);
+ await client1.connect(devNodeAddress);
const pid2 = await generatePeerId();
- const client2 = new FluenceClient(pid2);
- await client2.connect(
- '/dns4/dev.fluence.dev/tcp/19001/wss/p2p/12D3KooWEXNUbCXooUwHrHBbrmjsrpHXoEphPwbjQXEGyzbqKnE9',
- );
+ const client2 = new FluenceClientImpl(pid2);
+ await client2.connect(devNodeAddress);
client2.registerEvent('event_stream', 'test');
const resMakingPromise = new Promise((resolve) => {
@@ -323,8 +319,8 @@ export async function testCerts() {
const key2 = await generatePeerId();
// connect to two different nodes
- const cl1 = new FluenceClient(key1);
- const cl2 = new FluenceClient(key2);
+ const cl1 = new FluenceClientImpl(key1);
+ const cl2 = new FluenceClientImpl(key2);
await cl1.connect('/dns4/134.209.186.43/tcp/9003/ws/p2p/12D3KooWBUJifCTgaxAUrcM9JysqCcS4CS8tiYH5hExbdWCAoNwb');
await cl2.connect('/ip4/134.209.186.43/tcp/9002/ws/p2p/12D3KooWHk9BjDQBUqnavciRPhAYFvqKBe4ZiPPvde7vDaqgn5er');
diff --git a/src/__test__/util.ts b/src/__test__/util.ts
index c9e96ab1e..d263f1fdf 100644
--- a/src/__test__/util.ts
+++ b/src/__test__/util.ts
@@ -1,15 +1,16 @@
-import { FluenceClient, generatePeerId } from '..';
+import { generatePeerId } from '..';
+import { FluenceClientImpl } from '../internal/FluenceClientImpl';
export const createLocalClient = async () => {
const peerId = await generatePeerId();
- const client = new FluenceClient(peerId);
+ const client = new FluenceClientImpl(peerId);
await client.local();
return client;
};
export const createConnectedClient = async (node: string) => {
const peerId = await generatePeerId();
- const client = new FluenceClient(peerId);
+ const client = new FluenceClientImpl(peerId);
await client.connect(node);
return client;
};
diff --git a/src/api.ts b/src/api.ts
index 216d11673..6b1ad7830 100644
--- a/src/api.ts
+++ b/src/api.ts
@@ -4,12 +4,19 @@ import { genUUID, Particle } from './internal/particle';
import Multiaddr from 'multiaddr';
import PeerId, { isPeerId } from 'peer-id';
import { generatePeerId, seedToPeerId } from './internal/peerIdUtils';
+import { FluenceClientImpl } from './internal/FluenceClientImpl';
type Node = {
peerId: string;
multiaddr: string;
};
+/**
+ * Creates a Fluence client. If the `connectTo` is specified connects the client to the network
+ * @param { string | Multiaddr | Node } [connectTo] - Node in Fluence network to connect to. If not specified client will not be connected to the n
+ * @param { PeerId | string } [peerIdOrSeed] - The Peer Id of the created client. Specified either as PeerId structure or as seed string. Will be generated randomly if not specified
+ * @returns { Promise } Promise which will be resolved with the created FluenceClient
+ */
export const createClient = async (
connectTo?: string | Multiaddr | Node,
peerIdOrSeed?: PeerId | string,
@@ -25,7 +32,7 @@ export const createClient = async (
peerId = await seedToPeerId(peerIdOrSeed);
}
- const client = new FluenceClient(peerId);
+ const client = new FluenceClientImpl(peerId);
if (connectTo) {
let theAddress: Multiaddr;
@@ -42,28 +49,55 @@ export const createClient = async (
return client;
};
+/**
+ * Send a particle to Fluence Network using the specified Fluence Client.
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param { Particle } particle - The particle to send.
+ */
export const sendParticle = async (client: FluenceClient, particle: Particle): Promise => {
return await client.sendScript(particle.script, particle.data, particle.ttl);
};
+/**
+ * Registers a function which can be called on the client from Aquamarine. The registration is per client basis.
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param { string } serviceId - The identifier of service which would be used to make calls from Aquamarine
+ * @param { string } fnName - The identifier of function which would be used to make calls from Aquamarine
+ * @param { (args: any[], tetraplets: SecurityTetraplet[][]) => object } handler - The handler which would be called by Aquamarine infrastructure. The result is any object passed back to Aquamarine
+ */
export const registerServiceFunction = (
client: FluenceClient,
serviceId: string,
fnName: string,
handler: (args: any[], tetraplets: SecurityTetraplet[][]) => object,
) => {
- client.registerCallback(serviceId, fnName, handler);
+ (client as FluenceClientImpl).registerCallback(serviceId, fnName, handler);
};
// prettier-ignore
+/**
+ * Removes registers for the function previously registered with {@link registerServiceFunction}
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param { string } serviceId - The identifier of service used in {@link registerServiceFunction} call
+ * @param { string } fnName - The identifier of function used in {@link registerServiceFunction} call
+ */
export const unregisterServiceFunction = (
client: FluenceClient,
serviceId: string,
fnName: string
) => {
- client.unregisterCallback(serviceId, fnName);
+ (client as FluenceClientImpl).unregisterCallback(serviceId, fnName);
};
+/**
+ * Registers an event-like handler for all calls to the specific service\function pair from from Aquamarine. The registration is per client basis. Return a function which when called removes the subscription.
+ * Same as registerServiceFunction which immediately returns empty object.
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param { string } serviceId - The identifier of service calls to which from Aquamarine are transformed into events.
+ * @param { string } fnName - The identifier of function calls to which from Aquamarine are transformed into events.
+ * @param { (args: any[], tetraplets: SecurityTetraplet[][]) => object } handler - The handler which would be called by Aquamarine infrastructure
+ * @returns { Function } - A function which when called removes the subscription.
+ */
export const subscribeToEvent = (
client: FluenceClient,
serviceId: string,
@@ -84,6 +118,14 @@ export const subscribeToEvent = (
};
};
+/**
+ * Send a particle with a fetch-like semantics. In order to for this to work you have to you have to make a call to the same callbackServiceId\callbackFnName pair from Air script as specified by the parameters. The arguments of the call are returned as the resolve value of promise
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param { Particle } particle - The particle to send.
+ * @param { string } callbackFnName - The identifier of function which should be used in Air script to pass the data to fetch "promise"
+ * @param { [string]='_callback' } callbackServiceId - The service identifier which should be used in Air script to pass the data to fetch "promise"
+ * @returns { Promise } - A promise which would be resolved with the data returned from Aquamarine
+ */
export const sendParticleAsFetch = async (
client: FluenceClient,
particle: Particle,
diff --git a/src/index.ts b/src/index.ts
index c48be3ca0..d3bbaeb6d 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -19,3 +19,4 @@ export { FluenceClient } from './FluenceClient';
export { SecurityTetraplet, PeerIdB58 } from './internal/commonTypes';
export * from './api';
export { Particle } from './internal/particle';
+export * from './internal/builtins';
diff --git a/src/internal/FluenceClientBase.ts b/src/internal/FluenceClientBase.ts
index 73ca310b1..804ae9c8b 100644
--- a/src/internal/FluenceClientBase.ts
+++ b/src/internal/FluenceClientBase.ts
@@ -21,7 +21,6 @@ import { FluenceConnection } from './FluenceConnection';
import { ParticleProcessor } from './ParticleProcessor';
import { ParticleProcessorStrategy } from './ParticleProcessorStrategy';
-import log from 'loglevel';
import { PeerIdB58 } from './commonTypes';
export abstract class FluenceClientBase {
diff --git a/src/internal/FluenceClientImpl.ts b/src/internal/FluenceClientImpl.ts
new file mode 100644
index 000000000..9041e48a4
--- /dev/null
+++ b/src/internal/FluenceClientImpl.ts
@@ -0,0 +1,253 @@
+/*
+ * Copyright 2020 Fluence Labs Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import log from 'loglevel';
+import PeerId from 'peer-id';
+import { SecurityTetraplet, StepperOutcome } from './commonTypes';
+import { FluenceClientBase } from './FluenceClientBase';
+import { FluenceClient } from '../FluenceClient';
+import { build, genUUID, ParticleDto } from './particle';
+import { ParticleProcessor } from './ParticleProcessor';
+import { ParticleProcessorStrategy } from './ParticleProcessorStrategy';
+
+const fetchCallbackServiceName = '__callback';
+const selfRelayVarName = '__relay';
+
+const wrapRelayBasedCall = (script: string) => {
+ return `
+ (seq
+ (call ${selfRelayVarName} ("op" "identity") [])
+ ${script}
+ )
+ `;
+};
+
+const wrapFetchCall = (script: string, particleId: string, resultArgNames: string[]) => {
+ // TODO: sanitize
+ const resultTogether = resultArgNames.join(' ');
+ let res = `
+ (seq
+ ${script}
+ (seq
+ (call ${selfRelayVarName} ("op" "identity") [])
+ (call %init_peer_id% ("${fetchCallbackServiceName}" "${particleId}") [${resultTogether}])
+ )
+ )`;
+ return wrapRelayBasedCall(res);
+};
+
+export interface FluenceEvent {
+ type: string;
+ args: any[];
+}
+
+export type FluenceEventHandler = (event: FluenceEvent) => void;
+
+export class FluenceClientImpl extends FluenceClientBase implements FluenceClient {
+ private eventSubscribers: Map = new Map();
+ private eventValidators: Map = new Map();
+ private callbacks: Map = new Map();
+ private fetchParticles: Map = new Map();
+
+ constructor(selfPeerId: PeerId) {
+ super(selfPeerId);
+ this.processor = new ParticleProcessor(this.strategy, selfPeerId);
+ }
+
+ async fetch(script: string, resultArgNames: string[], data?: Map, ttl?: number): Promise {
+ data = this.addRelayToArgs(data);
+ const callBackId = genUUID();
+ script = wrapFetchCall(script, callBackId, resultArgNames);
+ const particle = await build(this.selfPeerIdFull, script, data, ttl, callBackId);
+
+ return new Promise((resolve, reject) => {
+ this.fetchParticles.set(callBackId, { resolve, reject });
+ this.processor.executeLocalParticle(particle);
+ });
+ }
+
+ // TODO:: better naming probably?
+ async fireAndForget(script: string, data?: Map, ttl?: number) {
+ data = this.addRelayToArgs(data);
+ script = wrapRelayBasedCall(script);
+
+ await this.sendScript(script, data, ttl);
+ }
+
+ registerEvent(
+ channel: string,
+ eventName: string,
+ validate?: (channel: string, eventName: string, args: any[], tetraplets: any[][]) => boolean,
+ ) {
+ if (!validate) {
+ validate = (c, e, a, t) => true;
+ }
+
+ this.eventValidators.set(`${channel}/${eventName}`, validate);
+ }
+
+ unregisterEvent(channel: string, eventName: string) {
+ this.eventValidators.delete(`${channel}/${eventName}`);
+ }
+
+ registerCallback(
+ serviceId: string,
+ fnName: string,
+ callback: (args: any[], tetraplets: SecurityTetraplet[][]) => object,
+ ) {
+ this.callbacks.set(`${serviceId}/${fnName}`, callback);
+ }
+
+ unregisterCallback(channel: string, eventName: string) {
+ this.eventValidators.delete(`${channel}/${eventName}`);
+ }
+
+ subscribe(channel: string, handler: FluenceEventHandler) {
+ if (!this.eventSubscribers.get(channel)) {
+ this.eventSubscribers.set(channel, []);
+ }
+
+ this.eventSubscribers.get(channel).push(handler);
+ }
+
+ protected strategy: ParticleProcessorStrategy = {
+ particleHandler: (serviceId: string, fnName: string, args: any[], tetraplets: SecurityTetraplet[][]) => {
+ // missing built-in op
+ if (serviceId === 'op' && fnName === 'identity') {
+ return {
+ ret_code: 0,
+ result: JSON.stringify(args),
+ };
+ }
+
+ // async fetch model handling
+ if (serviceId === fetchCallbackServiceName) {
+ const executingParticlePromiseFns = this.fetchParticles.get(fnName);
+ if (executingParticlePromiseFns) {
+ // don't block
+ setImmediate(() => {
+ this.fetchParticles.delete(fnName);
+ executingParticlePromiseFns.resolve(args);
+ });
+ }
+
+ return {
+ ret_code: 0,
+ result: JSON.stringify({}),
+ };
+ }
+
+ // event model handling
+ const eventPair = `${serviceId}/${fnName}`;
+ const eventValidator = this.eventValidators.get(eventPair);
+ if (eventValidator) {
+ try {
+ if (!eventValidator(serviceId, fnName, args, tetraplets)) {
+ return {
+ ret_code: 1, // TODO:: error codes
+ result: 'validation failed',
+ };
+ }
+ } catch (e) {
+ log.error('error running validation function: ' + e);
+ return {
+ ret_code: 1, // TODO:: error codes
+ result: 'validation failed',
+ };
+ }
+
+ // don't block
+ setImmediate(() => {
+ this.pushEvent(serviceId, {
+ type: fnName,
+ args: args,
+ });
+ });
+
+ return {
+ ret_code: 0,
+ result: JSON.stringify({}),
+ };
+ }
+
+ // callback model handling
+ const callback = this.callbacks.get(eventPair);
+ if (callback) {
+ try {
+ const res = callback(args, tetraplets);
+ return {
+ ret_code: 0,
+ result: JSON.stringify(res),
+ };
+ } catch (e) {
+ return {
+ ret_code: 1, // TODO:: error codes
+ result: JSON.stringify(e),
+ };
+ }
+ }
+
+ return {
+ ret_code: 1,
+ result: `Error. There is no service: ${serviceId}`,
+ };
+ },
+
+ sendParticleFurther: async (particle: ParticleDto) => {
+ try {
+ await this.connection.sendParticle(particle);
+ } catch (reason) {
+ log.error(`Error on sending particle with id ${particle.id}: ${reason}`);
+ }
+ },
+
+ onParticleTimeout: (particle: ParticleDto, now: number) => {
+ log.info(`Particle expired. Now: ${now}, ttl: ${particle.ttl}, ts: ${particle.timestamp}`);
+ const executingParticle = this.fetchParticles.get(particle.id);
+ if (executingParticle) {
+ executingParticle.reject(new Error(`particle ${particle.id} timed out`));
+ }
+ },
+ onLocalParticleRecieved: (particle: ParticleDto) => {},
+ onExternalParticleRecieved: (particle: ParticleDto) => {},
+ onStepperExecuting: (particle: ParticleDto) => {},
+ onStepperExecuted: (stepperOutcome: StepperOutcome) => {
+ log.info('inner interpreter outcome:');
+ log.info(stepperOutcome);
+ },
+ };
+
+ private pushEvent(channel: string, event: FluenceEvent) {
+ const subs = this.eventSubscribers.get(channel);
+ if (subs) {
+ for (let sub of subs) {
+ sub(event);
+ }
+ }
+ }
+
+ private addRelayToArgs(data: Map) {
+ if (data === undefined) {
+ data = new Map();
+ }
+
+ if (!data.has(selfRelayVarName)) {
+ data.set(selfRelayVarName, this.relayPeerId);
+ }
+
+ return data;
+ }
+}
diff --git a/src/internal/builtins.ts b/src/internal/builtins.ts
new file mode 100644
index 000000000..2a01f19d0
--- /dev/null
+++ b/src/internal/builtins.ts
@@ -0,0 +1,280 @@
+/*
+ * Copyright 2020 Fluence Labs Limited
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import bs58 from 'bs58';
+import { sendParticleAsFetch } from '../api';
+import { Particle } from './particle';
+import { FluenceClient } from '../FluenceClient';
+import { ModuleConfig } from './moduleConfig';
+
+const nodeIdentityCall = (client: FluenceClient): string => {
+ return `(call "${client.relayPeerId}" ("op" "identity") [])`;
+};
+
+const requestResponse = async (
+ client: FluenceClient,
+ name: string,
+ call: (nodeId: string) => string,
+ returnValue: string,
+ data: Map,
+ handleResponse: (args: any[]) => T,
+ nodeId?: string,
+ ttl?: number,
+): Promise => {
+ if (!ttl) {
+ ttl = 10000;
+ }
+
+ if (!nodeId) {
+ nodeId = client.relayPeerId;
+ }
+
+ let serviceCall = call(nodeId);
+
+ let script = `(seq
+ ${nodeIdentityCall(client)}
+ (seq
+ (seq
+ ${serviceCall}
+ ${nodeIdentityCall(client)}
+ )
+ (call "${client.selfPeerId}" ("_callback" "${name}") [${returnValue}])
+ )
+ )
+ `;
+
+ const res = await sendParticleAsFetch(client, new Particle(script, data, ttl), '');
+ return handleResponse(res);
+};
+
+/**
+ * Get all available modules hosted on a connected relay. @deprecated prefer using raw Particles instead
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @returns { Array } - list of available modules on the connected relay
+ */
+export const getModules = async (client: FluenceClient): Promise => {
+ const particle = new Particle(
+ `
+ (seq
+ (call __relay ("dist" "get_modules") [] result)
+ (call myPeerId ("_callback" "getModules") [result])
+ )
+ `,
+ {
+ __relay: client.relayPeerId,
+ myPeerId: client.selfPeerId,
+ },
+ );
+
+ return sendParticleAsFetch(client, particle, 'getModules');
+};
+
+/**
+ * Send a script to add module to a relay. Waiting for a response from a relay. @deprecated prefer using raw Particles instead
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param { string } name - Name of the uploaded module
+ * @param { string } moduleBase64 - Base64 content of the module
+ * @param { ModuleConfig } config - Module config
+ */
+export const uploadModule = async (
+ client: FluenceClient,
+ name: string,
+ moduleBase64: string,
+ config?: ModuleConfig,
+): Promise => {
+ if (!config) {
+ config = {
+ name: name,
+ mem_pages_count: 100,
+ logger_enabled: true,
+ wasi: {
+ envs: {},
+ preopened_files: ['/tmp'],
+ mapped_dirs: {},
+ },
+ };
+ }
+
+ let data = new Map();
+ data.set('module_bytes', moduleBase64);
+ data.set('module_config', config);
+ data.set('__relay', client.relayPeerId);
+ data.set('myPeerId', client.selfPeerId);
+
+ let script = `
+ (seq
+ (call __relay ("dist" "add_module") [module_bytes module_config] result)
+ (call myPeerId ("_callback" "getModules") [result])
+
+ )
+ `;
+
+ return sendParticleAsFetch(client, new Particle(script, data), 'result');
+};
+
+/**
+ * Send a script to add module to a relay. Waiting for a response from a relay. @deprecated prefer using raw Particles instead
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param { string } name - Name of the blueprint
+ * @param { Array } dependencies - Array of it's dependencies
+ * @param {[string]} blueprintId - Optional blueprint ID
+ * @param {[string]} nodeId - Optional node peer id to deploy blueprint to
+ * @param {[number]} ttl - Optional ttl for the particle which does the job
+ * @returns { string } - Created blueprint ID
+ */
+export const addBlueprint = async (
+ client: FluenceClient,
+ name: string,
+ dependencies: string[],
+ blueprintId?: string,
+ nodeId?: string,
+ ttl?: number,
+): Promise => {
+ let returnValue = 'blueprint_id';
+ let call = (nodeId: string) => `(call "${nodeId}" ("dist" "add_blueprint") [blueprint] ${returnValue})`;
+
+ let data = new Map();
+ data.set('blueprint', { name: name, dependencies: dependencies, id: blueprintId });
+
+ return requestResponse(
+ client,
+ 'addBlueprint',
+ call,
+ returnValue,
+ data,
+ (args: any[]) => args[0] as string,
+ nodeId,
+ ttl,
+ );
+};
+
+/**
+ * Send a script to create a service on the connected relay. Waiting for a response from the relay. @deprecated prefer using raw Particles instead
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param {string} blueprintId - The blueprint of the service
+ * @param {[string]} nodeId - Optional node peer id to deploy service to
+ * @param {[number]} ttl - Optional ttl for the particle which does the job
+ * @returns { string } - Created service ID
+ */
+export const createService = async (
+ client: FluenceClient,
+ blueprintId: string,
+ nodeId?: string,
+ ttl?: number,
+): Promise => {
+ let returnValue = 'service_id';
+ let call = (nodeId: string) => `(call "${nodeId}" ("srv" "create") [blueprint_id] ${returnValue})`;
+
+ let data = new Map();
+ data.set('blueprint_id', blueprintId);
+
+ return requestResponse(
+ client,
+ 'createService',
+ call,
+ returnValue,
+ data,
+ (args: any[]) => args[0] as string,
+ nodeId,
+ ttl,
+ );
+};
+
+/**
+ * Get all available blueprints hosted on a connected relay. @deprecated prefer using raw Particles instead
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param {[string]} nodeId - Optional node peer id to get available blueprints from
+ * @param {[number]} ttl - Optional ttl for the particle which does the job
+ * @returns { Array } - List of available blueprints
+ */
+export const getBlueprints = async (client: FluenceClient, nodeId: string, ttl?: number): Promise => {
+ let returnValue = 'blueprints';
+ let call = (nodeId: string) => `(call "${nodeId}" ("dist" "get_blueprints") [] ${returnValue})`;
+
+ return requestResponse(
+ client,
+ 'getBlueprints',
+ call,
+ returnValue,
+ new Map(),
+ (args: any[]) => args[0] as string[],
+ nodeId,
+ ttl,
+ );
+};
+
+/**
+ * Add a provider to DHT network to neighborhood around a key. @deprecated prefer using raw Particles instead
+ */
+export const addProvider = async (
+ client: FluenceClient,
+ key: Buffer,
+ providerPeer: string,
+ providerServiceId?: string,
+ nodeId?: string,
+ ttl?: number,
+): Promise => {
+ let call = (nodeId: string) => `(call "${nodeId}" ("dht" "add_provider") [key provider] void[])`;
+
+ key = bs58.encode(key) as any;
+
+ let provider = {
+ peer: providerPeer,
+ service_id: providerServiceId,
+ };
+
+ let data = new Map();
+ data.set('key', key);
+ data.set('provider', provider);
+
+ return requestResponse(client, 'addProvider', call, '', data, () => {}, nodeId, ttl);
+};
+
+/**
+ * Get a provider from DHT network from neighborhood around a key. @deprecated prefer using raw Particles instead
+ * @param { FluenceClient } client - The Fluence Client instance.
+ * @param {[string]} nodeId - Optional node peer id to get providers from
+ * @param {[number]} ttl - Optional ttl for the particle which does the job
+ * @returns { Array