feat(wallet): multi-sequencer client stub added

This commit is contained in:
Pravdyvy 2026-07-07 15:14:49 +03:00
parent a0ba6008c3
commit 10c9d89ec8
8 changed files with 182 additions and 88 deletions

View File

@ -33,17 +33,23 @@ impl WalletSubcommand for ChainSubcommand {
) -> Result<SubcommandReturnValue> {
match self {
Self::CurrentBlockId => {
let latest_block_id = wallet_core.sequencer_client.get_last_block_id().await?;
let latest_block_id = wallet_core
.optimal_sequencer_client()
.get_last_block_id()
.await?;
println!("Last block id is {latest_block_id}");
}
Self::Block { id } => {
let block = wallet_core.sequencer_client.get_block(id).await?;
let block = wallet_core.optimal_sequencer_client().get_block(id).await?;
println!("Last block id is {block:#?}");
}
Self::Transaction { hash } => {
let tx = wallet_core.sequencer_client.get_transaction(hash).await?;
let tx = wallet_core
.optimal_sequencer_client()
.get_transaction(hash)
.await?;
println!("Transaction is {tx:#?}");
}

View File

@ -37,7 +37,7 @@ impl ConfigSubcommand {
} else if let Some(key) = key {
match key.as_str() {
"sequencer_addr" => {
println!("{}", config.sequencer_addr);
println!("{:?}", config.sequencers_conn_data);
}
"seq_poll_timeout" => {
println!("{:?}", config.seq_poll_timeout);
@ -51,13 +51,6 @@ impl ConfigSubcommand {
"seq_block_poll_max_amount" => {
println!("{}", config.seq_block_poll_max_amount);
}
"basic_auth" => {
if let Some(basic_auth) = &config.basic_auth {
println!("{basic_auth}");
} else {
println!("Not set");
}
}
_ => {
println!("Unknown field");
}
@ -76,9 +69,6 @@ impl ConfigSubcommand {
) -> Result<SubcommandReturnValue> {
let mut config = wallet_core.config().clone();
match key.as_str() {
"sequencer_addr" => {
config.sequencer_addr = value.parse()?;
}
"seq_poll_timeout" => {
config.seq_poll_timeout = humantime::parse_duration(&value)
.map_err(|e| anyhow::anyhow!("Invalid duration: {e}"))?;
@ -92,9 +82,6 @@ impl ConfigSubcommand {
"seq_block_poll_max_amount" => {
config.seq_block_poll_max_amount = value.parse()?;
}
"basic_auth" => {
config.basic_auth = Some(value.parse()?);
}
"initial_accounts" => {
anyhow::bail!("Setting this field from wallet is not supported");
}

View File

@ -219,7 +219,7 @@ pub async fn execute_subcommand(
}
Command::CheckHealth => {
let remote_program_ids = wallet_core
.sequencer_client
.optimal_sequencer_client()
.get_program_ids()
.await
.expect("Error fetching program ids");
@ -287,7 +287,7 @@ pub async fn execute_subcommand(
let message = lee::program_deployment_transaction::Message::new(bytecode);
let transaction = ProgramDeploymentTransaction::new(message);
let _response = wallet_core
.sequencer_client
.optimal_sequencer_client()
.send_transaction(LeeTransaction::ProgramDeployment(transaction))
.await
.context("Transaction submission error")?;
@ -384,12 +384,13 @@ pub async fn execute_keys_restoration(wallet_core: &mut WalletCore, depth: u32)
wallet_core.sync_to_latest_block().await?;
let optimal_sequencer_client = wallet_core.optimal_sequencer_client_owned();
wallet_core
.storage
.key_chain_mut()
.cleanup_trees_remove_uninit_layered(depth, |account_id| {
wallet_core
.sequencer_client
optimal_sequencer_client
.get_account(account_id)
.map_err(Into::into)
})

View File

@ -7,6 +7,15 @@ use log::warn;
use serde::{Deserialize, Serialize};
use url::Url;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SequencerConnectionData {
/// Connection data of all known sequencers.
pub sequencer_addr: Url,
/// Basic authentication credentials
#[serde(skip_serializing_if = "Option::is_none")]
pub basic_auth: Option<BasicAuth>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GasConfig {
/// Gas spent per deploying one byte of data.
@ -28,8 +37,8 @@ pub struct GasConfig {
#[optfield::optfield(pub WalletConfigOverrides, rewrap, attrs = (derive(Debug, Default, Clone)))]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalletConfig {
/// Sequencer URL.
pub sequencer_addr: Url,
/// Connection data of all known sequencers.
pub sequencers_conn_data: Vec<SequencerConnectionData>,
/// Sequencer polling duration for new blocks.
#[serde(with = "humantime_serde")]
pub seq_poll_timeout: Duration,
@ -39,20 +48,19 @@ pub struct WalletConfig {
pub seq_poll_max_retries: u64,
/// Max amount of blocks to poll in one request.
pub seq_block_poll_max_amount: u64,
/// Basic authentication credentials
#[serde(skip_serializing_if = "Option::is_none")]
pub basic_auth: Option<BasicAuth>,
}
impl Default for WalletConfig {
fn default() -> Self {
Self {
sequencer_addr: "http://127.0.0.1:3040".parse().unwrap(),
sequencers_conn_data: vec![SequencerConnectionData {
sequencer_addr: "http://127.0.0.1:3040".parse().unwrap(),
basic_auth: None,
}],
seq_poll_timeout: Duration::from_secs(12),
seq_tx_poll_max_blocks: 5,
seq_poll_max_retries: 5,
seq_block_poll_max_amount: 100,
basic_auth: None,
}
}
}
@ -97,26 +105,24 @@ impl WalletConfig {
pub fn apply_overrides(&mut self, overrides: WalletConfigOverrides) {
let Self {
sequencer_addr,
sequencers_conn_data,
seq_poll_timeout,
seq_tx_poll_max_blocks,
seq_poll_max_retries,
seq_block_poll_max_amount,
basic_auth,
} = self;
let WalletConfigOverrides {
sequencer_addr: o_sequencer_addr,
sequencers_conn_data: o_sequencers_conn_data,
seq_poll_timeout: o_seq_poll_timeout,
seq_tx_poll_max_blocks: o_seq_tx_poll_max_blocks,
seq_poll_max_retries: o_seq_poll_max_retries,
seq_block_poll_max_amount: o_seq_block_poll_max_amount,
basic_auth: o_basic_auth,
} = overrides;
if let Some(v) = o_sequencer_addr {
warn!("Overriding wallet config 'sequencer_addr' to {v}");
*sequencer_addr = v;
if let Some(v) = o_sequencers_conn_data {
warn!("Overriding wallet config 'sequencers_conn_data' to {v:?}");
*sequencers_conn_data = v;
}
if let Some(v) = o_seq_poll_timeout {
warn!("Overriding wallet config 'seq_poll_timeout' to {v:?}");
@ -134,9 +140,5 @@ impl WalletConfig {
warn!("Overriding wallet config 'seq_block_poll_max_amount' to {v}");
*seq_block_poll_max_amount = v;
}
if let Some(v) = o_basic_auth {
warn!("Overriding wallet config 'basic_auth' to {v:#?}");
*basic_auth = v;
}
}
}

View File

@ -66,6 +66,15 @@ pub fn fetch_persistent_storage_path() -> Result<PathBuf> {
Ok(accs_path)
}
/// Fetch path to metrics storage from default home.
///
/// File must be created through setup beforehand.
pub fn fetch_metrics_path() -> Result<PathBuf> {
let home = get_home()?;
let metrics_path = home.join("metrics.json");
Ok(metrics_path)
}
#[expect(dead_code, reason = "Maybe used later")]
pub(crate) fn produce_random_nonces(size: usize) -> Vec<Nonce> {
let mut result = vec![[0; 16]; size];

View File

@ -26,13 +26,14 @@ use lee_core::{
account::Nonce, compute_digest_for_path, program::InstructionData,
};
use log::info;
use sequencer_service_rpc::{RpcClient as _, SequencerClient, SequencerClientBuilder};
use sequencer_service_rpc::{RpcClient as _, SequencerClient};
use storage::Storage;
use tokio::io::AsyncWriteExt as _;
use crate::{
account::{AccountIdWithPrivacy, Label},
config::WalletConfigOverrides,
multi_client::{Metrics, MultiSequencerClient},
poller::TxPoller,
storage::key_chain::SharedAccountEntry,
};
@ -42,6 +43,7 @@ mod account_manager;
pub mod cli;
pub mod config;
pub mod helperfunctions;
pub mod multi_client;
pub mod poller;
pub mod program_facades;
pub mod signing;
@ -92,8 +94,9 @@ pub struct WalletCore {
storage: Storage,
storage_path: PathBuf,
poller: TxPoller,
pub sequencer_client: SequencerClient,
_metrics_path: PathBuf,
pub multi_sequencer_client: MultiSequencerClient,
}
impl WalletCore {
@ -101,29 +104,44 @@ impl WalletCore {
pub fn from_env() -> Result<Self> {
let config_path = helperfunctions::fetch_config_path()?;
let storage_path = helperfunctions::fetch_persistent_storage_path()?;
let metrics_path = helperfunctions::fetch_metrics_path()?;
Self::new_update_chain(config_path, storage_path, None)
Self::new_update_chain(config_path, storage_path, metrics_path, None)
}
pub fn new_update_chain(
config_path: PathBuf,
storage_path: PathBuf,
metrics_path: PathBuf,
config_overrides: Option<WalletConfigOverrides>,
) -> Result<Self> {
let storage = Storage::from_path(&storage_path)
.with_context(|| format!("Failed to load storage from {}", storage_path.display()))?;
Self::new(config_path, storage_path, config_overrides, storage)
Self::new(
config_path,
storage_path,
metrics_path,
config_overrides,
storage,
)
}
pub fn new_init_storage(
config_path: PathBuf,
storage_path: PathBuf,
metrics_path: PathBuf,
config_overrides: Option<WalletConfigOverrides>,
password: &str,
) -> Result<(Self, Mnemonic)> {
let (storage, mnemonic) = Storage::new(password).context("Failed to create storage")?;
let wallet = Self::new(config_path, storage_path, config_overrides, storage)?;
let wallet = Self::new(
config_path,
storage_path,
metrics_path,
config_overrides,
storage,
)?;
Ok((wallet, mnemonic))
}
@ -131,6 +149,7 @@ impl WalletCore {
fn new(
config_path: PathBuf,
storage_path: PathBuf,
metrics_path: PathBuf,
config_overrides: Option<WalletConfigOverrides>,
storage: Storage,
) -> Result<Self> {
@ -145,25 +164,7 @@ impl WalletCore {
config.apply_overrides(config_overrides);
}
let sequencer_client = {
let mut builder = SequencerClientBuilder::default();
if let Some(basic_auth) = &config.basic_auth {
builder = builder.set_headers(
std::iter::once((
"Authorization".parse().expect("Header name is valid"),
format!("Basic {basic_auth}")
.parse()
.context("Invalid basic auth format")?,
))
.collect(),
);
}
builder
.build(config.sequencer_addr.clone())
.context("Failed to create sequencer client")?
};
let tx_poller = TxPoller::new(&config, sequencer_client.clone());
let multi_sequencer_client = MultiSequencerClient::new(&config.sequencers_conn_data)?;
Ok(Self {
config_path,
@ -171,8 +172,8 @@ impl WalletCore {
config,
storage_path,
storage,
poller: tx_poller,
sequencer_client,
_metrics_path: metrics_path,
multi_sequencer_client,
})
}
@ -186,6 +187,27 @@ impl WalletCore {
self.config = config;
}
pub fn optimal_poller(&self) -> TxPoller {
let metrics = self.get_metrics();
TxPoller::new(
self.config(),
self.multi_sequencer_client.optimal_client_clone(&metrics),
)
}
pub fn optimal_sequencer_client(&self) -> &SequencerClient {
let metrics = self.get_metrics();
self.multi_sequencer_client.optimal_client_ref(&metrics)
}
pub fn optimal_sequencer_client_owned(&self) -> SequencerClient {
let metrics = self.get_metrics();
self.multi_sequencer_client.optimal_client_clone(&metrics)
}
/// Get storage.
#[must_use]
pub const fn storage(&self) -> &Storage {
@ -430,14 +452,24 @@ impl WalletCore {
})
}
pub fn get_metrics(&self) -> Vec<Metrics> {
todo!();
}
/// Get account balance.
pub async fn get_account_balance(&self, acc: AccountId) -> Result<u128> {
Ok(self.sequencer_client.get_account_balance(acc).await?)
Ok(self
.optimal_sequencer_client()
.get_account_balance(acc)
.await?)
}
/// Get accounts nonces.
pub async fn get_accounts_nonces(&self, accs: Vec<AccountId>) -> Result<Vec<Nonce>> {
Ok(self.sequencer_client.get_accounts_nonces(accs).await?)
Ok(self
.optimal_sequencer_client()
.get_accounts_nonces(accs)
.await?)
}
pub async fn get_account(&self, account_id: AccountIdWithPrivacy) -> Result<Account> {
@ -455,7 +487,10 @@ impl WalletCore {
/// Get public account.
pub async fn get_account_public(&self, account_id: AccountId) -> Result<Account> {
Ok(self.sequencer_client.get_account(account_id).await?)
Ok(self
.optimal_sequencer_client()
.get_account(account_id)
.await?)
}
#[must_use]
@ -492,7 +527,7 @@ impl WalletCore {
/// Poll transactions.
pub async fn poll_native_token_transfer(&self, hash: HashType) -> Result<LeeTransaction> {
self.poller.poll_tx(hash).await
self.optimal_poller().poll_tx(hash).await
}
pub async fn check_private_account_initialized(
@ -500,7 +535,7 @@ impl WalletCore {
account_id: AccountId,
) -> Result<Option<MembershipProof>> {
if let Some(acc_comm) = self.get_private_account_commitment(account_id) {
self.sequencer_client
self.optimal_sequencer_client()
.get_proof_for_commitment(acc_comm)
.await
.map_err(Into::into)
@ -511,7 +546,7 @@ impl WalletCore {
pub async fn get_commitment_root(&self) -> Result<Option<CommitmentSetDigest>> {
let proof = self
.sequencer_client
.optimal_sequencer_client()
.get_proof_for_commitment(DUMMY_COMMITMENT)
.await?;
Ok(proof.map(|p| compute_digest_for_path(&DUMMY_COMMITMENT, &p)))
@ -643,7 +678,7 @@ impl WalletCore {
.collect();
Ok((
self.sequencer_client
self.optimal_sequencer_client()
.send_transaction(LeeTransaction::PrivacyPreserving(tx))
.await?,
shared_secrets,
@ -707,13 +742,13 @@ impl WalletCore {
let tx = lee::public_transaction::PublicTransaction::new(message, witness_set);
Ok(self
.sequencer_client
.optimal_sequencer_client()
.send_transaction(LeeTransaction::Public(tx))
.await?)
}
pub async fn sync_to_latest_block(&mut self) -> Result<u64> {
let latest_block_id = self.sequencer_client.get_last_block_id().await?;
let latest_block_id = self.optimal_sequencer_client().get_last_block_id().await?;
println!("Latest block is {latest_block_id}");
self.sync_to_block(latest_block_id).await?;
Ok(latest_block_id)
@ -735,7 +770,7 @@ impl WalletCore {
println!("Syncing to block {block_id}. Blocks to sync: {num_of_blocks}");
let poller = self.poller.clone();
let poller = self.optimal_poller().clone();
let mut blocks =
std::pin::pin!(poller.poll_block_range(last_synced_block.saturating_add(1)..=block_id));

View File

@ -8,8 +8,7 @@ use clap::{CommandFactory as _, Parser as _};
use wallet::{
WalletCore,
cli::{Args, execute_continuous_run, execute_subcommand, read_password_from_stdin},
config::WalletConfigOverrides,
helperfunctions::{fetch_config_path, fetch_persistent_storage_path},
helperfunctions::{fetch_config_path, fetch_metrics_path, fetch_persistent_storage_path},
};
// TODO #169: We have sample configs for sequencer, but not for wallet
@ -21,7 +20,7 @@ use wallet::{
async fn main() -> Result<()> {
let Args {
continuous_run,
auth,
auth: _auth,
command,
} = Args::parse();
@ -30,16 +29,11 @@ async fn main() -> Result<()> {
let config_path = fetch_config_path().context("Could not fetch config path")?;
let storage_path =
fetch_persistent_storage_path().context("Could not fetch persistent storage path")?;
// Override basic auth if provided via CLI
let config_overrides = WalletConfigOverrides {
basic_auth: auth.map(|auth| auth.parse()).transpose()?.map(Some),
..Default::default()
};
let metrics_path = fetch_metrics_path().context("Could not fetch metrics path")?;
if let Some(command) = command {
let mut wallet = if storage_path.exists() {
WalletCore::new_update_chain(config_path, storage_path, Some(config_overrides))?
WalletCore::new_update_chain(config_path, storage_path, metrics_path, None)?
} else {
// TODO: Maybe move to `WalletCore::from_env()` or similar?
@ -49,7 +43,8 @@ async fn main() -> Result<()> {
let (wallet, mnemonic) = WalletCore::new_init_storage(
config_path,
storage_path,
Some(config_overrides),
metrics_path,
None,
&password,
)?;
@ -68,7 +63,7 @@ async fn main() -> Result<()> {
Ok(())
} else if continuous_run {
let mut wallet =
WalletCore::new_update_chain(config_path, storage_path, Some(config_overrides))?;
WalletCore::new_update_chain(config_path, storage_path, metrics_path, None)?;
execute_continuous_run(&mut wallet).await
} else {
let help = Args::command().render_long_help();

View File

@ -0,0 +1,59 @@
use anyhow::{Context, Result};
use sequencer_service_rpc::{SequencerClient, SequencerClientBuilder};
use serde::{Deserialize, Serialize};
use crate::config::SequencerConnectionData;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Metrics {
pub latency_avg: u64,
pub latency_var: u64,
pub last_block_id: u64,
}
#[derive(Clone)]
pub struct MultiSequencerClient {
pub client_list: Vec<SequencerClient>,
}
impl MultiSequencerClient {
pub fn new(conn_data: &[SequencerConnectionData]) -> Result<Self> {
let mut client_list = vec![];
for SequencerConnectionData {
sequencer_addr,
basic_auth,
} in conn_data
{
let sequencer_client = {
let mut builder = SequencerClientBuilder::default();
if let Some(basic_auth) = &basic_auth {
builder = builder.set_headers(
std::iter::once((
"Authorization".parse().expect("Header name is valid"),
format!("Basic {basic_auth}")
.parse()
.context("Invalid basic auth format")?,
))
.collect(),
);
}
builder
.build(sequencer_addr)
.context("Failed to create sequencer client")?
};
client_list.push(sequencer_client);
}
Ok(Self { client_list })
}
pub fn optimal_client_ref(&self, _metrics: &[Metrics]) -> &SequencerClient {
todo!();
}
pub fn optimal_client_clone(&self, _metrics: &[Metrics]) -> SequencerClient {
todo!();
}
}