This commit is contained in:
Derrick Hammer 2023-03-23 19:05:44 -04:00
parent 93b4d502ba
commit 602b6dfee5
Signed by: pcfreak30
GPG Key ID: C997C339BE476FF2
12 changed files with 55 additions and 37 deletions

2
Cargo.lock generated
View File

@ -2070,10 +2070,10 @@ dependencies = [
"console_error_panic_hook", "console_error_panic_hook",
"ethers", "ethers",
"execution", "execution",
"futures",
"hex", "hex",
"serde", "serde",
"serde-wasm-bindgen 0.4.5", "serde-wasm-bindgen 0.4.5",
"serde_json",
"wasm-bindgen", "wasm-bindgen",
"wasm-bindgen-futures", "wasm-bindgen-futures",
"web-sys", "web-sys",

View File

@ -8,7 +8,7 @@ exclude = [
] ]
[build] [build]
target = "wasm64-unknown-unknown" target = "wasm32-unknown-unknown"
[workspace] [workspace]
members = [ members = [

View File

@ -37,8 +37,8 @@ use crate::rpc::Rpc;
#[derive(Default)] #[derive(Default)]
pub struct ClientBuilder { pub struct ClientBuilder {
network: Option<Network>, network: Option<Network>,
consensus_rpc: Option<wasm_bindgen::JsValue>, consensus_rpc: Option<Arc<wasm_bindgen::JsValue>>,
execution_rpc: Option<wasm_bindgen::JsValue>, execution_rpc: Option<Arc<wasm_bindgen::JsValue>>,
checkpoint: Option<Vec<u8>>, checkpoint: Option<Vec<u8>>,
#[cfg(not(target_arch = "wasm32"))] #[cfg(not(target_arch = "wasm32"))]
rpc_port: Option<u16>, rpc_port: Option<u16>,
@ -60,12 +60,12 @@ impl ClientBuilder {
self self
} }
pub fn consensus_rpc(mut self, consensus_rpc: wasm_bindgen::JsValue) -> Self { pub fn consensus_rpc(mut self, consensus_rpc: Arc<wasm_bindgen::JsValue>) -> Self {
self.consensus_rpc = Some(consensus_rpc); self.consensus_rpc = Some(consensus_rpc);
self self
} }
pub fn execution_rpc(mut self, execution_rpc: wasm_bindgen::JsValue) -> Self { pub fn execution_rpc(mut self, execution_rpc: Arc<wasm_bindgen::JsValue>) -> Self {
self.execution_rpc = Some(execution_rpc); self.execution_rpc = Some(execution_rpc);
self self
} }

View File

@ -1,4 +1,5 @@
use serde::Serialize; use serde::Serialize;
use std::sync::Arc;
use wasm_bindgen::JsValue; use wasm_bindgen::JsValue;
use crate::types::{ChainConfig, Forks}; use crate::types::{ChainConfig, Forks};
@ -9,7 +10,7 @@ use crate::utils::bytes_serialize;
pub struct BaseConfig { pub struct BaseConfig {
pub rpc_port: u16, pub rpc_port: u16,
#[serde(skip_serializing, skip_deserializing)] #[serde(skip_serializing, skip_deserializing)]
pub consensus_rpc: Option<JsValue>, pub consensus_rpc: Option<Arc<JsValue>>,
#[serde( #[serde(
deserialize_with = "bytes_deserialize", deserialize_with = "bytes_deserialize",
serialize_with = "bytes_serialize" serialize_with = "bytes_serialize"

View File

@ -4,6 +4,7 @@ use figment::{
}; };
use serde::de::Error; use serde::de::Error;
use serde::{Deserialize, Deserializer}; use serde::{Deserialize, Deserializer};
use std::sync::Arc;
use std::{path::PathBuf, process::exit}; use std::{path::PathBuf, process::exit};
use wasm_bindgen::JsValue; use wasm_bindgen::JsValue;
@ -16,9 +17,9 @@ use crate::utils::{bytes_deserialize, bytes_opt_deserialize};
#[derive(Deserialize, Debug, Default)] #[derive(Deserialize, Debug, Default)]
pub struct Config { pub struct Config {
#[serde(skip_serializing, skip_deserializing)] #[serde(skip_serializing, skip_deserializing)]
pub consensus_rpc: wasm_bindgen::JsValue, pub consensus_rpc: Arc<wasm_bindgen::JsValue>,
#[serde(skip_serializing, skip_deserializing)] #[serde(skip_serializing, skip_deserializing)]
pub execution_rpc: wasm_bindgen::JsValue, pub execution_rpc: Arc<wasm_bindgen::JsValue>,
pub rpc_port: Option<u16>, pub rpc_port: Option<u16>,
#[serde(deserialize_with = "bytes_deserialize")] #[serde(deserialize_with = "bytes_deserialize")]
pub default_checkpoint: Vec<u8>, pub default_checkpoint: Vec<u8>,

View File

@ -1,5 +1,6 @@
use common::utils::hex_str_to_bytes; use common::utils::hex_str_to_bytes;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::sync::Arc;
use strum::{Display, EnumIter}; use strum::{Display, EnumIter};
use wasm_bindgen::JsValue; use wasm_bindgen::JsValue;
@ -41,7 +42,7 @@ pub fn mainnet() -> BaseConfig {
) )
.unwrap(), .unwrap(),
rpc_port: 8545, rpc_port: 8545,
consensus_rpc: Some(JsValue::null()), consensus_rpc: Some(Arc::from(JsValue::null())),
chain: ChainConfig { chain: ChainConfig {
chain_id: 1, chain_id: 1,
genesis_time: 1606824023, genesis_time: 1606824023,

View File

@ -55,7 +55,7 @@ struct LightClientStore {
impl<R: ConsensusRpc> ConsensusClient<R> { impl<R: ConsensusRpc> ConsensusClient<R> {
pub fn new( pub fn new(
rpc_handler: wasm_bindgen::JsValue, rpc_handler: Arc<wasm_bindgen::JsValue>,
checkpoint_block_root: &[u8], checkpoint_block_root: &[u8],
config: Arc<Config>, config: Arc<Config>,
) -> Result<ConsensusClient<R>> { ) -> Result<ConsensusClient<R>> {
@ -660,8 +660,8 @@ mod tests {
async fn get_client(strict_checkpoint_age: bool) -> ConsensusClient<MockRpc> { async fn get_client(strict_checkpoint_age: bool) -> ConsensusClient<MockRpc> {
let base_config = networks::goerli(); let base_config = networks::goerli();
let config = Config { let config = Config {
consensus_rpc: wasm_bindgen::JsValue::null(), consensus_rpc: Arc::from(wasm_bindgen::JsValue::null()),
execution_rpc: wasm_bindgen::JsValue::null(), execution_rpc: Arc::from(wasm_bindgen::JsValue::null()),
chain: base_config.chain, chain: base_config.chain,
forks: base_config.forks, forks: base_config.forks,
strict_checkpoint_age, strict_checkpoint_age,
@ -672,9 +672,12 @@ mod tests {
hex::decode("1e591af1e90f2db918b2a132991c7c2ee9a4ab26da496bd6e71e4f0bd65ea870") hex::decode("1e591af1e90f2db918b2a132991c7c2ee9a4ab26da496bd6e71e4f0bd65ea870")
.unwrap(); .unwrap();
let mut client = let mut client = ConsensusClient::new(
ConsensusClient::new(wasm_bindgen::JsValue::null(), &checkpoint, Arc::new(config)) Arc::from(wasm_bindgen::JsValue::null()),
.unwrap(); &checkpoint,
Arc::new(config),
)
.unwrap();
client.bootstrap().await.unwrap(); client.bootstrap().await.unwrap();
client client
} }

View File

@ -2,6 +2,7 @@ pub mod nimbus_rpc;
use async_trait::async_trait; use async_trait::async_trait;
use eyre::Result; use eyre::Result;
use std::sync::Arc;
use crate::types::{BeaconBlock, Bootstrap, FinalityUpdate, OptimisticUpdate, Update}; use crate::types::{BeaconBlock, Bootstrap, FinalityUpdate, OptimisticUpdate, Update};
@ -9,7 +10,7 @@ use crate::types::{BeaconBlock, Bootstrap, FinalityUpdate, OptimisticUpdate, Upd
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] #[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))] #[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait ConsensusRpc { pub trait ConsensusRpc {
fn new(rpc_handler: wasm_bindgen::JsValue) -> Self; fn new(rpc_handler: Arc<wasm_bindgen::JsValue>) -> Self;
async fn get_bootstrap(&self, block_root: &'_ [u8]) -> Result<Bootstrap>; async fn get_bootstrap(&self, block_root: &'_ [u8]) -> Result<Bootstrap>;
async fn get_updates(&self, period: u64, count: u8) -> Result<Vec<Update>>; async fn get_updates(&self, period: u64, count: u8) -> Result<Vec<Update>>;
async fn get_finality_update(&self) -> Result<FinalityUpdate>; async fn get_finality_update(&self) -> Result<FinalityUpdate>;

View File

@ -1,11 +1,11 @@
use std::cmp; use std::cmp;
use std::fmt::{Display, Formatter, Result as FmtResult}; use std::fmt::{Display, Formatter, Result as FmtResult};
use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use eyre::{Result, WrapErr}; use eyre::{Result, WrapErr};
use js_sys::then;
use serde::Deserialize; use serde::Deserialize;
use serde_wasm_bindgen::from_value as from_js_value; use serde_json::from_str as from_json_str;
use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen::{JsCast, JsValue};
use wasm_bindgen_futures::JsFuture; use wasm_bindgen_futures::JsFuture;
@ -30,13 +30,12 @@ impl std::error::Error for RpcError {}
#[derive(Debug)] #[derive(Debug)]
pub struct NimbusRpc { pub struct NimbusRpc {
rpc_handler: wasm_bindgen::JsValue, rpc_handler: Arc<JsValue>,
} }
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] #[async_trait(?Send)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl ConsensusRpc for NimbusRpc { impl ConsensusRpc for NimbusRpc {
fn new(rpc_handler: JsValue) -> Self { fn new(rpc_handler: Arc<JsValue>) -> Self {
NimbusRpc { rpc_handler } NimbusRpc { rpc_handler }
} }
@ -142,7 +141,7 @@ struct Spec {
} }
impl NimbusRpc { impl NimbusRpc {
async fn request<T>(&self, path: String, error_type: &str) -> Result<T, JsValue> async fn request<T>(&self, path: String, error_type: &str) -> Result<T>
where where
for<'a> T: Deserialize<'a>, for<'a> T: Deserialize<'a>,
{ {
@ -150,18 +149,21 @@ impl NimbusRpc {
js_params.set(&JsValue::from_str("method"), &JsValue::from_str("GET")); js_params.set(&JsValue::from_str("method"), &JsValue::from_str("GET"));
js_params.set(&JsValue::from_str("path"), &JsValue::from_str(&path)); js_params.set(&JsValue::from_str("path"), &JsValue::from_str(&path));
let promise = self let rpc_handler_clone = self.rpc_handler.clone();
.rpc_handler let promise = Arc::clone(&rpc_handler_clone)
.dyn_into::<js_sys::Function>() .dyn_into::<js_sys::Function>()
.unwrap() .unwrap()
.call1(&JsValue::null(), &js_params) .call1(&JsValue::null(), &js_params)
.expect("Failed to make JSON-RPC request"); .expect("Failed to make JSON-RPC request");
let result = match promise.dyn_into::<JsValue>() { let result = match promise.dyn_into::<js_sys::Promise>() {
Ok(promise) => JsFuture::from(promise).await.unwrap(), Ok(promise) => JsFuture::from(promise).await.unwrap(),
Err(_) => panic!("Unable to convert JS value to Promise"), Err(_) => panic!("Unable to convert JS value to Promise"),
}; };
Ok(result) let json = result.as_string().unwrap();
let response: T = serde_json::from_str(&json)?;
Ok(response)
} }
} }

View File

@ -1,6 +1,7 @@
use std::error::Error; use std::error::Error;
use std::fmt::{Debug, Display, Formatter}; use std::fmt::{Debug, Display, Formatter};
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc;
use async_trait::async_trait; use async_trait::async_trait;
use ethers::prelude::{Address, Http}; use ethers::prelude::{Address, Http};
@ -30,7 +31,7 @@ use wasm_bindgen_futures::JsFuture;
pub struct HttpRpc { pub struct HttpRpc {
provider: Provider<LumeProvider>, provider: Provider<LumeProvider>,
rpc_handler: JsValue, rpc_handler: Arc<JsValue>,
} }
impl Clone for HttpRpc { impl Clone for HttpRpc {
@ -65,15 +66,17 @@ impl From<LumeError> for ProviderError {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub struct LumeProvider { pub struct LumeProvider {
pub rpc_handler: JsValue, pub rpc_handler: Arc<JsValue>,
} }
impl LumeProvider { impl LumeProvider {
pub fn new(rpc_handler: JsValue) -> Self { pub fn new(rpc_handler: Arc<JsValue>) -> Self {
LumeProvider { rpc_handler } LumeProvider { rpc_handler }
} }
} }
#[async_trait]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl JsonRpcClient for LumeProvider { impl JsonRpcClient for LumeProvider {
type Error = LumeError; type Error = LumeError;
@ -98,11 +101,9 @@ impl JsonRpcClient for LumeProvider {
} }
} }
#[cfg_attr(not(target_arch = "wasm32"), async_trait)] #[async_trait(?Send)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl ExecutionRpc for HttpRpc { impl ExecutionRpc for HttpRpc {
fn new(rpc_handler: wasm_bindgen::JsValue) -> Result<Self> { fn new(rpc_handler: Arc<JsValue>) -> Result<Self> {
let http = Http::from_str(rpc)?;
let mut client = LumeProvider::new(rpc_handler.clone()); let mut client = LumeProvider::new(rpc_handler.clone());
let provider = Provider::new(client); let provider = Provider::new(client);

View File

@ -1,3 +1,6 @@
[build]
target = "wasm32-unknown-unknown"
[package] [package]
name = "helios-ts" name = "helios-ts"
version = "0.1.0" version = "0.1.0"
@ -13,11 +16,12 @@ wasm-bindgen = "0.2.84"
wasm-bindgen-futures = "0.4.33" wasm-bindgen-futures = "0.4.33"
serde-wasm-bindgen = "0.4.5" serde-wasm-bindgen = "0.4.5"
console_error_panic_hook = "0.1.7" console_error_panic_hook = "0.1.7"
futures = "0.3"
serde = { version = "1.0.85", features = ["derive"] }
ethers = "1.0.0" ethers = "1.0.0"
hex = "0.4.3" hex = "0.4.3"
serde = { version = "1.0.143", features = ["derive"] }
serde_json = "1.0.85"
client = { path = "../client" } client = { path = "../client" }
common = { path = "../common" } common = { path = "../common" }

View File

@ -2,6 +2,7 @@ extern crate console_error_panic_hook;
extern crate web_sys; extern crate web_sys;
use std::str::FromStr; use std::str::FromStr;
use std::sync::Arc;
use common::types::BlockTag; use common::types::BlockTag;
use ethers::types::{Address, Filter, H256}; use ethers::types::{Address, Filter, H256};
@ -39,6 +40,9 @@ impl Client {
let chain_id = base.chain.chain_id; let chain_id = base.chain.chain_id;
let execution_rpc = Arc::new(execution_rpc);
let consensus_rpc = Arc::new(consensus_rpc);
let checkpoint = Some( let checkpoint = Some(
checkpoint checkpoint
.as_ref() .as_ref()