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

# Examples

> Current Rust SDK examples for clear execution, local MPC, bytecode, ClientStore inputs, network config, and observability.

These examples match the Stoffel 0.1.0 SDK in the `stoffel` repository.

Run examples from the repository root:

```bash theme={null}
cd /path/to/stoffel
cargo run -p stoffel-rust-sdk --example quickstart
cargo run -p stoffel-rust-sdk --example local_mpc_named_inputs
cargo run -p stoffel-rust-sdk --example local_mpc_client_input
```

## Clear local execution

Use clear execution for fast logic checks before moving to local MPC runs.

```rust theme={null}
use stoffel::prelude::*;

fn main() -> stoffel::Result<()> {
    let result = Stoffel::compile("def main(a: int64, b: int64) -> int64:\n  return a + b")?
        .with_inputs(&[("a", 42_i64), ("b", 58_i64)])
        .execute_clear()?;

    println!("Result: {}", result[0]);
    Ok(())
}
```

Expected output:

```text theme={null}
Result: 100
```

Repository file: `crates/stoffel-rust-sdk/examples/quickstart.rs`.

## Direct `secret int64` arguments

The repository includes `crates/stoffel-rust-sdk/examples/quickstart_mpc.rs`, which demonstrates direct `secret int64` function arguments:

```rust theme={null}
use stoffel::prelude::*;

#[tokio::main]
async fn main() -> stoffel::Result<()> {
    let result = Stoffel::compile(
        "def main(a: secret int64, b: secret int64) -> secret int64:\n  return a + b",
    )?
    .parties(5)
    .threshold(1)
    .with_inputs(&[("a", 42_i64), ("b", 58_i64)])
    .execute_local()
    .await;

    match result {
        Ok(values) => println!("Private result: {}", values[0]),
        Err(stoffel::Error::Unsupported(message)) => println!("Local MPC unavailable: {message}"),
        Err(error) => return Err(error),
    }

    Ok(())
}
```

Use the `Share` and `ClientStore` examples below as local MPC smoke tests. They exercise explicit private inputs and deliberate reveal points.

## Named `Share` inputs

Use this when the source function accepts share values directly and opens only the intended output.

```rust theme={null}
use stoffel::prelude::*;

#[tokio::main]
async fn main() -> stoffel::Result<()> {
    let source = r#"
def add_private_values(a: Share, b: Share) -> int64:
  var sum = Share.add(a, b)
  return sum.open()
"#;

    match Stoffel::compile(source)?
        .parties(5)
        .threshold(1)
        .with_inputs(&[("a", 42_i64), ("b", 58_i64)])
        .execute_local_function("add_private_values")
        .await
    {
        Ok(result) => println!("Local MPC named-input result: {}", result[0]),
        Err(stoffel::Error::Unsupported(message)) => println!("Local MPC unavailable: {message}"),
        Err(error) => return Err(error),
    }

    Ok(())
}
```

Repository file: `crates/stoffel-rust-sdk/examples/local_mpc_named_inputs.rs`.

## ClientStore local inputs

Use `ClientStore.take_share` when modeling local client slots.

```rust theme={null}
use stoffel::prelude::*;

#[tokio::main]
async fn main() -> stoffel::Result<()> {
    let source = r#"
def main() -> int64:
  var share = ClientStore.take_share(0, 0)
  var opened: int64 = share.open()
  return opened + 5
"#;

    let runtime = Stoffel::compile(source)?.parties(5).threshold(1).build()?;
    let client = runtime.program().client(0).expect("client slot 0");
    println!(
        "Program expects {} input(s) from client slot {}",
        client.input_count(),
        client.client_slot()
    );

    match Stoffel::load(&runtime.program().to_bytecode()?)?
        .parties(5)
        .threshold(1)
        .with_client_input(0, &[42_i64])
        .execute_local()
        .await
    {
        Ok(result) => println!("Local MPC result: {}", result[0]),
        Err(stoffel::Error::Unsupported(message)) => println!("Local MPC unavailable: {message}"),
        Err(error) => return Err(error),
    }

    Ok(())
}
```

Repository file: `crates/stoffel-rust-sdk/examples/local_mpc_client_input.rs`.

## Bytecode round trip

Compile source, save bytecode, load it back, and execute with inputs.

```rust theme={null}
use std::time::{SystemTime, UNIX_EPOCH};

use stoffel::prelude::*;

fn main() -> stoffel::Result<()> {
    let source = "def main(a: int64, b: int64) -> int64:\n  return a * b";
    let runtime = Stoffel::compile(source)?.build()?;

    let bytecode_path = std::env::temp_dir().join(format!(
        "stoffel-sdk-bytecode-{}-{}.stflb",
        std::process::id(),
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|duration| duration.as_nanos())
            .unwrap_or_default()
    ));
    runtime.save_bytecode(&bytecode_path)?;
    let summary = runtime.bytecode_summary()?;

    let result = Stoffel::load_file(&bytecode_path)?
        .with_inputs(&[("a", 6_i64), ("b", 7_i64)])
        .execute_clear()?;

    let _ = std::fs::remove_file(&bytecode_path);
    println!(
        "Bytecode round-trip result: {} ({} bytes, {} function(s))",
        result[0], summary.byte_len, summary.program.function_count
    );
    Ok(())
}
```

Repository file: `crates/stoffel-rust-sdk/examples/bytecode_roundtrip.rs`.

## Network configuration

Generate TOML configs for a local network deployment and build server/client handles from those configs.

```rust theme={null}
use stoffel::prelude::*;

fn main() -> stoffel::Result<()> {
    let deployment = NetworkDeployment::builder([
        "127.0.0.1:19200",
        "127.0.0.1:19201",
        "127.0.0.1:19202",
        "127.0.0.1:19203",
        "127.0.0.1:19204",
    ])
    .expected_clients(1)
    .threshold(1)
    .backend(MpcBackend::HoneyBadger)
    .preprocessing(1000, 500)
    .build()?;

    let config_dir = std::env::temp_dir().join("stoffel-sdk-network-configs");
    let paths = deployment.save_toml_files(&config_dir)?;
    let reparsed = NetworkConfig::from_toml_file(&paths[0])?;
    let _ = std::fs::remove_dir_all(&config_dir);

    let server = StoffelServer::builder(0)
        .network_deployment(&deployment)
        .build()?;
    let client = StoffelClient::builder().network_config(&reparsed).build()?;

    println!(
        "Configured party {} on {} with {} peer(s); client sees {} server(s)",
        server.party_id(),
        server.bind_addr(),
        server.peers().len(),
        client.servers().len()
    );
    Ok(())
}
```

Repository file: `crates/stoffel-rust-sdk/examples/network_config.rs`.

## Observability and health

```rust theme={null}
use std::time::Duration;

use stoffel::prelude::*;
use tracing::Level;

fn main() -> stoffel::Result<()> {
    let tracing = TracingConfig::builder()
        .service_name("stoffel-observability-example")
        .max_level(Level::INFO)
        .ansi(false)
        .build();

    let server = StoffelServer::builder(0)
        .bind("127.0.0.1:19400")
        .with_preprocessing(100, 50)
        .build()?;

    server.metrics().record_connected_peers(4);
    server.metrics().record_connected_clients(1);
    server.metrics().record_preprocessing_remaining(80, 40);
    server
        .metrics()
        .record_computation_latency(Duration::from_millis(25));
    server.metrics().increment_computations_completed();

    let snapshot = server.metrics().snapshot();
    println!(
        "health={} peers={} completed={}",
        server.health(),
        snapshot.connected_peers,
        snapshot.computations_completed
    );

    let error = Error::Preprocessing("not enough triples".to_owned());
    println!(
        "error_category={} recoverable={} hint={:?}",
        error.category(),
        error.is_recoverable(),
        error.recovery_hint()
    );

    println!("Tracing summary: {:?}", tracing.summary());
    Ok(())
}
```

Repository file: `crates/stoffel-rust-sdk/examples/observability.rs`.

## Choosing an input style

| Program shape                                | SDK input API                                                               | CLI equivalent                                 |
| -------------------------------------------- | --------------------------------------------------------------------------- | ---------------------------------------------- |
| `def main(a: int64, b: int64)`               | `.with_inputs(&[("a", 1_i64), ("b", 2_i64)])`                               | `--input a=1 --input b=2`                      |
| `def main(a: secret int64, b: secret int64)` | `.with_inputs(&[("a", 1_i64), ("b", 2_i64)])` plus `.execute_local().await` | `--input a=1 --input b=2` with local execution |
| `ClientStore.take_share(0, 0)`               | `.with_client_input(0, &[1_i64])`                                           | `--client-input 0=1`                           |

## Next steps

* [Rust SDK Installation](./installation)
* [Quick Start](../getting-started/quick-start)
* [CLI Overview](../cli/overview)
