Skip to main content

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

Payment guarantees

The payer signs a payment. The recipient redeems it for core’s guarantee receipt and verifies it.
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.

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

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

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.
sign_request signs it as an EIP-712 PaymentAuthorization under the ClearingHouse domain, through the signer’s sign_hash:

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

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):
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

X402 flow

Pay 402-protected HTTP resources with fetch or X402Flow.

Payment middleware

Charge for a FastAPI or Flask route with 4mica-x402.

Errors

Catch and distinguish 4Mica SDK errors.