Metadata-Version: 2.5
Name: arrekta-sdk
Version: 0.1.0
Summary: Python SDK for Arrekta: sync and async clients, typed models and wallet helpers over the reference implementation
Project-URL: Homepage, https://arrekta.com
Project-URL: Documentation, https://docs.arrekta.com/sdk/python
Project-URL: Repository, https://github.com/arrekta/arrekta
License-Expression: MIT OR Apache-2.0
License-File: LICENSE-APACHE
License-File: LICENSE-MIT
Requires-Python: >=3.13
Requires-Dist: arrekta>=0.1.0
Requires-Dist: httpx<1,>=0.27
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.24; extra == 'dev'
Requires-Dist: pytest-timeout>=2.3; extra == 'dev'
Requires-Dist: pytest>=8.3; extra == 'dev'
Requires-Dist: ruff>=0.7; extra == 'dev'
Description-Content-Type: text/markdown

# arrekta-sdk (Python)

Python SDK for Arrekta, the post-quantum, multi-asset UTXO chain. It provides sync and async
clients for the node REST API and the gateway, standalone actions, typed models generated from
the frozen v1 OpenAPI contract, and wallet helpers. These cover accounts, payments, assets, PST
multisig, HTLCs, fee bumping and light-client checks.

All protocol logic comes from the reference package `arrekta` (`core/arrekta_core`): encoding,
hashing, ML-DSA keys, addresses, locks, policies, transactions, PST, filters and checkpoints. The
SDK reuses it rather than reimplementing it, so it cannot drift from consensus. The shared
contract with the TypeScript SDK is `docs/SDK_DESIGN.md`.

## Install

```sh
cd sdk/python
python3.13 -m venv .venv
.venv/bin/pip install -e ../../core -e '.[dev]'     # or: make venv
```

Requires Python 3.13 or later. Runtime dependencies are `arrekta` and `httpx`.

## Quick start

```python
from arrekta_sdk import Client, keychain_from_seed, generate_seed, format_arrk

client = Client("http://127.0.0.1:28332", admin_token="...")   # admin token only for regtest mining
alice = keychain_from_seed(bytes.fromhex("a1" * 32), network="regtest")
bob = keychain_from_seed(generate_seed(), network="regtest")

client.mine(alice.address(0), 101)                    # regtest: mature coinbase coins
sent = client.send_payment(alice, bob.address(0), "1.5")
client.mine(alice.address(0), 1)
print(sent.txid, format_arrk(client.get_address(bob.address(0))["balances"][0]["spendable"]))
```

The same call works with `AsyncClient`:

```python
async with AsyncClient(url) as client:
    sent = await client.send_payment(alice, bob.address(0), "1.5")
```

## Design

- **One core, two clients (web3.py v7).** Each action is a *program*, a generator that yields
  HTTP calls described as data. `Client` runs the program with blocking httpx and
  `AsyncClient` runs it with `await`. Multi-request flows such as "collect coins, build, sign,
  send" are therefore written once.
- **Standalone actions (viem).** `get_chain(client)`, `send_payment(client, ...)` and the
  others are plain functions. Each is also a method on every client. With an async client the
  function returns an awaitable.
- **Middleware.** `Client(url, middleware=[obj])` calls `obj.request(call) -> call` and
  `obj.response(call, result) -> result` around every request. GET requests are retried on
  transport errors and on 429/502/503/504 (`retries=2`). POST requests are never retried.
- **Subscriptions (@solana/kit).** `watch_events()` is a generator on `Client` and an async
  iterator on `AsyncClient`. Every stream starts with a `stream.open` event. After a drop, the
  client reconnects and sends `Last-Event-ID`; the gateway replays the missed events. You can
  stop the stream with `break`, by cancelling it, or by setting `stop=Event()`.
- **Typed errors.** Problem documents (RFC 9457) become `ArrektaError(status, code, title,
  detail)`. A failure to connect raises `TransportError` (status 0). The local protocol errors
  (`DecodeError`, `ValidationError(code)`, `PolicyError`, `AddressError`, `PstError`,
  `InsufficientFunds`) come from the reference package. All of these errors share the base
  class `arrekta_core.errors.ArrektaError`.

## API surface

| Area | Python |
|---|---|
| Clients | `Client(url)`, `AsyncClient(url)`, `GatewayClient(url, api_key)`, `AsyncGatewayClient(url, api_key)`. Options: `network`, `admin_token`, `timeout`, `headers`, `middleware`, `retries`, `transport`, `cache` (conditional reads: `If-None-Match` → reuse on 304); gateway clients also `signing_key` (signed partner requests; `sign_request`, `RequestSigner`) |
| Chain | `get_chain`, `get_network`, `get_blocks`, `get_tip`, `get_block(id, txs)`, `get_raw_block`, `get_deployments`, `get_checkpoints`, `submit_checkpoint` |
| Transactions | `get_transaction`, `get_raw_transaction`, `fetch_transaction`, `decode_transaction`, `send_transaction(tx\|hex)`, `send_package(parent, child)` |
| Addresses, assets | `get_address`, `get_utxos(address, asset)`, `get_address_history`, `get_assets`, `get_asset(id_or_ticker)`, `get_frozen`, `get_metadata_hash` |
| Mempool, mining | `get_mempool`, `estimate_fee`, `get_mining_template`, `submit_block`, `create_aux_block`, `submit_aux_block`, `mine` (admin) |
| Light clients | `get_block_filter`, `get_filter_headers`; `verify_filter`, `verify_block_filter`, `match_filter`, `verify_merkle_branch`, `verify_checkpoint`, `network_signer_set` |
| Events | `watch_events(client, last_event_id=, types=, stop=)` |
| Keys | `generate_seed`, `keychain_from_seed(seed, network=, scheme=)` returns a Keychain with `key`, `lock`, `address`, `signing_keys`, `origin`, `account_at`; `private_key_from_seed(seed32)` returns an `Account` with `public_key`, `key_hash`, `sign`, `lock`, `address`; `encode_address`, `decode_address` |
| Locks, policies | `lock_from_public_key`, `multisig_policy`, `multisig_lock`, `policy_lock`; `key`, `multi`, `after`, `older`, `sha3`, `and_`, `or_`, `thresh`; `htlc`, `vault`, `vesting`; `verify_witness` |
| Transactions (pure) | `build_transaction(coins, payments, change, fee_rate=, issuances=, mints=, freezes=, version=, valid_until=)`, `sign_transaction`, `txid`, `wtxid`, `sighash`, `serialize_transaction`, `deserialize_transaction`, `coins_from_utxos`, `make_issuance` |
| Wallet flows | `get_coins`, `send_payment`, `send_payments`, `issue_asset`, `mint_asset`, `freeze_asset`, `unfreeze_asset`, `clawback_asset`, `bump_fee` (RBF), `cpfp` (package) |
| PST | `create_pst`, `update_pst`, `sign_pst`, `combine_pst`, `finalize_pst(preimages=)`, `decode_pst`, `encode_pst`, `pst_status`, `pst_summary` |
| Units | `parse_arrk("1.5") == 150000000`, `format_arrk(150000000) == "1.5"`, `parse_units`, `format_units` |
| Models | `arrekta_sdk.models`: TypedDicts for every schema in `docs/api/openapi.json` (`ChainInfo`, `Tx`, `Utxo`, `Problem`, ...). `parse(name, data)` validates data with the node's own pydantic models (`arrekta_node.api.models`) |

## Examples

The `examples/` folder holds the scenarios that the docs show side by side with TypeScript.
Each example lists numbered steps in its comments, and the TypeScript twin follows the same
order.

| File | Scenario |
|---|---|
| `send_payment.py` | connect, derive wallets, fund, pay 1.5 ARRK, confirm and read the balance |
| `issue_asset.py` | issue a mintable and freezable asset with metadata, pay it, mint more, freeze, unfreeze |
| `multisig_pst.py` | 2-of-3 vault: fund it, create a PST, two co-signers sign independently, combine, finalize |
| `htlc.py` | HTLC: Bob claims with the preimage (passed only to the finalizer) |
| `light_client.py` | filter headers, verify a block filter end to end, match locally, verify the latest checkpoint |
| `watch_events.py` | async event stream: on `stream.open`, cause a payment and a block, then stop |

Run an example like this:

```sh
ARREKTA_URL=http://127.0.0.1:28332 ARREKTA_ADMIN_TOKEN=... .venv/bin/python examples/send_payment.py
```

## Payment channels (L2)

```python
from arrekta_sdk import ChanneldClient, decode_invoice, verify_preimage

inv = decode_invoice("arrektapay:…")                  # offline: decodes and verifies the signature
with ChanneldClient("http://127.0.0.1:9737", token) as ln:
    paid = ln.pay("arrektapay:…")
    assert paid["status"] == "succeeded" and verify_preimage(inv.payment_hash, paid["preimage"])
```

`ChanneldClient` covers the whole `arrekta-channeld` API: peers, channels, invoices, payments,
routes, the graph and the watchtower. See `examples/payment_channels.py` and docs/CHANNELD.md.

## Development

```sh
make gen            # regenerate arrekta_sdk/_generated.py (also tools/sdkgen/gen.sh)
make test           # stale check + ruff + all tests (starts a throwaway regtest node)
make test-offline   # unit + conformance only
make test-rust      # integration + examples against node-rs/target/release/arrekta-node-rs
```

- `tests/test_conformance.py` loads `core/vectors/*.json` (keys, hashing, transactions, pst,
  base_layer, security checkpoints) through the SDK API and checks the results byte for byte.
- `tests/test_integration.py` runs each scenario with both `Client` and `AsyncClient` against a
  regtest node. The node runs on free ports in a temp directory. By default the tests use
  `core/.venv/bin/arrekta-node`; set `ARREKTA_TEST_NODE` to use another binary.
- `tests/test_examples.py` runs every example against that node.
