Skip to main content

Python SDK for interacting with the 4Mica payment network.

Project description

4Mica Python SDK

Asyncio-first bindings for the 4mica credit flow used by x402. This mirrors the Rust SDK surface (payer, recipient, X402 helpers, strongly typed request/response models) and now matches the docs in ~/x402-4mica.

Installation

pip install .           # from this repo
# Optional: remuneration requires BLS decoding
pip install 'sdk-4mica[bls]'

Quick integration (resource servers)

Use the facilitator (for example https://x402.4mica.xyz/) to open tabs and settle signed guarantees:

  • Advertise scheme = "4mica-credit" and a supported network in your 402 Payment Required responses. Embed your POST tab endpoint in paymentRequirements.extra.tabEndpoint, alongside payTo / asset / maxAmountRequired.
  • Implement the tab endpoint to accept { userAddress, paymentRequirements }, call the facilitator’s POST /tabs with { userAddress, recipientAddress = payTo, erc20Token = asset, ttlSeconds? }, and return the tab response (at least tabId and userAddress). Cache tabs per (user, recipient, asset) to avoid extra calls; the facilitator will also reuse them.
  • When a retried request arrives with X-PAYMENT, base64-decode it and send { x402Version, paymentHeader, paymentRequirements } to /verify (optional preflight) and /settle (to obtain the certificate).

Quick integration (clients)

Install the SDK and sign the X-PAYMENT header with X402Flow (same flow as the TypeScript and Rust SDKs in ~/x402-4mica):

pip install sdk-4mica
import asyncio
from fourmica_sdk import Client, ConfigBuilder, PaymentRequirements, X402Flow

payer_key = "0x..."    # wallet private key
user_address = "0x..." # address to embed in the claims

async def main():
    cfg = ConfigBuilder().wallet_private_key(payer_key).rpc_url("https://api.4mica.xyz/").build()
    client = await Client.new(cfg)
    flow = X402Flow.from_client(client)

    # Fetch the recipient's paymentRequirements (must include extra.tabEndpoint)
    req_raw = fetch_requirements_somehow()[0]
    requirements = PaymentRequirements.from_raw(req_raw)

    payment = await flow.sign_payment(requirements, user_address)
    headers = {"X-PAYMENT": payment.header}  # base64 string to send with the retry

    # Optional: settle immediately if the recipient delegates settlement to you
    settlement = await flow.settle_payment(payment, requirements, facilitator_url="https://x402.4mica.xyz/")
    print("Settlement:", settlement.settlement)

    await client.aclose()

asyncio.run(main())

SDK quick start (direct 4mica calls)

import asyncio
from fourmica_sdk import (
    Client, ConfigBuilder, PaymentGuaranteeRequestClaims, SigningScheme
)

async def main():
    cfg = ConfigBuilder().from_env().wallet_private_key("0x...").build()
    client = await Client.new(cfg)

    # Deposit 1 ETH
    await client.user.deposit(10**18)

    # Create a tab as the recipient
    tab_id = await client.recipient.create_tab(
        user_address="0xUser",
        recipient_address=client.recipient._recipient_address,  # or set explicitly
        erc20_token=None,
        ttl=3600,
    )

    # Sign a payment as the user
    claims = PaymentGuaranteeRequestClaims.new(
        "0xUser",
        client.recipient._recipient_address,
        tab_id,
        10**17,
        timestamp=int(__import__("time").time()),
        erc20_token=None,
    )
    sig = await client.user.sign_payment(claims, SigningScheme.EIP712)

    # Issue a guarantee as the recipient
    cert = await client.recipient.issue_payment_guarantee(claims, sig.signature, sig.scheme)
    print("Guarantee:", cert)

    await client.aclose()

asyncio.run(main())

X-PAYMENT header schema

X-PAYMENT is a base64-encoded JSON envelope:

{
  "x402Version": 1,
  "scheme": "4mica-credit",
  "network": "polygon-amoy",
  "payload": {
    "claims": {
      "user_address": "<0x-prefixed checksum string>",
      "recipient_address": "<0x-prefixed checksum string>",
      "tab_id": "<decimal or 0x value>",
      "amount": "<decimal or 0x value>",
      "asset_address": "<0x-prefixed checksum string>",
      "timestamp": 1716500000,
      "version": 1
    },
    "signature": "<0x-prefixed wallet signature>",
    "scheme": "eip712"
  }
}

Facilitators enforce that scheme / network match /supported, payTo matches recipient_address in the claims, and asset / maxAmountRequired equal the signed amount.

End-to-end credit flow (x402)

  1. Resource sends 402 Payment Required with (scheme, network) and a tab endpoint.
  2. Client calls the tab endpoint with { userAddress, erc20Token?, ttlSeconds? }; the recipient calls /tabs and returns tab metadata.
  3. Client signs a guarantee with the SDK and wraps it into X-PAYMENT.
  4. Client retries the protected call with X-PAYMENT: <base64>.
  5. Recipient optionally calls /verify with { x402Version, paymentHeader, paymentRequirements }.
  6. Recipient calls /settle to obtain the certificate, then relays repayment details to the payer.

Configuration

  • wallet_private_key (required)
  • rpc_url (defaults to https://api.4mica.xyz/)
  • ethereum_http_rpc_url and contract_address are auto-fetched from the facilitator unless provided.

Environment variables mirror the Rust SDK:

4MICA_WALLET_PRIVATE_KEY
4MICA_RPC_URL
4MICA_ETHEREUM_HTTP_RPC_URL
4MICA_CONTRACT_ADDRESS
4MICA_ADMIN_API_KEY

Notes

  • All methods are async; use asyncio.run or your event loop of choice.
  • Remuneration requires py-ecc (pip install 'sdk-4mica[bls]') to expand BLS signatures into the on-chain format.
  • Numeric values accept int or hex/decimal strings and are serialized to 0x-prefixed hex when sent to the facilitator.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

sdk_4mica-0.2.1.tar.gz (26.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

sdk_4mica-0.2.1-py3-none-any.whl (24.5 kB view details)

Uploaded Python 3

File details

Details for the file sdk_4mica-0.2.1.tar.gz.

File metadata

  • Download URL: sdk_4mica-0.2.1.tar.gz
  • Upload date:
  • Size: 26.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for sdk_4mica-0.2.1.tar.gz
Algorithm Hash digest
SHA256 7fc1e4ebf723ab3042fa730c6b9f81685a9f5cfaedf34053012e45bed71ab799
MD5 e7ebfe05474f1d330e7d53391b841920
BLAKE2b-256 c9efabb0a18e7d4a8107fac192de73fce62111919b5a58611394c2fcd40f2a65

See more details on using hashes here.

File details

Details for the file sdk_4mica-0.2.1-py3-none-any.whl.

File metadata

  • Download URL: sdk_4mica-0.2.1-py3-none-any.whl
  • Upload date:
  • Size: 24.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.3

File hashes

Hashes for sdk_4mica-0.2.1-py3-none-any.whl
Algorithm Hash digest
SHA256 e4194cce7ce68fa0a21cbec381f7dc098db1b059917e122ae15ec5c861b3324a
MD5 51b073d4241c9b488c13698bde35d924
BLAKE2b-256 5bc66912e5952afa560563d147ede572606b0a3440d5cb7a721fd795d41491ad

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page