Skip to main content

xian-py

xian-py is the Python SDK for talking to Xian nodes from applications, workers, automation jobs, and operator tooling. It exposes a clean sync / async client surface over node RPCs, indexed BDS queries, and the CometBFT websocket, plus reusable projector primitives for building local read models.

The published PyPI package is xian-tech-py. The import package remains xian_py.

SDK Shape

flowchart LR
  App["Application or worker"] --> Sync["Xian sync client"]
  App --> Async["XianAsync client"]
  Sync --> RPC["Node RPC"]
  Async --> RPC
  Async --> WS["CometBFT websocket"]
  Sync --> BDS["Indexed BDS APIs"]
  Async --> BDS
  BDS --> Projector["EventProjector and cursors"]
  Wallet["Wallet"] --> Sync
  Wallet --> Async

Quick Start

Install the SDK:

uv add xian-tech-py

Read state and submit a transaction with the synchronous client:

import os

from xian_py import Wallet, Xian, chi_to_supply

wallet = Wallet(private_key=os.environ["XIAN_PRIVATE_KEY"])

with Xian("http://127.0.0.1:26657", wallet=wallet) as client:
    balance = client.token().balance_of(wallet.public_key)
    submission = client.token().transfer("bob", 5, mode="checktx")
    print(balance, submission.accepted)

Watch indexed events with the async client:

import asyncio

from xian_py import XianAsync


async def main() -> None:
    async with XianAsync("http://127.0.0.1:26657") as client:
        async for event in client.token().transfers().watch(after_id=0):
            print(event.id, event.data)


asyncio.run(main())

For low-latency delivery without BDS-backed cursoring, use raw live websocket events:

import asyncio

from xian_py import XianAsync


async def main() -> None:
    async with XianAsync("http://127.0.0.1:26657") as client:
        async for event in client.token().transfers().watch_live():
            print(event.tx_hash, event.data)


asyncio.run(main())

The SDK derives the websocket endpoint from the RPC URL by default (http://127.0.0.1:26657 → ws://127.0.0.1:26657/websocket). Override with WatcherConfig(websocket_url="ws://rpc-host:26657/websocket").

XianAsync closes sessions it creates and leaves caller-supplied sessions open. If a reused client creates its own session after close(), the next context exit or close() call closes that session as well.

For visibility into transport retries, attach a callback to RetryPolicy(on_retry=...). The callback receives a typed RetryEvent with the operation kind, attempt number, next backoff delay, and exception.

Optional extras:

uv add "xian-tech-py[app]"   # FastAPI examples
uv add "xian-tech-py[compile]" # Offline source-to-artifact utilities
uv add "xian-tech-py[eth]"   # Ethereum-style key helpers
uv add "xian-tech-py[hd]"    # Mnemonic account derivation

SDK Cookbook

The examples below assume a running node at http://127.0.0.1:26657. Use xian-stack or xian-cli to start a local node, then pass the same RPC URL into the SDK.

Create or import a wallet:

import os

from xian_py import Wallet
from xian_py.wallet import HDWallet

# Generate a fresh Ed25519 account.
wallet = Wallet()
print(wallet.public_key)

# Restore an existing account from a hex private key. Only an omitted key
# (None) generates one; an empty or malformed key raises ValueError.
wallet = Wallet(private_key=os.environ["XIAN_PRIVATE_KEY"])

# Generate a recovery phrase and its first account. Requires [hd].
hd = HDWallet()
derived_wallet = hd.get_wallet(account_index=0)

# Browser/mobile wallet recovery. Also requires [hd].
wallet = Wallet.from_mnemonic(os.environ["XIAN_RECOVERY_PHRASE"])
second_account = Wallet.from_mnemonic(
    os.environ["XIAN_RECOVERY_PHRASE"], account_index=1
)

HDWallet(phrase).get_wallet(account_index=i) and Wallet.from_mnemonic(phrase, account_index=i) produce the same account as the browser and mobile wallets. Both default to account index 0. Recovery requires the same phrase and index; indices are integers from 0 through 4294967295.

All Xian mnemonic accounts use SHA-256 of the BIP39 seed (empty passphrase), xian-wallet-seed-v2, and the four-byte big-endian account index. Derivation paths are not accepted by HDWallet.get_wallet; use account_index instead.

Inspect node and indexer health:

from xian_py import Xian

with Xian("http://127.0.0.1:26657") as client:
    status = client.get_node_status()
    bds = client.get_bds_status()
    print(status.network, status.latest_block_height, status.catching_up)
    print(bds.indexed_height, bds.height_lag, bds.alerts)

Read state, simulate a call, and retrieve contract source:

from xian_py import Xian

address = "bob"

with Xian("http://127.0.0.1:26657") as client:
    balance = client.token().balance_of(address)
    raw_balance = client.state_key("currency", "balances", address).get()
    simulated = client.contract("currency").simulate(
        "balance_of",
        address=address,
    )
    source = client.contract("currency").get_source()
    vm_ir = client.contract("currency").get_ir()
    print(balance, raw_balance, simulated["result"])

Estimate chi, submit a transaction, and wait for finality:

import os

from xian_py import Wallet, Xian

wallet = Wallet(private_key=os.environ["XIAN_PRIVATE_KEY"])

with Xian("http://127.0.0.1:26657", wallet=wallet) as client:
    estimate = client.estimate_chi(
        "currency",
        "transfer",
        {"to": "bob", "amount": 5},
    )
    submission = client.token().transfer(
        "bob",
        5,
        chi=chi_to_supply(estimate["estimated"]),
        mode="checktx",
        wait_for_tx=True,
    )
    print(submission.tx_hash, submission.accepted, submission.finalized)
    if submission.receipt:
        print(submission.receipt.success, submission.receipt.chi_used)

estimate_chi returns the simulated estimated chi with the full simulation. chi_to_supply(estimated) turns it into the chi to supply: the estimate plus CHI_ESTIMATE_MARGIN (2 chi), never more than the chain's per-transaction cap MAX_TX_CHI (200,000); an estimate above the cap raises TransactionError. Automatic sends use the same rule, and an explicit chi always wins unchanged. The margin covers a transaction that lands between the estimate and execution and grows a stored value by a byte, which costs one chi more; a paid transaction pays half of the chi it leaves unused, so the margin costs at most one chi. A generous explicit chi pays half of its unused budget. If the state changes more than that (for example a pool moved or a recipient was created), the transaction can still run out of chi and fails with Out of chi.; estimate again and resubmit. Automatic sends simulate with the nonce they sign with (estimate_chi(..., nonce=n); its digits are bytes the transaction pays for) and raise SimulationError, carrying the simulation's error text, instead of submitting a call whose simulation failed, which would fail on chain and pay its fee. xian-js uses the same rule.

A "tx already exists in cache/mempool" response is reported as submitted=True, accepted=None under the local transaction hash, and the automatic nonce stays reserved until the network nonce advances: the node holds those bytes, but that proves neither admission nor execution. With wait_for_tx=True, a receipt for the hash marks it accepted and finalized. A sync/async broadcast the node refuses with a JSON-RPC error (for example "mempool is full" or "endpoint is closed while node is catching up", sent with HTTP 500) is reported as submitted=False and releases the automatic nonce. A lost response, or an error answering a commit broadcast, keeps it reserved until the network nonce advances.

Deploy a contract from source:

import os

from xian_py import Wallet, Xian

wallet = Wallet(private_key=os.environ["XIAN_PRIVATE_KEY"])
source = """
counter = Variable()

@construct
def seed():
    counter.set(0)

@export
def increment():
    counter.set(counter.get() + 1)
    return counter.get()
"""

with Xian("http://127.0.0.1:26657", wallet=wallet) as client:
    deployed = client.deploy_contract(
        "con_counter",
        source,
        mode="checktx",
        wait_for_tx=True,
    )
    result = client.contract("con_counter").send(
        "increment",
        mode="checktx",
        wait_for_tx=True,
    )
    print(deployed.tx_hash, result.tx_hash)

deploy_contract and submit_contract submit cleartext source. Nodes compile submitted source and persist canonical IR, so normal deployment does not require the compile extra. To inspect the same V2 profile offline, install xian-tech-py[compile], which adds the Rust compiler core (xian-tech-compiler-core), and use its artifact API.

import xian_compiler_core

artifact = xian_compiler_core.compile_contract_artifact("con_counter", source)
assert artifact["vm_profile"] == "xian_vm_v2"

To reproduce an archived V1 artifact, pass vm_profile="xian_vm_v1" to compile_contract_artifact.

Query BDS-backed history:

from xian_py import Xian

address = "bob"

with Xian("http://127.0.0.1:26657") as client:
    recent_blocks = client.list_blocks(limit=5)
    token_contracts = client.get_token_contracts(limit=20)
    token_balances = client.get_token_balances(address, include_zero=False)
    currency_txs = client.list_txs_by_contract("currency", limit=20)
    transfer_events = client.list_events("currency", "Transfer", after_id=0)
    balance_history = client.get_state_history(f"currency.balances:{address}")
    print(
        len(recent_blocks),
        token_contracts.total,
        token_balances.total,
        len(currency_txs),
        len(transfer_events),
        len(balance_history),
    )

Use the async client in a service or worker:

import asyncio
import os

from xian_py import Wallet, XianAsync


async def main() -> None:
    wallet = Wallet(private_key=os.environ["XIAN_PRIVATE_KEY"])
    async with XianAsync("http://127.0.0.1:26657", wallet=wallet) as client:
        chain_id = await client.get_chain_id()
        balance = await client.token().balance_of(wallet.public_key)
        submission = await client.token().transfer(
            "bob",
            5,
            mode="checktx",
            wait_for_tx=True,
        )
        print(chain_id, balance, submission.tx_hash)


asyncio.run(main())

Build a resumable SQLite projection:

import asyncio
import sqlite3

from xian_py import (
    EventProjector,
    EventSource,
    SQLiteProjectionState,
    XianAsync,
    merged_event_payload,
)


async def main() -> None:
    connection = sqlite3.connect("projection.db")
    connection.row_factory = sqlite3.Row
    connection.execute(
        "CREATE TABLE IF NOT EXISTS transfers "
        "(event_id INTEGER PRIMARY KEY, tx_hash TEXT, amount TEXT)"
    )
    state = SQLiteProjectionState(connection)
    state.init_schema()

    source = EventSource("currency", "Transfer")

    async def apply_transfer(event, _hydrated):
        payload = merged_event_payload(event)
        connection.execute(
            "INSERT OR IGNORE INTO transfers VALUES (?, ?, ?)",
            (event.id, event.tx_hash, str(payload.get("amount"))),
        )
        state.set_int(source.key, event.id or 0)
        connection.commit()
        return True

    async with XianAsync("http://127.0.0.1:26657") as client:
        projector = EventProjector(
            client=client,
            event_sources=[source],
            get_cursor=lambda event_source: state.get_int(event_source.key),
            apply_event=apply_transfer,
        )
        await projector.sync_once()


asyncio.run(main())

Tune retries, transaction defaults, and watcher behavior:

from xian_py import (
    RetryEvent,
    RetryPolicy,
    SubmissionConfig,
    WatcherConfig,
    Xian,
    XianClientConfig,
)


def log_retry(event: RetryEvent) -> None:
    print(
        event.operation,
        event.attempt,
        event.max_attempts,
        event.next_delay_seconds,
        event.error,
    )


config = XianClientConfig(
    retry=RetryPolicy(max_attempts=5, on_retry=log_retry),
    submission=SubmissionConfig(mode="checktx", wait_for_tx=True),
    watcher=WatcherConfig(mode="auto", batch_limit=250),
)

with Xian("http://127.0.0.1:26657", config=config) as client:
    print(client.get_chain_id())

Talk to a shielded relayer:

from xian_py import ShieldedRelayerClient

with ShieldedRelayerClient("http://127.0.0.1:38480") as relayer:
    info = relayer.get_info()
    quote = relayer.get_quote(
        kind="shielded_command",
        contract="shielded_note_token",
        target_contract="currency",
    )
    print(info.available, quote.relayer_fee, quote.expires_at)

Principles

  • One mental model, two clients. Sync and async clients stay aligned, so the same concepts work in scripts, services, and workers.
  • Explicit transaction submission. Choose a broadcast mode (async, checktx, commit) deliberately. The SDK does not hide retry, blocking, or finality behavior.
  • Plumbing, not policy. Read models and projector loops belong in application code. The SDK owns the repetitive plumbing (websocket delivery, catch-up cursors, raw CometBFT decoding, typed event conversion).
  • Reference apps live alongside, not inside, the wheel. Examples demonstrate how to integrate Xian into Python systems but are not part of the published package.
  • No node orchestration. Operator workflow and node lifecycle live in xian-cli and xian-stack.

Key Directories

  • src/xian_py/ — clients, wallet helpers, transactions, models, projectors.
    • xian.py, xian_async.py — primary sync and async clients.
    • application_clients.py — thin helper clients (contract, token, events, state_key).
    • transaction.py, wallet.py, crypto.py — signing, building, and submitting transactions.
    • projectors.py — reusable polling, ordering, and checkpoint primitives.
    • models.py — typed transaction, event, block, and status models.
    • shielded_relayer.py — client for the private-submission relayer.
    • x402.py — native-Xian x402 exact-payment helpers.
  • examples/ — service, worker, and reference-app examples built on the SDK (credits_ledger/, registry_approval/, workflow_backend/, x402_exact/, fastapi_service.py, event_worker.py, admin_job.py).
  • tests/ — SDK transport, decoding, and integration-shape coverage.
  • docs/ — compatibility notes and SDK backlog items.

Capabilities

  • read current state via ABCI query paths and simulate readonly contract calls
  • retrieve canonical contract source and Xian VM IR separately
  • create, sign, and broadcast transactions with explicit async, checktx, and commit modes; wait for final receipts
  • query indexed blocks, transactions, events, state history, and developer reward aggregates from BDS-backed nodes
  • watch indexed events with websocket live delivery plus resumable BDS cursors
  • watch raw live websocket events without BDS when low-latency delivery matters more than replayable cursors
  • use thin helper clients for common patterns: contract, token, event, and state-key access
  • sign, verify, settle, and retry native-Xian x402 exact-payment requests; x402_request only signs options within the caller's required chain, token, settlement contract and maximum amount
  • build SQLite-backed read models with the shared projector primitives, using CometBFT websocket wakeups and BDS cursor reconciliation

Event watching uses the CometBFT websocket directly and expects a BDS-enabled node for cursorable indexed catch-up and canonical event IDs. Use watch_live_events() or .watch_live() when you explicitly want websocket-only, non-resumable delivery.

The Python SDK defaults to xian_vm_v2 for clients, signing, simulation and receipt decoding. Use Python integers and Decimal("0.000000000000000000000000000001") for contract arguments. Token helpers also accept decimal text. The SDK checks range and precision before signing or simulation. Successful calls return typed integers and ContractingDecimal values.

For archived V1 test configurations, pass config=XianClientConfig(vm_profile="xian_vm_v1") to Xian or XianAsync. Standalone helpers such as create_tx, simulate_tx_async and get_tx_async accept vm_profile="xian_vm_v1".

Core API Layers

  • Xian / XianAsync — primary sync and async clients
  • client.contract(...), client.token(...), client.events(...), client.state_key(...) — thin helper clients for common patterns
  • Typed models and error classes — predictable result handling instead of raw dictionaries
  • EventProjector, EventSource, SQLiteProjectionState — reusable polling / ordering / checkpoint primitives for local projections
  • Wallet — Ed25519 signing helper for Xian transactions

Typical Use Cases

  • backend APIs that read state and submit transactions
  • background workers that react to indexed events
  • automation jobs that reconcile or administer contracts
  • local projections that mirror chain activity into an application-owned SQLite read model
  • operator or integration scripts that need a clean Python surface over node RPCs and indexed queries

Example Paths

Validation

uv sync --group dev --extra compile
uv run ruff check .
uv run ruff format --check .
uv run pytest

Metadata

Release files for xian-tech-py 0.5.3

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for xian-tech-py 0.5.3
File Size Uploaded Provenance Actions
xian_tech_py-0.5.3.tar.gz 63.0 kB With provenance Details for xian_tech_py-0.5.3.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for xian-tech-py 0.5.3
File Interpreter ABI Platform Actions
xian_tech_py-0.5.3-py3-none-any.whl Python 3 none any Details for xian_tech_py-0.5.3-py3-none-any.whl

Total release size: 125.5 kB

Release files / xian_tech_py-0.5.3.tar.gz

Download URL xian_tech_py-0.5.3.tar.gz
Size 63.0 kB
Tags Source
SHA-256 checksum
How to use checksums
3986a0313b225df26658f0cb2442eada52f4c8e81b255022de5e984e56e1825d
BLAKE2b-256 checksum
How to use checksums
839ca66a6df56bce615bb9b93bbfee7c9df3cb7dc33946ba04cb822e0a095506
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Release files / xian_tech_py-0.5.3-py3-none-any.whl

Download URL xian_tech_py-0.5.3-py3-none-any.whl
Size 62.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
6b7809c2cad95ef02affa1c358cd8107523c12bb3a7aad2eda3376bc37eab21b
BLAKE2b-256 checksum
How to use checksums
950b67dc928e6f9743ba0d7ead656a9b8bdddb8bbb5afb5529f812d9860972a9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/6.1.0 CPython/3.13.13

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

Security for xian-tech-py 0.5.3

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for xian_tech_py-0.5.3.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 17, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page