feat: update rust to 1.94.0

This commit is contained in:
Daniil Polyakov 2026-03-10 00:17:43 +03:00
parent 3b0e842a42
commit 252848a145
68 changed files with 440 additions and 436 deletions

View File

@ -14,7 +14,7 @@ use reqwest::{Client, Url};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use tokio_retry::Retry; use tokio_retry::Retry;
/// Fibonacci backoff retry strategy configuration /// Fibonacci backoff retry strategy configuration.
#[derive(Debug, Copy, Clone, Serialize, Deserialize)] #[derive(Debug, Copy, Clone, Serialize, Deserialize)]
pub struct BackoffConfig { pub struct BackoffConfig {
#[serde(with = "humantime_serde")] #[serde(with = "humantime_serde")]

View File

@ -111,14 +111,14 @@ impl From<Block> for HashableBlockData {
} }
} }
/// Helper struct for account (de-)serialization /// Helper struct for account (de-)serialization.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountInitialData { pub struct AccountInitialData {
pub account_id: AccountId, pub account_id: AccountId,
pub balance: u128, pub balance: u128,
} }
/// Helper struct to (de-)serialize initial commitments /// Helper struct to (de-)serialize initial commitments.
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CommitmentsInitialData { pub struct CommitmentsInitialData {
pub npk: nssa_core::NullifierPublicKey, pub npk: nssa_core::NullifierPublicKey,

View File

@ -14,11 +14,11 @@ pub struct RpcParseError(pub String);
pub struct RpcError { pub struct RpcError {
#[serde(flatten)] #[serde(flatten)]
pub error_struct: Option<RpcErrorKind>, pub error_struct: Option<RpcErrorKind>,
/// Deprecated please use the `error_struct` instead /// Deprecated please use the `error_struct` instead.
pub code: i64, pub code: i64,
/// Deprecated please use the `error_struct` instead /// Deprecated please use the `error_struct` instead.
pub message: String, pub message: String,
/// Deprecated please use the `error_struct` instead /// Deprecated please use the `error_struct` instead.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>, pub data: Option<Value>,
} }
@ -38,7 +38,7 @@ pub enum RpcRequestValidationErrorKind {
ParseError { error_message: String }, ParseError { error_message: String },
} }
/// A general Server Error /// A general Server Error.
#[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)] #[derive(serde::Serialize, serde::Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum ServerError { pub enum ServerError {
Timeout, Timeout,
@ -101,7 +101,7 @@ impl RpcError {
} }
/// Helper method to define extract `INTERNAL_ERROR` in separate `RpcErrorKind` /// Helper method to define extract `INTERNAL_ERROR` in separate `RpcErrorKind`
/// Returns `HANDLER_ERROR` if the error is not internal one /// Returns `HANDLER_ERROR` if the error is not internal one.
#[must_use] #[must_use]
pub fn new_internal_or_handler_error(error_data: Option<Value>, error_struct: Value) -> Self { pub fn new_internal_or_handler_error(error_data: Option<Value>, error_struct: Value) -> Self {
if error_struct["name"] == "INTERNAL_ERROR" { if error_struct["name"] == "INTERNAL_ERROR" {

View File

@ -210,7 +210,7 @@ pub enum Message {
/// message. /// message.
/// ///
/// This variant has no direct constructor and is expected to be constructed manually. /// This variant has no direct constructor and is expected to be constructed manually.
Batch(Vec<Message>), Batch(Vec<Self>),
/// An unmatched sub entry in a `Batch`. /// An unmatched sub entry in a `Batch`.
/// ///
/// When there's a `Batch` and an element doesn't comform to the JSONRPC 2.0 format, that one /// When there's a `Batch` and an element doesn't comform to the JSONRPC 2.0 format, that one
@ -363,7 +363,7 @@ mod tests {
use super::*; use super::*;
/// Test serialization and deserialization of the Message /// Test serialization and deserialization of the Message.
/// ///
/// We first deserialize it from a string. That way we check deserialization works. /// We first deserialize it from a string. That way we check deserialization works.
/// But since serialization doesn't have to produce the exact same result (order, spaces, …), /// But since serialization doesn't have to produce the exact same result (order, spaces, …),
@ -488,7 +488,7 @@ mod tests {
/// ///
/// Check that the given JSON string parses, but is not recognized as a valid RPC message. /// Check that the given JSON string parses, but is not recognized as a valid RPC message.
/// ///
/// Test things that are almost but not entirely JSONRPC are rejected /// Test things that are almost but not entirely JSONRPC are rejected.
/// ///
/// The reject is done by returning it as Unmatched. /// The reject is done by returning it as Unmatched.
#[test] #[test]
@ -521,7 +521,7 @@ mod tests {
} }
} }
/// Test some non-trivial aspects of the constructors /// Test some non-trivial aspects of the constructors.
/// ///
/// This doesn't have a full coverage, because there's not much to actually test there. /// This doesn't have a full coverage, because there's not much to actually test there.
/// Most of it is related to the ids. /// Most of it is related to the ids.

View File

@ -84,7 +84,7 @@ pub struct GetBlockDataRequest {
pub block_id: u64, pub block_id: u64,
} }
/// Get a range of blocks from `start_block_id` to `end_block_id` (inclusive) /// Get a range of blocks from `start_block_id` to `end_block_id` (inclusive).
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct GetBlockRangeDataRequest { pub struct GetBlockRangeDataRequest {
pub start_block_id: u64, pub start_block_id: u64,
@ -213,7 +213,7 @@ pub struct GetProgramIdsResponse {
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
pub struct GetInitialTestnetAccountsResponse { pub struct GetInitialTestnetAccountsResponse {
/// Hex encoded account id /// Hex encoded account id.
pub account_id: String, pub account_id: String,
pub balance: u64, pub balance: u64,
} }

View File

@ -105,7 +105,7 @@ impl SequencerClient {
} }
} }
/// Get block data at `block_id` from sequencer /// Get block data at `block_id` from sequencer.
pub async fn get_block( pub async fn get_block(
&self, &self,
block_id: u64, block_id: u64,
@ -141,7 +141,7 @@ impl SequencerClient {
Ok(resp_deser) Ok(resp_deser)
} }
/// Get last known `blokc_id` from sequencer /// Get last known `blokc_id` from sequencer.
pub async fn get_last_block(&self) -> Result<GetLastBlockResponse, SequencerClientError> { pub async fn get_last_block(&self) -> Result<GetLastBlockResponse, SequencerClientError> {
let block_req = GetLastBlockRequest {}; let block_req = GetLastBlockRequest {};
@ -225,7 +225,7 @@ impl SequencerClient {
Ok(resp_deser) Ok(resp_deser)
} }
/// Send transaction to sequencer /// Send transaction to sequencer.
pub async fn send_tx_public( pub async fn send_tx_public(
&self, &self,
transaction: nssa::PublicTransaction, transaction: nssa::PublicTransaction,
@ -245,7 +245,7 @@ impl SequencerClient {
Ok(resp_deser) Ok(resp_deser)
} }
/// Send transaction to sequencer /// Send transaction to sequencer.
pub async fn send_tx_private( pub async fn send_tx_private(
&self, &self,
transaction: nssa::PrivacyPreservingTransaction, transaction: nssa::PrivacyPreservingTransaction,
@ -265,7 +265,7 @@ impl SequencerClient {
Ok(resp_deser) Ok(resp_deser)
} }
/// Get genesis id from sequencer /// Get genesis id from sequencer.
pub async fn get_genesis_id(&self) -> Result<GetGenesisIdResponse, SequencerClientError> { pub async fn get_genesis_id(&self) -> Result<GetGenesisIdResponse, SequencerClientError> {
let genesis_req = GetGenesisIdRequest {}; let genesis_req = GetGenesisIdRequest {};
@ -281,7 +281,7 @@ impl SequencerClient {
Ok(resp_deser) Ok(resp_deser)
} }
/// Get initial testnet accounts from sequencer /// Get initial testnet accounts from sequencer.
pub async fn get_initial_testnet_accounts( pub async fn get_initial_testnet_accounts(
&self, &self,
) -> Result<Vec<GetInitialTestnetAccountsResponse>, SequencerClientError> { ) -> Result<Vec<GetInitialTestnetAccountsResponse>, SequencerClientError> {
@ -299,7 +299,7 @@ impl SequencerClient {
Ok(resp_deser) Ok(resp_deser)
} }
/// Get proof for commitment /// Get proof for commitment.
pub async fn get_proof_for_commitment( pub async fn get_proof_for_commitment(
&self, &self,
commitment: nssa_core::Commitment, commitment: nssa_core::Commitment,
@ -339,7 +339,7 @@ impl SequencerClient {
Ok(resp_deser) Ok(resp_deser)
} }
/// Get Ids of the programs used by the node /// Get Ids of the programs used by the node.
pub async fn get_program_ids( pub async fn get_program_ids(
&self, &self,
) -> Result<HashMap<String, ProgramId>, SequencerClientError> { ) -> Result<HashMap<String, ProgramId>, SequencerClientError> {

View File

@ -15,13 +15,13 @@ pub fn sequencer_sign_key_for_testing() -> nssa::PrivateKey {
// Dummy producers // Dummy producers
/// Produce dummy block with /// Produce dummy block with.
/// ///
/// `id` - block id, provide zero for genesis /// `id` - block id, provide zero for genesis.
/// ///
/// `prev_hash` - hash of previous block, provide None for genesis /// `prev_hash` - hash of previous block, provide None for genesis.
/// ///
/// `transactions` - vector of `EncodedTransaction` objects /// `transactions` - vector of `EncodedTransaction` objects.
#[must_use] #[must_use]
pub fn produce_dummy_block( pub fn produce_dummy_block(
id: u64, id: u64,

View File

@ -26,7 +26,7 @@ type Instruction = (u8, Vec<u8>);
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
struct Cli { struct Cli {
/// Path to program binary /// Path to program binary.
program_path: String, program_path: String,
#[command(subcommand)] #[command(subcommand)]
@ -35,7 +35,7 @@ struct Cli {
#[derive(Subcommand, Debug)] #[derive(Subcommand, Debug)]
enum Command { enum Command {
/// Write instruction into one account /// Write instruction into one account.
WritePublic { WritePublic {
account_id: String, account_id: String,
greeting: String, greeting: String,
@ -44,7 +44,7 @@ enum Command {
account_id: String, account_id: String,
greeting: String, greeting: String,
}, },
/// Move data between two accounts /// Move data between two accounts.
MoveDataPublicToPublic { MoveDataPublicToPublic {
from: String, from: String,
to: String, to: String,

View File

@ -1,4 +1,4 @@
FROM rust:1.91.1-trixie AS builder FROM rust:1.94.0-trixie AS builder
# Install cargo-binstall, which makes it easier to install other # Install cargo-binstall, which makes it easier to install other
# cargo extensions like cargo-leptos # cargo extensions like cargo-leptos

View File

@ -2,7 +2,7 @@ use indexer_service_protocol::{Account, AccountId, Block, BlockId, HashType, Tra
use leptos::prelude::*; use leptos::prelude::*;
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
/// Search results structure /// Search results structure.
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct SearchResults { pub struct SearchResults {
pub blocks: Vec<Block>, pub blocks: Vec<Block>,
@ -10,7 +10,7 @@ pub struct SearchResults {
pub accounts: Vec<(AccountId, Account)>, pub accounts: Vec<(AccountId, Account)>,
} }
/// RPC client type /// RPC client type.
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
pub type IndexerRpcClient = jsonrpsee::http_client::HttpClient; pub type IndexerRpcClient = jsonrpsee::http_client::HttpClient;
@ -142,7 +142,7 @@ pub async fn get_transactions_by_account(
.map_err(|e| ServerFnError::ServerError(format!("RPC error: {e}"))) .map_err(|e| ServerFnError::ServerError(format!("RPC error: {e}")))
} }
/// Create the RPC client for the indexer service (server-side only) /// Create the RPC client for the indexer service (server-side only).
#[cfg(feature = "ssr")] #[cfg(feature = "ssr")]
pub fn create_indexer_rpc_client(url: &url::Url) -> Result<IndexerRpcClient, String> { pub fn create_indexer_rpc_client(url: &url::Url) -> Result<IndexerRpcClient, String> {
use jsonrpsee::http_client::HttpClientBuilder; use jsonrpsee::http_client::HttpClientBuilder;

View File

@ -4,7 +4,7 @@ use leptos_router::components::A;
use crate::format_utils; use crate::format_utils;
/// Get CSS class for bedrock status /// Get CSS class for bedrock status.
const fn status_class(status: &BedrockStatus) -> &'static str { const fn status_class(status: &BedrockStatus) -> &'static str {
match status { match status {
BedrockStatus::Pending => "status-pending", BedrockStatus::Pending => "status-pending",

View File

@ -2,7 +2,7 @@ use indexer_service_protocol::Transaction;
use leptos::prelude::*; use leptos::prelude::*;
use leptos_router::components::A; use leptos_router::components::A;
/// Get transaction type name and CSS class /// Get transaction type name and CSS class.
const fn transaction_type_info(tx: &Transaction) -> (&'static str, &'static str) { const fn transaction_type_info(tx: &Transaction) -> (&'static str, &'static str) {
match tx { match tx {
Transaction::Public(_) => ("Public", "tx-type-public"), Transaction::Public(_) => ("Public", "tx-type-public"),

View File

@ -1,6 +1,6 @@
//! Formatting utilities for the explorer //! Formatting utilities for the explorer.
/// Format timestamp to human-readable string /// Format timestamp to human-readable string.
#[expect( #[expect(
clippy::integer_division, clippy::integer_division,
clippy::integer_division_remainder_used, clippy::integer_division_remainder_used,

View File

@ -16,7 +16,7 @@ async fn main() {
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[command(version, about, long_about = None)] #[command(version, about, long_about = None)]
struct Args { struct Args {
/// Indexer RPC URL /// Indexer RPC URL.
#[arg(long, env = "INDEXER_RPC_URL", default_value = "http://localhost:8779")] #[arg(long, env = "INDEXER_RPC_URL", default_value = "http://localhost:8779")]
indexer_rpc_url: url::Url, indexer_rpc_url: url::Url,
} }

View File

@ -27,13 +27,13 @@ pub struct ClientConfig {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IndexerConfig { pub struct IndexerConfig {
/// Home dir of sequencer storage /// Home dir of sequencer storage.
pub home: PathBuf, pub home: PathBuf,
/// List of initial accounts data /// List of initial accounts data.
pub initial_accounts: Vec<AccountInitialData>, pub initial_accounts: Vec<AccountInitialData>,
/// List of initial commitments /// List of initial commitments.
pub initial_commitments: Vec<CommitmentsInitialData>, pub initial_commitments: Vec<CommitmentsInitialData>,
/// Sequencers signing key /// Sequencers signing key.
pub signing_key: [u8; 32], pub signing_key: [u8; 32],
#[serde(with = "humantime_serde")] #[serde(with = "humantime_serde")]
pub consensus_info_polling_interval: Duration, pub consensus_info_polling_interval: Duration,

View File

@ -24,14 +24,14 @@ pub struct IndexerCore {
} }
#[derive(Clone)] #[derive(Clone)]
/// This struct represents one L1 block data fetched from backfilling /// This struct represents one L1 block data fetched from backfilling.
pub struct BackfillBlockData { pub struct BackfillBlockData {
l2_blocks: Vec<Block>, l2_blocks: Vec<Block>,
l1_header: HeaderId, l1_header: HeaderId,
} }
#[derive(Clone)] #[derive(Clone)]
/// This struct represents data fetched fom backfilling in one iteration /// This struct represents data fetched fom backfilling in one iteration.
pub struct BackfillData { pub struct BackfillData {
block_data: VecDeque<BackfillBlockData>, block_data: VecDeque<BackfillBlockData>,
curr_fin_l1_lib_header: HeaderId, curr_fin_l1_lib_header: HeaderId,
@ -187,7 +187,7 @@ impl IndexerCore {
} }
/// WARNING: depending on channel state, /// WARNING: depending on channel state,
/// may take indefinite amount of time /// may take indefinite amount of time.
pub async fn search_for_channel_start(&self) -> Result<BackfillData> { pub async fn search_for_channel_start(&self) -> Result<BackfillData> {
let mut curr_last_l1_lib_header = self.get_lib().await?; let mut curr_last_l1_lib_header = self.get_lib().await?;
let mut backfill_start = curr_last_l1_lib_header; let mut backfill_start = curr_last_l1_lib_header;

View File

@ -1,5 +1,5 @@
# Chef stage - uses pre-built cargo-chef image # Chef stage - uses pre-built cargo-chef image
FROM lukemathwalker/cargo-chef:latest-rust-1.91.1-slim-trixie AS chef FROM lukemathwalker/cargo-chef:latest-rust-1.94.0-slim-trixie AS chef
# Install build dependencies # Install build dependencies
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \

View File

@ -1,4 +1,4 @@
//! Conversions between `indexer_service_protocol` types and `nssa/nssa_core` types //! Conversions between `indexer_service_protocol` types and `nssa/nssa_core` types.
use crate::{ use crate::{
Account, AccountId, BedrockStatus, Block, BlockBody, BlockHeader, Ciphertext, Commitment, Account, AccountId, BedrockStatus, Block, BlockBody, BlockHeader, Ciphertext, Commitment,

View File

@ -191,7 +191,7 @@ pub enum Transaction {
} }
impl Transaction { impl Transaction {
/// Get the hash of the transaction /// Get the hash of the transaction.
#[expect(clippy::same_name_method, reason = "This is handy")] #[expect(clippy::same_name_method, reason = "This is handy")]
#[must_use] #[must_use]
pub const fn hash(&self) -> &self::HashType { pub const fn hash(&self) -> &self::HashType {

View File

@ -368,7 +368,7 @@ impl Drop for TestContext {
} }
} }
/// A test context to be used in normal #[test] tests /// A test context to be used in normal #[test] tests.
pub struct BlockingTestContext { pub struct BlockingTestContext {
ctx: Option<TestContext>, ctx: Option<TestContext>,
runtime: tokio::runtime::Runtime, runtime: tokio::runtime::Runtime,

View File

@ -17,7 +17,7 @@ use nssa::AccountId;
use tokio::test; use tokio::test;
use wallet::cli::{Command, programs::native_token_transfer::AuthTransferSubcommand}; use wallet::cli::{Command, programs::native_token_transfer::AuthTransferSubcommand};
/// Timeout in milliseconds to reliably await for block finalization /// Timeout in milliseconds to reliably await for block finalization.
const L2_TO_L1_TIMEOUT_MILLIS: u64 = 600_000; const L2_TO_L1_TIMEOUT_MILLIS: u64 = 600_000;
#[test] #[test]

View File

@ -12,7 +12,7 @@ use crate::key_management::{
pub struct ChildKeysPrivate { pub struct ChildKeysPrivate {
pub value: (KeyChain, nssa::Account), pub value: (KeyChain, nssa::Account),
pub ccc: [u8; 32], pub ccc: [u8; 32],
/// Can be [`None`] if root /// Can be [`None`] if root.
pub cci: Option<u32>, pub cci: Option<u32>,
} }

View File

@ -8,7 +8,7 @@ pub struct ChildKeysPublic {
pub csk: nssa::PrivateKey, pub csk: nssa::PrivateKey,
pub cpk: nssa::PublicKey, pub cpk: nssa::PublicKey,
pub ccc: [u8; 32], pub ccc: [u8; 32],
/// Can be [`None`] if root /// Can be [`None`] if root.
pub cci: Option<u32>, pub cci: Option<u32>,
} }

View File

@ -177,7 +177,7 @@ impl<N: KeyNode> KeyTree<N> {
/// For given `depth` adds children to a tree such that their `ChainIndex::depth(&self) < /// For given `depth` adds children to a tree such that their `ChainIndex::depth(&self) <
/// depth`. /// depth`.
/// ///
/// Tree must be empty before start /// Tree must be empty before start.
pub fn generate_tree_for_depth(&mut self, depth: u32) { pub fn generate_tree_for_depth(&mut self, depth: u32) {
let mut id_stack = vec![ChainIndex::root()]; let mut id_stack = vec![ChainIndex::root()];
@ -197,16 +197,16 @@ impl<N: KeyNode> KeyTree<N> {
} }
impl KeyTree<ChildKeysPrivate> { impl KeyTree<ChildKeysPrivate> {
/// Cleanup of all non-initialized accounts in a private tree /// Cleanup of all non-initialized accounts in a private tree.
/// ///
/// For given `depth` checks children to a tree such that their `ChainIndex::depth(&self) < /// For given `depth` checks children to a tree such that their `ChainIndex::depth(&self) <
/// depth`. /// depth`.
/// ///
/// If account is default, removes them. /// If account is default, removes them.
/// ///
/// Chain must be parsed for accounts beforehand /// Chain must be parsed for accounts beforehand.
/// ///
/// Fast, leaves gaps between accounts /// Fast, leaves gaps between accounts.
pub fn cleanup_tree_remove_uninit_for_depth(&mut self, depth: u32) { pub fn cleanup_tree_remove_uninit_for_depth(&mut self, depth: u32) {
let mut id_stack = vec![ChainIndex::root()]; let mut id_stack = vec![ChainIndex::root()];
@ -231,13 +231,13 @@ impl KeyTree<ChildKeysPrivate> {
} }
} }
/// Cleanup of non-initialized accounts in a private tree /// Cleanup of non-initialized accounts in a private tree.
/// ///
/// If account is default, removes them, stops at first non-default account. /// If account is default, removes them, stops at first non-default account.
/// ///
/// Walks through tree in lairs of same depth using `ChainIndex::chain_ids_at_depth()` /// Walks through tree in lairs of same depth using `ChainIndex::chain_ids_at_depth()`.
/// ///
/// Chain must be parsed for accounts beforehand /// Chain must be parsed for accounts beforehand.
/// ///
/// Slow, maintains tree consistency. /// Slow, maintains tree consistency.
pub fn cleanup_tree_remove_uninit_layered(&mut self, depth: u32) { pub fn cleanup_tree_remove_uninit_layered(&mut self, depth: u32) {
@ -259,14 +259,14 @@ impl KeyTree<ChildKeysPrivate> {
} }
impl KeyTree<ChildKeysPublic> { impl KeyTree<ChildKeysPublic> {
/// Cleanup of all non-initialized accounts in a public tree /// Cleanup of all non-initialized accounts in a public tree.
/// ///
/// For given `depth` checks children to a tree such that their `ChainIndex::depth(&self) < /// For given `depth` checks children to a tree such that their `ChainIndex::depth(&self) <
/// depth`. /// depth`.
/// ///
/// If account is default, removes them. /// If account is default, removes them.
/// ///
/// Fast, leaves gaps between accounts /// Fast, leaves gaps between accounts.
pub async fn cleanup_tree_remove_ininit_for_depth( pub async fn cleanup_tree_remove_ininit_for_depth(
&mut self, &mut self,
depth: u32, depth: u32,
@ -298,11 +298,11 @@ impl KeyTree<ChildKeysPublic> {
Ok(()) Ok(())
} }
/// Cleanup of non-initialized accounts in a public tree /// Cleanup of non-initialized accounts in a public tree.
/// ///
/// If account is default, removes them, stops at first non-default account. /// If account is default, removes them, stops at first non-default account.
/// ///
/// Walks through tree in lairs of same depth using `ChainIndex::chain_ids_at_depth()` /// Walks through tree in lairs of same depth using `ChainIndex::chain_ids_at_depth()`.
/// ///
/// Slow, maintains tree consistency. /// Slow, maintains tree consistency.
pub async fn cleanup_tree_remove_uninit_layered( pub async fn cleanup_tree_remove_uninit_layered(

View File

@ -1,9 +1,9 @@
/// Trait, that reperesents a Node in hierarchical key tree /// Trait, that reperesents a Node in hierarchical key tree.
pub trait KeyNode { pub trait KeyNode {
/// Tree root node /// Tree root node.
fn root(seed: [u8; 64]) -> Self; fn root(seed: [u8; 64]) -> Self;
/// `cci`'s child of node /// `cci`'s child of node.
#[must_use] #[must_use]
fn nth_child(&self, cci: u32) -> Self; fn nth_child(&self, cci: u32) -> Self;

View File

@ -12,7 +12,7 @@ pub mod secret_holders;
pub type PublicAccountSigningKey = [u8; 32]; pub type PublicAccountSigningKey = [u8; 32];
#[derive(Serialize, Deserialize, Clone, Debug)] #[derive(Serialize, Deserialize, Clone, Debug)]
/// Entrypoint to key management /// Entrypoint to key management.
pub struct KeyChain { pub struct KeyChain {
pub secret_spending_key: SecretSpendingKey, pub secret_spending_key: SecretSpendingKey,
pub private_key_holder: PrivateKeyHolder, pub private_key_holder: PrivateKeyHolder,

View File

@ -14,14 +14,14 @@ pub type PublicKey = AffinePoint;
#[derive(Clone, Debug, Serialize, Deserialize)] #[derive(Clone, Debug, Serialize, Deserialize)]
pub struct NSSAUserData { pub struct NSSAUserData {
/// Default public accounts /// Default public accounts.
pub default_pub_account_signing_keys: BTreeMap<nssa::AccountId, nssa::PrivateKey>, pub default_pub_account_signing_keys: BTreeMap<nssa::AccountId, nssa::PrivateKey>,
/// Default private accounts /// Default private accounts.
pub default_user_private_accounts: pub default_user_private_accounts:
BTreeMap<nssa::AccountId, (KeyChain, nssa_core::account::Account)>, BTreeMap<nssa::AccountId, (KeyChain, nssa_core::account::Account)>,
/// Tree of public keys /// Tree of public keys.
pub public_key_tree: KeyTreePublic, pub public_key_tree: KeyTreePublic,
/// Tree of private keys /// Tree of private keys.
pub private_key_tree: KeyTreePrivate, pub private_key_tree: KeyTreePrivate,
} }
@ -84,9 +84,9 @@ impl NSSAUserData {
}) })
} }
/// Generated new private key for public transaction signatures /// Generated new private key for public transaction signatures.
/// ///
/// Returns the `account_id` of new account /// Returns the `account_id` of new account.
pub fn generate_new_public_transaction_private_key( pub fn generate_new_public_transaction_private_key(
&mut self, &mut self,
parent_cci: Option<ChainIndex>, parent_cci: Option<ChainIndex>,
@ -103,7 +103,7 @@ impl NSSAUserData {
} }
} }
/// Returns the signing key for public transaction signatures /// Returns the signing key for public transaction signatures.
#[must_use] #[must_use]
pub fn get_pub_account_signing_key( pub fn get_pub_account_signing_key(
&self, &self,
@ -114,9 +114,9 @@ impl NSSAUserData {
.or_else(|| self.public_key_tree.get_node(account_id).map(Into::into)) .or_else(|| self.public_key_tree.get_node(account_id).map(Into::into))
} }
/// Generated new private key for privacy preserving transactions /// Generated new private key for privacy preserving transactions.
/// ///
/// Returns the `account_id` of new account /// Returns the `account_id` of new account.
pub fn generate_new_privacy_preserving_transaction_key_chain( pub fn generate_new_privacy_preserving_transaction_key_chain(
&mut self, &mut self,
parent_cci: Option<ChainIndex>, parent_cci: Option<ChainIndex>,
@ -133,7 +133,7 @@ impl NSSAUserData {
} }
} }
/// Returns the signing key for public transaction signatures /// Returns the signing key for public transaction signatures.
#[must_use] #[must_use]
pub fn get_private_account( pub fn get_private_account(
&self, &self,
@ -144,7 +144,7 @@ impl NSSAUserData {
.or_else(|| self.private_key_tree.get_node(account_id).map(Into::into)) .or_else(|| self.private_key_tree.get_node(account_id).map(Into::into))
} }
/// Returns the signing key for public transaction signatures /// Returns the signing key for public transaction signatures.
pub fn get_private_account_mut( pub fn get_private_account_mut(
&mut self, &mut self,
account_id: &nssa::AccountId, account_id: &nssa::AccountId,

View File

@ -38,7 +38,7 @@ impl<T> MemPool<T> {
} }
} }
/// Push an item to the front of the mempool (will be popped first) /// Push an item to the front of the mempool (will be popped first).
pub fn push_front(&mut self, item: T) { pub fn push_front(&mut self, item: T) {
self.front_buffer.push(item); self.front_buffer.push(item);
} }
@ -53,7 +53,7 @@ impl<T> MemPoolHandle<T> {
Self { sender } Self { sender }
} }
/// Send an item to the mempool blocking if max size is reached /// Send an item to the mempool blocking if max size is reached.
pub async fn push(&self, item: T) -> Result<(), tokio::sync::mpsc::error::SendError<T>> { pub async fn push(&self, item: T) -> Result<(), tokio::sync::mpsc::error::SendError<T>> {
self.sender.send(item).await self.sender.send(item).await
} }

View File

@ -15,7 +15,7 @@ pub mod data;
pub type Nonce = u128; pub type Nonce = u128;
/// Account to be used both in public and private contexts /// Account to be used both in public and private contexts.
#[derive( #[derive(
Default, Clone, Eq, PartialEq, Serialize, Deserialize, BorshSerialize, BorshDeserialize, Default, Clone, Eq, PartialEq, Serialize, Deserialize, BorshSerialize, BorshDeserialize,
)] )]

View File

@ -16,7 +16,7 @@ pub const DUMMY_COMMITMENT: Commitment = Commitment([
165, 33, 34, 172, 227, 30, 215, 20, 85, 47, 230, 29, 165, 33, 34, 172, 227, 30, 215, 20, 85, 47, 230, 29,
]); ]);
/// The hash of the dummy commitment /// The hash of the dummy commitment.
/// ```python /// ```python
/// from hashlib import sha256 /// from hashlib import sha256
/// hasher = sha256() /// hasher = sha256()
@ -50,7 +50,7 @@ impl std::fmt::Debug for Commitment {
impl Commitment { impl Commitment {
/// Generates the commitment to a private account owned by user for npk: /// Generates the commitment to a private account owned by user for npk:
/// SHA256(npk || `program_owner` || balance || nonce || SHA256(data)) /// SHA256(npk || `program_owner` || balance || nonce || SHA256(data)).
#[must_use] #[must_use]
pub fn new(npk: &NullifierPublicKey, account: &Account) -> Self { pub fn new(npk: &NullifierPublicKey, account: &Account) -> Self {
let mut bytes = Vec::new(); let mut bytes = Vec::new();
@ -78,7 +78,7 @@ pub type CommitmentSetDigest = [u8; 32];
pub type MembershipProof = (usize, Vec<[u8; 32]>); pub type MembershipProof = (usize, Vec<[u8; 32]>);
/// Computes the resulting digest for the given membership proof and corresponding commitment /// Computes the resulting digest for the given membership proof and corresponding commitment.
#[must_use] #[must_use]
pub fn compute_digest_for_path( pub fn compute_digest_for_path(
commitment: &Commitment, commitment: &Commitment,

View File

@ -53,10 +53,10 @@ impl From<(&ProgramId, &PdaSeed)> for AccountId {
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] #[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]
pub struct ChainedCall { pub struct ChainedCall {
/// The program ID of the program to execute /// The program ID of the program to execute.
pub program_id: ProgramId, pub program_id: ProgramId,
pub pre_states: Vec<AccountWithMetadata>, pub pre_states: Vec<AccountWithMetadata>,
/// The instruction data to pass /// The instruction data to pass.
pub instruction_data: InstructionData, pub instruction_data: InstructionData,
pub pda_seeds: Vec<PdaSeed>, pub pda_seeds: Vec<PdaSeed>,
} }
@ -133,18 +133,18 @@ impl AccountPostState {
self.claim self.claim
} }
/// Returns the underlying account /// Returns the underlying account.
#[must_use] #[must_use]
pub const fn account(&self) -> &Account { pub const fn account(&self) -> &Account {
&self.account &self.account
} }
/// Returns the underlying account /// Returns the underlying account.
pub const fn account_mut(&mut self) -> &mut Account { pub const fn account_mut(&mut self) -> &mut Account {
&mut self.account &mut self.account
} }
/// Consumes the post state and returns the underlying account /// Consumes the post state and returns the underlying account.
#[must_use] #[must_use]
pub fn into_account(self) -> Account { pub fn into_account(self) -> Account {
self.account self.account
@ -154,9 +154,9 @@ impl AccountPostState {
#[derive(Serialize, Deserialize, Clone)] #[derive(Serialize, Deserialize, Clone)]
#[cfg_attr(any(feature = "host", test), derive(Debug, PartialEq, Eq))] #[cfg_attr(any(feature = "host", test), derive(Debug, PartialEq, Eq))]
pub struct ProgramOutput { pub struct ProgramOutput {
/// The instruction data the program received to produce this output /// The instruction data the program received to produce this output.
pub instruction_data: InstructionData, pub instruction_data: InstructionData,
/// The account pre states the program received to produce this output /// The account pre states the program received to produce this output.
pub pre_states: Vec<AccountWithMetadata>, pub pre_states: Vec<AccountWithMetadata>,
pub post_states: Vec<AccountPostState>, pub post_states: Vec<AccountPostState>,
pub chained_calls: Vec<ChainedCall>, pub chained_calls: Vec<ChainedCall>,
@ -248,7 +248,7 @@ pub fn write_nssa_outputs_with_chained_call(
env::commit(&output); env::commit(&output);
} }
/// Validates well-behaved program execution /// Validates well-behaved program execution.
/// ///
/// # Parameters /// # Parameters
/// - `pre_states`: The list of input accounts, each annotated with authorization metadata. /// - `pre_states`: The list of input accounts, each annotated with authorization metadata.

View File

@ -35,7 +35,7 @@ impl MerkleTree {
} }
} }
/// Number of levels required to hold all nodes /// Number of levels required to hold all nodes.
fn depth(&self) -> usize { fn depth(&self) -> usize {
usize::try_from(self.length.next_power_of_two().trailing_zeros()) usize::try_from(self.length.next_power_of_two().trailing_zeros())
.expect("u32 fits in usize") .expect("u32 fits in usize")
@ -70,7 +70,7 @@ impl MerkleTree {
} }
/// Reallocates storage of Merkle tree for double capacity. /// Reallocates storage of Merkle tree for double capacity.
/// The current tree is embedded into the new tree as a subtree /// The current tree is embedded into the new tree as a subtree.
fn reallocate_to_double_capacity(&mut self) { fn reallocate_to_double_capacity(&mut self) {
let old_capacity = self.capacity; let old_capacity = self.capacity;
let new_capacity = old_capacity << 1; let new_capacity = old_capacity << 1;
@ -142,7 +142,7 @@ impl MerkleTree {
} }
} }
/// Compute parent as the hash of two child nodes /// Compute parent as the hash of two child nodes.
fn hash_two(left: &Node, right: &Node) -> Node { fn hash_two(left: &Node, right: &Node) -> Node {
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();
hasher.update(left); hasher.update(left);

View File

@ -16,7 +16,7 @@ use crate::{
state::MAX_NUMBER_CHAINED_CALLS, state::MAX_NUMBER_CHAINED_CALLS,
}; };
/// Proof of the privacy preserving execution circuit /// Proof of the privacy preserving execution circuit.
#[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)] #[derive(Debug, Clone, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
pub struct Proof(pub(crate) Vec<u8>); pub struct Proof(pub(crate) Vec<u8>);

View File

@ -32,7 +32,7 @@ impl EncryptedAccountData {
} }
} }
/// Computes the tag as the first byte of SHA256("/NSSA/v0.2/ViewTag/" || Npk || vpk) /// Computes the tag as the first byte of SHA256("/NSSA/v0.2/ViewTag/" || Npk || vpk).
#[must_use] #[must_use]
pub fn compute_view_tag(npk: &NullifierPublicKey, vpk: &ViewingPublicKey) -> ViewTag { pub fn compute_view_tag(npk: &NullifierPublicKey, vpk: &ViewingPublicKey) -> ViewTag {
let mut hasher = Sha256::new(); let mut hasher = Sha256::new();

View File

@ -12,7 +12,7 @@ use crate::{
}; };
/// Maximum number of cycles for a public execution. /// Maximum number of cycles for a public execution.
/// TODO: Make this variable when fees are implemented /// TODO: Make this variable when fees are implemented.
const MAX_NUM_CYCLES_PUBLIC_EXECUTION: u64 = 1024 * 1024 * 32; // 32M cycles const MAX_NUM_CYCLES_PUBLIC_EXECUTION: u64 = 1024 * 1024 * 32; // 32M cycles
#[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)] #[derive(Clone, Debug, PartialEq, Eq, BorshSerialize, BorshDeserialize)]
@ -74,7 +74,7 @@ impl Program {
Ok(program_output) Ok(program_output)
} }
/// Writes inputs to `env_builder` in the order expected by the programs /// Writes inputs to `env_builder` in the order expected by the programs.
pub(crate) fn write_inputs( pub(crate) fn write_inputs(
pre_states: &[AccountWithMetadata], pre_states: &[AccountWithMetadata],
instruction_data: &[u32], instruction_data: &[u32],
@ -137,7 +137,7 @@ mod tests {
}; };
impl Program { impl Program {
/// A program that changes the nonce of an account /// A program that changes the nonce of an account.
#[must_use] #[must_use]
pub fn nonce_changer_program() -> Self { pub fn nonce_changer_program() -> Self {
use test_program_methods::{NONCE_CHANGER_ELF, NONCE_CHANGER_ID}; use test_program_methods::{NONCE_CHANGER_ELF, NONCE_CHANGER_ID};
@ -148,7 +148,7 @@ mod tests {
} }
} }
/// A program that produces more output accounts than the inputs it received /// A program that produces more output accounts than the inputs it received.
#[must_use] #[must_use]
pub fn extra_output_program() -> Self { pub fn extra_output_program() -> Self {
use test_program_methods::{EXTRA_OUTPUT_ELF, EXTRA_OUTPUT_ID}; use test_program_methods::{EXTRA_OUTPUT_ELF, EXTRA_OUTPUT_ID};
@ -159,7 +159,7 @@ mod tests {
} }
} }
/// A program that produces less output accounts than the inputs it received /// A program that produces less output accounts than the inputs it received.
#[must_use] #[must_use]
pub fn missing_output_program() -> Self { pub fn missing_output_program() -> Self {
use test_program_methods::{MISSING_OUTPUT_ELF, MISSING_OUTPUT_ID}; use test_program_methods::{MISSING_OUTPUT_ELF, MISSING_OUTPUT_ID};
@ -170,7 +170,7 @@ mod tests {
} }
} }
/// A program that changes the program owner of an account to [0, 1, 2, 3, 4, 5, 6, 7] /// A program that changes the program owner of an account to [0, 1, 2, 3, 4, 5, 6, 7].
#[must_use] #[must_use]
pub fn program_owner_changer() -> Self { pub fn program_owner_changer() -> Self {
use test_program_methods::{PROGRAM_OWNER_CHANGER_ELF, PROGRAM_OWNER_CHANGER_ID}; use test_program_methods::{PROGRAM_OWNER_CHANGER_ELF, PROGRAM_OWNER_CHANGER_ID};
@ -181,7 +181,7 @@ mod tests {
} }
} }
/// A program that transfers balance without caring about authorizations /// A program that transfers balance without caring about authorizations.
#[must_use] #[must_use]
pub fn simple_balance_transfer() -> Self { pub fn simple_balance_transfer() -> Self {
use test_program_methods::{SIMPLE_BALANCE_TRANSFER_ELF, SIMPLE_BALANCE_TRANSFER_ID}; use test_program_methods::{SIMPLE_BALANCE_TRANSFER_ELF, SIMPLE_BALANCE_TRANSFER_ID};
@ -192,7 +192,7 @@ mod tests {
} }
} }
/// A program that modifies the data of an account /// A program that modifies the data of an account.
#[must_use] #[must_use]
pub fn data_changer() -> Self { pub fn data_changer() -> Self {
use test_program_methods::{DATA_CHANGER_ELF, DATA_CHANGER_ID}; use test_program_methods::{DATA_CHANGER_ELF, DATA_CHANGER_ID};
@ -203,7 +203,7 @@ mod tests {
} }
} }
/// A program that mints balance /// A program that mints balance.
#[must_use] #[must_use]
pub fn minter() -> Self { pub fn minter() -> Self {
use test_program_methods::{MINTER_ELF, MINTER_ID}; use test_program_methods::{MINTER_ELF, MINTER_ID};
@ -214,7 +214,7 @@ mod tests {
} }
} }
/// A program that burns balance /// A program that burns balance.
#[must_use] #[must_use]
pub fn burner() -> Self { pub fn burner() -> Self {
use test_program_methods::{BURNER_ELF, BURNER_ID}; use test_program_methods::{BURNER_ELF, BURNER_ID};

View File

@ -10,7 +10,7 @@ pub struct TestVector {
} }
/// Test vectors from /// Test vectors from
/// <https://github.com/bitcoin/bips/blob/master/bip-0340/test-vectors.csv> /// <https://github.com/bitcoin/bips/blob/master/bip-0340/test-vectors.csv>.
// //
pub fn test_vectors() -> Vec<TestVector> { pub fn test_vectors() -> Vec<TestVector> {
vec![ vec![

View File

@ -29,7 +29,7 @@ impl CommitmentSet {
self.merkle_tree.root() self.merkle_tree.root()
} }
/// Queries the `CommitmentSet` for a membership proof of commitment /// Queries the `CommitmentSet` for a membership proof of commitment.
pub fn get_proof_for(&self, commitment: &Commitment) -> Option<MembershipProof> { pub fn get_proof_for(&self, commitment: &Commitment) -> Option<MembershipProof> {
let index = *self.commitments.get(commitment)?; let index = *self.commitments.get(commitment)?;
@ -363,7 +363,7 @@ pub mod tests {
self.public_state.insert(account_id, account); self.public_state.insert(account_id, account);
} }
/// Include test programs in the builtin programs map /// Include test programs in the builtin programs map.
#[must_use] #[must_use]
pub fn with_test_programs(mut self) -> Self { pub fn with_test_programs(mut self) -> Self {
self.insert_program(Program::nonce_changer_program()); self.insert_program(Program::nonce_changer_program());

View File

@ -40,7 +40,7 @@ impl Challenge {
} }
} }
/// A pinata program /// A pinata program.
fn main() { fn main() {
// Read input accounts. // Read input accounts.
// It is expected to receive only two accounts: [pinata_account, winner_account] // It is expected to receive only two accounts: [pinata_account, winner_account]

View File

@ -46,7 +46,7 @@ impl Challenge {
} }
} }
/// A pinata program /// A pinata program.
fn main() { fn main() {
// Read input accounts. // Read input accounts.
// It is expected to receive three accounts: [pinata_definition, pinata_token_holding, // It is expected to receive three accounts: [pinata_definition, pinata_token_holding,

View File

@ -26,7 +26,7 @@ pub enum Instruction {
amm_program_id: ProgramId, amm_program_id: ProgramId,
}, },
/// Adds liquidity to the Pool /// Adds liquidity to the Pool.
/// ///
/// Required accounts: /// Required accounts:
/// - AMM Pool (initialized) /// - AMM Pool (initialized)
@ -42,7 +42,7 @@ pub enum Instruction {
max_amount_to_add_token_b: u128, max_amount_to_add_token_b: u128,
}, },
/// Removes liquidity from the Pool /// Removes liquidity from the Pool.
/// ///
/// Required accounts: /// Required accounts:
/// - AMM Pool (initialized) /// - AMM Pool (initialized)
@ -85,11 +85,11 @@ pub struct PoolDefinition {
pub liquidity_pool_supply: u128, pub liquidity_pool_supply: u128,
pub reserve_a: u128, pub reserve_a: u128,
pub reserve_b: u128, pub reserve_b: u128,
/// Fees are currently not used /// Fees are currently not used.
pub fees: u128, pub fees: u128,
/// A pool becomes inactive (active = false) /// A pool becomes inactive (active = false)
/// once all of its liquidity has been removed (e.g., reserves are emptied and /// once all of its liquidity has been removed (e.g., reserves are emptied and
/// `liquidity_pool_supply` = 0) /// `liquidity_pool_supply` = 0).
pub active: bool, pub active: bool,
} }

View File

@ -29,7 +29,7 @@ pub enum Instruction {
/// - Token Metadata account (uninitialized). /// - Token Metadata account (uninitialized).
NewDefinitionWithMetadata { NewDefinitionWithMetadata {
new_definition: NewTokenDefinition, new_definition: NewTokenDefinition,
/// Boxed to avoid large enum variant size /// Boxed to avoid large enum variant size.
metadata: Box<NewTokenMetadata>, metadata: Box<NewTokenMetadata>,
}, },
@ -196,7 +196,7 @@ impl From<&TokenHolding> for Data {
pub struct NewTokenMetadata { pub struct NewTokenMetadata {
/// Metadata standard. /// Metadata standard.
pub standard: MetadataStandard, pub standard: MetadataStandard,
/// Pointer to off-chain metadata /// Pointer to off-chain metadata.
pub uri: String, pub uri: String,
/// Creators of the token. /// Creators of the token.
pub creators: String, pub creators: String,

View File

@ -1,5 +1,5 @@
# Should be kept in sync with Dockerfiles # Should be kept in sync with Dockerfiles
[toolchain] [toolchain]
channel = "1.91.1" channel = "1.94.0"
profile = "default" profile = "default"

View File

@ -74,7 +74,7 @@ pub trait BlockSettlementClientTrait: Clone {
} }
} }
/// A component that posts block data to logos blockchain /// A component that posts block data to logos blockchain.
#[derive(Clone)] #[derive(Clone)]
pub struct BlockSettlementClient { pub struct BlockSettlementClient {
client: BedrockClient, client: BedrockClient,

View File

@ -20,51 +20,51 @@ use url::Url;
// TODO: Provide default values // TODO: Provide default values
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
pub struct SequencerConfig { pub struct SequencerConfig {
/// Home dir of sequencer storage /// Home dir of sequencer storage.
pub home: PathBuf, pub home: PathBuf,
/// Override rust log (env var logging level) /// Override rust log (env var logging level).
pub override_rust_log: Option<String>, pub override_rust_log: Option<String>,
/// Genesis id /// Genesis id.
pub genesis_id: u64, pub genesis_id: u64,
/// If `True`, then adds random sequence of bytes to genesis block /// If `True`, then adds random sequence of bytes to genesis block.
pub is_genesis_random: bool, pub is_genesis_random: bool,
/// Maximum number of transactions in block /// Maximum number of transactions in block.
pub max_num_tx_in_block: usize, pub max_num_tx_in_block: usize,
/// Maximum block size (includes header and transactions) /// Maximum block size (includes header and transactions).
#[serde(default = "default_max_block_size")] #[serde(default = "default_max_block_size")]
pub max_block_size: ByteSize, pub max_block_size: ByteSize,
/// Mempool maximum size /// Mempool maximum size.
pub mempool_max_size: usize, pub mempool_max_size: usize,
/// Interval in which blocks produced /// Interval in which blocks produced.
#[serde(with = "humantime_serde")] #[serde(with = "humantime_serde")]
pub block_create_timeout: Duration, pub block_create_timeout: Duration,
/// Interval in which pending blocks are retried /// Interval in which pending blocks are retried.
#[serde(with = "humantime_serde")] #[serde(with = "humantime_serde")]
pub retry_pending_blocks_timeout: Duration, pub retry_pending_blocks_timeout: Duration,
/// Port to listen /// Port to listen.
pub port: u16, pub port: u16,
/// List of initial accounts data /// List of initial accounts data.
pub initial_accounts: Vec<AccountInitialData>, pub initial_accounts: Vec<AccountInitialData>,
/// List of initial commitments /// List of initial commitments.
pub initial_commitments: Vec<CommitmentsInitialData>, pub initial_commitments: Vec<CommitmentsInitialData>,
/// Sequencer own signing key /// Sequencer own signing key.
pub signing_key: [u8; 32], pub signing_key: [u8; 32],
/// Bedrock configuration options /// Bedrock configuration options.
pub bedrock_config: BedrockConfig, pub bedrock_config: BedrockConfig,
/// Indexer RPC URL /// Indexer RPC URL.
pub indexer_rpc_url: Url, pub indexer_rpc_url: Url,
} }
#[derive(Clone, Serialize, Deserialize)] #[derive(Clone, Serialize, Deserialize)]
pub struct BedrockConfig { pub struct BedrockConfig {
/// Fibonacci backoff retry strategy configuration /// Fibonacci backoff retry strategy configuration.
#[serde(default)] #[serde(default)]
pub backoff: BackoffConfig, pub backoff: BackoffConfig,
/// Bedrock channel ID /// Bedrock channel ID.
pub channel_id: ChannelId, pub channel_id: ChannelId,
/// Bedrock Url /// Bedrock Url.
pub node_url: Url, pub node_url: Url,
/// Bedrock auth /// Bedrock auth.
pub auth: Option<BasicAuth>, pub auth: Option<BasicAuth>,
} }

View File

@ -335,7 +335,7 @@ impl<BC: BlockSettlementClientTrait, IC: IndexerClientTrait> SequencerCore<BC, I
} }
} }
/// Load signing key from file or generate a new one if it doesn't exist /// Load signing key from file or generate a new one if it doesn't exist.
fn load_or_create_signing_key(path: &Path) -> Result<Ed25519Key> { fn load_or_create_signing_key(path: &Path) -> Result<Ed25519Key> {
if path.exists() { if path.exists() {
let key_bytes = std::fs::read(path)?; let key_bytes = std::fs::read(path)?;

View File

@ -77,7 +77,7 @@ impl<
} }
impl<BC: BlockSettlementClientTrait, IC: IndexerClientTrait> JsonHandler<BC, IC> { impl<BC: BlockSettlementClientTrait, IC: IndexerClientTrait> JsonHandler<BC, IC> {
/// Example of request processing /// Example of request processing.
fn process_temp_hello(request: Request) -> Result<Value, RpcErr> { fn process_temp_hello(request: Request) -> Result<Value, RpcErr> {
let _hello_request = HelloRequest::parse(Some(request.params))?; let _hello_request = HelloRequest::parse(Some(request.params))?;
@ -194,8 +194,8 @@ impl<BC: BlockSettlementClientTrait, IC: IndexerClientTrait> JsonHandler<BC, IC>
respond(response) respond(response)
} }
/// Returns the initial accounts for testnet /// Returns the initial accounts for testnet.
/// `ToDo`: Useful only for testnet and needs to be removed later /// `ToDo`: Useful only for testnet and needs to be removed later.
async fn get_initial_testnet_accounts(&self, request: Request) -> Result<Value, RpcErr> { async fn get_initial_testnet_accounts(&self, request: Request) -> Result<Value, RpcErr> {
let _get_initial_testnet_accounts_request = let _get_initial_testnet_accounts_request =
GetInitialTestnetAccountsRequest::parse(Some(request.params))?; GetInitialTestnetAccountsRequest::parse(Some(request.params))?;
@ -284,7 +284,7 @@ impl<BC: BlockSettlementClientTrait, IC: IndexerClientTrait> JsonHandler<BC, IC>
respond(response) respond(response)
} }
/// Returns the commitment proof, corresponding to commitment /// Returns the commitment proof, corresponding to commitment.
async fn process_get_proof_by_commitment(&self, request: Request) -> Result<Value, RpcErr> { async fn process_get_proof_by_commitment(&self, request: Request) -> Result<Value, RpcErr> {
let get_proof_req = GetProofForCommitmentRequest::parse(Some(request.params))?; let get_proof_req = GetProofForCommitmentRequest::parse(Some(request.params))?;

View File

@ -1,5 +1,5 @@
# Chef stage - uses pre-built cargo-chef image # Chef stage - uses pre-built cargo-chef image
FROM lukemathwalker/cargo-chef:latest-rust-1.91.1-slim-trixie AS chef FROM lukemathwalker/cargo-chef:latest-rust-1.94.0-slim-trixie AS chef
# Install dependencies # Install dependencies
RUN apt-get update && apt-get install -y \ RUN apt-get update && apt-get install -y \
@ -26,7 +26,7 @@ RUN ARCH=$(uname -m); \
else \ else \
echo "Using manual build for $ARCH"; \ echo "Using manual build for $ARCH"; \
git clone --depth 1 --branch release-3.0 https://github.com/risc0/risc0.git; \ git clone --depth 1 --branch release-3.0 https://github.com/risc0/risc0.git; \
git clone --depth 1 --branch r0.1.91.1 https://github.com/risc0/rust.git; \ git clone --depth 1 --branch r0.1.94.0 https://github.com/risc0/rust.git; \
cd /risc0; \ cd /risc0; \
cargo install --path rzup; \ cargo install --path rzup; \
rzup build --path /rust rust --verbose; \ rzup build --path /rust rust --verbose; \

View File

@ -21,7 +21,7 @@ pub const RUST_LOG: &str = "RUST_LOG";
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[clap(version)] #[clap(version)]
struct Args { struct Args {
/// Path to configs /// Path to configs.
home_dir: PathBuf, home_dir: PathBuf,
} }

View File

@ -11,46 +11,46 @@ use rocksdb::{
use crate::error::DbError; use crate::error::DbError;
/// Maximal size of stored blocks in base /// Maximal size of stored blocks in base.
/// ///
/// Used to control db size /// Used to control db size.
/// ///
/// Currently effectively unbounded. /// Currently effectively unbounded.
pub const BUFF_SIZE_ROCKSDB: usize = usize::MAX; pub const BUFF_SIZE_ROCKSDB: usize = usize::MAX;
/// Size of stored blocks cache in memory /// Size of stored blocks cache in memory.
/// ///
/// Keeping small to not run out of memory /// Keeping small to not run out of memory.
pub const CACHE_SIZE: usize = 1000; pub const CACHE_SIZE: usize = 1000;
/// Key base for storing metainformation about id of first block in db /// Key base for storing metainformation about id of first block in db.
pub const DB_META_FIRST_BLOCK_IN_DB_KEY: &str = "first_block_in_db"; pub const DB_META_FIRST_BLOCK_IN_DB_KEY: &str = "first_block_in_db";
/// Key base for storing metainformation about id of last current block in db /// Key base for storing metainformation about id of last current block in db.
pub const DB_META_LAST_BLOCK_IN_DB_KEY: &str = "last_block_in_db"; pub const DB_META_LAST_BLOCK_IN_DB_KEY: &str = "last_block_in_db";
/// Key base for storing metainformation about id of last observed L1 lib header in db /// Key base for storing metainformation about id of last observed L1 lib header in db.
pub const DB_META_LAST_OBSERVED_L1_LIB_HEADER_ID_IN_DB_KEY: &str = pub const DB_META_LAST_OBSERVED_L1_LIB_HEADER_ID_IN_DB_KEY: &str =
"last_observed_l1_lib_header_in_db"; "last_observed_l1_lib_header_in_db";
/// Key base for storing metainformation which describe if first block has been set /// Key base for storing metainformation which describe if first block has been set.
pub const DB_META_FIRST_BLOCK_SET_KEY: &str = "first_block_set"; pub const DB_META_FIRST_BLOCK_SET_KEY: &str = "first_block_set";
/// Key base for storing metainformation about the last breakpoint /// Key base for storing metainformation about the last breakpoint.
pub const DB_META_LAST_BREAKPOINT_ID: &str = "last_breakpoint_id"; pub const DB_META_LAST_BREAKPOINT_ID: &str = "last_breakpoint_id";
/// Interval between state breakpoints /// Interval between state breakpoints.
pub const BREAKPOINT_INTERVAL: u8 = 100; pub const BREAKPOINT_INTERVAL: u8 = 100;
/// Name of block column family /// Name of block column family.
pub const CF_BLOCK_NAME: &str = "cf_block"; pub const CF_BLOCK_NAME: &str = "cf_block";
/// Name of meta column family /// Name of meta column family.
pub const CF_META_NAME: &str = "cf_meta"; pub const CF_META_NAME: &str = "cf_meta";
/// Name of breakpoint column family /// Name of breakpoint column family.
pub const CF_BREAKPOINT_NAME: &str = "cf_breakpoint"; pub const CF_BREAKPOINT_NAME: &str = "cf_breakpoint";
/// Name of hash to id map column family /// Name of hash to id map column family.
pub const CF_HASH_TO_ID: &str = "cf_hash_to_id"; pub const CF_HASH_TO_ID: &str = "cf_hash_to_id";
/// Name of tx hash to id map column family /// Name of tx hash to id map column family.
pub const CF_TX_TO_ID: &str = "cf_tx_to_id"; pub const CF_TX_TO_ID: &str = "cf_tx_to_id";
/// Name of account meta column family /// Name of account meta column family.
pub const CF_ACC_META: &str = "cf_acc_meta"; pub const CF_ACC_META: &str = "cf_acc_meta";
/// Name of account id to tx hash map column family /// Name of account id to tx hash map column family.
pub const CF_ACC_TO_TX: &str = "cf_acc_to_tx"; pub const CF_ACC_TO_TX: &str = "cf_acc_to_tx";
pub type DbResult<T> = Result<T, DbError>; pub type DbResult<T> = Result<T, DbError>;

View File

@ -8,37 +8,37 @@ use rocksdb::{
use crate::error::DbError; use crate::error::DbError;
/// Maximal size of stored blocks in base /// Maximal size of stored blocks in base.
/// ///
/// Used to control db size /// Used to control db size.
/// ///
/// Currently effectively unbounded. /// Currently effectively unbounded.
pub const BUFF_SIZE_ROCKSDB: usize = usize::MAX; pub const BUFF_SIZE_ROCKSDB: usize = usize::MAX;
/// Size of stored blocks cache in memory /// Size of stored blocks cache in memory.
/// ///
/// Keeping small to not run out of memory /// Keeping small to not run out of memory.
pub const CACHE_SIZE: usize = 1000; pub const CACHE_SIZE: usize = 1000;
/// Key base for storing metainformation about id of first block in db /// Key base for storing metainformation about id of first block in db.
pub const DB_META_FIRST_BLOCK_IN_DB_KEY: &str = "first_block_in_db"; pub const DB_META_FIRST_BLOCK_IN_DB_KEY: &str = "first_block_in_db";
/// Key base for storing metainformation about id of last current block in db /// Key base for storing metainformation about id of last current block in db.
pub const DB_META_LAST_BLOCK_IN_DB_KEY: &str = "last_block_in_db"; pub const DB_META_LAST_BLOCK_IN_DB_KEY: &str = "last_block_in_db";
/// Key base for storing metainformation which describe if first block has been set /// Key base for storing metainformation which describe if first block has been set.
pub const DB_META_FIRST_BLOCK_SET_KEY: &str = "first_block_set"; pub const DB_META_FIRST_BLOCK_SET_KEY: &str = "first_block_set";
/// Key base for storing metainformation about the last finalized block on Bedrock /// Key base for storing metainformation about the last finalized block on Bedrock.
pub const DB_META_LAST_FINALIZED_BLOCK_ID: &str = "last_finalized_block_id"; pub const DB_META_LAST_FINALIZED_BLOCK_ID: &str = "last_finalized_block_id";
/// Key base for storing metainformation about the latest block meta /// Key base for storing metainformation about the latest block meta.
pub const DB_META_LATEST_BLOCK_META_KEY: &str = "latest_block_meta"; pub const DB_META_LATEST_BLOCK_META_KEY: &str = "latest_block_meta";
/// Key base for storing the NSSA state /// Key base for storing the NSSA state.
pub const DB_NSSA_STATE_KEY: &str = "nssa_state"; pub const DB_NSSA_STATE_KEY: &str = "nssa_state";
/// Name of block column family /// Name of block column family.
pub const CF_BLOCK_NAME: &str = "cf_block"; pub const CF_BLOCK_NAME: &str = "cf_block";
/// Name of meta column family /// Name of meta column family.
pub const CF_META_NAME: &str = "cf_meta"; pub const CF_META_NAME: &str = "cf_meta";
/// Name of state column family /// Name of state column family.
pub const CF_NSSA_STATE_NAME: &str = "cf_nssa_state"; pub const CF_NSSA_STATE_NAME: &str = "cf_nssa_state";
pub type DbResult<T> = Result<T, DbError>; pub type DbResult<T> = Result<T, DbError>;

View File

@ -9,7 +9,7 @@ type Instruction = (u128, ProgramId, u32, Option<PdaSeed>);
/// A program that calls another program `num_chain_calls` times. /// A program that calls another program `num_chain_calls` times.
/// It permutes the order of the input accounts on the subsequent call /// It permutes the order of the input accounts on the subsequent call
/// The `ProgramId` in the instruction must be the `program_id` of the authenticated transfers /// The `ProgramId` in the instruction must be the `program_id` of the authenticated transfers
/// program /// program.
fn main() { fn main() {
let ( let (
ProgramInput { ProgramInput {

View File

@ -6,41 +6,41 @@
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)] #[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WalletFfiError { pub enum WalletFfiError {
/// Operation completed successfully /// Operation completed successfully.
Success = 0, Success = 0,
/// A null pointer was passed where a valid pointer was expected /// A null pointer was passed where a valid pointer was expected.
NullPointer = 1, NullPointer = 1,
/// Invalid UTF-8 string /// Invalid UTF-8 string.
InvalidUtf8 = 2, InvalidUtf8 = 2,
/// Wallet handle is not initialized /// Wallet handle is not initialized.
WalletNotInitialized = 3, WalletNotInitialized = 3,
/// Configuration error /// Configuration error.
ConfigError = 4, ConfigError = 4,
/// Storage/persistence error /// Storage/persistence error.
StorageError = 5, StorageError = 5,
/// Network/RPC error /// Network/RPC error.
NetworkError = 6, NetworkError = 6,
/// Account not found /// Account not found.
AccountNotFound = 7, AccountNotFound = 7,
/// Key not found for account /// Key not found for account.
KeyNotFound = 8, KeyNotFound = 8,
/// Insufficient funds for operation /// Insufficient funds for operation.
InsufficientFunds = 9, InsufficientFunds = 9,
/// Invalid account ID format /// Invalid account ID format.
InvalidAccountId = 10, InvalidAccountId = 10,
/// Tokio runtime error /// Tokio runtime error.
RuntimeError = 11, RuntimeError = 11,
/// Password required but not provided /// Password required but not provided.
PasswordRequired = 12, PasswordRequired = 12,
/// Block synchronization error /// Block synchronization error.
SyncError = 13, SyncError = 13,
/// Serialization/deserialization error /// Serialization/deserialization error.
SerializationError = 14, SerializationError = 14,
/// Invalid conversion from FFI types to NSSA types /// Invalid conversion from FFI types to NSSA types.
InvalidTypeConversion = 15, InvalidTypeConversion = 15,
/// Invalid Key value /// Invalid Key value.
InvalidKeyValue = 16, InvalidKeyValue = 16,
/// Internal error (catch-all) /// Internal error (catch-all).
InternalError = 99, InternalError = 99,
} }

View File

@ -1,4 +1,4 @@
//! NSSA Wallet FFI Library //! NSSA Wallet FFI Library.
//! //!
//! This crate provides C-compatible bindings for the NSSA wallet functionality. //! This crate provides C-compatible bindings for the NSSA wallet functionality.
//! //!

View File

@ -31,7 +31,7 @@ pub struct FfiProgramId {
pub data: [u32; 8], pub data: [u32; 8],
} }
/// U128 - 16 bytes little endian /// U128 - 16 bytes little endian.
#[repr(C)] #[repr(C)]
#[derive(Clone, Copy, Default)] #[derive(Clone, Copy, Default)]
pub struct FfiU128 { pub struct FfiU128 {
@ -45,13 +45,13 @@ pub struct FfiU128 {
#[repr(C)] #[repr(C)]
pub struct FfiAccount { pub struct FfiAccount {
pub program_owner: FfiProgramId, pub program_owner: FfiProgramId,
/// Balance as little-endian [u8; 16] /// Balance as little-endian [u8; 16].
pub balance: FfiU128, pub balance: FfiU128,
/// Pointer to account data bytes /// Pointer to account data bytes.
pub data: *const u8, pub data: *const u8,
/// Length of account data /// Length of account data.
pub data_len: usize, pub data_len: usize,
/// Nonce as little-endian [u8; 16] /// Nonce as little-endian [u8; 16].
pub nonce: FfiU128, pub nonce: FfiU128,
} }
@ -70,11 +70,11 @@ impl Default for FfiAccount {
/// Public keys for a private account (safe to expose). /// Public keys for a private account (safe to expose).
#[repr(C)] #[repr(C)]
pub struct FfiPrivateAccountKeys { pub struct FfiPrivateAccountKeys {
/// Nullifier public key (32 bytes) /// Nullifier public key (32 bytes).
pub nullifier_public_key: FfiBytes32, pub nullifier_public_key: FfiBytes32,
/// viewing public key (compressed secp256k1 point) /// viewing public key (compressed secp256k1 point).
pub viewing_public_key: *const u8, pub viewing_public_key: *const u8,
/// Length of viewing public key (typically 33 bytes) /// Length of viewing public key (typically 33 bytes).
pub viewing_public_key_len: usize, pub viewing_public_key_len: usize,
} }
@ -123,9 +123,9 @@ impl Default for FfiAccountList {
#[repr(C)] #[repr(C)]
pub struct FfiTransferResult { pub struct FfiTransferResult {
// TODO: Replace with HashType FFI representation // TODO: Replace with HashType FFI representation
/// Transaction hash (null-terminated string, or null on failure) /// Transaction hash (null-terminated string, or null on failure).
pub tx_hash: *mut c_char, pub tx_hash: *mut c_char,
/// Whether the transfer succeeded /// Whether the transfer succeeded.
pub success: bool, pub success: bool,
} }

View File

@ -36,75 +36,75 @@
*/ */
typedef enum WalletFfiError { typedef enum WalletFfiError {
/** /**
* Operation completed successfully * Operation completed successfully.
*/ */
SUCCESS = 0, SUCCESS = 0,
/** /**
* A null pointer was passed where a valid pointer was expected * A null pointer was passed where a valid pointer was expected.
*/ */
NULL_POINTER = 1, NULL_POINTER = 1,
/** /**
* Invalid UTF-8 string * Invalid UTF-8 string.
*/ */
INVALID_UTF8 = 2, INVALID_UTF8 = 2,
/** /**
* Wallet handle is not initialized * Wallet handle is not initialized.
*/ */
WALLET_NOT_INITIALIZED = 3, WALLET_NOT_INITIALIZED = 3,
/** /**
* Configuration error * Configuration error.
*/ */
CONFIG_ERROR = 4, CONFIG_ERROR = 4,
/** /**
* Storage/persistence error * Storage/persistence error.
*/ */
STORAGE_ERROR = 5, STORAGE_ERROR = 5,
/** /**
* Network/RPC error * Network/RPC error.
*/ */
NETWORK_ERROR = 6, NETWORK_ERROR = 6,
/** /**
* Account not found * Account not found.
*/ */
ACCOUNT_NOT_FOUND = 7, ACCOUNT_NOT_FOUND = 7,
/** /**
* Key not found for account * Key not found for account.
*/ */
KEY_NOT_FOUND = 8, KEY_NOT_FOUND = 8,
/** /**
* Insufficient funds for operation * Insufficient funds for operation.
*/ */
INSUFFICIENT_FUNDS = 9, INSUFFICIENT_FUNDS = 9,
/** /**
* Invalid account ID format * Invalid account ID format.
*/ */
INVALID_ACCOUNT_ID = 10, INVALID_ACCOUNT_ID = 10,
/** /**
* Tokio runtime error * Tokio runtime error.
*/ */
RUNTIME_ERROR = 11, RUNTIME_ERROR = 11,
/** /**
* Password required but not provided * Password required but not provided.
*/ */
PASSWORD_REQUIRED = 12, PASSWORD_REQUIRED = 12,
/** /**
* Block synchronization error * Block synchronization error.
*/ */
SYNC_ERROR = 13, SYNC_ERROR = 13,
/** /**
* Serialization/deserialization error * Serialization/deserialization error.
*/ */
SERIALIZATION_ERROR = 14, SERIALIZATION_ERROR = 14,
/** /**
* Invalid conversion from FFI types to NSSA types * Invalid conversion from FFI types to NSSA types.
*/ */
INVALID_TYPE_CONVERSION = 15, INVALID_TYPE_CONVERSION = 15,
/** /**
* Invalid Key value * Invalid Key value.
*/ */
INVALID_KEY_VALUE = 16, INVALID_KEY_VALUE = 16,
/** /**
* Internal error (catch-all) * Internal error (catch-all).
*/ */
INTERNAL_ERROR = 99, INTERNAL_ERROR = 99,
} WalletFfiError; } WalletFfiError;
@ -150,7 +150,7 @@ typedef struct FfiProgramId {
} FfiProgramId; } FfiProgramId;
/** /**
* U128 - 16 bytes little endian * U128 - 16 bytes little endian.
*/ */
typedef struct FfiU128 { typedef struct FfiU128 {
uint8_t data[16]; uint8_t data[16];
@ -165,19 +165,19 @@ typedef struct FfiU128 {
typedef struct FfiAccount { typedef struct FfiAccount {
struct FfiProgramId program_owner; struct FfiProgramId program_owner;
/** /**
* Balance as little-endian [u8; 16] * Balance as little-endian [u8; 16].
*/ */
struct FfiU128 balance; struct FfiU128 balance;
/** /**
* Pointer to account data bytes * Pointer to account data bytes.
*/ */
const uint8_t *data; const uint8_t *data;
/** /**
* Length of account data * Length of account data.
*/ */
uintptr_t data_len; uintptr_t data_len;
/** /**
* Nonce as little-endian [u8; 16] * Nonce as little-endian [u8; 16].
*/ */
struct FfiU128 nonce; struct FfiU128 nonce;
} FfiAccount; } FfiAccount;
@ -194,15 +194,15 @@ typedef struct FfiPublicAccountKey {
*/ */
typedef struct FfiPrivateAccountKeys { typedef struct FfiPrivateAccountKeys {
/** /**
* Nullifier public key (32 bytes) * Nullifier public key (32 bytes).
*/ */
struct FfiBytes32 nullifier_public_key; struct FfiBytes32 nullifier_public_key;
/** /**
* viewing public key (compressed secp256k1 point) * viewing public key (compressed secp256k1 point).
*/ */
const uint8_t *viewing_public_key; const uint8_t *viewing_public_key;
/** /**
* Length of viewing public key (typically 33 bytes) * Length of viewing public key (typically 33 bytes).
*/ */
uintptr_t viewing_public_key_len; uintptr_t viewing_public_key_len;
} FfiPrivateAccountKeys; } FfiPrivateAccountKeys;
@ -212,11 +212,11 @@ typedef struct FfiPrivateAccountKeys {
*/ */
typedef struct FfiTransferResult { typedef struct FfiTransferResult {
/** /**
* Transaction hash (null-terminated string, or null on failure) * Transaction hash (null-terminated string, or null on failure).
*/ */
char *tx_hash; char *tx_hash;
/** /**
* Whether the transfer succeeded * Whether the transfer succeeded.
*/ */
bool success; bool success;
} FfiTransferResult; } FfiTransferResult;

View File

@ -12,63 +12,63 @@ use crate::{
helperfunctions::{AccountPrivacyKind, HumanReadableAccount, parse_addr_with_privacy_prefix}, helperfunctions::{AccountPrivacyKind, HumanReadableAccount, parse_addr_with_privacy_prefix},
}; };
/// Represents generic chain CLI subcommand /// Represents generic chain CLI subcommand.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum AccountSubcommand { pub enum AccountSubcommand {
/// Get account data /// Get account data.
Get { Get {
/// Flag to get raw account data /// Flag to get raw account data.
#[arg(short, long)] #[arg(short, long)]
raw: bool, raw: bool,
/// Display keys (pk for public accounts, npk/vpk for private accounts) /// Display keys (pk for public accounts, npk/vpk for private accounts).
#[arg(short, long)] #[arg(short, long)]
keys: bool, keys: bool,
/// Valid 32 byte base58 string with privacy prefix /// Valid 32 byte base58 string with privacy prefix.
#[arg(short, long)] #[arg(short, long)]
account_id: String, account_id: String,
}, },
/// Produce new public or private account /// Produce new public or private account.
#[command(subcommand)] #[command(subcommand)]
New(NewSubcommand), New(NewSubcommand),
/// Sync private accounts /// Sync private accounts.
SyncPrivate, SyncPrivate,
/// List all accounts owned by the wallet /// List all accounts owned by the wallet.
#[command(visible_alias = "ls")] #[command(visible_alias = "ls")]
List { List {
/// Show detailed account information (like `account get`) /// Show detailed account information (like `account get`).
#[arg(short, long)] #[arg(short, long)]
long: bool, long: bool,
}, },
/// Set a label for an account /// Set a label for an account.
Label { Label {
/// Valid 32 byte base58 string with privacy prefix /// Valid 32 byte base58 string with privacy prefix.
#[arg(short, long)] #[arg(short, long)]
account_id: String, account_id: String,
/// The label to assign to the account /// The label to assign to the account.
#[arg(short, long)] #[arg(short, long)]
label: String, label: String,
}, },
} }
/// Represents generic register CLI subcommand /// Represents generic register CLI subcommand.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum NewSubcommand { pub enum NewSubcommand {
/// Register new public account /// Register new public account.
Public { Public {
#[arg(long)] #[arg(long)]
/// Chain index of a parent node /// Chain index of a parent node.
cci: Option<ChainIndex>, cci: Option<ChainIndex>,
#[arg(short, long)] #[arg(short, long)]
/// Label to assign to the new account /// Label to assign to the new account.
label: Option<String>, label: Option<String>,
}, },
/// Register new private account /// Register new private account.
Private { Private {
#[arg(long)] #[arg(long)]
/// Chain index of a parent node /// Chain index of a parent node.
cci: Option<ChainIndex>, cci: Option<ChainIndex>,
#[arg(short, long)] #[arg(short, long)]
/// Label to assign to the new account /// Label to assign to the new account.
label: Option<String>, label: Option<String>,
}, },
} }
@ -409,7 +409,7 @@ impl WalletSubcommand for AccountSubcommand {
} }
} }
/// Formats account details for display, returning (description, `json_view`) /// Formats account details for display, returning (description, `json_view`).
fn format_account_details(account: &Account) -> (String, String) { fn format_account_details(account: &Account) -> (String, String) {
let auth_tr_prog_id = Program::authenticated_transfer_program().id(); let auth_tr_prog_id = Program::authenticated_transfer_program().id();
let token_prog_id = Program::token().id(); let token_prog_id = Program::token().id();

View File

@ -7,19 +7,19 @@ use crate::{
cli::{SubcommandReturnValue, WalletSubcommand}, cli::{SubcommandReturnValue, WalletSubcommand},
}; };
/// Represents generic chain CLI subcommand /// Represents generic chain CLI subcommand.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum ChainSubcommand { pub enum ChainSubcommand {
/// Get current block id from sequencer /// Get current block id from sequencer.
CurrentBlockId, CurrentBlockId,
/// Get block at id from sequencer /// Get block at id from sequencer.
Block { Block {
#[arg(short, long)] #[arg(short, long)]
id: u64, id: u64,
}, },
/// Get transaction at hash from sequencer /// Get transaction at hash from sequencer.
Transaction { Transaction {
/// hash - valid 32 byte hex string /// hash - valid 32 byte hex string.
#[arg(short = 't', long)] #[arg(short = 't', long)]
hash: HashType, hash: HashType,
}, },

View File

@ -6,20 +6,20 @@ use crate::{
cli::{SubcommandReturnValue, WalletSubcommand}, cli::{SubcommandReturnValue, WalletSubcommand},
}; };
/// Represents generic config CLI subcommand /// Represents generic config CLI subcommand.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum ConfigSubcommand { pub enum ConfigSubcommand {
/// Getter of config fields /// Getter of config fields.
Get { Get {
/// Print all config fields /// Print all config fields.
#[arg(short, long)] #[arg(short, long)]
all: bool, all: bool,
/// Config field key to get /// Config field key to get.
key: Option<String>, key: Option<String>,
}, },
/// Setter of config fields /// Setter of config fields.
Set { key: String, value: String }, Set { key: String, value: String },
/// Prints description of corresponding field /// Prints description of corresponding field.
Description { key: String }, Description { key: String },
} }

View File

@ -28,62 +28,62 @@ pub(crate) trait WalletSubcommand {
-> Result<SubcommandReturnValue>; -> Result<SubcommandReturnValue>;
} }
/// Represents CLI command for a wallet /// Represents CLI command for a wallet.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
#[clap(about)] #[clap(about)]
pub enum Command { pub enum Command {
/// Authenticated transfer subcommand /// Authenticated transfer subcommand.
#[command(subcommand)] #[command(subcommand)]
AuthTransfer(AuthTransferSubcommand), AuthTransfer(AuthTransferSubcommand),
/// Generic chain info subcommand /// Generic chain info subcommand.
#[command(subcommand)] #[command(subcommand)]
ChainInfo(ChainSubcommand), ChainInfo(ChainSubcommand),
/// Account view and sync subcommand /// Account view and sync subcommand.
#[command(subcommand)] #[command(subcommand)]
Account(AccountSubcommand), Account(AccountSubcommand),
/// Pinata program interaction subcommand /// Pinata program interaction subcommand.
#[command(subcommand)] #[command(subcommand)]
Pinata(PinataProgramAgnosticSubcommand), Pinata(PinataProgramAgnosticSubcommand),
/// Token program interaction subcommand /// Token program interaction subcommand.
#[command(subcommand)] #[command(subcommand)]
Token(TokenProgramAgnosticSubcommand), Token(TokenProgramAgnosticSubcommand),
/// AMM program interaction subcommand /// AMM program interaction subcommand.
#[command(subcommand)] #[command(subcommand)]
AMM(AmmProgramAgnosticSubcommand), AMM(AmmProgramAgnosticSubcommand),
/// Check the wallet can connect to the node and builtin local programs /// Check the wallet can connect to the node and builtin local programs
/// match the remote versions /// match the remote versions.
CheckHealth, CheckHealth,
/// Command to setup config, get and set config fields /// Command to setup config, get and set config fields.
#[command(subcommand)] #[command(subcommand)]
Config(ConfigSubcommand), Config(ConfigSubcommand),
/// Restoring keys from given password at given `depth` /// Restoring keys from given password at given `depth`.
/// ///
/// !!!WARNING!!! will rewrite current storage /// !!!WARNING!!! will rewrite current storage.
RestoreKeys { RestoreKeys {
#[arg(short, long)] #[arg(short, long)]
/// Indicates, how deep in tree accounts may be. Affects command complexity. /// Indicates, how deep in tree accounts may be. Affects command complexity.
depth: u32, depth: u32,
}, },
/// Deploy a program /// Deploy a program.
DeployProgram { binary_filepath: PathBuf }, DeployProgram { binary_filepath: PathBuf },
} }
/// To execute commands, env var `NSSA_WALLET_HOME_DIR` must be set into directory with config /// To execute commands, env var `NSSA_WALLET_HOME_DIR` must be set into directory with config.
/// ///
/// All account addresses must be valid 32 byte base58 strings. /// All account addresses must be valid 32 byte base58 strings.
/// ///
/// All account `account_ids` must be provided as {`privacy_prefix}/{account_id`}, /// All account `account_ids` must be provided as {`privacy_prefix}/{account_id`},
/// where valid options for `privacy_prefix` is `Public` and `Private` /// where valid options for `privacy_prefix` is `Public` and `Private`.
#[derive(Parser, Debug)] #[derive(Parser, Debug)]
#[clap(version, about)] #[clap(version, about)]
pub struct Args { pub struct Args {
/// Continious run flag /// Continious run flag.
#[arg(short, long)] #[arg(short, long)]
pub continuous_run: bool, pub continuous_run: bool,
/// Basic authentication in the format `user` or `user:password` /// Basic authentication in the format `user` or `user:password`.
#[arg(long)] #[arg(long)]
pub auth: Option<String>, pub auth: Option<String>,
/// Wallet command /// Wallet command.
#[command(subcommand)] #[command(subcommand)]
pub command: Option<Command>, pub command: Option<Command>,
} }

View File

@ -9,22 +9,22 @@ use crate::{
program_facades::amm::Amm, program_facades::amm::Amm,
}; };
/// Represents generic CLI subcommand for a wallet working with amm program /// Represents generic CLI subcommand for a wallet working with amm program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum AmmProgramAgnosticSubcommand { pub enum AmmProgramAgnosticSubcommand {
/// Produce a new pool /// Produce a new pool.
/// ///
/// `user_holding_a` and `user_holding_b` must be owned. /// `user_holding_a` and `user_holding_b` must be owned.
/// ///
/// Only public execution allowed /// Only public execution allowed.
New { New {
/// `user_holding_a` - valid 32 byte base58 string with privacy prefix /// `user_holding_a` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_a: String, user_holding_a: String,
/// `user_holding_b` - valid 32 byte base58 string with privacy prefix /// `user_holding_b` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_b: String, user_holding_b: String,
/// `user_holding_lp` - valid 32 byte base58 string with privacy prefix /// `user_holding_lp` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_lp: String, user_holding_lp: String,
#[arg(long)] #[arg(long)]
@ -32,39 +32,39 @@ pub enum AmmProgramAgnosticSubcommand {
#[arg(long)] #[arg(long)]
balance_b: u128, balance_b: u128,
}, },
/// Swap /// Swap.
/// ///
/// The account associated with swapping token must be owned /// The account associated with swapping token must be owned.
/// ///
/// Only public execution allowed /// Only public execution allowed.
Swap { Swap {
/// `user_holding_a` - valid 32 byte base58 string with privacy prefix /// `user_holding_a` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_a: String, user_holding_a: String,
/// `user_holding_b` - valid 32 byte base58 string with privacy prefix /// `user_holding_b` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_b: String, user_holding_b: String,
#[arg(long)] #[arg(long)]
amount_in: u128, amount_in: u128,
#[arg(long)] #[arg(long)]
min_amount_out: u128, min_amount_out: u128,
/// `token_definition` - valid 32 byte base58 string WITHOUT privacy prefix /// `token_definition` - valid 32 byte base58 string WITHOUT privacy prefix.
#[arg(long)] #[arg(long)]
token_definition: String, token_definition: String,
}, },
/// Add liquidity /// Add liquidity.
/// ///
/// `user_holding_a` and `user_holding_b` must be owned. /// `user_holding_a` and `user_holding_b` must be owned.
/// ///
/// Only public execution allowed /// Only public execution allowed.
AddLiquidity { AddLiquidity {
/// `user_holding_a` - valid 32 byte base58 string with privacy prefix /// `user_holding_a` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_a: String, user_holding_a: String,
/// `user_holding_b` - valid 32 byte base58 string with privacy prefix /// `user_holding_b` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_b: String, user_holding_b: String,
/// `user_holding_lp` - valid 32 byte base58 string with privacy prefix /// `user_holding_lp` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_lp: String, user_holding_lp: String,
#[arg(long)] #[arg(long)]
@ -74,19 +74,19 @@ pub enum AmmProgramAgnosticSubcommand {
#[arg(long)] #[arg(long)]
max_amount_b: u128, max_amount_b: u128,
}, },
/// Remove liquidity /// Remove liquidity.
/// ///
/// `user_holding_lp` must be owned. /// `user_holding_lp` must be owned.
/// ///
/// Only public execution allowed /// Only public execution allowed.
RemoveLiquidity { RemoveLiquidity {
/// `user_holding_a` - valid 32 byte base58 string with privacy prefix /// `user_holding_a` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_a: String, user_holding_a: String,
/// `user_holding_b` - valid 32 byte base58 string with privacy prefix /// `user_holding_b` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_b: String, user_holding_b: String,
/// `user_holding_lp` - valid 32 byte base58 string with privacy prefix /// `user_holding_lp` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
user_holding_lp: String, user_holding_lp: String,
#[arg(long)] #[arg(long)]

View File

@ -11,35 +11,35 @@ use crate::{
program_facades::native_token_transfer::NativeTokenTransfer, program_facades::native_token_transfer::NativeTokenTransfer,
}; };
/// Represents generic CLI subcommand for a wallet working with native token transfer program /// Represents generic CLI subcommand for a wallet working with native token transfer program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum AuthTransferSubcommand { pub enum AuthTransferSubcommand {
/// Initialize account under authenticated transfer program /// Initialize account under authenticated transfer program.
Init { Init {
/// `account_id` - valid 32 byte base58 string with privacy prefix /// `account_id` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
account_id: String, account_id: String,
}, },
/// Send native tokens from one account to another with variable privacy /// Send native tokens from one account to another with variable privacy.
/// ///
/// If receiver is private, then `to` and (`to_npk` , `to_vpk`) is a mutually exclusive /// If receiver is private, then `to` and (`to_npk` , `to_vpk`) is a mutually exclusive
/// patterns. /// patterns.
/// ///
/// First is used for owned accounts, second otherwise. /// First is used for owned accounts, second otherwise.
Send { Send {
/// from - valid 32 byte base58 string with privacy prefix /// from - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// to - valid 32 byte base58 string with privacy prefix /// to - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
to: Option<String>, to: Option<String>,
/// `to_npk` - valid 32 byte hex string /// `to_npk` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to_npk: Option<String>, to_npk: Option<String>,
/// `to_vpk` - valid 33 byte hex string /// `to_vpk` - valid 33 byte hex string.
#[arg(long)] #[arg(long)]
to_vpk: Option<String>, to_vpk: Option<String>,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
@ -188,114 +188,114 @@ impl WalletSubcommand for AuthTransferSubcommand {
} }
} }
/// Represents generic CLI subcommand for a wallet working with native token transfer program /// Represents generic CLI subcommand for a wallet working with native token transfer program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum NativeTokenTransferProgramSubcommand { pub enum NativeTokenTransferProgramSubcommand {
/// Send native token transfer from `from` to `to` for `amount` /// Send native token transfer from `from` to `to` for `amount`.
/// ///
/// Public operation /// Public operation.
Public { Public {
/// from - valid 32 byte hex string /// from - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// to - valid 32 byte hex string /// to - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to: String, to: String,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
/// Private execution /// Private execution.
#[command(subcommand)] #[command(subcommand)]
Private(NativeTokenTransferProgramSubcommandPrivate), Private(NativeTokenTransferProgramSubcommandPrivate),
/// Send native token transfer from `from` to `to` for `amount` /// Send native token transfer from `from` to `to` for `amount`.
/// ///
/// Deshielded operation /// Deshielded operation.
Deshielded { Deshielded {
/// from - valid 32 byte hex string /// from - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// to - valid 32 byte hex string /// to - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to: String, to: String,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
/// Shielded execution /// Shielded execution.
#[command(subcommand)] #[command(subcommand)]
Shielded(NativeTokenTransferProgramSubcommandShielded), Shielded(NativeTokenTransferProgramSubcommandShielded),
} }
/// Represents generic shielded CLI subcommand for a wallet working with native token transfer /// Represents generic shielded CLI subcommand for a wallet working with native token transfer
/// program /// program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum NativeTokenTransferProgramSubcommandShielded { pub enum NativeTokenTransferProgramSubcommandShielded {
/// Send native token transfer from `from` to `to` for `amount` /// Send native token transfer from `from` to `to` for `amount`.
/// ///
/// Shielded operation /// Shielded operation.
ShieldedOwned { ShieldedOwned {
/// from - valid 32 byte hex string /// from - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// to - valid 32 byte hex string /// to - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to: String, to: String,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
/// Send native token transfer from `from` to `to` for `amount` /// Send native token transfer from `from` to `to` for `amount`.
/// ///
/// Shielded operation /// Shielded operation.
ShieldedForeign { ShieldedForeign {
/// from - valid 32 byte hex string /// from - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// `to_npk` - valid 32 byte hex string /// `to_npk` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to_npk: String, to_npk: String,
/// `to_vpk` - valid 33 byte hex string /// `to_vpk` - valid 33 byte hex string.
#[arg(long)] #[arg(long)]
to_vpk: String, to_vpk: String,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
} }
/// Represents generic private CLI subcommand for a wallet working with native token transfer /// Represents generic private CLI subcommand for a wallet working with native token transfer
/// program /// program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum NativeTokenTransferProgramSubcommandPrivate { pub enum NativeTokenTransferProgramSubcommandPrivate {
/// Send native token transfer from `from` to `to` for `amount` /// Send native token transfer from `from` to `to` for `amount`.
/// ///
/// Private operation /// Private operation.
PrivateOwned { PrivateOwned {
/// from - valid 32 byte hex string /// from - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// to - valid 32 byte hex string /// to - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to: String, to: String,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
/// Send native token transfer from `from` to `to` for `amount` /// Send native token transfer from `from` to `to` for `amount`.
/// ///
/// Private operation /// Private operation.
PrivateForeign { PrivateForeign {
/// from - valid 32 byte hex string /// from - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// `to_npk` - valid 32 byte hex string /// `to_npk` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to_npk: String, to_npk: String,
/// `to_vpk` - valid 33 byte hex string /// `to_vpk` - valid 33 byte hex string.
#[arg(long)] #[arg(long)]
to_vpk: String, to_vpk: String,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },

View File

@ -11,12 +11,12 @@ use crate::{
program_facades::pinata::Pinata, program_facades::pinata::Pinata,
}; };
/// Represents generic CLI subcommand for a wallet working with pinata program /// Represents generic CLI subcommand for a wallet working with pinata program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum PinataProgramAgnosticSubcommand { pub enum PinataProgramAgnosticSubcommand {
/// Claim pinata /// Claim pinata.
Claim { Claim {
/// to - valid 32 byte base58 string with privacy prefix /// to - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
to: String, to: String,
}, },
@ -52,42 +52,42 @@ impl WalletSubcommand for PinataProgramAgnosticSubcommand {
} }
} }
/// Represents generic CLI subcommand for a wallet working with pinata program /// Represents generic CLI subcommand for a wallet working with pinata program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum PinataProgramSubcommand { pub enum PinataProgramSubcommand {
/// Public execution /// Public execution.
#[command(subcommand)] #[command(subcommand)]
Public(PinataProgramSubcommandPublic), Public(PinataProgramSubcommandPublic),
/// Private execution /// Private execution.
#[command(subcommand)] #[command(subcommand)]
Private(PinataProgramSubcommandPrivate), Private(PinataProgramSubcommandPrivate),
} }
/// Represents generic public CLI subcommand for a wallet working with pinata program /// Represents generic public CLI subcommand for a wallet working with pinata program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum PinataProgramSubcommandPublic { pub enum PinataProgramSubcommandPublic {
// TODO: Testnet only. Refactor to prevent compilation on mainnet. // TODO: Testnet only. Refactor to prevent compilation on mainnet.
// Claim piñata prize // Claim piñata prize
Claim { Claim {
/// `pinata_account_id` - valid 32 byte hex string /// `pinata_account_id` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
pinata_account_id: String, pinata_account_id: String,
/// `winner_account_id` - valid 32 byte hex string /// `winner_account_id` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
winner_account_id: String, winner_account_id: String,
}, },
} }
/// Represents generic private CLI subcommand for a wallet working with pinata program /// Represents generic private CLI subcommand for a wallet working with pinata program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum PinataProgramSubcommandPrivate { pub enum PinataProgramSubcommandPrivate {
// TODO: Testnet only. Refactor to prevent compilation on mainnet. // TODO: Testnet only. Refactor to prevent compilation on mainnet.
// Claim piñata prize // Claim piñata prize
ClaimPrivateOwned { ClaimPrivateOwned {
/// `pinata_account_id` - valid 32 byte hex string /// `pinata_account_id` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
pinata_account_id: String, pinata_account_id: String,
/// `winner_account_id` - valid 32 byte hex string /// `winner_account_id` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
winner_account_id: String, winner_account_id: String,
}, },

View File

@ -11,15 +11,15 @@ use crate::{
program_facades::token::Token, program_facades::token::Token,
}; };
/// Represents generic CLI subcommand for a wallet working with token program /// Represents generic CLI subcommand for a wallet working with token program.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum TokenProgramAgnosticSubcommand { pub enum TokenProgramAgnosticSubcommand {
/// Produce a new token /// Produce a new token.
New { New {
/// `definition_account_id` - valid 32 byte base58 string with privacy prefix /// `definition_account_id` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
definition_account_id: String, definition_account_id: String,
/// `supply_account_id` - valid 32 byte base58 string with privacy prefix /// `supply_account_id` - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
supply_account_id: String, supply_account_id: String,
#[arg(short, long)] #[arg(short, long)]
@ -27,68 +27,68 @@ pub enum TokenProgramAgnosticSubcommand {
#[arg(short, long)] #[arg(short, long)]
total_supply: u128, total_supply: u128,
}, },
/// Send tokens from one account to another with variable privacy /// Send tokens from one account to another with variable privacy.
/// ///
/// If receiver is private, then `to` and (`to_npk` , `to_vpk`) is a mutually exclusive /// If receiver is private, then `to` and (`to_npk` , `to_vpk`) is a mutually exclusive
/// patterns. /// patterns.
/// ///
/// First is used for owned accounts, second otherwise. /// First is used for owned accounts, second otherwise.
Send { Send {
/// from - valid 32 byte base58 string with privacy prefix /// from - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
from: String, from: String,
/// to - valid 32 byte base58 string with privacy prefix /// to - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
to: Option<String>, to: Option<String>,
/// `to_npk` - valid 32 byte hex string /// `to_npk` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
to_npk: Option<String>, to_npk: Option<String>,
/// `to_vpk` - valid 33 byte hex string /// `to_vpk` - valid 33 byte hex string.
#[arg(long)] #[arg(long)]
to_vpk: Option<String>, to_vpk: Option<String>,
/// amount - amount of balance to move /// amount - amount of balance to move.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
/// Burn tokens on `holder`, modify `definition`. /// Burn tokens on `holder`, modify `definition`.
/// ///
/// `holder` is owned /// `holder` is owned.
/// ///
/// Also if `definition` is private then it is owned, because /// Also if `definition` is private then it is owned, because
/// we can not modify foreign accounts. /// we can not modify foreign accounts.
Burn { Burn {
/// definition - valid 32 byte base58 string with privacy prefix /// definition - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
definition: String, definition: String,
/// holder - valid 32 byte base58 string with privacy prefix /// holder - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
holder: String, holder: String,
/// amount - amount of balance to burn /// amount - amount of balance to burn.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
/// Mint tokens on `holder`, modify `definition`. /// Mint tokens on `holder`, modify `definition`.
/// ///
/// `definition` is owned /// `definition` is owned.
/// ///
/// If `holder` is private, then `holder` and (`holder_npk` , `holder_vpk`) is a mutually /// If `holder` is private, then `holder` and (`holder_npk` , `holder_vpk`) is a mutually
/// exclusive patterns. /// exclusive patterns.
/// ///
/// First is used for owned accounts, second otherwise. /// First is used for owned accounts, second otherwise.
Mint { Mint {
/// definition - valid 32 byte base58 string with privacy prefix /// definition - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
definition: String, definition: String,
/// holder - valid 32 byte base58 string with privacy prefix /// holder - valid 32 byte base58 string with privacy prefix.
#[arg(long)] #[arg(long)]
holder: Option<String>, holder: Option<String>,
/// `holder_npk` - valid 32 byte hex string /// `holder_npk` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
holder_npk: Option<String>, holder_npk: Option<String>,
/// `to_vpk` - valid 33 byte hex string /// `to_vpk` - valid 33 byte hex string.
#[arg(long)] #[arg(long)]
holder_vpk: Option<String>, holder_vpk: Option<String>,
/// amount - amount of balance to mint /// amount - amount of balance to mint.
#[arg(long)] #[arg(long)]
amount: u128, amount: u128,
}, },
@ -394,27 +394,27 @@ impl WalletSubcommand for TokenProgramAgnosticSubcommand {
} }
} }
/// Represents generic CLI subcommand for a wallet working with `token_program` /// Represents generic CLI subcommand for a wallet working with `token_program`.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum TokenProgramSubcommand { pub enum TokenProgramSubcommand {
/// Creation of new token /// Creation of new token.
#[command(subcommand)] #[command(subcommand)]
Create(CreateNewTokenProgramSubcommand), Create(CreateNewTokenProgramSubcommand),
/// Public execution /// Public execution.
#[command(subcommand)] #[command(subcommand)]
Public(TokenProgramSubcommandPublic), Public(TokenProgramSubcommandPublic),
/// Private execution /// Private execution.
#[command(subcommand)] #[command(subcommand)]
Private(TokenProgramSubcommandPrivate), Private(TokenProgramSubcommandPrivate),
/// Deshielded execution /// Deshielded execution.
#[command(subcommand)] #[command(subcommand)]
Deshielded(TokenProgramSubcommandDeshielded), Deshielded(TokenProgramSubcommandDeshielded),
/// Shielded execution /// Shielded execution.
#[command(subcommand)] #[command(subcommand)]
Shielded(TokenProgramSubcommandShielded), Shielded(TokenProgramSubcommandShielded),
} }
/// Represents generic public CLI subcommand for a wallet working with `token_program` /// Represents generic public CLI subcommand for a wallet working with `token_program`.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum TokenProgramSubcommandPublic { pub enum TokenProgramSubcommandPublic {
// Transfer tokens using the token program // Transfer tokens using the token program
@ -446,7 +446,7 @@ pub enum TokenProgramSubcommandPublic {
}, },
} }
/// Represents generic private CLI subcommand for a wallet working with `token_program` /// Represents generic private CLI subcommand for a wallet working with `token_program`.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum TokenProgramSubcommandPrivate { pub enum TokenProgramSubcommandPrivate {
// Transfer tokens using the token program // Transfer tokens using the token program
@ -462,10 +462,10 @@ pub enum TokenProgramSubcommandPrivate {
TransferTokenPrivateForeign { TransferTokenPrivateForeign {
#[arg(short, long)] #[arg(short, long)]
sender_account_id: String, sender_account_id: String,
/// `recipient_npk` - valid 32 byte hex string /// `recipient_npk` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
recipient_npk: String, recipient_npk: String,
/// `recipient_vpk` - valid 33 byte hex string /// `recipient_vpk` - valid 33 byte hex string.
#[arg(long)] #[arg(long)]
recipient_vpk: String, recipient_vpk: String,
#[arg(short, long)] #[arg(short, long)]
@ -502,7 +502,7 @@ pub enum TokenProgramSubcommandPrivate {
}, },
} }
/// Represents deshielded public CLI subcommand for a wallet working with `token_program` /// Represents deshielded public CLI subcommand for a wallet working with `token_program`.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum TokenProgramSubcommandDeshielded { pub enum TokenProgramSubcommandDeshielded {
// Transfer tokens using the token program // Transfer tokens using the token program
@ -534,7 +534,7 @@ pub enum TokenProgramSubcommandDeshielded {
}, },
} }
/// Represents generic shielded CLI subcommand for a wallet working with `token_program` /// Represents generic shielded CLI subcommand for a wallet working with `token_program`.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum TokenProgramSubcommandShielded { pub enum TokenProgramSubcommandShielded {
// Transfer tokens using the token program // Transfer tokens using the token program
@ -550,10 +550,10 @@ pub enum TokenProgramSubcommandShielded {
TransferTokenShieldedForeign { TransferTokenShieldedForeign {
#[arg(short, long)] #[arg(short, long)]
sender_account_id: String, sender_account_id: String,
/// `recipient_npk` - valid 32 byte hex string /// `recipient_npk` - valid 32 byte hex string.
#[arg(long)] #[arg(long)]
recipient_npk: String, recipient_npk: String,
/// `recipient_vpk` - valid 33 byte hex string /// `recipient_vpk` - valid 33 byte hex string.
#[arg(long)] #[arg(long)]
recipient_vpk: String, recipient_vpk: String,
#[arg(short, long)] #[arg(short, long)]
@ -590,12 +590,12 @@ pub enum TokenProgramSubcommandShielded {
}, },
} }
/// Represents generic initialization subcommand for a wallet working with `token_program` /// Represents generic initialization subcommand for a wallet working with `token_program`.
#[derive(Subcommand, Debug, Clone)] #[derive(Subcommand, Debug, Clone)]
pub enum CreateNewTokenProgramSubcommand { pub enum CreateNewTokenProgramSubcommand {
/// Create a new token using the token program /// Create a new token using the token program.
/// ///
/// Definition - public, supply - public /// Definition - public, supply - public.
NewPublicDefPublicSupp { NewPublicDefPublicSupp {
#[arg(short, long)] #[arg(short, long)]
definition_account_id: String, definition_account_id: String,
@ -606,9 +606,9 @@ pub enum CreateNewTokenProgramSubcommand {
#[arg(short, long)] #[arg(short, long)]
total_supply: u128, total_supply: u128,
}, },
/// Create a new token using the token program /// Create a new token using the token program.
/// ///
/// Definition - public, supply - private /// Definition - public, supply - private.
NewPublicDefPrivateSupp { NewPublicDefPrivateSupp {
#[arg(short, long)] #[arg(short, long)]
definition_account_id: String, definition_account_id: String,
@ -619,9 +619,9 @@ pub enum CreateNewTokenProgramSubcommand {
#[arg(short, long)] #[arg(short, long)]
total_supply: u128, total_supply: u128,
}, },
/// Create a new token using the token program /// Create a new token using the token program.
/// ///
/// Definition - private, supply - public /// Definition - private, supply - public.
NewPrivateDefPublicSupp { NewPrivateDefPublicSupp {
#[arg(short, long)] #[arg(short, long)]
definition_account_id: String, definition_account_id: String,
@ -632,9 +632,9 @@ pub enum CreateNewTokenProgramSubcommand {
#[arg(short, long)] #[arg(short, long)]
total_supply: u128, total_supply: u128,
}, },
/// Create a new token using the token program /// Create a new token using the token program.
/// ///
/// Definition - private, supply - private /// Definition - private, supply - private.
NewPrivateDefPrivateSupp { NewPrivateDefPrivateSupp {
#[arg(short, long)] #[arg(short, long)]
definition_account_id: String, definition_account_id: String,

View File

@ -86,7 +86,7 @@ pub struct PersistentStorage {
pub accounts: Vec<PersistentAccountData>, pub accounts: Vec<PersistentAccountData>,
pub last_synced_block: u64, pub last_synced_block: u64,
/// Account labels keyed by account ID string (e.g., /// Account labels keyed by account ID string (e.g.,
/// "2rnKprXqWGWJTkDZKsQbFXa4ctKRbapsdoTKQFnaVGG8") /// "2rnKprXqWGWJTkDZKsQbFXa4ctKRbapsdoTKQFnaVGG8").
#[serde(default)] #[serde(default)]
pub labels: HashMap<String, Label>, pub labels: HashMap<String, Label>,
} }
@ -167,42 +167,42 @@ impl From<InitialAccountData> for PersistentAccountData {
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GasConfig { pub struct GasConfig {
/// Gas spent per deploying one byte of data /// Gas spent per deploying one byte of data.
pub gas_fee_per_byte_deploy: u64, pub gas_fee_per_byte_deploy: u64,
/// Gas spent per reading one byte of data in VM /// Gas spent per reading one byte of data in VM.
pub gas_fee_per_input_buffer_runtime: u64, pub gas_fee_per_input_buffer_runtime: u64,
/// Gas spent per one byte of contract data in runtime /// Gas spent per one byte of contract data in runtime.
pub gas_fee_per_byte_runtime: u64, pub gas_fee_per_byte_runtime: u64,
/// Cost of one gas of runtime in public balance /// Cost of one gas of runtime in public balance.
pub gas_cost_runtime: u64, pub gas_cost_runtime: u64,
/// Cost of one gas of deployment in public balance /// Cost of one gas of deployment in public balance.
pub gas_cost_deploy: u64, pub gas_cost_deploy: u64,
/// Gas limit for deployment /// Gas limit for deployment.
pub gas_limit_deploy: u64, pub gas_limit_deploy: u64,
/// Gas limit for runtime /// Gas limit for runtime.
pub gas_limit_runtime: u64, pub gas_limit_runtime: u64,
} }
#[optfield::optfield(pub WalletConfigOverrides, rewrap, attrs = (derive(Debug, Default, Clone)))] #[optfield::optfield(pub WalletConfigOverrides, rewrap, attrs = (derive(Debug, Default, Clone)))]
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct WalletConfig { pub struct WalletConfig {
/// Override rust log (env var logging level) /// Override rust log (env var logging level).
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub override_rust_log: Option<String>, pub override_rust_log: Option<String>,
/// Sequencer URL /// Sequencer URL.
pub sequencer_addr: Url, pub sequencer_addr: Url,
/// Sequencer polling duration for new blocks /// Sequencer polling duration for new blocks.
#[serde(with = "humantime_serde")] #[serde(with = "humantime_serde")]
pub seq_poll_timeout: Duration, pub seq_poll_timeout: Duration,
/// Sequencer polling max number of blocks to find transaction /// Sequencer polling max number of blocks to find transaction.
pub seq_tx_poll_max_blocks: usize, pub seq_tx_poll_max_blocks: usize,
/// Sequencer polling max number error retries /// Sequencer polling max number error retries.
pub seq_poll_max_retries: u64, pub seq_poll_max_retries: u64,
/// Max amount of blocks to poll in one request /// Max amount of blocks to poll in one request.
pub seq_block_poll_max_amount: u64, pub seq_block_poll_max_amount: u64,
/// Initial accounts for wallet /// Initial accounts for wallet.
pub initial_accounts: Vec<InitialAccountData>, pub initial_accounts: Vec<InitialAccountData>,
/// Basic authentication credentials /// Basic authentication credentials.
#[serde(skip_serializing_if = "Option::is_none")] #[serde(skip_serializing_if = "Option::is_none")]
pub basic_auth: Option<BasicAuth>, pub basic_auth: Option<BasicAuth>,
} }

View File

@ -66,14 +66,14 @@ pub fn get_home() -> Result<PathBuf> {
get_home_nssa_var().or_else(|_| get_home_default_path()) get_home_nssa_var().or_else(|_| get_home_default_path())
} }
/// Fetch config path from default home /// Fetch config path from default home.
pub fn fetch_config_path() -> Result<PathBuf> { pub fn fetch_config_path() -> Result<PathBuf> {
let home = get_home()?; let home = get_home()?;
let config_path = home.join("wallet_config.json"); let config_path = home.join("wallet_config.json");
Ok(config_path) Ok(config_path)
} }
/// Fetch path to data storage from default home /// Fetch path to data storage from default home.
/// ///
/// File must be created through setup beforehand. /// File must be created through setup beforehand.
pub fn fetch_persistent_storage_path() -> Result<PathBuf> { pub fn fetch_persistent_storage_path() -> Result<PathBuf> {
@ -82,7 +82,7 @@ pub fn fetch_persistent_storage_path() -> Result<PathBuf> {
Ok(accs_path) Ok(accs_path)
} }
/// Produces data for storage /// Produces data for storage.
#[must_use] #[must_use]
pub fn produce_data_for_storage( pub fn produce_data_for_storage(
user_data: &NSSAUserData, user_data: &NSSAUserData,

View File

@ -148,25 +148,25 @@ impl WalletCore {
}) })
} }
/// Get configuration with applied overrides /// Get configuration with applied overrides.
#[must_use] #[must_use]
pub const fn config(&self) -> &WalletConfig { pub const fn config(&self) -> &WalletConfig {
&self.storage.wallet_config &self.storage.wallet_config
} }
/// Get storage /// Get storage.
#[must_use] #[must_use]
pub const fn storage(&self) -> &WalletChainStore { pub const fn storage(&self) -> &WalletChainStore {
&self.storage &self.storage
} }
/// Reset storage /// Reset storage.
pub fn reset_storage(&mut self, password: String) -> Result<()> { pub fn reset_storage(&mut self, password: String) -> Result<()> {
self.storage = WalletChainStore::new_storage(self.storage.wallet_config.clone(), password)?; self.storage = WalletChainStore::new_storage(self.storage.wallet_config.clone(), password)?;
Ok(()) Ok(())
} }
/// Store persistent data at home /// Store persistent data at home.
pub async fn store_persistent_data(&self) -> Result<()> { pub async fn store_persistent_data(&self) -> Result<()> {
let data = produce_data_for_storage( let data = produce_data_for_storage(
&self.storage.user_data, &self.storage.user_data,
@ -188,7 +188,7 @@ impl WalletCore {
Ok(()) Ok(())
} }
/// Store persistent data at home /// Store persistent data at home.
pub async fn store_config_changes(&self) -> Result<()> { pub async fn store_config_changes(&self) -> Result<()> {
let config = serde_json::to_vec_pretty(&self.storage.wallet_config)?; let config = serde_json::to_vec_pretty(&self.storage.wallet_config)?;
@ -220,7 +220,7 @@ impl WalletCore {
.generate_new_privacy_preserving_transaction_key_chain(chain_index) .generate_new_privacy_preserving_transaction_key_chain(chain_index)
} }
/// Get account balance /// Get account balance.
pub async fn get_account_balance(&self, acc: AccountId) -> Result<u128> { pub async fn get_account_balance(&self, acc: AccountId) -> Result<u128> {
Ok(self Ok(self
.sequencer_client .sequencer_client
@ -229,7 +229,7 @@ impl WalletCore {
.balance) .balance)
} }
/// Get accounts nonces /// Get accounts nonces.
pub async fn get_accounts_nonces(&self, accs: Vec<AccountId>) -> Result<Vec<u128>> { pub async fn get_accounts_nonces(&self, accs: Vec<AccountId>) -> Result<Vec<u128>> {
Ok(self Ok(self
.sequencer_client .sequencer_client
@ -238,7 +238,7 @@ impl WalletCore {
.nonces) .nonces)
} }
/// Get account /// Get account.
pub async fn get_account_public(&self, account_id: AccountId) -> Result<Account> { pub async fn get_account_public(&self, account_id: AccountId) -> Result<Account> {
let response = self.sequencer_client.get_account(account_id).await?; let response = self.sequencer_client.get_account(account_id).await?;
Ok(response.account) Ok(response.account)
@ -268,7 +268,7 @@ impl WalletCore {
Some(Commitment::new(&keys.nullifer_public_key, account)) Some(Commitment::new(&keys.nullifer_public_key, account))
} }
/// Poll transactions /// Poll transactions.
pub async fn poll_native_token_transfer(&self, hash: HashType) -> Result<NSSATransaction> { pub async fn poll_native_token_transfer(&self, hash: HashType) -> Result<NSSATransaction> {
let transaction_encoded = self.poller.poll_tx(hash).await?; let transaction_encoded = self.poller.poll_tx(hash).await?;
let tx_base64_decode = BASE64.decode(transaction_encoded)?; let tx_base64_decode = BASE64.decode(transaction_encoded)?;
@ -325,13 +325,14 @@ impl WalletCore {
Ok(()) Ok(())
} }
// TODO: handle large Err-variant properly
#[expect(clippy::result_large_err, reason = "ExecutionFailureKind is large, tracked by TODO")]
pub async fn send_privacy_preserving_tx( pub async fn send_privacy_preserving_tx(
&self, &self,
accounts: Vec<PrivacyPreservingAccount>, accounts: Vec<PrivacyPreservingAccount>,
instruction_data: InstructionData, instruction_data: InstructionData,
program: &ProgramWithDependencies, program: &ProgramWithDependencies,
) -> Result<(SendTxResponse, Vec<SharedSecretKey>), ExecutionFailureKind> { ) -> Result<(SendTxResponse, Vec<SharedSecretKey>), ExecutionFailureKind> {
// TODO: handle large Err-variant properly
self.send_privacy_preserving_tx_with_pre_check(accounts, instruction_data, program, |_| { self.send_privacy_preserving_tx_with_pre_check(accounts, instruction_data, program, |_| {
Ok(()) Ok(())
}) })

View File

@ -7,7 +7,7 @@ use log::{info, warn};
use crate::config::WalletConfig; use crate::config::WalletConfig;
#[derive(Clone)] #[derive(Clone)]
/// Helperstruct to poll transactions /// Helperstruct to poll transactions.
pub struct TxPoller { pub struct TxPoller {
polling_max_blocks_to_query: usize, polling_max_blocks_to_query: usize,
polling_max_error_attempts: u64, polling_max_error_attempts: u64,

View File

@ -9,8 +9,11 @@ pub mod private;
pub mod public; pub mod public;
pub mod shielded; pub mod shielded;
#[expect(clippy::multiple_inherent_impl, reason = "impl blocks split across multiple files for organization")]
pub struct NativeTokenTransfer<'wallet>(pub &'wallet WalletCore); pub struct NativeTokenTransfer<'wallet>(pub &'wallet WalletCore);
// TODO: handle large Err-variant properly
#[expect(clippy::result_large_err, reason = "ExecutionFailureKind is large, tracked by TODO")]
fn auth_transfer_preparation( fn auth_transfer_preparation(
balance_to_move: u128, balance_to_move: u128,
) -> ( ) -> (