> ## 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.

# Python SDK

> Install and use sdk-4mica, the async Python SDK for the 4Mica payment network.

# Python SDK

`sdk-4mica` is the official Python SDK for the 4Mica payment network. You import it as `fourmica_sdk`. Use it to deposit collateral, pay for HTTP 402-protected resources, withdraw, sign and settle guarantees, and report payments for your own listings.

It has two layers:

* **`FourMica`**: connect once, then deposit, pay, and withdraw with amounts written as `"5 USDC"`. Start here.
* **`Client`**: the exact-control layer, with intent builders for every deposit, withdrawal, guarantee, and settlement route, and amounts in base units. Reach it from a session with `await client.low_level()`.

## Async throughout

Every call that reaches a network is a coroutine, so run the SDK inside an event loop. HTTP goes through `httpx`, and `client.fetch` returns an `httpx.Response`. A session belongs to the event loop it was connected on. The package ships its type annotations (`py.typed`).

## Install

Python 3.10 or later is required.

```bash pip theme={null}
pip install sdk-4mica
```

```bash uv theme={null}
uv add sdk-4mica
```

```bash poetry theme={null}
poetry add sdk-4mica
```

To sign with a Coinbase CDP wallet, install the `cdp` extra: `pip install "sdk-4mica[cdp]"`.

## Your first session

Connect, deposit, and make a paid request. Start on Base Sepolia with a test wallet.

```python theme={null}
import asyncio
import os

from fourmica_sdk import FourMica


async def main() -> None:
    async with await FourMica.connect(
        private_key=os.environ["PRIVATE_KEY"],
        network="base-sepolia",
    ) as client:
        await client.deposit("5 USDC")
        response = await client.fetch("https://api.example.com/data")
        print(response.status_code, client.payment_for(response))


asyncio.run(main())
```

> [!WARNING]
>
> The default network is Base mainnet (`base`). If you omit `network`, the
> session connects to mainnet and every deposit and payment moves real funds.
> Pass `network="base-sepolia"` while you develop.

`FourMica.connect` reaches the core service for its public parameters and checks that core accepts the payment payload version this SDK signs. `async with` closes the session when the block exits, even if a call raises. Outside a `with` block, call `await client.aclose()` in a `finally` clause. The other samples on these pages run inside a coroutine like `main`.

Test collateral on the testnets is Aave's test USDC, minted from Aave's public faucet contract. [Get test tokens](https://docs.4mica.io/getting-started/test-tokens.md) shows how to mint it.

| Call | What it does |
| - | - |
| `await client.deposit("5 USDC")` | Deposits collateral, gasless where the network's facilitator can sponsor it. Returns once core counts it. |
| `await client.balance()` / `await client.balance("USDC")` | Collateral per asset: `total`, `locked`, and `available` as decimal strings, plus integers under `raw`. |
| `await client.fetch(url, method="GET", **kwargs)` | An `httpx` request. Pays a 4Mica 402 within the session's spend limits and retries once. |
| `client.payment_for(response)` | What `fetch` paid for a response, or `None`. |
| `await client.withdraw("2 USDC")` | Requests a withdrawal. The grace period starts now. |
| `await client.withdrawals()` | Pending withdrawal requests, each with `ready_at` and `ready`. |
| `await client.finalize_withdrawal("USDC")` | Pays out a requested withdrawal once its grace period has ended. |
| `await client.cancel_withdrawal("USDC")` | Cancels a requested withdrawal. |
| `await client.positions()` | What the wallet still owes and is still owed: one entry per asset and settlement cycle, soonest deadline first. |
| `await client.settle(only=None)` | Pays every open debit and claims every open credit. Returns one result per position. |
| `await client.low_level(network=None)` | The underlying `Client`, for anything the facade does not cover. |
| `await client.aclose()` | Closes the session. `async with` calls it for you. |
| `client.address` / `client.network` | The signer address, and the session's network. |

Every call that touches a network except `fetch` takes a `network=` keyword to use another network. The session connects it on first use.

### Deposits

`deposit` does not raise when core is slow to count a mined deposit. It returns a `DepositResult` with `status="pending"`, and `await result.spendable()` waits again. Pass `wait="mined"` to return as soon as the transaction is mined, `gas="self"` to send the wallet's own transaction, and `timeout_secs=` to change the 60-second wait.

### Amounts

Amounts are decimal strings with their asset: `"5 USDC"` or `{"amount": "5", "asset": "USDC"}`. The asset is a symbol core lists (any case), `"ETH"` for the native asset, or a token address. Numbers are rejected on purpose, since `5` could mean 5 USDC or 5 base units. An amount with more decimals than the token has raises `AmountPrecisionError`. The SDK never rounds.

## Networks

4Mica is live on Base, Base Sepolia, and Ethereum Sepolia. Ethereum mainnet is coming soon. Select a network with the `network` argument of `FourMica.connect` or the `FOURMICA_NETWORK` environment variable; see [supported networks](https://docs.4mica.io/getting-started/supported-networks.md).

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

The default is `base` (`DEFAULT_NETWORK`), which is Base mainnet. Selecting a network also selects its hosted facilitator, so deposits and withdrawals go gasless by default on all three.

Read network details from the exported `NETWORKS` mapping:

```python theme={null}
from fourmica_sdk import NETWORKS, to_caip2

print(NETWORKS["base-sepolia"].caip2)  # "eip155:84532"
print(NETWORKS["base-sepolia"].facilitator_url)  # "https://testnet.payment.4mica.io/"
print(to_caip2("BASE_SEPOLIA"))  # "eip155:84532"
```

## Exact control with `Client`

`await client.low_level()` returns the session's `Client`, which the session closes for you. Its capability sub-clients take amounts in base units:

* **`deposit`**: deposit collateral in ETH or ERC-20 tokens, choosing the route.
* **`withdraw`**: request, cancel, and finalize withdrawals.
* **`payment`**: sign, issue, and verify payment guarantees.
* **`settlement`**: settle a cleared cycle from either side. The debtor pays, the creditor claims.
* **`account`** / **`tokens`**: the signer's balances and supported-token metadata.

Alongside it, `X402Flow` turns a `402 Payment Required` response into a signed payment header, and `fourmica_sdk.app` is the seller's client for the app API behind the 4Mica dashboard.

To build a `Client` yourself, use `ConfigBuilder` and `Client.connect`; see [Configuration](https://docs.4mica.io/sdks/python/configuration.md#advanced-exact-control).

> [!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/python/configuration.md)
>
> `FourMica.connect` options, environment variables, custom signers, and `ConfigBuilder`.

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

> [card] [X402 flow](https://docs.4mica.io/sdks/python/x402-flow.md)
>
> Pay a `402 Payment Required` response with `fetch` or `X402Flow`.

> [card] [Errors](https://docs.4mica.io/sdks/python/errors.md)
>
> Catch and distinguish 4Mica SDK errors.


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