Metadata-Version: 2.4
Name: armachain
Version: 0.3.0
Summary: Official Python SDK for ArmaChain -- independent L1 blockchain with integrated CEX-grade DEX
Author: ArmaChain Team
License: MIT
Project-URL: Documentation, https://docs.armascan.io
Keywords: armachain,blockchain,dex,sdk,web3
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.25
Provides-Extra: signing
Requires-Dist: pyblake3>=0.3; extra == "signing"
Requires-Dist: pycryptodome>=3.19; extra == "signing"
Requires-Dist: eth_keys>=0.4; extra == "signing"
Provides-Extra: dev
Requires-Dist: pytest>=7; extra == "dev"
Requires-Dist: pytest-asyncio>=0.21; extra == "dev"
Requires-Dist: pyblake3>=0.3; extra == "dev"
Requires-Dist: pycryptodome>=3.19; extra == "dev"
Requires-Dist: eth_keys>=0.4; extra == "dev"
Dynamic: license-file

# armachain

Official Python SDK for ArmaChain -- independent L1 blockchain with integrated CEX-grade DEX.

## Installation

```bash
pip install armachain
```

For development:

```bash
pip install -e ".[dev]"
```

## Quick Start

```python
import asyncio
from armachain import ArmaChainClient

async def main():
    client = ArmaChainClient(
        api_url="https://api.armascan.io",   # REST API
        rpc_url="https://rpc.armascan.io",   # JSON-RPC
    )

    # Check block height
    height = await client.rpc.get_block_number()
    print(f"Block height: {height}")

    # Get DEX orderbook
    book = await client.dex.get_orderbook(0)
    print(f"Bids: {len(book['bids'])}, Asks: {len(book['asks'])}")

    # Get oracle prices
    prices = await client.oracle.get_prices()
    for p in prices:
        print(f"{p['symbol']}: {p['mark_price']}")

asyncio.run(main())
```

## Modules

| Module | Methods | Description |
|--------|---------|-------------|
| `client.rpc` | 22 | JSON-RPC, health, network, balances, transactions |
| `client.dex` | 30 | Perpetual futures, orders, positions, funding, analytics |
| `client.spot` | 6 | Spot trading, immediate-delivery markets |
| `client.oracle` | 4 | Mark prices, oracle health, quorum |
| `client.bridge` | 2 | Cross-chain transfer status, bridge status |
| `client.tokenomics` | 4 | Fees, burns, revenue share, vesting |
| `client.staking` | 10 | Validators, delegation, governance, proposals |
| `client.explorer` | 12 | Batches, transactions, addresses, contracts |

**Total: ~104 methods** across 9 modules.

## Breaking changes in 0.3.0

Removed: the methods the public API does not serve. A call to any of them could only be refused, so they no longer exist
(an `AttributeError` instead of a runtime refusal): `initiate_transfer`, `get_internal_transactions`, `submit_price`,
`get_peers`, `get_trader_fees`, `get_loyalty_tier`, `claim_revenue_share`, `set_auto_compound`.

Changed, same meaning on a public route: `is_ready` and `is_alive` read `/health/ready` and `/health/live` and return
true only for status `ready` / `alive`; `get_transaction_count` uses JSON-RPC `eth_getTransactionCount`.

## Examples

### DEX Trading

```python
# Get all DEX markets
markets = await client.dex.get_markets()

# Get BTC/USDC orderbook (market_id=0)
book = await client.dex.get_orderbook(0)

# List open positions
positions = await client.dex.get_positions("0x...")

# Get OHLCV candles
candles = await client.dex.get_candles(market_id=0, interval="1h", limit=50)

# Submit an order
result = await client.dex.submit_order(
    payload={"market_id": 0, "side": "buy", "price": 65000, "size": 1.0, "order_type": "Limit"},
    signature="0x...",
)
```

### Spot Trading

```python
# List spot markets
markets = await client.spot.get_markets()

# Get spot orderbook
book = await client.spot.get_orderbook(5)

# Submit a limit buy
result = await client.spot.submit_order(
    address="0x...",
    market_id=5,
    side="Buy",
    price=65000,
    size=100,
)
```

### RPC & Network

```python
# Chain state
height = await client.rpc.get_block_number()
chain_id = await client.rpc.get_chain_id()
balance = await client.rpc.get_balance("0x...")

# JSON-RPC calls
gas = await client.rpc.gas_price()
receipt = await client.rpc.get_transaction_receipt("0x...")

# Broadcast signed tx
tx_hash = await client.rpc.send_raw_transaction("0xsigned...")
```

### Tokenomics

```python
# Fee schedule (9 tiers: Base to VIP3)
tiers = await client.tokenomics.get_fee_schedule()

# Burn statistics
burns = await client.tokenomics.get_burn_stats()

# Revenue share (Validators 35% | Stakers 30% | Burn 25% | Treasury 10%)
revenue = await client.tokenomics.get_revenue_share()
```

### Staking & Governance

```python
# List validators
validators = await client.staking.get_validators()

# Governance proposals
proposals = await client.staking.get_proposals()
```

### Explorer

```python
# Get batch by height
batch = await client.explorer.get_batch(12345)

# Get transaction
tx = await client.explorer.get_transaction("0x...")

# Address info
balance = await client.explorer.get_address_balance("0x...")
txs = await client.explorer.get_address_transactions("0x...")
```

## Configuration

| Parameter | Default | Description |
|-----------|---------|-------------|
| `api_url` | `https://api.armascan.io` | REST API base URL |
| `rpc_url` | `https://rpc.armascan.io` | JSON-RPC endpoint URL |
| `timeout` | `10.0` | Request timeout in seconds |

## Error Handling

```python
from armachain import ArmaChainError

try:
    balance = await client.rpc.get_balance("0xinvalid")
except ArmaChainError as e:
    print(f"Error [{e.code}]: {e.message}")
    if e.status_code:
        print(f"HTTP status: {e.status_code}")
```

## Testing

```bash
pip install -e ".[dev]"
pytest
```

## Chain Info

- **Chain ID**: 2028
- **Total Supply**: 1,000,000,000 ARMA
- **Order Types**: Market, Limit, ReduceOnly, PostOnly, plus the advanced orders TWAP, Iceberg, OCO and the Mark-triggered conditional order (`POST /api/dex/advanced-orders/v2/conditional`). StopLimit, StopMarket, TrailingStop, TakeLimit and TakeMarket trigger on the last trade price and cannot be placed on any market: they are retired on perpetual markets (the node refuses them with 400), and spot markets take resting GTC limit orders only. For a stop-loss or take-profit on a perpetual market, use the Mark-triggered conditional order.
- **Fee Tiers**: 9 (Base 8/4 bps to VIP3 2/-3 bps)

### Native ML-DSA library

Offline ML-DSA-65 signing loads `libarmadilithium3.dylib` / `.so` from the package directory, or from the path in
`ARMA_DILITHIUM3_LIB`. Without it, key generation and signing raise `ImportError` and nothing is signed.

CI and release gates must set `ARMA_DILITHIUM3_REQUIRED=1` and `ARMA_DILITHIUM3_LIB`: then a missing library fails the
signature tests. Unset (or `0`), they skip and the session ends with a `native-skipped` count.

### Signed atomic ARMA money bodies (version 3)

`dex.withdraw` requires explicit keyword arguments `chain_id`, `nonce`,
`pq_signature` and `pq_pubkey`. Old unsigned calls fail locally before HTTP.
The amount is **atomic ARMA units**, supplied as a positive Python integer or
ASCII decimal string (up to u128); floats and booleans are rejected. Only ARMA
is supported. There is no automatic nonce allocation, signing, key acquisition,
key storage or retry in `DexModule`.

```python
from armachain import build_signed_money

# Read accepted time with await client.dex.get_committed_clock().
# Get an advisory quote with client.dex.get_opening_quote(submitter, gross).
# Choose max_open_fee/expires_at_ms explicitly from the quote and your policy.
# Every signature binds the 32-byte network id N (GET /health dex_bridge_network_id).
# Missing, malformed or all-zero raises NetworkBindingError; there is no default and no v1 form.
network_id = await client.bridge.network_id()  # or pin: network_id(pin="0x...")
body = build_signed_money(
    "deposit", submitter=submitter, chain_id=2028, nonce=nonce, asset=0,
    amount=gross_atomic, source_ref=source_ref, timestamp_ms=chain_time_ms,
    max_open_fee=max_open_fee, expires_at_ms=expires_at_ms,
    public_key=public_key, signer=offline_signer, network_id=network_id,
)
await client.dex.deposit(network_id=network_id, **body)
```

Fresh money requests contain `submitter` and no claimed `trader_id` or `address`.
WithdrawV3 additionally signs `vault_address=None` for self or the owned Sub address.
Legacy Fund/Deposit/Withdraw-v2 forms are retired and refused locally.


Use `secret_key=caller_owned_bytes` instead of `signer` only when the native
Dilithium library is available. Keys are neither acquired nor stored by the SDK.
The signing key must derive `submitter`; chain ID remains explicitly 2028.
`source_ref` is an explicit 32-byte caller reference, never a registry identity.

Responses describe admission, not committed balance movement. A transport failure
has an unknown outcome; reconcile the exact attempt before allocating another
nonce. The existing lost-transaction nonce guard remains active for final bodies.

Faucet requests are address requests that the server signs; send no amount. One claim gives 100 ARMA on L1 and 1,000 mock USDC on the exchange.

### Keyless Sub creation and DEX transfers

`build_signed_action("create_sub_account", ...)` encodes tag35 and
`build_signed_action("dex_transfer", ...)` encodes tag36. Both require all final
fields explicitly, use `signature_scheme=0` for ML-DSA-65 or `2` for EIP712,
and support caller-owned ephemeral key bytes or an offline digest signer.
For EIP712 supply the independently trusted consensus domain salt; use
`account_action_typed_data` to present the exact typed fields in a wallet.

`derive_sub_address(trusted_network, master, index)` hashes the approved domain,
N, full master address, and BE32 index. Its Borsh index remains LE32. Read N only
from a caller-trusted configured node's `get_subaccount_network_id()` result
(`/health/ready.dex_bridge_network_id`), or independently trusted local identity.
Do not substitute a genesis hash, anchor, chain ID or signing-session salt.

Submit the built bodies with `dex.create_sub_account(**body)` and
`dex.transfer(**body)`. `get_sub_accounts`, `get_sub_account` and
`get_account_action_quote` require an `authorize` callback producing ArmaSignedRead
for the exact target. No master override is sent. Quotes remain advisory;
the SDK validates the node's eligible/blocked capacity and reason without choosing a quota
equation. A transfer's signed source vault is distinct from its signer/nonce owner.

### Durable receipt reconciliation

Freeze a `TransferExpectation` with the original transaction/signing hashes,
master nonce, kind and expected monetary source/destination. Use
`dex.get_transfer_status(expected)` for the original ID, or
`dex.get_transfer_attempts(expected)` for the master's nonce slot. These perform
GET requests only. Repeating the read never signs or automatically posts anything.

A returned per-attempt `outcome.final` releases the corresponding lost nonce.
Refusal names alone do not determine this: consumed Insufficient/NotYetValid can
be final, an unused opening refusal can remain nonfinal, and historical v2 nonce
facts remain `None`. Every inclusion retains its own `trader_id`; an applied vault
withdrawal and a later duplicate rendered against master can coexist for one ID.
The final monetary `source_account` and `beneficiary` are distinct from signer.

`dex.get_transfer_history(authorize=...)` reads the existing private history
endpoint with an exact ArmaSignedRead target. New create/transfer kinds and nullable
legacy effects are preserved. Every signature (ML-DSA and EIP-712) binds the network id N:
the EIP-712 domain salt IS N, and `create_sub_account` / `transfer` take `network_id=N`.
Sub details support explicit `positions_cursor`/`positions_limit` and retain the
returned `positions_next_cursor` instead of silently dropping a later page.


### Master trading on a keyless Sub

Use the master trading envelope for an existing own Sub. The actual master signs and allocates its own nonce; `vaultAddress` / `vault_address` selects the economic account and is signed together with the complete original action bytes. The server independently checks current ownership, nonce and expiry. A trading agent has no authority through this API.

The codec supports place4, cancel5, amend6, advanced create7/cancel8/amend9, cancel-action18, TP/SL19, leverage20 and amend-v2 22. Use the existing canonical signable body with `unsignedMasterTradeAction` / `unsigned_master_trade_action`, or an existing full tagged body with the master builder: only the decoded signature/key containers are cleared. All semantic fields and the original inner scheme stay unchanged. Cancel-action18 uses its existing EIP712 scheme1; leverage20/amend22 use2. Place version2 is invalid. Current cancel-action/leverage bodies are version3 signed timestamps; old height/deadline encodings must not be relabeled.

TypeScript exports `buildMasterTrade`, `buildUnsignedMasterPlaceOrder`, `signMasterTrade`, `encodeMasterTrade`, `decodeMasterTrade` and `DexModule.submitMasterTrade`. Large values are bigint or canonical decimal strings. Python exports `MasterTrade`, `build_master_trade`, `sign_master_trade`, `encode_master_trade`, `decode_master_trade` and `DexModule.submit_master_trade`. Both Rust SDKs export `MasterTradeTx` and `submit_master_trade`; the maintained Rust SDK also provides existing local-key MLDSA/ECDSA signing adapters. Pure encoders never invent an account key, nonce, timestamp, source reference or leverage value.

Submit the full original tagged bytes to `POST /api/dex/master-trade` as the sole JSON field `tx`. A response with `accepted:true,pending:true` confirms the action was received, not that it was applied. Retry the same signed bytes while following the original outer transaction hash. EIP712 uses the network id N (GET /health `dex_bridge_network_id`) as its domain salt; the ML-DSA scheme signs the domain hash with the same N (`sign_master_trade(..., network_id=N)`).

Private reads append canonical lowercase `vault_address=0x<40 hex digits>` before authorizing the exact target. The signer/session remains the master; the server checks current own-Sub read authority. TypeScript `selectedAccountReadQuery`, Python `selected_account_read_query`, and Rust selected-target/query helpers preserve this boundary. Outcome `economic_account` and `wire` may be null for legacy Unknown records; never infer a selected Sub from `address`. `signing_nonce` is a lossless decimal string. `master_verified_refusal` and `master_consumed_refusal` remain distinct; terminal state follows the response's explicit finality and nonce-consumption fields.
