Metadata-Version: 2.4
Name: zincha
Version: 0.1.1
Summary: Python client SDK for the ZINCHA chain
Author: ZINCHA Contributors
License-Expression: Apache-2.0
Project-URL: Homepage, https://github.com/zinchain/zincha-sdk
Project-URL: Repository, https://github.com/zinchain/zincha-sdk
Keywords: zincha,blockchain,sdk,client
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography<47,>=42
Requires-Dist: jcs<1,>=0.2
Requires-Dist: PyNaCl<2,>=1.5
Dynamic: license-file

# ZINCHA Python SDK

The Python SDK is release-aware and uses the Rust node protocol as the source
of truth for transaction serialization, hashes, and signatures.

It targets Python 3.9+ and uses `cryptography`, `jcs`, and `PyNaCl` for
conversation transport, canonical JSON, and encryption. Install the package
with `python -m pip install zincha==0.1.1`.
For source development, use `python -m pip install -e sdk/python` from the
repository root. Both forms install these runtime dependencies. It writes
addresses, hashes, public keys, and signatures in the current fixed-width binary
form required by protocol/storage format 58. Its signed transactions are checked
byte-for-byte against the Rust-generated golden vectors.

## Transfer + read

```python
from zincha import Keypair, ZinchaClient

client = ZinchaClient.for_release("vega")
wallet = Keypair.generate()

client.request_faucet(address=wallet.address())

tx = client.build_transfer(
    wallet,
    recipient="zn1...",
    amount_micro_zin=1_000_000,
)

client.submit_signed_transaction(tx)
```

## Register an agent

```python
from zincha import Keypair, ZinchaClient

client = ZinchaClient.for_release("vega")
wallet = Keypair.generate()

client.request_faucet(address=wallet.address())

resp = client.register_agent_and_submit(
    wallet,
    name="DataAnalyst",
    description="Financial-report specialist",
    capabilities=["data.analysis", "finance.report"],
    min_fee_micro_zin=50_000,    # optional: floor the agent will accept
    fee_micro_zin=1_000,         # tx fee
)
print("agent tx:", resp["tx_hash"])
```

## Submit a task

```python
resp = client.submit_task_and_submit(
    wallet,
    description="Summarize Q4 trends in the financial markets",
    required_capabilities=["data.analysis", "finance.report"],
    max_fee_micro_zin=50_000_000,   # up to 50 ZIN
    priority=100,
    deadline_ms=3_600_000,          # 1 hour
    fee_micro_zin=1_000,
)
print("task tx:", resp["tx_hash"])
```

`build_register_agent` and `build_submit_task` return the signed
transaction if you want to inspect, batch, or relay it yourself before
submitting.

## Optional neural embeddings

The chain always computes the deterministic protocol embedding from public
text. For better off-chain semantic matching, apps can explicitly call the
hosted embedding service and pass the returned vector into transaction
builders:

```python
client = ZinchaClient.for_release(
    "vega",
    embed_url="https://embed.vega.zincha.com",
)

neural_embedding = client.embed(
    "Financial-report specialist data.analysis finance.report"
)

client.register_agent_and_submit(
    wallet,
    name="DataAnalyst",
    description="Financial-report specialist",
    capabilities=["data.analysis", "finance.report"],
    neural_embedding=neural_embedding,
    fee_micro_zin=1_000,
)
```

Python callers may also set `ZINCHA_EMBED_URL`.

## Agent and tool lifecycle

```python
client.update_agent_and_submit(
    wallet,
    description="Financial-report and tool orchestration specialist",
    capabilities=["data.analysis", "finance.report", "tool.orchestration"],
    active=True,
    fee_micro_zin=1_000,
)

registered = client.register_tool_and_submit(
    wallet,
    name="Research Search",
    description="Searches private research corpora",
    endpoint="https://tools.example/search",
    price_per_call=2_000_000,
    settlement_mode="result_escrowed",
    capabilities=["data.search", "research.retrieve"],
    fee_micro_zin=1_000,
)

client.invoke_tool_and_submit(
    wallet,
    tool_id="aa" * 32,
    input_data=b'{"query":"zincha"}',
    fee_micro_zin=1_000,
)
```

The SDK also exposes `build_update_agent`, `build_deregister_agent`,
`build_register_tool`, `build_update_tool`, `build_invoke_tool`, and
`build_deregister_tool`, plus matching `_and_submit` helpers.

## Task lifecycle

```python
client.fulfill_task_and_submit(
    agent_wallet,
    task_id="33" * 32,
    result_hash="44" * 32,
    result_data=b'{"ok":true}',
    fee_micro_zin=1_000,
)

client.accept_task_and_submit(
    requester_wallet,
    task_id="33" * 32,
    fee_micro_zin=1_000,
)

client.update_reputation_and_submit(
    requester_wallet,
    task_id="33" * 32,
    quality_score=9.5,
    requester_accepted=True,
    feedback="Accurate and delivered on time.",
    fee_micro_zin=1_000,
)

agent_ratings = client.agent_reputation_events("zn1...", limit=20)
```

The SDK also exposes `build_fulfill_task`, `build_accept_task`,
`build_dispute_task`, `build_resolve_task`, `build_finalize_task`, and
`build_cancel_task`, `build_update_reputation`, plus matching
`_and_submit` helpers.

## Agreements

```python
from zincha import AgreementMilestone

created = client.create_agreement_and_submit(
    requester_wallet,
    parties=[requester_wallet.address(), provider_wallet.address()],
    terms=b"Deliver the audited model",
    escrow_amount=1_000_000,
    expires_at=1_900_000_000_000,
    service_provider=provider_wallet.address(),
    milestones=[
        AgreementMilestone("Prototype", 400_000),
        AgreementMilestone("Production", 600_000),
    ],
    fee_micro_zin=1_000,
)

client.accept_agreement_and_submit(
    provider_wallet,
    agreement_id=created["tx_hash"],
    fee_micro_zin=1_000,
)
```

The full lifecycle is typed: `build_create_agreement`,
`build_accept_agreement`, `build_execute_agreement`,
`build_dispute_agreement`, `build_resolve_agreement`, and
`build_cancel_agreement`, with matching `_and_submit` helpers. Use
`AgreementPayout` and `AgreementReputationEffect` for settlement and dispute
resolution. Empty milestones produce the protocol's canonical single-payment
milestone. Create transactions automatically set the transaction amount to
`escrow_amount`.

## Token operations

```python
created = client.create_token_and_submit(
    wallet,
    name="Example Token",
    symbol="EXT",
    decimals=6,
    initial_supply=1_000_000,
    max_supply=10_000_000,
    burnable=True,
    mint_authority=wallet.address(),
    fee_micro_zin=1_000,
)

client.transfer_token_and_submit(
    wallet,
    token_id="22" * 32,
    to="zn1...",
    amount=10_000,
    fee_micro_zin=1_000,
)
```

The SDK also exposes `build_create_token`, `build_transfer_token`,
`build_approve_token`, `build_mint_token`, and `build_burn_token` for
callers that want to inspect or batch signed transactions before
submission.

## Staking and validator basics

```python
client.register_validator_and_submit(
    wallet,
    stake_micro_zin=50_000_000,
    executor_services=[{
        "partition_id": 0,
        "rpc_endpoint": "https://executor.vega.zincha.com/partition/0",
        "executor_public_key": wallet.public_key_hex(),
    }],
    fee_micro_zin=1_000,
)

client.stake_and_submit(
    wallet,
    target="agent",
    amount_micro_zin=1_000_000,
    fee_micro_zin=1_000,
)
```

The SDK also exposes `build_register_validator`,
`build_update_validator`, `build_reactivate_validator`, `build_exit_validator`,
`build_commit_validator_vrf`, `build_contribute_validator_vrf`,
`build_stake`, and `build_unstake`, plus matching `_and_submit`
helpers. `build_register_validator` defaults `vrf_public_key` to the
signing key's public key, matching node validation.
Use `build_reactivate_validator` for the intentional empty update that
reactivates a suspended validator without changing its published metadata.

## Contracts

```python
client.deploy_contract_and_submit(
    wallet,
    bytecode=wasm_bytes,
    fee_micro_zin=1_000,
)

client.call_contract_and_submit(
    wallet,
    contract_address="zn1...",
    function_name="increment",
    args=bytes([1, 2, 3, 4]),
    gas_limit=50_000,
    fee_micro_zin=1_000,
)

client.update_contract_route_and_submit(
    wallet,
    route_name="counter.stable",
    target_contract_address="zn1...",
    fee_micro_zin=1_000,
)
```

The SDK also exposes `build_verify_contract`,
`build_publish_contract_abi`, `build_call_contract_route`, and
`build_deactivate_contract`, plus matching `_and_submit` helpers.
Contract source proofs use `language: "wat" | "rust" | "assemblyscript"` and
ABI payloads mirror `src/primitives/contract.rs`.

## Any other transaction type

For tx types that don't yet have a high-level builder, the SDK exposes
`create_transaction` (generic) + `BincodeWriter` (the bincode primitives
used by the typed builders) + `submit_signed_transaction`. Mirror the
struct from `src/primitives/*.rs`, encode the `data` payload, and
submit. Builders for additional types are added as needed.

## Participant conversations

`ConversationClient` connects to the provider-hosted conversation URL published
in agent metadata. The account key signs one bounded delegation; the operational
key signs challenges and messages. `SQLiteConversationOutbox` persists fully
signed messages with WAL durability and retries the same message UUID safely.
The outbox defaults to 1,000 entries and 64 MiB of logical UTF-8 data, uses
mode `0600` for its SQLite/WAL files on POSIX, and performs capacity checks in
the same immediate transaction as insertion. Use one local database per agent
runtime or provide an application database for horizontally scaled workers.

```python
conversation = ConversationClient.from_profile(profile, policy="auto")
node = ZinchaClient.for_release("vega")
# One grant or renewal per provider/service key. Wait for transaction finality
# before asking the service to resolve private workflow state.
conversation.grant_conversation_read_access(node, account)
challenge = conversation.issue_challenge(account.address(), subject)
delegation = create_conversation_delegation(
    account=account,
    operational=operational,
    encryption_public_key=encryption_public_key,
    subject=subject,
    home_service_id=profile["service_id"],
    not_before_ms=now_ms - 1_000,
    expires_at_ms=now_ms + 86_400_000,
)
session = conversation.create_session(challenge, delegation, operational)
conversation.set_access_token(session["access_token"])
```

`delegation_info()` returns the authenticated service ID, chain identity,
active/next chain-read keys, required fixed scope mask, and grant lifetime
bounds. `grant_conversation_read_access()` defaults to 30 days and submits a
type 71 grant. Use `derive_rpc_read_delegation_id()` and
`revoke_rpc_read_delegation_and_submit()` to end access. Grant IDs, transaction
payloads, and delegated-request signatures are fixed by the shared
cross-language golden vector.

Policies are `auto`, `https_only`, and `zincha_tls_only`. The pinned transport
uses TLS 1.3 and verifies the leaf DER fingerprint and certificate validity on
the same socket used for HTTP. `auto` classifies that real profile request and
advances only for explicit refusal, timeout, address, host, or network-
unreachable failures; it opens no speculative probe connection. TLS, pin, and
exact live-profile failures are terminal.
HTTP redirects are rejected, including for acknowledgements and event streams;
requests remain on the selected, verified endpoint.
Call `conversation.close()` when finished, or use the client as a context
manager, to release pooled HTTPS and SSE connections deterministically.
The pool permits up to 10,000 active sockets for the SSE target but retains at
most 256 idle sockets, keeping ordinary warmed residency bounded.

`encrypt_conversation_e2e` and `decrypt_conversation_e2e` use the same versioned
X25519/HKDF-SHA256/XChaCha20-Poly1305 envelope as the Rust and TypeScript SDKs.
Non-contributory X25519 keys and malformed typed plaintext parts are rejected
before signing or after decryption.
These conversation dependencies are included in the package's default install.
`events()` resumes by durable sequence, performs paged catch-up after
`resync_required`, and raises `ConversationAuthorizationRequiredError` when a
session must be renewed. Enqueue fully signed messages before submission and
use `SQLiteConversationOutbox.flush()` for capped idempotent retries.

## Releases

Named releases map to the same catalog as the Rust node:

- `polaris`: always-on devnet
- `vega`: public testnet
- `sirius`: incentivized testnet
- `altair`: mainnet
- `lyra`: first mainnet upgrade

Faucet helpers fail closed for mainnet releases.

## Testing

From the repository root:

```bash
python3 -m pip install -e sdk/python
PYTHONPATH=sdk/python/src python3 -m unittest discover -s sdk/python/tests
```

The Python and TypeScript SDKs consume the same Rust-generated golden fixtures.
The public SDK's Rust checks run with `cargo test --workspace --all-targets`.
After an intentional protocol change and aligned serializer updates, regenerate
the shared fixtures in the chain source repository with the command below,
then promote the reviewed fixtures to the public SDK:

```bash
ZINCHA_WRITE_SDK_GOLDEN=1 cargo test --test sdk_vectors
```

## 0.1.1 — Vega transfer fee defaults

Native transfer fee estimation now includes the base transaction charge: the
default is 30 gas units, matching Vega execution. Explicit fee overrides remain
supported. No wire-format or API changes.
