> ## Documentation Index
> Fetch the complete documentation index at: https://docs.privacyboost.io/llms.txt
> Use this file to discover all available pages before exploring further.

# Api reference

# API Reference

Complete API reference for the Privacy Boost CLI library (Rust).

## Generated Documentation

Full API documentation can be generated using `cargo doc`:

```bash theme={null}
# From rust-sdk directory
make docs-rust

# CLI-specific docs
cargo doc --no-deps -p privacy-boost-cli
```

***

## PrivacyBoostCLI

Main CLI SDK interface for Rust applications.

### Constructor

```rust theme={null}
pub fn new(config: CliConfig) -> Result<Self, CliError>
```

Creates a new CLI SDK instance.

**Parameters:**

* `config` - CLI configuration

**Returns:** `Result<PrivacyBoostCLI, CliError>`

**Example:**

```rust theme={null}
use privacy_boost_cli::{PrivacyBoostCLI, CliConfig};

let config = CliConfig::new(
    "https://optimism.sepolia.privacyboost.io".into(),
    0,
    String::new(),
    "https://sepolia.optimism.io".into(),
);

let sdk = PrivacyBoostCLI::new(config)?;
```

### Connection & Authentication Methods

#### authenticate

```rust theme={null}
pub fn authenticate(
    &self,
    private_key: &str,
    key_source: Option<KeySource>,
    token_provider: Option<&dyn TokenProvider>,
) -> Result<AuthResult, CliError>
```

Connect wallet using a private key, derive privacy keys, and authenticate with the Privacy Boost backend in a single call.

**Parameters:**

* `private_key` - Hex-encoded private key
* `key_source` - Optional key derivation source. `None` defaults to `WalletDerived`. Options: `KeySource::WalletDerived`, `KeySource::Mnemonic { phrase }`, `KeySource::RawSeed { hex_seed }`
* `token_provider` - Optional custom token provider for server-mediated auth flows

**Returns:** `Result<AuthResult, CliError>` - either `Authenticated(LoginResult)` or `CredentialRequired(CredentialChallenge)`

#### submit\_credential

```rust theme={null}
pub fn submit_credential(&self, credential: &str) -> Result<LoginResult, CliError>
```

Submit a credential when `authenticate()` returns `CredentialRequired`.

**Returns:** `Result<LoginResult, CliError>`

#### logout

```rust theme={null}
pub fn logout(&self)
```

End session completely, clear all state.

#### clear\_session

```rust theme={null}
pub fn clear_session(&self)
```

Clear JWT only, keep keys for quick re-auth.

#### is\_authenticated

```rust theme={null}
pub fn is_authenticated(&self) -> bool
```

Check if authenticated.

### State Accessors

```rust theme={null}
pub fn get_privacy_address(&self) -> Option<String>
pub fn get_mpk(&self) -> Option<String>
pub fn get_wallet_address(&self) -> Option<String>
pub fn get_status(&self) -> StatusInfo
```

### Balance Methods

#### get\_balance

```rust theme={null}
pub fn get_balance(&self, token_address: &str) -> Result<TokenBalance, CliError>
```

Get balance for a specific token.

#### get\_all\_balances

```rust theme={null}
pub fn get_all_balances(&self) -> Result<Vec<TokenBalance>, CliError>
```

Get all token balances.

### Vault Operations

#### deposit

```rust theme={null}
pub fn shield(
    &self,
    token_address: &str,
    amount: &str,
) -> Result<ShieldResult, CliError>
```

Deposit tokens into the shielded pool.

**Parameters:**

* `token_address` - Token contract address
* `amount` - Amount in wei (as string)

#### withdraw

```rust theme={null}
pub fn unshield(
    &self,
    token_address: &str,
    amount: &str,
    recipient: &str
) -> Result<UnshieldResult, CliError>
```

Withdraw tokens from the shielded pool.

**Parameters:**

* `token_address` - Token contract address
* `amount` - Amount in wei (as string)
* `recipient` - Recipient Ethereum address

#### send

```rust theme={null}
pub fn send(
    &self,
    token_address: &str,
    amount: &str,
    recipient_privacy_address: &str
) -> Result<TransferResult, CliError>
```

Send a private transfer.

**Parameters:**

* `token_address` - Token contract address
* `amount` - Amount in wei (as string)
* `recipient_privacy_address` - Recipient's 194-char privacy address

#### prepare\_shield

```rust theme={null}
pub fn prepare_shield(
    &self,
    token_address: &str,
    amount: &str,
    recipient: Option<&str>,
) -> Result<PreparedShield, CliError>
```

Build a deposit payload **without submitting it** — for relaying the transaction
yourself (a gasless relayer, an EIP-7702 session key, or a plain raw
transaction). Returns the wrap/approve/`requestDeposit` calldata plus the note
commitment; nothing is sent on-chain. Needs an authenticated session (keys) but
no wallet. After relaying, settle from the mined receipt with
`privacy_boost_core::operations::finalize_shield`.

**Parameters:**

* `token_address` - Token contract address (use `0x0` for ETH)
* `amount` - Amount in wei (as string)
* `recipient` - Recipient privacy address; `None` shields to yourself

> CLI subcommands `prepare-shield` and `finalize-shield` wrap these for shell
> use — see the [Commands Reference](./guides/commands#prepare-shield).

### Transaction History

```rust theme={null}
pub fn get_transaction_history(
    &self,
    tx_type: Option<&str>,
    token_address: Option<&str>,
    limit: Option<u32>
) -> Result<Vec<Transaction>, CliError>
```

Get transaction history.

### Session Persistence

#### export\_session

```rust theme={null}
pub fn export_session(&self) -> Option<ExportedSession>
```

Export session data for persistence.

#### import\_session

```rust theme={null}
pub fn import_session(&self, session: &ExportedSession) -> Result<bool, CliError>
```

Import session from persistence.

### Address Lookup

#### resolve\_identity

```rust theme={null}
pub fn resolve_identity(&self, identifier: &str) -> Result<IdentityResult, CliError>
```

Look up a user's privacy address by MPK or Ethereum address.

**Parameters:**

* `identifier` - MPK or Ethereum address

**Returns:** `Result<IdentityResult, CliError>`

### Utilities

```rust theme={null}
pub fn is_valid_privacy_address(&self, address: &str) -> bool
pub fn is_valid_address(&self, address: &str) -> bool
pub fn parse_amount(&self, amount: &str, decimals: u8) -> Result<String, CliError>
pub fn format_amount(&self, wei: &str, decimals: u8) -> Result<String, CliError>
```

***

## Module Functions

```rust theme={null}
pub fn sdk_version() -> String
```

Returns the SDK version string.

***

## CliConfig

CLI configuration struct.

```rust theme={null}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PrivacyBoostConfig {
    pub server_url: String,
    #[serde(default)]
    pub chain_id: u64,                        // 0 = auto-discover from server
    #[serde(default)]
    pub shield_contract_address: String,      // empty = auto-discover from server
    pub weth_contract_address: Option<String>,
    pub rpc_url: String,
    pub timeout_secs: u64,
    pub app_id: Option<String>,
    pub tee_public_key: Option<String>,
    pub persistence_storage: Option<String>,
    pub persistence_unlock: Option<String>,
}
```

### Constructor

```rust theme={null}
pub fn new(
    server_url: String,
    chain_id: u64,
    shield_contract_address: String,
    rpc_url: String,
) -> Self
```

### Builder Methods

```rust theme={null}
pub fn with_weth_contract_address(self, weth_contract_address: String) -> Self
pub fn with_timeout(self, timeout_secs: u64) -> Self
```

### File Operations

```rust theme={null}
pub fn default_config_path() -> Result<PathBuf, CliError>
pub fn load_from_file(path: &PathBuf) -> Result<Self, CliError>
pub fn load_from_default() -> Result<Option<Self>, CliError>
pub fn save_to_file(&self, path: &PathBuf) -> Result<(), CliError>
pub fn save_to_default(&self) -> Result<PathBuf, CliError>
```

### Environment

```rust theme={null}
pub fn from_environment() -> Self
```

***

## NetworkPreset

Network preset enumeration.

```rust theme={null}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkPreset {
    Local,
    OpSepolia,
}
```

### Methods

```rust theme={null}
pub fn config(&self) -> CliConfig
pub fn parse(s: &str) -> Option<Self>
```

**Parse aliases:**

* `Local`: `"local"`, `"localhost"`, `"dev"`
* `OpSepolia`: `"op-sepolia"`, `"optimism-sepolia"`, `"opsepolia"`

**Example:**

```rust theme={null}
let preset = NetworkPreset::parse("op-sepolia").unwrap();
let config = preset.config();
```

***

## Types

### KeySource

```rust theme={null}
pub enum KeySource {
    WalletDerived,
    Mnemonic { phrase: String },
    RawSeed { hex_seed: String },
}
```

Key derivation source, passed to `authenticate()`. `WalletDerived` derives keys from a wallet signature, `Mnemonic` from a BIP-39 phrase, and `RawSeed` from a raw 32-byte hex seed.

### AuthResult

```rust theme={null}
pub enum AuthResult {
    Authenticated(LoginResult),
    CredentialRequired(CredentialChallenge),
}
```

### LoginResult

```rust theme={null}
pub struct LoginResult {
    pub wallet_address: String,
    pub privacy_address: String,
    pub mpk: String,
}
```

### TokenBalance

```rust theme={null}
pub struct TokenBalance {
    pub token_address: String,
    pub shielded_balance: String,
    pub wallet_balance: String,
    pub symbol: Option<String>,
    pub decimals: u8,
}
```

### ShieldResult

```rust theme={null}
pub struct ShieldResult {
    pub tx_hash: String,
    pub commitment: String,
}
```

### UnshieldResult

```rust theme={null}
pub struct UnshieldResult {
    pub tx_hash: String,
    pub fee: String,
}
```

### TransferResult

```rust theme={null}
pub struct TransferResult {
    pub tx_hash: String,
    pub fee: String,
}
```

### PreparedShield

Returned by `prepare_shield`. Re-exported from
`privacy_boost_core::operations`. Carries no private material, so it is safe to
hand to a relayer. Each `Call` is a single on-chain call to relay; `value` and
`data` are 0x-hex.

```rust theme={null}
pub struct Call {
    pub to: String,
    pub value: String,    // 0x-hex wei quantity ("0x0" for non-payable calls)
    pub data: String,     // ABI-encoded calldata (0x-prefixed)
}

pub struct ShieldFinalizeMeta {
    pub shield_contract: String,   // the DepositRequested emitter
    pub token_id: u16,
}

pub struct PreparedShield {
    pub approve: Option<Call>,     // ERC-20 approve(pool, amount); omitted when suppressed
    pub wrap: Option<Call>,        // WETH deposit() wrap; present only for native ETH
    pub shield: Call,              // the requestDeposit(...) call
    pub commitment: String,
    pub finalize: ShieldFinalizeMeta,
}
```

### Transaction

```rust theme={null}
pub struct Transaction {
    pub tx_hash: String,
    pub tx_type: String,
    pub token_address: String,
    pub amount: String,
    pub direction: String,
    pub sender_pub_key: String,
    pub receiver_pub_keys: Vec<String>,
    pub created_at: u64,
}
```

### StatusInfo

```rust theme={null}
pub struct StatusInfo {
    pub connected: bool,
    pub authenticated: bool,
    pub wallet_address: Option<String>,
    pub privacy_address: Option<String>,
    pub mpk: Option<String>,
}
```

### IdentityResult

```rust theme={null}
pub struct IdentityResult {
    pub mpk: String,
    pub ethereum_address: String,
    pub viewing_public_key_x: String,
    pub viewing_public_key_y: String,
    pub privacy_address: String,
}
```

### ExportedSession

Re-exported from `privacy_boost_core::sdk_state::ExportedSession`:

```rust theme={null}
pub struct ExportedSession {
    pub wallet_public_key_x: String,
    pub wallet_public_key_y: String,
    pub viewing_key: String,
    pub viewing_public_key_x: String,
    pub viewing_public_key_y: String,
    pub nullifying_key: String,
    pub nullifying_public_key_x: String,
    pub nullifying_public_key_y: String,
    pub mpk: String,
    pub account_id: String,
    pub jwt: String,
    pub jwt_expiry: u64,
    pub wallet_address: String,
}
```

***

## CliError

```rust theme={null}
pub enum CliError {
    NotConnected,
    NotAuthenticated,
    InvalidConfig { message: String },
    InvalidPrivateKey { message: String },
    NetworkError { message: String },
    WalletError { message: String },
    SigningError { message: String },
    TransactionFailed { message: String },
    InsufficientBalance,
    InvalidAddress,
    InvalidAmount,
    SerializationError { message: String },
    InternalError { message: String },
    ConfigFileError { message: String },
}
```

***

## Default Values

```rust theme={null}
pub mod defaults {
    pub const RPC_URL: &str = "http://localhost:8545";
    pub const SERVER_URL: &str = "http://localhost:8080";
    pub const WETH_CONTRACT_ADDRESS: &str = "0x36c02da8a0983159322a80ffe9f24b1acff8b570";
    pub const TEST_TOKEN_CONTRACT: &str = "0x36c02da8a0983159322a80ffe9f24b1acff8b570";
}
```

***

## Complete Example

```rust theme={null}
use privacy_boost_cli::{PrivacyBoostCLI, CliConfig, NetworkPreset};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load configuration from preset
    let config = NetworkPreset::OpSepolia.config();

    // Or load from file
    // let config = CliConfig::load_from_default()?.unwrap();

    // Create SDK
    let sdk = PrivacyBoostCLI::new(config)?;

    // Authenticate with private key
    let private_key = std::env::var("PRIVATE_KEY")?;
    let auth_result = sdk.authenticate(&private_key, None, None)?;
    match auth_result {
        AuthResult::Authenticated(login_result) => {
            println!("Privacy Address: {}", login_result.privacy_address);
        }
        AuthResult::CredentialRequired(challenge) => {
            let login_result = sdk.submit_credential(&credential)?;
            println!("Privacy Address: {}", login_result.privacy_address);
        }
    }

    // Check balance
    let token = "0x4200000000000000000000000000000000000006";
    let balance = sdk.get_balance(token)?;
    println!("Balance: {} wei", balance.shielded_balance);

    // Deposit
    let deposit_result = sdk.shield(token, "1000000000000000000")?;
    println!("Deposit TX: {}", deposit_result.tx_hash);

    // Export session for later
    if let Some(session) = sdk.export_session() {
        let json = serde_json::to_string(&session)?;
        std::fs::write("session.json", json)?;
    }

    // Logout
    sdk.logout();

    Ok(())
}
```

## Gift & Portal Commands

Claimable transfers and portal deposit addresses are preview features (pending
external audit), exposed as CLI subcommands:

* [Claimable Transfers](./guides/claimable-transfers) — `gift-fund-to-wallet`,
  `gift-fund`, `gift-list`, `gift-claim`, `gift-claim-from-link`,
  `gift-refund-by-record`, `gift-refund`, `gift-decode-link`
* [Portal Deposits](./guides/portal-deposits) — `portal create | list | status |
  deposits | sweep | reclaim | withdraw`

## See Also

* [Getting Started](./getting-started) - Basic CLI usage
* [Commands Reference](./guides/commands) - CLI commands
* [Claimable Transfers](./guides/claimable-transfers) - Send to an unregistered wallet
* [Portal Deposits](./guides/portal-deposits) - Reusable public deposit addresses
* [Network Presets](./guides/network-presets) - Network configuration
