Skip to content

Commit

Permalink
Rewrite service
Browse files Browse the repository at this point in the history
  • Loading branch information
InversionSpaces committed Mar 7, 2024
1 parent 4c117c9 commit 0df43e5
Show file tree
Hide file tree
Showing 20 changed files with 1,157 additions and 1,067 deletions.
1,379 changes: 972 additions & 407 deletions Cargo.lock

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[workspace]
resolver = "2"
members = [ "wasm-modules/eth-rpc", "wasm-modules/curl-adapter" ]
members = [ "eth-rpc/eth-rpc" ]
Binary file added eth-rpc/curl-adapter/curl_adapter.wasm
Binary file not shown.
12 changes: 12 additions & 0 deletions eth-rpc/curl-adapter/module.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# yaml-language-server: $schema=../../.fluence/schemas/module.json
version: 0

type: compiled

name: curl_adapter

mountedBinaries:
curl: /usr/bin/curl

volumes:
/tmp/vault: /tmp
12 changes: 5 additions & 7 deletions wasm-modules/eth-rpc/Cargo.toml → eth-rpc/eth-rpc/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "eth_rpc"
version = "0.1.0"
version = "0.2.0"
edition = "2021"
authors = ["Fluence Labs"]
publish = false
Expand All @@ -9,18 +9,16 @@ publish = false
name = "eth_rpc"
path = "src/main.rs"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
web3 = { version = "=0.19.0", features = [], default-features = false }
#async-std = "1.12.0" # async-std does not support wasm32-wasi
serde_json = "=1.0.108"
serde = "=1.0.193"
jsonrpc-core = "=18.0.0"
tokio = { version = "=1.34.0", default-features = false, features = ["rt"] }
eyre = "=0.6.9"

marine-rs-sdk = "=0.10.1"
log = "=0.4.20"
marine-rs-sdk = { version = "=0.14.0", features = ["logger"] }
curl-effector-imports = { git = "https://github.com/fluencelabs/effectors.git", branch = "introduce-crates" }

[dev-dependencies]
marine-rs-sdk-test = "=0.11.1"
marine-rs-sdk-test = "=0.16.0"
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@
# Documentation: https://github.com/fluencelabs/fluence-cli/tree/main/docs/configs/module.md

version: 0

type: rust
name: eth_rpc
111 changes: 111 additions & 0 deletions eth-rpc/eth-rpc/src/curl_transport.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
use std::fs;
use std::io::BufReader;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

use jsonrpc_core::types::request::Call;
use jsonrpc_core::Output;
use marine_rs_sdk;
use serde_json::json;
use serde_json::Value;
use web3::futures::future::BoxFuture;
use web3::{RequestId, Transport};

use curl_effector_imports::curl_post;
use curl_effector_imports::{CurlRequest, HttpHeader};

pub type FutResult = BoxFuture<'static, web3::error::Result<Value>>;

#[derive(Debug, Clone)]
pub struct CurlTransport {
pub uri: String,
id: Arc<AtomicUsize>,
}

impl CurlTransport {
pub fn new(uri: String) -> Self {
Self {
uri,
id: Arc::new(AtomicUsize::new(0)),
}
}

pub fn next_id(&self) -> RequestId {
self.id.fetch_add(1, Ordering::AcqRel)
}
}

impl Transport for CurlTransport {
type Out = FutResult;

fn prepare(&self, method: &str, params: Vec<Value>) -> (RequestId, Call) {
let id = self.next_id();
let request = web3::helpers::build_request(id, method, params.clone());
(id, request)
}

fn send(&self, id: RequestId, call: Call) -> Self::Out {
if let Call::MethodCall(call) = call {
let uri = self.uri.clone();

Box::pin(async move {
let json: String = json!(call).to_string();
let data_filename = format!("request-{}.json", id);
let data_path = vault_path(&data_filename);

let response_filename = format!("response-{}.json", id);
let response_path = vault_path(&response_filename);

let headers = vec![
HttpHeader {
name: "accept".to_string(),
value: "application/json".to_string(),
},
HttpHeader {
name: "content-type".to_string(),
value: "application/json".to_string(),
},
];
let request = CurlRequest { url: uri, headers };

fs::write(&data_path, json.as_bytes())?;
let result = curl_post(request, data_path, response_path.clone());

if !result.success {
return Err(web3::error::Error::Transport(
web3::error::TransportError::Message(format!("error: {}", result.error)),
));
}

let response_file = fs::File::open(&response_path)?;
let rdr = BufReader::new(response_file);
let response: Value = serde_json::from_reader(rdr)?;
let response: Output = serde_json::from_value(response)?;
let result = match response {
Output::Success(jsonrpc_core::types::Success { result, .. }) => result,
Output::Failure(jsonrpc_core::types::Failure { error, .. }) => {
serde_json::to_value(error.message).unwrap()
}
};

Ok(result)
})
} else {
todo!()
}
}
}

// Since all effectors are working via the Particle Vault, you need to provide a correct path to the vault.
// At the moment, we don't have any nice library for this sort of things, so you need to do it manually.
//
// Here we need to create a path to the vault which has a form of `/tmp/vault/{particle-id}-{particle-token}`.
// In this directory, you can freely write and read any files you need. Note that this directory exists only when
// a particle that called the function exsits, so you'll see here a different path each run.
fn vault_path(filename: &str) -> String {
let cp = marine_rs_sdk::get_call_parameters();
format!(
"/tmp/vault/{}-{}/{}",
cp.particle.id, cp.particle.token, filename
)
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use eyre::eyre;
use marine_rs_sdk::marine;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use tokio::runtime::Builder;
use web3::Transport;
Expand All @@ -27,31 +26,6 @@ pub fn eth_call(uri: String, method: &str, json_args: Vec<String>) -> JsonString
result.into()
}

#[marine]
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RPCResult {
provider_name: String,
stdout: String,
stderr: String,
}

pub fn eth_call_2(uri: String, method: &str, json_args: Vec<String>) -> JsonString {
let result: eyre::Result<Value> = try {
let rt = Builder::new_current_thread().build()?;

let args: Result<Vec<Value>, _> = json_args
.into_iter()
.map(|a| serde_json::from_str(&a))
.collect();
let transport = CurlTransport::new(uri);
let result = rt.block_on(transport.execute(method, args?))?;

result
};

result.into()
}

#[cfg(test)]
mod tests {
use marine_rs_sdk_test::marine_test;
Expand All @@ -67,8 +41,6 @@ mod tests {

let accounts = rpc.eth_call(uri, method, json_args);
println!("bad uri call: {:?}", accounts);
// println!("accounts: {:?}", accounts);
// assert_eq!(accounts.len(), 0);
}

#[marine_test(
Expand All @@ -95,9 +67,6 @@ mod tests {

let accounts = rpc.eth_call(uri, method, json_args);
println!("all good: {:?}", accounts);

// println!("accounts: {:?}", accounts);
// assert_eq!(accounts.len(), 0);
}

#[marine_test(
Expand Down
17 changes: 17 additions & 0 deletions eth-rpc/eth-rpc/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
#![feature(try_blocks)]

use marine_rs_sdk::module_manifest;
use marine_rs_sdk::WasmLoggerBuilder;

pub mod curl_transport;
pub mod eth_call;
pub mod values;

module_manifest!();

pub fn main() {
WasmLoggerBuilder::new()
.with_log_level(log::LevelFilter::Info)
.build()
.unwrap();
}
26 changes: 26 additions & 0 deletions eth-rpc/eth-rpc/src/values.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
use marine_rs_sdk::marine;
use serde_json::Value;

#[marine]
pub struct JsonString {
pub value: String,
pub success: bool,
pub error: String,
}

impl From<eyre::Result<Value>> for JsonString {
fn from(value: eyre::Result<Value>) -> Self {
match value {
Ok(value) => JsonString {
value: value.to_string(),
success: true,
error: String::new(),
},
Err(err) => JsonString {
value: String::new(),
success: false,
error: format!("{}\n{:?}", err, err),
},
}
}
}
File renamed without changes.
4 changes: 3 additions & 1 deletion fluence.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ deployments:
services:
- eth_rpc
spells: []
effectors:
- bafybeiazogjvmbfjpg3dtk4jtjqq2oi53ufb24fyzcgeo7ugw3nc565ncm

services:
eth_rpc:
get: wasm-modules
get: eth-rpc

aquaDependencies:
"@fluencelabs/aqua-lib": 0.10.1
Expand Down
9 changes: 9 additions & 0 deletions provider.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ version: 0

providerName: fRPC-Provider

nox:
effectors:
curl:
wasmCID: bafybeiazogjvmbfjpg3dtk4jtjqq2oi53ufb24fyzcgeo7ugw3nc565ncm
allowedBinaries:
curl: /usr/bin/curl

computePeers:
nox-0:
computeUnits: 32
Expand All @@ -23,6 +30,8 @@ offers:
- nox-0
- nox-1
- nox-2
effectors:
- bafybeiazogjvmbfjpg3dtk4jtjqq2oi53ufb24fyzcgeo7ugw3nc565ncm

capacityCommitments:
nox-0:
Expand Down
14 changes: 0 additions & 14 deletions wasm-modules/curl-adapter/Cargo.toml

This file was deleted.

11 changes: 0 additions & 11 deletions wasm-modules/curl-adapter/module.yaml

This file was deleted.

32 changes: 0 additions & 32 deletions wasm-modules/curl-adapter/src/main.rs

This file was deleted.

Loading

0 comments on commit 0df43e5

Please sign in to comment.