Metadata-Version: 2.4
Name: chimerakit
Version: 0.1.1
Summary: Python client for the Chimera partner bank API
Keywords: chimera,politics-and-war,banking,api-client,discord-bot
Classifier: Development Status :: 4 - Beta
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: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Games/Entertainment
Requires-Python: >=3.9
Description-Content-Type: text/markdown
Requires-Dist: httpx<1,>=0.27

# chimerakit

**The Python client for the Chimera partner bank API.** You run your own bank: your own bot, your own clients, your own Discord. Chimera holds the funds and keeps the ledger, so you don't have to.

```
pip install chimerakit
```

Three calls get a client's funds in, and three get them back out. The rest of this page is the detail.

---

## How it works, in one minute

Every movement of funds needs **two things to agree**, and either one alone does nothing:

1. **An API call**, signed with your secret. It proves *who is asking*, and Chimera answers with a short **code**.
2. **A transfer in the game**, alliance to alliance, carrying that code **as the whole note**. It proves *the funds are real*.

Chimera watches your alliance's bank records. When a transfer shows up whose note is exactly a code it issued, for exactly the amounts it was told to expect, it credits the client. Until then nothing has happened, and nothing is lost.

That is the whole design. A leaked secret cannot move funds on its own, and an in-game transfer with no matching call is just a transfer.

```
your bot  ──  create_deposit()  ──▶  Chimera  ──▶  code "K7FQ3MXB4RNT9WYZ"
your bot  ──  send in game, note = that code  ──▶  Chimera's alliance
Chimera   ──  sees both, credits the client  ──▶  get_deposit() == "credited"
```

---

## Try it with no account and no real funds

A pretend Chimera runs on your own computer. It gives the same answers as the real API, down to the status codes, and a test in Chimera's repository holds the two together. Copy this whole block and run it:

```python
from chimerakit import Chimera
from chimerakit.sandbox import Sandbox, SANDBOX_SECRET

with Sandbox() as box:                                   # a pretend Chimera, forgotten on exit
    bank = Chimera(SANDBOX_SECRET, base_url=box.url)

    # 1. open an account for one of your clients
    bank.open_account(discord_id="110000000000000001", nation_id=111)

    # 2. tell Chimera funds are coming, and get the code
    deposit = bank.create_deposit(
        discord_id="110000000000000001", nation_id=111,
        amounts={"money": "250.00"},
    )
    print("send $250.00 with this as the whole note:", deposit.code)

    # 3. in real life you now send it in the game. Here, act it out:
    box.arrive(deposit.code, money="250.00")

    print(bank.get_deposit(deposit.deposit_id).status)    # credited

    page, _ = bank.accounts()
    print(page[0].balances["money"])                      # 250.00
```

The sandbox needs no secret of your own, reaches nothing outside your computer, and never expires a code. Run it as a server instead, and point a real bot at it:

```
python -m chimerakit.sandbox          # http://127.0.0.1:8099
```

---

## Deposits: funds in

```python
deposit = bank.create_deposit(
    discord_id="110000000000000001",
    nation_id=111,
    amounts={"money": "1000.00", "steel": "50"},
)
```

You get back a `code`, an `alliance_id` to send to, the `amounts` to send, and an `expires_at`. Then:

1. **Send exactly those amounts** in the game, from your registered alliance to Chimera's (`deposit.alliance_id`).
2. **Put the code in the note, alone.** `K7FQ3MXB4RNT9WYZ` is credited. `deposit K7FQ3MXB4RNT9WYZ` is not.
3. **Do it inside 30 minutes**, before `expires_at`.
4. **Watch for it:** `bank.get_deposit(deposit.deposit_id).status` becomes `credited`.

| Status | Means |
|---|---|
| `waiting` | Chimera is watching for the transfer |
| `credited` | Done. The balance has moved |
| `expired` | The 30 minutes ran out. Start a new deposit |
| `under_review` | Something didn't line up. A person at Chimera settles it |

### The four things that trip people up

- **The note must be only the code.** No prefix, no suffix, no punctuation. This is the most common mistake by a wide margin.
- **The amounts must match to the cent.** A cent short is not credited; it goes to `under_review`.
- **It must come from your registered alliance.** A send from a nation, a trade, or another alliance is never credited automatically.
- **One deposit per client at a time.** A second `create_deposit` for the same client while one is still open is refused with `Conflict`. Finish the first, or let it expire.

Nothing in that list loses funds. Anything that doesn't line up becomes `under_review`, and a person settles it.

---

## Handoffs: one transfer, many clients

The tool for a raid. Everything leaves your alliance in a single transfer, and each client is credited their own share.

```python
from chimerakit import Line

handoff = bank.create_handoff([
    Line(discord_id="110000000000000001", nation_id=111, amounts={"money": "250.00"}),
    Line(discord_id="110000000000000002", nation_id=222, amounts={"money": "750.00", "steel": "10"}),
])

print("send", handoff.amounts, "with note", handoff.code)
```

Send `handoff.amounts` — the total, already added up for you — with `handoff.code` as the whole note. Then watch `get_handoff(handoff.handoff_id)`, which carries the same four statuses as a deposit.

**It credits every line or none.** If a client is frozen or unknown, the whole handoff is refused up front. If the total you send is off by a cent, nobody is credited and a person settles it. Up to 500 lines, and your limits count the total.

A handoff doesn't block a client's own deposit, and a client can be in more than one at a time.

---

## Withdrawals: funds out

**Chimera pays your alliance, and you pay your client.** Chimera never sends to a client's nation — that is deliberate, so your bank stays the only thing your clients ever deal with.

```python
w = bank.create_withdrawal(
    discord_id="110000000000000002", nation_id=222,
    amounts={"money": "400.00"},
)
# the client's balance is ALREADY down by 400.00 at this point
```

1. **The debit is immediate.** `create_withdrawal` takes the funds off the client's balance in the same transaction that records the payout, so there is no window in which the client could spend it twice.
2. **Chimera sends to your alliance**, with `w.code` as the note. When that is done, the status becomes `sent`.
3. **Check it yourself before you pay anyone.** Find the transfer in your alliance's bank record and confirm its note equals `w.code`. This is your half of the handshake, and it is what stops you paying out against a transfer that never arrived.
4. **Pay your client** out of your alliance, however your bank normally does it.
5. **Tell Chimera:** `bank.confirm_withdrawal(w.withdrawal_id, w.code)`. Saying it twice is harmless.
6. It becomes `completed` once your confirmation and the game's own record agree.

```python
w = bank.get_withdrawal(w.withdrawal_id)
if w.status == "sent":
    # ... you found the transfer, its note == w.code, and you paid your client
    bank.confirm_withdrawal(w.withdrawal_id, w.code)
```

| Status | Means | What to do |
|---|---|---|
| `processing` | Debited, not yet sent. May be waiting on a person | Keep checking. Don't send another |
| `sent` | It is in your alliance's bank record | Verify the note, pay your client, then confirm |
| `completed` | Your confirmation and the game record agree | Nothing |
| `under_review` | A person at Chimera is settling it | Nothing. Ask Chimera if it sits there |
| `failed` | It will not be sent | Ask Chimera. The funds are not returned automatically |

**Two honest notes.** A large withdrawal can sit at `processing` while a person approves it, and that is on purpose: telling you *why* it was held would tell you something about Chimera's float. And `confirm_withdrawal` is refused with `Conflict` until the status is `sent` — you cannot confirm something that hasn't gone out.

A client may have **five withdrawals in progress at once**. A sixth is refused with `Conflict`.

---

## Accounts and balances

```python
account = bank.open_account(discord_id="110000000000000001", nation_id=111)
```

Opening an account is harmless to repeat — you get the existing one back. A new account starts empty. Every client needs one before they can deposit, be in a handoff, or withdraw.

To walk every client you have, use `iter_accounts()` and let the paging happen for you:

```python
for account in bank.iter_accounts():
    print(account.discord_id, account.balances["money"], account.frozen)
```

If you'd rather page by hand, `accounts()` hands back a **two-tuple**, not a list:

```python
page, after = bank.accounts()
while True:
    for account in page:
        ...
    if after is None:
        break
    page, after = bank.accounts(after=after)
```

An `Account` carries `accountid`, `discord_id`, `nation_id`, `custody`, `frozen`, `balances` and `pending_deposits`.

---

## Amounts

Pass amounts as `Decimal`, `int` or `str`, with at most two decimal places. **A `float` is refused**, because by the time you hand one over it has already been rounded, and this is a bank. Amounts always come back as `Decimal`.

```python
{"money": "1000.00"}            # good
{"money": Decimal("1000.00")}   # good
{"money": 1000}                 # good
{"money": 1000.00}              # TypeError, on purpose
```

The twelve names are `money`, `food`, `coal`, `oil`, `uranium`, `lead`, `iron`, `bauxite`, `gasoline`, `munitions`, `steel` and `aluminum`. Leave out anything you aren't sending; a zero is refused.

---

## When a call goes wrong

Every error carries `status` and `request_id`, and all of them come from `ChimeraError`.

```python
from chimerakit import Conflict, Unavailable

try:
    w = bank.create_withdrawal(discord_id=..., nation_id=..., amounts={"money": "10.00"})
except Conflict as e:
    print("cannot right now:", e)           # frozen, short of funds, too many in progress
except Unavailable as e:
    w = bank.create_withdrawal(..., request_id=e.request_id)    # SAME id, never a new one
```

| Error | Means | What to do |
|---|---|---|
| `AccessDenied` | Wrong, revoked or expired secret; a scope you don't have; or your bank isn't switched on | Don't retry. Talk to Chimera |
| `LimitExceeded` | Over your bank's limit for one transfer, or for the day | Don't retry. Chimera sets the limits |
| `NotFound` | Missing, or not yours | Don't retry |
| `Conflict` | Can't go ahead as things stand — frozen, short of funds, a deposit already open, an ID reused | Read the message |
| `InvalidRequest` | The request itself is wrong | Fix it |
| `RateLimited` | Over 300 calls a minute, after the retries | Slow down |
| `Unavailable` | No clear answer, after the retries | Repeat with the **same** request ID |

---

## Retries, and why they're safe

Failed calls are retried for you, four tries in all, with a pause that grows. Anything that creates something carries a **request ID**, and Chimera acts on an ID exactly once — so a retry can never deposit or withdraw twice.

`Unavailable` is the one to understand. **It does not mean the call failed.** It means there was no clear answer. Repeat the call with `e.request_id`:

```python
try:
    w = bank.create_withdrawal(discord_id=..., nation_id=..., amounts={"money": "10.00"})
except Unavailable as e:
    w = bank.create_withdrawal(discord_id=..., nation_id=..., amounts={"money": "10.00"},
                               request_id=e.request_id)
```

Never retry with a fresh ID. A new ID on a withdrawal is a *second* withdrawal, and it will debit your client again.

To be safe across a crash, and not just a timeout, make the ID yourself, write it down, and only then call:

```python
from chimerakit import new_request_id

rid = new_request_id()
save_somewhere(rid)                        # a row in your own database
bank.create_withdrawal(..., request_id=rid)
```

Reusing an ID with different details is refused with `Conflict`, which is how you find out you crossed two requests.

---

## Your secret

Treat it as a key to your clients' funds, because that is what it is.

```python
import os
from chimerakit import Chimera

bank = Chimera(os.environ["CHIMERA_SECRET"], base_url="https://api.projectimagite.com")
```

Keep it in an environment variable. Never commit it, never log it, never put it in a Discord message. The client refuses to send it anywhere but HTTPS — the one exception is your own computer, for the sandbox — and it does not follow redirects.

Your secret begins `chim_`. Chimera stores only a hash of it, so nobody there can read it back to you: a lost secret is replaced, not recovered. **If it leaks, tell Chimera at once.** Replacing it takes seconds, and your clients' balances do not change.

### What your secret is allowed to do

A secret carries **scopes**. Chimera decides which yours has; you cannot change them yourself.

| Scope | Lets you call |
|---|---|
| `balances` | `open_account`, `accounts`, `iter_accounts` |
| `deposits` | `create_deposit`, `get_deposit`, `create_handoff`, `get_handoff` |
| `withdrawals` | `create_withdrawal`, `get_withdrawal`, `confirm_withdrawal` |
| `transfers` | Reserved for moving funds between clients. No method uses it yet |

A call outside your scopes fails with `AccessDenied` — and so does a wrong secret, a revoked one, an expired one, and a bank that is switched off. **They are deliberately the same error.** It tells you nothing about which, so a stolen secret learns nothing by probing. If you get `AccessDenied` and believe you shouldn't have, ask Chimera; retrying never helps.

---

## Every method

| Method | What it does |
|---|---|
| `open_account(discord_id, nation_id)` | Opens an empty account. Harmless to repeat |
| `iter_accounts()` | Every client and balance as one sequence, paging for you. **Use this one** |
| `accounts(after, limit)` | One page by hand. Returns `(accounts, after)` — pass `after` back, or it is `None` at the end |
| `create_deposit(discord_id, nation_id, amounts, request_id)` | Says funds are coming, and gets the code |
| `get_deposit(deposit_id)` | `waiting`, `credited`, `expired`, `under_review` |
| `create_handoff(lines, request_id)` | One transfer split across up to 500 clients |
| `get_handoff(handoff_id)` | The same four statuses |
| `create_withdrawal(discord_id, nation_id, amounts, request_id)` | Debits the client at once, and queues the payout to your alliance |
| `get_withdrawal(withdrawal_id)` | `processing`, `sent`, `completed`, `failed`, `under_review` |
| `confirm_withdrawal(withdrawal_id, code)` | Your word that the funds reached you |
| `health()` | `True` if the API is answering |

---

## For a Discord bot: the async client

`AsyncChimera` has exactly the same methods, awaited. Both clients are built from one shared description of every call, so the two cannot drift apart.

```python
import os
from chimerakit import AsyncChimera

async def run():
    async with AsyncChimera(os.environ["CHIMERA_SECRET"],
                            base_url="https://api.projectimagite.com") as bank:
        deposit = await bank.create_deposit(discord_id="110000000000000001", nation_id=111,
                                            amounts={"money": "100"})
        print(deposit.code)

        async for account in bank.iter_accounts():
            print(account.discord_id, account.balances["money"])
```

Use `Chimera` for a script or a worker, and `AsyncChimera` for a Discord bot or anything else on asyncio.

---

## Going live

1. Build and test the whole thing against `python -m chimerakit.sandbox`. You need nothing from Chimera to start.
2. Ask Chimera to register your bank. You give them your **alliance ID** and your Discord server; they give you a secret and set your limits.
3. Put the secret in an environment variable, and point `base_url` at `https://api.projectimagite.com`.
4. Check `bank.health()`, then open one account for yourself.
5. Run one small real deposit end to end before you let a client near it.
6. Keep your request IDs in your own database. It is the one piece of bookkeeping that is yours, and the one that saves you after a crash.

Two worked examples, `quickstart.py` and `discord_bot.py`, come with the source archive rather than the installed package. To get them without the repository:

```
pip download --no-binary :all: --no-deps chimerakit
```

Questions, a leaked secret, a withdrawal stuck under review, or a limit that is too low: talk to Chimera.
