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

# Errors

> Match on 4Mica Rust SDK error variants, handle unknown outcomes safely, and read revert reasons.

# Errors

Each sub-client returns its own error enum, with typed variants for the states you branch on. The umbrella `sdk_4mica::Error` implements `From` for every one of them, so a function that mixes operations can use one `?`.

```rust theme={null}
use sdk_4mica::Error;
use sdk_4mica::error::{
    AccountError, AuthError, ClientError, ConfigError, DepositError, PaymentError,
    SettlementError, SponsorshipError, TokenError, WithdrawError, X402Error,
};
```

| Error | Returned by | What it covers |
| - | - | - |
| `ConfigError` | `ClientBuilder::build`, `ClientBuilder::from_env` | `Missing` and `InvalidValue` configuration. |
| `ClientError` | `Client::connect`, and other enums as `Client(..)` | Core unreachable (`Rpc`), an Ethereum endpoint that fails (`Provider`), `Initialization`, `ChainRpcUnavailable`, and `MissingTokenDomainSeparator`. |
| `AuthError` | `client.login`, and other enums as `Auth(..)` | SIWE sign-in and token refresh failures. |
| `SponsorshipError` | Withdrawals and settlement, as `Sponsorship(..)` | What a facilitator call can end in: `NotConfigured`, `Rejected`, `InvalidParams`, `Transport`, `OutcomeUnknown`. |
| `DepositError` | `client.deposit` | Deposit refusals, allowances, reverts, and facilitator answers. |
| `WithdrawError` | `client.withdraw` | Request, cancel, and finalize failures. |
| `SettlementError` | `client.settlement` | Net-debit payment and net-credit claim failures. |
| `PaymentError` | `client.payment` | Signing, issuing, verifying, and checkpointing. |
| `AccountError`, `TokenError` | `client.account`, `client.tokens` | Balance reads and ERC-20 approvals. |
| `X402Error` | `X402Flow` | Bad scheme or version, invalid requirements, and `/settle` transport. |

## Unknown outcomes

A request that has reached the facilitator cannot be called back, and an answer that never arrives does not mean it failed. The SDK reports that case as `OutcomeUnknown`, never as an ordinary failure, so that a retry loop does not move the same money twice.

| Operation | Variant |
| - | - |
| Deposit | `DepositError::OutcomeUnknown(message)` |
| Withdrawal | `WithdrawError::Sponsorship(SponsorshipError::OutcomeUnknown(message))` |
| Settlement | `SettlementError::Sponsorship(SponsorshipError::OutcomeUnknown(message))` |

The SDK returns it when the request was sent and no usable answer came back: a timeout, a dropped connection, an HTTP 5xx or 408, or a response it cannot read. An unpinned `.send()` never falls back to a self-funded transaction after an unknown outcome.

Do not retry it blindly. Look at what the operation would have changed first:

* **Deposit.** A second authorization is a second deposit, not a retry. Read the balance with `client.account.assets()` before you sign again.
* **Withdrawal request.** A second request overwrites the first and restarts the grace period. Read `withdrawal_request_amount` from `client.account.assets()`.
* **Settlement.** A second payment or claim reverts after paying gas when the first one went through. Confirm on-chain whether the cycle was settled before you send again.

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

match client.deposit.of(asset, amount).send().await {
    Ok(receipt) => println!("deposited: {}", receipt.tx_hash),
    Err(DepositError::OutcomeUnknown(message)) => {
        eprintln!("deposit outcome unknown: {message}");
        for position in client.account.assets().await? {
            println!("{}: {}", position.asset, position.collateral);
        }
    }
    Err(err) => return Err(err.into()),
}
```

A refusal is not an unknown outcome. `Transport` from a facilitator call means the facilitator did not act on the request: the connection failed, or it answered an HTTP 4xx other than 408. `Rejected` means the facilitator read the request and declined it. Nothing was submitted in either case.

> [!NOTE]
>
> For the wallet's own transactions, `Transport` covers both the broadcast and
> the wait for the receipt. If a `.self_funded()` or unpinned terminal returns
> it, the transaction may still be mined. Check the chain before you send it
> again.

## Facilitator refusals

A facilitator refusal carries a machine-readable `code`, a `message`, and `retryable`, which says whether the identical request may succeed later.

* Withdrawals and settlement return `SponsorshipError::Rejected { code, message, retryable }` inside `Sponsorship(..)`.
* Deposits return `DepositError::Facilitator { code, message, retryable }`, except that `sponsorship_unavailable` is `DepositError::FacilitatorNotConfigured`, the same variant as when no facilitator URL is set.

`code` is passed through verbatim, for example `rate_limited` or `simulation_reverted`, so you can branch on a code the SDK does not know.

Two allowance errors have their own variants on `DepositError` and `SettlementError`:

* `Permit2AllowanceRequired { message, eip2612_nonce }`: the facilitator found no Permit2 approval. When `eip2612_nonce` is present, pin `.permit2().sponsor_approval()` to sign the approval. When it is absent, the wallet must send `approve(PERMIT2, ...)` itself.
* `Erc20AllowanceRequired { token, spender, allowance, needed }`: the SDK checked the allowance before a self-funded fallback and found it too low. Grant it with the builder's `.self_funded().approve()` and retry.

## Reverts

A revert the SDK recognizes becomes a typed variant:

| Enum | Typed reverts |
| - | - |
| `DepositError` | `AmountZero`, `UnsupportedAsset`, `DepositsDisabled`, `StablecoinDepositsDisabled`, `PoolInsolvent`, `Paused`, `ValueMismatch`, `ZeroCollateralCredit` |
| `WithdrawError` | `AmountZero`, `InsufficientAvailable`, `NoWithdrawalRequested`, `GracePeriodNotElapsed`, `TransferFailed`, `UnsupportedAsset`, `InsufficientLiquidity`, `Paused`, `InvalidSignature`, `AuthorizationExpired`, `AuthorizationNotYetValid`, `AuthorizationAlreadyUsed` |
| `SettlementError` | `AmountZero`, `CycleNotFound`, `InvalidCycleStatus`, `PaymentWindowElapsed`, `PaymentFinalityPending`, `AlreadyPaid`, `AlreadyClaimed`, `InvalidProof`, `ResolvedDebitExceedsCommitted`, `ClaimedCreditExceedsCommitted`, `AuthorizationCycleMismatch`, `ExactPaymentRequired`, `NativeAssetUnsupported`, `CycleUnderfunded`, `ClaimExceedsFundedLiquidity`, `ClaimConversionShortfall`; and from the Treasury the ClearingHouse moves escrow through, `Paused`, `TransferFailed`, `EscrowUnderflow`, `ReconciliationLoss`, `EthReconciliationLoss` |
| `AccountError` | `UnsupportedAsset` |

Any other revert is `UnknownRevert { selector, data }`, and it carries its reason. When `data` is a standard `Error(string)` revert, the error's `Display` output is `reverted: <reason>`. Aave's numeric reason codes are spelled out, for example `reverted: 51 (Aave: supply cap exceeded)`. A revert that is one of the contracts' own errors without a variant above prints its name, for example `reverted: EscrowUnderflow (selector 0x...)`. Anything else prints `unknown revert (selector 0x...)`. `data` holds the raw bytes either way.

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

match client.withdraw.finalize(asset).self_funded().send().await {
    Ok(receipt) => println!("finalized: {}", receipt.tx_hash),
    Err(WithdrawError::GracePeriodNotElapsed) => println!("not ready yet"),
    Err(WithdrawError::InsufficientLiquidity { available, .. }) => {
        println!("the pool can pay out {available} right now");
    }
    Err(err @ WithdrawError::UnknownRevert { .. }) => eprintln!("{err}"),
    Err(err) => return Err(err.into()),
}
```

Settlement adds `SettlementError::RevertedOnChain { tx_hash }` for a transaction that was mined and reverted, so gas was spent. On a gasless route, a revert is caught in the facilitator's simulation and arrives as a refusal with the code `simulation_reverted`.

## Coded refusals

When core refuses a payment or a checkpoint with a stable code, `PaymentError` has a variant that carries the decoded details.

| Variant | Core code | Meaning |
| - | - | - |
| `CheckpointRequired(details)` | `CHECKPOINT_REQUIRED` | The payer holds too many guarantees past its latest checkpoint. Submit one and retry. |
| `CheckpointMismatch { details, reason }` | `CHECKPOINT_MISMATCH` | The checkpoint no longer matches what core holds. Read the batch again and re-sign. |
| `CycleMismatch(details)` | `CYCLE_MISMATCH` | The payment was signed for a cycle other than the active one. |
| `FutureTimestamp(details)` | `FUTURE_TIMESTAMP` | The payment is stamped later than core's clock. |
| `StaleTimestamp(details)` | `STALE_TIMESTAMP` | The payment is stamped before its cycle opened. |
| `TimestampNotPastCutoff(details)` | `TIMESTAMP_NOT_PAST_CUTOFF` | The payment is stamped at or before the payer's latest checkpoint cutoff. |

The SDK records core's clock and the new cycle from these refusals, and the cutoff when the refusal names its own payer. Build a fresh payment with `new_payment` and it is stamped correctly. Any other refusal from core arrives as `PaymentError::Rpc(err)`, where `err.status()` and `err.code()` report the HTTP status and core's code.

## Receipt errors

`client.payment.verify_guarantee` and `verify_guarantee_receipt` return these `PaymentError` variants:

| Variant | When it is returned |
| - | - |
| `MalformedReceipt(..)` | The receipt does not decode: not hex, too short, or an unknown layout. |
| `UnreadableReceiptSignature` | The receipt's signature is not a readable ECDSA signature. |
| `ReceiptSignerMismatch { expected, recovered }` | The receipt was signed by someone other than core's guarantee signer. |

## Distinguishing errors

Match on the variants you can act on and pass the rest up.

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

match recipient_client.payment.issue_guarantee(request).await {
    Ok(receipt) => {
        recipient_client.payment.verify_guarantee(&receipt)?;
    }
    Err(PaymentError::CheckpointRequired(details)) => {
        // The payer must checkpoint details.cycle_id before core issues more.
        eprintln!("{} of {} uncheckpointed", details.uncheckpointed, details.max_uncheckpointed);
    }
    Err(PaymentError::CycleMismatch(_)) => {
        // The cycle rolled over. Ask the payer for a fresh payment.
    }
    Err(PaymentError::Rpc(err)) => eprintln!("core refused ({:?}): {err}", err.code()),
    Err(err) => return Err(err.into()),
}

match client.settlement.pay(cycle_id.clone()).send().await {
    Ok(receipt) => println!("paid over {:?}", receipt.route),
    Err(SettlementError::Erc20AllowanceRequired { .. }) => {
        client.settlement.pay(cycle_id.clone()).self_funded().approve().await?;
    }
    Err(SettlementError::Sponsorship(SponsorshipError::OutcomeUnknown(message))) => {
        // It may have been paid. Check before paying again.
        eprintln!("payment outcome unknown: {message}");
    }
    Err(SettlementError::RevertedOnChain { tx_hash }) => eprintln!("reverted: {tx_hash}"),
    Err(err) => return Err(err.into()),
}
```

> [!NOTE]
>
> Every error implements `std::error::Error` and converts into
> `sdk_4mica::Error`, so you can return that umbrella type to handle any SDK
> failure in one place.

## Next steps

> [card] [Overview](https://docs.4mica.io/sdks/rust/overview.md)
>
> Install the SDK and see the capabilities at a glance.

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


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