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

# Client operations

> Deposit collateral, sign payments, issue guarantees, and settle cleared cycles.

# Client operations

Every field on the client is an intent-builder sub-client: an entry captures what to do (`client.deposit.of(...)`), a route pin narrows how (`.self_funded()`), and a terminal does it (`.send()`, `.approve()`, `.action()`). Amounts are integers in the asset's base units, and an asset is a token address, or `None` for native ETH.

The samples below use `client` for a `Client`: the one a session returns from `await session.low_level()`, or one you [build yourself](https://docs.4mica.io/sdks/python/configuration.md#advanced-exact-control). Build it on `base-sepolia` while you develop.

Settlement is **cycle-based**. Core nets each participant's obligations for a settlement cycle into a single net debit or net credit per asset, committed to an on-chain Merkle root. Participants settle by fetching their prepared clearing action (contract address, amount, and Merkle proof) from core, then calling the `ClearingHouse`. The `cycle_id` that settlement takes is core's text cycle id (`cycle_id_text` in clearing responses, `"{asset}:{period_start}"`). Core does not resolve the on-chain `bytes32` id in this path.

## Deposits and withdrawals

Deposit collateral, then sign a payment:

```python theme={null}
# Deposit ETH collateral (in wei); a None asset is native ETH
await client.deposit.of(None, 10**15).send()  # 0.001 ETH

# Build a payment for the asset's active settlement cycle, then sign it
payload = await client.payment.new_payment(
    recipient_address,
    1000,  # amount in the asset's base units
)  # asset omitted = native ETH

request = await client.payment.sign_request(payload)
```

An unpinned `send()` on a token takes the cheapest route that works: gasless through the facilitator where one is configured, then the wallet's own transaction. To self-fund an ERC-20 deposit, grant the allowance first:

```python theme={null}
await client.deposit.of(token_address, 1000).self_funded().approve()
await client.deposit.of(token_address, 1000).self_funded().send()
```

> [!NOTE]
>
> `approve()` returns `None` when the existing allowance is already
> sufficient. A self-funded deposit with a missing allowance is refused with a
> typed `Erc20AllowanceRequiredError` before any gas is spent.

A withdrawal waits out a grace period, one builder per step:

```python theme={null}
await client.withdraw.request(token_address, 500).send()  # grace period starts
await client.withdraw.cancel(token_address).send()  # any time before it is finalized
await client.withdraw.finalize(token_address).send()  # after the grace period ends
```

## Payment guarantees

The payer signs a payment. The recipient redeems it for core's guarantee receipt and verifies it.

> [!NOTE]
>
> Core issues a guarantee only to a token that carries the `guarantee:issue` scope and whose wallet is the payment's recipient or holds the `facilitator` role. A SIWE session gets core's default scopes, `payment:read` alone, unless core's operator granted the wallet more, so an ordinary recipient is refused with a 401 `missing scope`. In the x402 flow the facilitator issues the guarantee on the recipient's behalf.

```python theme={null}
# Payer side
payload = await payer.payment.new_payment(recipient_address, amount, asset)
request = await payer.payment.sign_request(payload)

# Recipient side
receipt = await recipient.payment.issue_guarantee(request)

# Verify: check the ECDSA signature of core's guarantee signer offline and decode the guarantee
guarantee = recipient.payment.verify_guarantee(receipt)
print("guaranteed", guarantee.amount, "in cycle", hex(guarantee.cycle_id))
```

### `client.payment` methods

* `new_payment(recipient, amount, asset=None)`: a payment payload scoped to the asset's active settlement cycle.
* `sign_request(payload)`: sign the payload as the payer, returning a `PaymentRequest`.
* `issue_guarantee(request)`: redeem a signed request for core's `GuaranteeReceipt`.
* `verify_guarantee(receipt)`: check the receipt was signed by the guarantee signer core publishes, and return the `Guarantee` it attests. This one is synchronous.
* `list_received(cycle_id, limit=None, after=None)`: one page of the guarantees issued to the signer as a recipient in a cycle, each with its payer, request id, amount, timestamp, and status. Takes the on-chain `bytes32` cycle id; pass the page's `next_cursor` back as `after` for the next.
* `list_issued(cycle_id, limit=None, after=None)`: one page of the guarantees the signer issued in a cycle.
* `checkpoint_active_cycle(asset=None)` / `checkpoint_cycle(asset, cycle_id)`: sign and submit a checkpoint (see [Checkpoints](#checkpoints)).

> [!NOTE]
>
> Verification is offline. A service that never builds a `Client` can run the
> same check with `verify_guarantee_receipt(receipt,
>     guarantee_registry_domain_separator(chain_id, guarantee_registry_address),
>     guarantee_signer)`, taking the three values from core's public parameters.

## Settling a cleared cycle

The debtor pays what they owe, and the creditor claims what they are owed. Terms always come from core's prepared action. The caller only names which cycle.

### Everything at once

`settle()` on a `FourMica` session asks core which positions are open, pays each debit and claims each credit, and returns one result per position. A position that fails does not stop the others.

```python theme={null}
import os

from fourmica_sdk import FourMica

async with await FourMica.connect(
    private_key=os.environ["PRIVATE_KEY"], network="base-sepolia"
) as session:
    for result in await session.settle():
        position = result.position
        print(result.action, position.amount, position.asset.symbol, result.status)
        if result.status == "unknown":
            # Sent, and no answer came back. It may have gone through:
            # look before settling again.
            ...
```

| `status` | Meaning |
| - | - |
| `"settled"` | Paid or claimed. `tx_hash` is the transaction. |
| `"skipped"` | Not attempted; `reason` says why. A position is skipped until its cycle's commit is confirmed on-chain. |
| `"failed"` | Refused or reverted; `error` is the typed error. Nothing moved. |
| `"unknown"` | Sent, and no answer came back; `error` is an `OutcomeUnknownError`. Check before running it again. |

A debit is paid gaslessly where a facilitator can relay it. Otherwise the wallet sends its own transaction, and for a token the ClearingHouse may not pull yet, an approval for the exact amount before it: two transactions, both paid for in the network's native asset.

`session.settle(only="pay")` settles only what the wallet owes, and `only="claim"` only what it is owed. Pay first if you settle in two steps: an unpaid debit is taken from the wallet's collateral once its deadline passes.

`session.positions()` lists the same positions without settling anything: `role` (`"debtor"` or `"creditor"`), `amount`, `asset`, `pay_by`, `final_at`, `commit_confirmed`, and `cycle`, the id the calls below take.

### One cycle

The same calls on the `Client` settle one cycle, and choose its route. `settlement.positions()` returns the open positions as core reports them. Pass a position's `cycle_id_text` as `cycle_id`.

```python theme={null}
# Debtor: pay the committed net debit
await client.settlement.pay(cycle_id).send()

# Self-funded ERC-20 cycles need the ClearingHouse allowance first
await client.settlement.pay(cycle_id).self_funded().approve()

# Creditor: claim the committed net credit
await client.settlement.claim(cycle_id).send()

# Sponsor someone else's claim (the payout still goes to the committed leaf)
await client.settlement.claim(cycle_id).creditor(creditor_address).send()

# Inspect the prepared terms without sending anything
action = await client.settlement.pay(cycle_id).action()
```

To see what a cycle's debit is made of, `client.payment.list_issued(position.cycle_id)` lists the guarantees the wallet issued in it: recipient, request id, amount, and status. This call takes the on-chain id, not the text id. It returns one page; pass its `next_cursor` back as `after` for the next.

```python theme={null}
page = await client.payment.list_issued(position.cycle_id)
while page.next_cursor:
    page = await client.payment.list_issued(position.cycle_id, after=page.next_cursor)
```

## Gasless routes

With a facilitator configured, deposits, withdrawals, and settlement can run without the signer paying gas: the signer produces an authorization and the facilitator submits it at its own expense. `ConfigBuilder.network(...)` configures the network's hosted facilitator, and `facilitator_url(...)` or `FOURMICA_FACILITATOR_URL` names another. Every route credits the authorization's signer. The choice only changes who pays, and the receipt's `route` field reports which one ran.

```python theme={null}
# Auto route: EIP-3009, then Permit2 with the approval sponsored, then self-funded
# only if Permit2 still needs an approval. Other facilitator refusals are raised.
await client.deposit.of(usdc, 1_000_000).send()

# Pin a scheme; a pinned route fails rather than trying another one.
await client.deposit.of(usdc, 1_000_000).gasless().send()
await client.deposit.of(usdc, 1_000_000).permit2().sponsor_approval().send()

# Sign now, submit elsewhere: the submitter needs no signer of their own.
auth = await client.deposit.of(usdc, 1_000_000).eip3009().sign()
await client.deposit.of(usdc, 1_000_000).eip3009().authorization(auth).verify()
await client.deposit.of(usdc, 1_000_000).eip3009().authorization(auth).send()

# Withdrawals work for ETH too; a claim needs no signature at all.
await client.withdraw.request(None, 10**17).gasless().send()
await client.settlement.pay(cycle_id).gasless().send()
await client.settlement.claim(cycle_id).gasless().send()
```

> [!NOTE]
>
> Native ETH has no gasless deposit route, since no authorization scheme covers
> it, and native-asset debits cannot be pulled by signature. Both self-fund.
> `client.deposit.is_gasless_available()` reports whether a facilitator is
> configured at all. A rejection surfaces as `FacilitatorRejectedError`
> carrying the facilitator's snake\_case reason (such as `simulation_reverted`) as
> `code`, except `sponsorship_unavailable` (`FacilitatorNotConfiguredError`)
> and `permit2_allowance_required` (`Permit2AllowanceRequiredError`). An `OutcomeUnknownError` means the facilitator may already have
> submitted: do not blindly retry it.

## Balances

```python theme={null}
positions = await client.account.assets()  # per-asset on-chain positions
balance = await client.account.asset_balance(token_address)  # core's view, incl. locked
tokens = (await client.tokens.supported()).tokens  # depositable assets
```

`asset_balance` returns `None` when the signer holds nothing in the asset. It lags the chain: a fresh deposit appears once core has observed it.

`client.account.stablecoin_position(token)` reports a stablecoin pool position: the principal and yield split, plus the pool's share accounting (`user_shares`, `total_user_shares`, `protocol_shares`, `pool_shares`, `pool_assets`) and the `strategy` backing the pool, which is the zero address while its assets sit idle.

## Building payments

Build payments with `client.payment.new_payment`. A payment is scoped to the asset's active settlement cycle, which it reads from core, so it cannot be built offline. It is stamped by core's clock rather than this machine's, gets a random `uint256` `req_id`, and a random `salt` that blinds the recipient. The asset defaults to the zero address, which represents native ETH.

```python theme={null}
payload = await client.payment.new_payment(
    recipient_address,
    amount,  # int, in base units
    erc20_token,  # optional; omit for native ETH
)
# payload.cycle_id, payload.req_id, payload.timestamp, payload.salt, ...
```

`sign_request` signs it as an EIP-712 `PaymentAuthorization` under the ClearingHouse domain, through the signer's `sign_hash`:

```python theme={null}
request = await client.payment.sign_request(payload)
# request.payload, request.signature
```

## Validated guarantees

A payer can agree that a guarantee only becomes payable once an external validator approves it, by attaching a `ValidationRequirement` to the payload before signing. The requirement is bound into the salted recipient commitment the payer signs:

```python theme={null}
from fourmica_sdk import ValidationRequirement

payload = (
    await client.payment.new_payment(recipient_address, amount, erc20_token)
).with_validation(
    ValidationRequirement(
        validator="validator-id",  # must be on core's allowlist
        subject="0x...",  # 32-byte hash the validator must approve
        deadline=1700000600,  # optional; core tightens it to the cycle cutoff
        params="0x",  # optional validator-specific policy bytes
    )
)

request = await client.payment.sign_request(payload)
receipt = await client.payment.issue_guarantee(request)
```

In the x402 flow, the same requirement travels as `extra.validation` on the payment requirements and is attached automatically.

## Checkpoints

A checkpoint is the payer's signed running total of its payments in a cycle. Core caps how many guarantees a payer may hold past its latest checkpoint. Past the cap, issuance is refused with a `CheckpointRequiredError`. Only the payer can sign its checkpoint, so run these on the payer's client.

```python theme={null}
from fourmica_sdk import CheckpointRequiredError

# Cover everything outstanding in the asset's active cycle
await payer.payment.checkpoint_active_cycle(erc20_token)  # None when there is nothing to cover

# Or cover the cycle a refusal names, then retry
try:
    receipt = await recipient.payment.issue_guarantee(request)
except CheckpointRequiredError as exc:
    await payer.payment.checkpoint_cycle(
        exc.details.asset_address, exc.details.cycle_id
    )
```

Both methods read the batch and sign once more when core answers `CheckpointMismatchError` because the batch moved while it was being signed. A second mismatch is raised. `cycle_id` here is the on-chain `bytes32` id, not the text id settlement takes.

> [!NOTE]
>
> Core's batch is checked before it is signed: every payment must be one the
> payer signed, in this cycle and asset, past the previous checkpoint, and
> counted once. A batch that fails those checks raises
> `UntrustedCheckpointBatchError` rather than being signed, since signing it
> could inflate what the payer can be charged on default.

## Transaction receipt options

Terminals that can send the wallet's own transaction accept an optional `TxReceiptWaitOptions` to override receipt polling. Terminals pinned to a gasless route take none.

```python theme={null}
from fourmica_sdk import TxReceiptWaitOptions

await client.deposit.of(token_address, 1000).send(
    TxReceiptWaitOptions(timeout_secs=90, poll_latency_secs=2)
)
```

## Sellers: the app API

`fourmica_sdk.app` talks to the app API behind the 4Mica dashboard with a listing's or agent's API key. `resource()` describes the listing or agent the key belongs to. `resolve_customer()` says whether a payer may pay, and how much after quotas, coupons, and credit. `report_payment()` records a payment, and is idempotent per `req_id`.

In an x402 after-settle hook, `parse_settlement(context)` reads off what `report_payment()` needs. The app API calls the two halves of the guarantee receipt `guarantee_claims` (the receipt's `receipt` field) and `guarantee_signature` (its `signature`):

```python theme={null}
from fourmica_sdk.app import AppClient, parse_settlement

async with AppClient(api_key) as app:
    settled = parse_settlement(context)
    reported = await app.report_payment(
        req_id=settled.req_id,
        payer_address=settled.payer_address,
        recipient_address=pay_to,
        network="base-sepolia",
        amount=settled.amount,  # base units
        guarantee_claims=settled.guarantee_claims,
        guarantee_signature=settled.guarantee_signature,
    )
    print(reported["payment"]["status"], reported["created"])
```

Responses are dictionaries with the API's own camelCase keys, such as `resolution["allowed"]` and `resolution["payable"]`. Networks take any form of the name: `base-sepolia`, `BASE_SEPOLIA`, or `eip155:84532`. A refusal or an unreachable API raises `AppError`, with `status`, `code`, and `issues`.

## Next steps

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

> [card] [Payment middleware](https://docs.4mica.io/seller/payment-middleware.md)
>
> Charge for a FastAPI or Flask route with `4mica-x402`.

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