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

# Get started with Rust

> Add Ark payments to your Rust application. Create a wallet, generate addresses, and check your balance in minutes.

Use this prompt to get started quickly.

# Bark SDK: Rust

Build Ark wallet apps in Rust with the `bark-wallet` crate. Ark is a bitcoin layer 2 protocol for instant, low-fee, self-custodial payments.

## Prerequisites

* The latest stable Rust with Cargo
* `protoc` (the Protocol Buffers compiler) in `PATH`, or its full path in the `PROTOC` environment variable

## Install

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo add bark-wallet
cargo add tokio --features full
cargo add anyhow
```

## Create a wallet

```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
use std::path::PathBuf;

use bark::ark::bitcoin::Network;
use bark::bip39::Mnemonic;
use bark::{Config, OpenWalletArgs, Wallet, WalletSeed};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let network = Network::Signet;

    // Signet tests only: don't store a real mnemonic in an unencrypted file
    let mnemonic_path = PathBuf::from("bark-mnemonic");
    let mnemonic: Mnemonic = if mnemonic_path.exists() {
        let words = tokio::fs::read_to_string(&mnemonic_path).await?;
        words.trim().parse()?
    } else {
        let mnemonic = Mnemonic::generate(12)?;
        tokio::fs::write(&mnemonic_path, mnemonic.to_string()).await?;
        mnemonic
    };

    // Configure the signet endpoints
    let config = Config {
        server_address: "https://ark.signet.2nd.dev".into(),
        esplora_address: Some("https://esplora.signet.2nd.dev".into()),
        ..Config::network_default(network)
    };

    let datadir = PathBuf::from("bark");

    // Create the wallet in datadir, or reopen it on later launches
    let wallet = Wallet::open(
        network,
        WalletSeed::new_from_mnemonic(network, &mnemonic),
        config,
        OpenWalletArgs {
            datadir: Some(datadir),
            ..Default::default()
        },
    )
    .await?;

    Ok(())
}
```

## Get address and check balance

Add these lines at the end of `main`, before `Ok(())`:

```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
let address = wallet.new_address().await?;
println!("Ark address: {address}");
wallet.sync().await;
let balance = wallet.balance().await?;
println!("Spendable: {} sats", balance.spendable.to_sat());
```

## Signet test environment

* Ark server: [https://ark.signet.2nd.dev](https://ark.signet.2nd.dev)
* Esplora API: [https://esplora.signet.2nd.dev](https://esplora.signet.2nd.dev)
* Faucet for test bitcoin: [https://signet.2nd.dev/](https://signet.2nd.dev/)
* Network enum: `Network::Signet`

## Rules

* Open wallets with `Wallet::open(network, WalletSeed::new_from_mnemonic(network, &mnemonic), config, OpenWalletArgs { datadir: Some(datadir), ..Default::default() })`. It creates the wallet on first launch and reopens it afterwards. Don't use `Wallet::create()`, a low-level call that only writes a new wallet and returns `anyhow::Result<()>`, not a `Wallet`.
* Build `Config` with `server_address`, `esplora_address`, and `..Config::network_default(network)` for the other fields. `Wallet::open()` fails without an Esplora URL or bitcoind settings.
* Bark creates `datadir` if it doesn't exist. Only one open `Wallet` can use a `datadir` at a time, even within one process. A second `Wallet::open()` on it fails with "another process is already using datadir". Open the wallet once and clone the `Wallet` where you need it.
* Reuse the same mnemonic on every launch. `Wallet::open()` fails with "incorrect mnemonic" if it doesn't match the wallet stored in `datadir`.
* Keep the `Wallet` in scope for the life of your app. `Wallet::open()` starts Bark's background sync, which stops when you drop the last `Wallet` clone.
* Wallet operations are async. Run them inside a Tokio runtime, such as `#[tokio::main]`.
* `wallet.sync().await` returns `()`. Don't put `?` after it.
* Balance amounts are `Amount` values from `bark::ark::bitcoin`. Call `.to_sat()` to get sats.
* Import `Network` from `bark::ark::bitcoin` and `Mnemonic` from `bark::bip39` instead of adding the `bitcoin` or `bip39` crates. Their latest versions can differ from Bark's.
* Use `Network::Signet` for testing. Mainnet is `Network::Bitcoin`. Never use mainnet without user confirmation.
* Never hardcode or log mnemonics in production code.
* The crate name is `bark-wallet`, not `bark`, `bark-bitcoin`, or `bark-sdk`. Its library name is `bark`, as in `use bark::Wallet`.
* Correct terminology: Ark (not ARC), VTXO (not vtxo), on-chain (not onchain), off-chain (not offchain).
* "Bark" (capitalized) in prose, "bark" (lowercase) for the crate name and CLI commands.

> [!TIP]
>
> These examples connect to **signet** so you can test for free. To go live, point the same configuration at Second's mainnet endpoints from [Connection details](https://second.tech/docs/connection-details.md) and select the mainnet network.

## Prerequisites

* The latest stable [Rust](https://rust-lang.org/tools/install/) with Cargo
* `protoc`, the Protocol Buffers compiler

Install `protoc` for your platform:

> [tab] macOS
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> brew install protobuf
> ```

> [tab] Debian and Ubuntu
>
> ```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
> sudo apt install protobuf-compiler
> ```

> [tab] Windows
>
> Download `protoc-<version>-win64.zip` from the [protobuf releases](https://github.com/protocolbuffers/protobuf/releases) and extract it. Then add its `bin` folder to your `PATH`, or set the `PROTOC` environment variable to the full path of `protoc.exe`.

## Getting started

**1. Install the SDK**

In your project directory, run:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo add bark-wallet
```

Then add Tokio and `anyhow`:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
cargo add tokio --features full
cargo add anyhow
```

Import `bitcoin` and `bip39` types from Bark's re-exports, `bark::ark::bitcoin` and `bark::bip39`, instead of adding those crates.

**2. Create a wallet**

Generate a BIP39 mnemonic, configure the signet endpoints, and open the wallet in a data directory. `Wallet::open()` creates the wallet on the first launch and reopens it on later ones.

```rust src/main.rs theme={"theme":{"light":"github-light","dark":"github-dark"}}
use std::path::PathBuf;

use bark::ark::bitcoin::Network;
use bark::bip39::Mnemonic;
use bark::{Config, OpenWalletArgs, Wallet, WalletSeed};

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let network = Network::Signet;

    // Signet tests only: don't store a real mnemonic in an unencrypted file
    let mnemonic_path = PathBuf::from("bark-mnemonic");
    let mnemonic: Mnemonic = if mnemonic_path.exists() {
        let words = tokio::fs::read_to_string(&mnemonic_path).await?;
        words.trim().parse()?
    } else {
        let mnemonic = Mnemonic::generate(12)?;
        tokio::fs::write(&mnemonic_path, mnemonic.to_string()).await?;
        mnemonic
    };

    // Configure the signet endpoints
    let config = Config {
        server_address: "https://ark.signet.2nd.dev".into(),
        esplora_address: Some("https://esplora.signet.2nd.dev".into()),
        ..Config::network_default(network)
    };

    let datadir = PathBuf::from("bark");

    // Create the wallet in datadir, or reopen it on later launches
    let wallet = Wallet::open(
        network,
        WalletSeed::new_from_mnemonic(network, &mnemonic),
        config,
        OpenWalletArgs {
            datadir: Some(datadir),
            ..Default::default()
        },
    )
    .await?;

    Ok(())
}
```

> [!WARNING]
>
> The sample code stores the mnemonic in an unencrypted file so that the next launch reopens the same wallet. That is acceptable for signet tests only. In a production app, store the mnemonic in your platform's secure storage. Also set up [continuous wallet data backups](https://second.tech/docs/backups.md), so users can restore their wallet without the Ark server's cooperation.

**3. Get a receiving address**

Generate an Ark address to receive bitcoin. Add these lines at the end of `main`, before `Ok(())`:

```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
let address = wallet.new_address().await?;
println!("Ark address: {address}");
```

Run `cargo run` to print the address. Send some signet sats to this address using [the faucet](https://signet.2nd.dev/).

**4. Check your balance**

Bark syncs the wallet in the background while it's open. Call `sync()` when you need an up-to-date balance right away.

Add these lines after the address lines, before `Ok(())`:

```rust theme={"theme":{"light":"github-light","dark":"github-dark"}}
wallet.sync().await;

let balance = wallet.balance().await?;
println!("Spendable: {} sats", balance.spendable.to_sat());
```

Balance amounts are `Amount` values from `bark::ark::bitcoin`.

Run `cargo run` again. The program reopens the same wallet and prints your spendable balance in sats.

## Next steps

> [card] [API reference](https://docs.rs/bark-wallet/latest/bark/index.html)
>
> Full Rust API documentation on docs.rs.

> [card] [How Ark works](https://second.tech/docs/learn/intro.md)
>
> Learn about the protocol powering your wallet.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.