2024-05-09 11:01:53 -07:00
|
|
|
use crate::model::config::Config;
|
2024-05-25 19:16:36 -07:00
|
|
|
use crate::neptune_rpc;
|
|
|
|
|
use anyhow::Context;
|
|
|
|
|
use clap::Parser;
|
2024-05-09 11:01:53 -07:00
|
|
|
use neptune_core::config_models::network::Network;
|
2024-05-25 19:16:36 -07:00
|
|
|
use neptune_core::models::blockchain::block::block_selector::BlockSelector;
|
2024-05-09 11:01:53 -07:00
|
|
|
use neptune_core::prelude::twenty_first::math::digest::Digest;
|
|
|
|
|
use neptune_core::rpc_server::RPCClient;
|
2024-05-25 19:16:36 -07:00
|
|
|
use std::sync::Arc;
|
|
|
|
|
use tokio::sync::RwLock;
|
2024-05-09 11:01:53 -07:00
|
|
|
|
2024-05-25 19:16:36 -07:00
|
|
|
pub struct AppStateInner {
|
2024-05-09 11:01:53 -07:00
|
|
|
pub network: Network,
|
|
|
|
|
pub config: Config,
|
|
|
|
|
pub rpc_client: RPCClient,
|
|
|
|
|
pub genesis_digest: Digest,
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-25 19:16:36 -07:00
|
|
|
#[derive(Clone)]
|
|
|
|
|
pub struct AppState(Arc<RwLock<AppStateInner>>);
|
|
|
|
|
|
|
|
|
|
impl std::ops::Deref for AppState {
|
|
|
|
|
type Target = Arc<RwLock<AppStateInner>>;
|
|
|
|
|
|
|
|
|
|
fn deref(&self) -> &Self::Target {
|
|
|
|
|
&self.0
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2024-05-09 11:01:53 -07:00
|
|
|
impl From<(Network, Config, RPCClient, Digest)> for AppState {
|
|
|
|
|
fn from(
|
|
|
|
|
(network, config, rpc_client, genesis_digest): (Network, Config, RPCClient, Digest),
|
|
|
|
|
) -> Self {
|
2024-05-25 19:16:36 -07:00
|
|
|
Self(Arc::new(RwLock::new(AppStateInner {
|
2024-05-09 11:01:53 -07:00
|
|
|
network,
|
|
|
|
|
config,
|
|
|
|
|
rpc_client,
|
|
|
|
|
genesis_digest,
|
2024-05-25 19:16:36 -07:00
|
|
|
})))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl AppState {
|
|
|
|
|
pub async fn init() -> Result<Self, anyhow::Error> {
|
|
|
|
|
let rpc_client = neptune_rpc::gen_rpc_client()
|
|
|
|
|
.await
|
|
|
|
|
.with_context(|| "Failed to create RPC client")?;
|
|
|
|
|
let network = rpc_client
|
|
|
|
|
.network(tarpc::context::current())
|
|
|
|
|
.await
|
|
|
|
|
.with_context(|| "Failed calling neptune-core api: network")?;
|
|
|
|
|
let genesis_digest = rpc_client
|
|
|
|
|
.block_digest(tarpc::context::current(), BlockSelector::Genesis)
|
|
|
|
|
.await
|
|
|
|
|
.with_context(|| "Failed calling neptune-core api: block_digest")?
|
|
|
|
|
.with_context(|| "neptune-core failed to provide a genesis block")?;
|
|
|
|
|
|
|
|
|
|
Ok(Self::from((
|
|
|
|
|
network,
|
|
|
|
|
Config::parse(),
|
|
|
|
|
rpc_client,
|
|
|
|
|
genesis_digest,
|
|
|
|
|
)))
|
2024-05-09 11:01:53 -07:00
|
|
|
}
|
|
|
|
|
}
|