> ## 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, withdraw, sign payments, issue guarantees, checkpoint, and settle cleared cycles with the Rust SDK.

# Client operations

Every field on `Client` is an intent-builder 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()`). See [the builder grammar](https://docs.4mica.io/sdks/rust/overview.md#the-builder-grammar).

Settlement is **cycle-based**. A cycle is a fixed window scoped to one asset. Core nets every guarantee issued in the window into one net debit or net credit per participant and commits the result on-chain as a Merkle root. Each side then makes one settlement call for the cycle.

The examples below assume a connected `client` on Base Sepolia and these values:

```rust theme={null}
use sdk_4mica::{Address, Asset, U256};

let usdc: Address = "0xba50Cd2A20f6DA35D788639E581bca8d0B5d4D5f".parse()?;
let asset = Asset::Erc20(usdc);
let amount = U256::from(5_000_000u64); // 5 USDC in base units
```

## Collateral

### Deposit

An unpinned deposit takes the cheapest route the asset and configuration allow:

```rust theme={null}
let receipt = client.deposit.of(asset, amount).send().await?;
println!("deposited over {:?}: {}", receipt.route, receipt.tx_hash);
```

For an ERC-20 with a facilitator configured, it tries EIP-3009 first, then Permit2 with the approval sponsored. It falls back to the wallet's own transaction when no gasless route applies: native ETH, no facilitator, or a token whose Permit2 approval cannot be sponsored.

### Approve

Gasless deposits carry their own authorization. Only a self-funded ERC-20 deposit needs an allowance first. The builder knows the token, the spender, and the amount:

```rust theme={null}
let deposit = client.deposit.of(asset, amount).self_funded();
deposit.approve().await?;
deposit.send().await?;
```

`client.tokens.approve(token, amount)` grants the same allowance for an amount you choose.

> [!NOTE]
>
> When an unpinned deposit falls back after the gasless routes were refused, it
> checks the allowance first. A missing allowance returns
> `DepositError::Erc20AllowanceRequired` before any gas is spent.

### Positions

```rust theme={null}
for position in client.account.assets().await? {
    println!(
        "{}: collateral {}, pending withdrawal {}",
        position.asset, position.collateral, position.withdrawal_request_amount,
    );
}

let withdrawable = client.account.withdrawable_balance(asset).await?;

if let Some(balance) = client.account.asset_balance(asset).await? {
    println!("total {}, locked {}", balance.total, balance.locked);
}

let supported = client.tokens.supported().await?;
```

* `assets()`, `principal_balance(asset)`, and `withdrawable_balance(asset)` read the contract.
* `asset_balance(asset)` reads core's view, including the amount locked behind guarantees. It lags the chain: a deposit appears once core has confirmed it.
* `stablecoin_position(token)` reports the principal and yield split of a yield-bearing stablecoin, plus the pool's share accounting.
* `tokens.supported()` lists the assets core accepts, with `symbol`, `address`, and `decimals`.

## Withdrawals

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

```rust theme={null}
client.withdraw.request(asset, U256::from(2_000_000u64)).send().await?;
client.withdraw.cancel(asset).send().await?;
client.withdraw.finalize(asset).send().await?;
```

`request` starts the grace period. `cancel` removes the pending request before the grace period ends. `finalize` pays out after it ends.

Each step goes through the facilitator where possible and falls back to the wallet's own transaction when no facilitator is configured or the facilitator declines to sponsor. A rejection that names the request itself, such as an amount above the available balance, is returned and not retried.

To check a finalization without spending gas, preflight it on the gasless pin:

```rust theme={null}
client.withdraw.finalize(asset).gasless().verify().await?;
```

## Gasless routes

With a facilitator configured, deposits, withdrawals, and settlement can run without the signer paying gas. The signer produces an EIP-712 authorization and the facilitator submits it at its own expense. Every route credits the authorization's signer. The route only changes who pays.

| Operation | Pins |
| - | - |
| `deposit.of`, `settlement.pay` | `.gasless()`, `.eip3009()`, `.permit2()`, `.permit2().sponsor_approval()`, `.self_funded()` |
| `withdraw.request`, `withdraw.cancel`, `withdraw.finalize`, `settlement.claim` | `.gasless()`, `.self_funded()` |

```rust theme={null}
// A pinned route fails rather than trying another one.
client.deposit.of(asset, amount).gasless().send().await?;
client.deposit.of(asset, amount).permit2().sponsor_approval().send().await?;

// Sign now, submit elsewhere. The submitting client's signer is not used.
let auth = client.deposit.of(asset, amount).eip3009().sign().await?;
let deposit = client.deposit.of(asset, amount).eip3009().authorization(auth);
deposit.verify().await?;
deposit.send().await?;

// Withdrawals are gasless for native ETH too.
client
    .withdraw
    .request(Asset::Native, U256::from(1_000_000_000_000_000u64))
    .gasless()
    .send()
    .await?;
```

* `.gasless()` on a deposit or a payment tries EIP-3009, then Permit2 with the approval sponsored. It never falls back to a self-funded transaction.
* `.permit2()` needs a one-time on-chain `approve(PERMIT2, ...)` from the signer. Without it the call fails with `Permit2AllowanceRequired`. `.sponsor_approval()` signs that approval as an EIP-2612 permit where the token supports it.
* `.sign()` exists on `.eip3009()` and `.permit2()` pins, and on the `.gasless()` pin of a withdrawal request or cancellation. A finalization and a claim need no signature.

Each receipt reports the route that ran. Deposits and payments report a `TokenRoute` (`Eip3009`, `Permit2`, `SponsoredPermit2`, `SelfFunded`). Withdrawals and claims report a `Route` (`Gasless`, `SelfFunded`). Both have `is_gasless()`.

> [!NOTE]
>
> Native ETH has no gasless deposit route, and a native-asset debit cannot be
> pulled by signature. Both are self-funded. `is_gasless_available()` on
> `client.deposit`, `client.withdraw`, and `client.settlement` reports whether
> a facilitator is configured at all. A refusal carries the facilitator's
> `code`. An `OutcomeUnknown` error means the facilitator may already have
> submitted the transaction, so do not retry it blindly; see
> [Errors](https://docs.4mica.io/sdks/rust/errors.md#unknown-outcomes).

## Payment guarantees

The payer signs a payment. The recipient redeems it for core's guarantee receipt and verifies it. In the example, `recipient` is the recipient's `Address`.

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

// Payer
let payload = client
    .payment
    .new_payment(recipient, U256::from(100_000u64), asset)
    .await?;
let request = client.payment.sign_request(payload).await?;

// Recipient, on its own client
let receipt = recipient_client.payment.issue_guarantee(request).await?;
let Guarantee::V1(guarantee) = recipient_client.payment.verify_guarantee(&receipt)?;
println!("{} guaranteed to {}", guarantee.amount, guarantee.recipient);
```

`new_payment` scopes the payload to the asset's active settlement cycle, which it reads from core. It generates a random `req_id` and a random salt that blinds the recipient, and stamps the payment by core's clock, not this machine's. `sign_request` signs the payload as an EIP-712 message with the client's signer.

### `client.payment` methods

* `new_payment(recipient, amount, asset)`: a payment payload scoped to the asset's active cycle.
* `sign_request(payload)`: signs the payload as the payer and returns a `PaymentRequest`.
* `issue_guarantee(request)`: redeems a signed request for core's `GuaranteeReceipt`, as the recipient.
* `verify_guarantee(&receipt)`: checks that core's guarantee signer signed the receipt and returns the `Guarantee` it attests.
* `list_received()`: deprecated. It reads core's `GET /core/recipients/{recipient}/payments`, which no longer records new payments. List what a recipient was paid in a cycle with core's [`GET /core/recipients/{recipient}/guarantees`](https://docs.4mica.io/api-reference/operator/list-guarantees); this SDK does not wrap it yet.
* `active_cycle(asset)`: the cycle payments for the asset must be signed for right now.
* `checkpoint_active_cycle(asset)` and `checkpoint_cycle(asset, cycle_id)`: sign and submit a checkpoint; see [Checkpoints](#checkpoints).

> [!NOTE]
>
> Verification is offline. It reaches neither the chain nor core. A
> service that holds no `Client` can run the same check with
> `sdk_4mica::verify_guarantee_receipt`, which takes the receipt, the
> GuaranteeRegistry EIP-712 domain, and the address of core's guarantee signer. A
> receipt that has not been verified attests nothing.

### Validated guarantees

A payer can agree that a guarantee only becomes payable once an external validator approves it. Attach a `ValidationRequirement` to the payload before you sign it:

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

let payload = client
    .payment
    .new_payment(recipient, amount, asset)
    .await?
    .with_validation(ValidationRequirement {
        validator: "validator-id".to_string(), // must be on core's allowlist
        subject,                               // B256: what the validator must approve
        deadline: Some(1_800_000_000),         // optional, unix seconds
        params: Default::default(),            // optional validator-specific bytes
    });
let request = client.payment.sign_request(payload).await?;
```

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

## 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 `PaymentError::CheckpointRequired`. Only the payer can sign its checkpoint, so run these calls on the payer's client.

```rust theme={null}
use sdk_4mica::error::PaymentError;

// Cover everything outstanding in the asset's active cycle.
// Returns `None` when there is nothing to cover.
client.payment.checkpoint_active_cycle(asset).await?;

// Or cover the cycle a refusal names. `refusal` is the error the recipient's
// `issue_guarantee` call returned.
if let PaymentError::CheckpointRequired(details) = refusal {
    client
        .payment
        .checkpoint_cycle(asset, details.cycle_id.parse()?)
        .await?;
    // Build and sign a fresh payment, then retry.
}
```

Both methods read the batch and sign once more when core answers that the batch moved while it was being signed. A second refusal returns `PaymentError::CheckpointMismatch`. Submitting a checkpoint that core already accepted succeeds and covers nothing, so a retry is safe. `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 returns
> `PaymentError::UntrustedCheckpointBatch` and nothing is signed, because the
> checkpoint total is what the payer can be charged on default.

## Settlement

Once a cycle's netting is committed on-chain, the debtor pays what it owes and the creditor claims what it is owed. The terms always come from core's prepared action. You only name the cycle.

Settlement takes the cycle's text id, `{asset_address}:{period_start}`. `active_cycle` returns it while the cycle is open:

```rust theme={null}
let cycle = client.payment.active_cycle(asset).await?;
let cycle_id = cycle.cycle_id_text;
```

### Pay a net debit

```rust theme={null}
let receipt = client.settlement.pay(cycle_id.clone()).send().await?;
println!("paid over {:?}: {}", receipt.route, receipt.tx_hash);
```

For an ERC-20 cycle with a facilitator configured, the debtor signs an authorization for the exact committed amount: EIP-3009 where the token supports it, Permit2 otherwise. The facilitator submits it and pays the gas, so the debtor needs no native balance. A native-asset cycle is always self-funded, with the debit sent as the transaction's value.

A self-funded ERC-20 payment needs the ClearingHouse allowance first. The builder resolves the token, the spender, and the committed amount from the cycle:

```rust theme={null}
let pay = client.settlement.pay(cycle_id.clone()).self_funded();
pay.approve().await?;
pay.send().await?;
```

This approval targets the ClearingHouse, a different contract from the one a deposit approval targets.

To inspect the prepared terms without sending anything:

```rust theme={null}
let action = client.settlement.pay(cycle_id.clone()).action().await?;
println!("{} to {}", action.amount, action.contract_address);
```

### Claim a net credit

```rust theme={null}
let receipt = client.settlement.claim(cycle_id.clone()).send().await?;

// Claim on someone else's behalf. The payout still goes to the creditor.
client
    .settlement
    .claim(cycle_id.clone())
    .creditor(creditor_address)
    .send()
    .await?;

// Preflight a claim without spending gas.
client.settlement.claim(cycle_id).gasless().verify().await?;
```

A claim needs no signature from the creditor. The payout goes to the address the committed Merkle leaf names, for the amount it fixes, so a submitter can neither redirect nor inflate it. With a facilitator configured, `send()` goes through its relayer and falls back to the caller's own transaction when the facilitator declines to sponsor.

> [!NOTE]
>
> A rejection that names the payment or the claim itself is returned and not
> retried self-funded, because the wallet's own transaction would revert for
> the same reason. A transaction that was mined and reverted returns
> `SettlementError::RevertedOnChain` with its `tx_hash`.

## Next steps

> [card] [X402 flow](https://docs.4mica.io/sdks/rust/x402-flow.md)
>
> Sign payment headers for `402`-protected HTTP resources.

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

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