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

# Rust SDK

> Install and use sdk-4mica, the Rust SDK for collateral, payments, and settlement on the 4Mica payment network.

# Rust SDK

`sdk-4mica` is the official Rust SDK for the 4Mica payment network. Use it to deposit collateral, sign payments, pay for HTTP 402-protected resources, withdraw, and settle cleared cycles.

It has two parts:

* **`Client`**: connect once, then deposit, withdraw, sign payments, and settle through intent builders. Amounts are `U256` values in the asset's base units.
* **`X402Flow`**: turn the payment requirements from a `402 Payment Required` response into a signed payment header.

The SDK covers the wallet side of 4Mica. It has no HTTP server middleware. To charge for a route, use `@4mica/x402` (TypeScript) or `4mica-x402` (Python); see [payment middleware](https://docs.4mica.io/seller/payment-middleware.md).

## Install

The crate is published as `sdk-4mica` and imported as `sdk_4mica`. It uses the Rust 2024 edition, so build it with a current stable toolchain.

```bash theme={null}
cargo add sdk-4mica
cargo add alloy@2
cargo add tokio --features macros,rt-multi-thread
```

`alloy` provides the signer types. Add the same major version the SDK depends on, so your signer implements the traits the SDK expects. The SDK's async calls run on Tokio.

## Your first session

Connect, deposit, and sign a payment. Start on Base Sepolia with a test wallet.

```rust theme={null}
use alloy::signers::local::PrivateKeySigner;
use sdk_4mica::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let signer: PrivateKeySigner = std::env::var("PRIVATE_KEY")?.parse()?;
    let client = Client::builder()
        .network(Network::BaseSepolia)
        .signer(signer)
        .connect()
        .await?;

    // Aave's test USDC on Base Sepolia. It has 6 decimals.
    let usdc: Address = "0xba50Cd2A20f6DA35D788639E581bca8d0B5d4D5f".parse()?;

    let receipt = client
        .deposit
        .of(Asset::Erc20(usdc), U256::from(5_000_000u64))
        .send()
        .await?;
    println!("deposited over {:?}: {}", receipt.route, receipt.tx_hash);

    let recipient: Address = std::env::var("RECIPIENT_ADDRESS")?.parse()?;
    let payload = client
        .payment
        .new_payment(recipient, U256::from(100_000u64), Asset::Erc20(usdc))
        .await?;
    let request = client.payment.sign_request(payload).await?;
    println!("signed payment: {}", request.signature);

    Ok(())
}
```

`connect()` reaches the core service for its public parameters and checks that core accepts the payment payload version this SDK signs. With the network's hosted facilitator, the deposit is gasless where the token supports it. `receipt.route` reports which route ran.

> [!WARNING]
>
> Without `.network(...)`, the client connects to Base mainnet and moves real
> funds. Keep `Network::BaseSepolia` in your code until you mean to go live.

The testnets accept Aave's test USDC as collateral. See [Get test tokens](https://docs.4mica.io/getting-started/test-tokens.md) for how to mint it.

`Client` groups its calls by what you are doing:

| Field | What it does |
| - | - |
| `client.deposit` | Deposits collateral, gasless or self-funded. |
| `client.withdraw` | Requests, cancels, and finalizes withdrawals. |
| `client.payment` | Signs payments, issues and verifies guarantees, and submits checkpoints. |
| `client.settlement` | Pays a net debit or claims a net credit for a cleared cycle. |
| `client.account` | Reads the signer's balances and positions. |
| `client.tokens` | Lists supported tokens and approves ERC-20 allowances. |

`sdk_4mica::prelude` exports the names most integrations need: `Client`, `ClientBuilder`, `Network`, `Asset`, `Address`, `U256`, `Credentials`, `Error`, and the receipt and route types.

### Amounts and assets

Amounts are `U256` values in the asset's base units: `U256::from(5_000_000u64)` is 5 USDC. Name the asset with `Asset::Erc20(address)` or `Asset::Native` for ETH.

## The builder grammar

Every deposit, withdrawal, and settlement call follows the same three steps.

1. **Entry.** State what to do: `client.deposit.of(asset, amount)`, `client.withdraw.request(asset, amount)`, `client.settlement.pay(cycle_id)`. An entry does no I/O. It returns a builder.
2. **Route pin (optional).** State how to do it: `.gasless()`, `.eip3009()`, `.permit2()`, `.permit2().sponsor_approval()`, or `.self_funded()`. Without a pin, the terminal takes the cheapest route available and may fall back to the wallet's own transaction.
3. **Terminal.** Run it.

| Terminal | Available on | What it does |
| - | - | - |
| `.send()` | Every builder | Executes the operation and returns a receipt. |
| `.sign()` | `.eip3009()` and `.permit2()` pins, and the `.gasless()` pin of a withdrawal request or cancellation | Signs an authorization for someone else to submit. |
| `.authorization(auth)` | The same pins as `.sign()` | Attaches an authorization signed elsewhere. The result offers `.verify()` and `.send()`. |
| `.verify()` | Authorized builders, and the `.gasless()` pin of a finalization or a claim | Runs the facilitator's checks without spending gas. |
| `.approve()` | `.self_funded()` pins of a deposit or a net-debit payment | Sends the ERC-20 approval the self-funded route needs. |
| `.action()` | Unpinned settlement builders | Fetches the prepared settlement call without sending it. |

```rust theme={null}
client.deposit.of(asset, amount).send().await?;
client.deposit.of(asset, amount).eip3009().sign().await?;
client.withdraw.request(asset, amount).gasless().send().await?;
client.settlement.claim(cycle_id).creditor(address).send().await?;
```

Each pin changes the builder's type, so a builder only offers the terminals that exist for its route. Every receipt reports the route that ran in `receipt.route`, and `receipt.route.is_gasless()` tells you whether someone else paid the gas.

## Networks

4Mica is live on three networks; see [supported networks](https://docs.4mica.io/getting-started/supported-networks.md). Select one with `.network(...)` on the builder or with the `4MICA_NETWORK` environment variable.

| Shorthand | `Network` variant | CAIP-2 | Core API URL | Hosted facilitator |
| - | - | - | - | - |
| `base` | `Network::Base` | `eip155:8453` | `https://base.api.4mica.io/` | `https://payment.4mica.io/` |
| `base-sepolia` | `Network::BaseSepolia` | `eip155:84532` | `https://base.sepolia.api.4mica.io/` | `https://testnet.payment.4mica.io/` |
| `ethereum-sepolia` | `Network::EthereumSepolia` | `eip155:11155111` | `https://ethereum.sepolia.api.4mica.io/` | `https://testnet.payment.4mica.io/` |

Ethereum mainnet is coming soon. The default is Base mainnet. Selecting a network also selects its hosted facilitator; see [Configuration](https://docs.4mica.io/sdks/rust/configuration.md#networks-and-the-facilitator).

`Network` parses from a shorthand or a CAIP-2 id, and reports its own details:

```rust theme={null}
use sdk_4mica::Network;

let network: Network = "base-sepolia".parse()?;

assert_eq!(network, Network::BaseSepolia);
assert_eq!(network.caip2(), "eip155:84532");
assert_eq!(network.facilitator_url(), Some("https://testnet.payment.4mica.io/"));
```

> [!WARNING]
>
> Keep private keys in environment variables instead of committing them to your
> code. Use a dedicated test wallet while you develop.

## Next steps

> [card] [Configuration](https://docs.4mica.io/sdks/rust/configuration.md)
>
> `ClientBuilder`, environment variables, signers, and authentication.

> [card] [Client operations](https://docs.4mica.io/sdks/rust/client-operations.md)
>
> Deposit collateral, withdraw, sign payments, and settle cleared cycles.

> [card] [X402 flow](https://docs.4mica.io/sdks/rust/x402-flow.md)
>
> Turn a `402 Payment Required` response into a signed payment header.

> [card] [Errors](https://docs.4mica.io/sdks/rust/errors.md)
>
> Match on error variants and handle unknown outcomes safely.


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