> ## Documentation Index
> Fetch the complete documentation index at: https://docs.cowboy.inc/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Reference

> What every function, class and decorator in the actor SDK (`cowboy_sdk`) does

Every function, class and decorator in the actor SDK, `cowboy_sdk`. To learn it step by step, start with
[Build your first actor](https://docs.cowboy.inc/developers/your-first-actor.md). For the rules actor code runs under, see
[Determinism](https://docs.cowboy.inc/build/sdk/determinism.md).

Where `call()` and `send()` below refer to `payload_codec.CODECS`, the members of
that set and the behavior of each are documented under **Payload codecs** and
**Strict JSON codec**; [CIP-6 §9.5](https://docs.cowboy.inc/cips/cip-6-sdk.md) is the normative version.

## Actors (Actor)

*Module: `cowboy_sdk.actor`*

### `Actor`

```python theme={"system"}
class Actor
```

```text theme={"system"}
The base class of a Cowboy actor: ``class Vault(Actor)``.

It gives the actor ``self.address``, its own address, ``self.storage``, its
storage, and ``self.sender``, the caller of the current message. Its
handlers are the methods marked ``@public`` or ``@callable_by``; every
other method is an ordinary one, which nothing outside the actor reaches.

Creating a class costs nothing per handler: a handler's checks run when
it's called. A library base an actor inherits, such as ``Pausable``, is
itself an Actor, so it composes as ``class Vault(Pausable)``.
```

### `ActorRef`

```python theme={"system"}
class ActorRef
```

```text theme={"system"}
Actor reference, providing synchronous call syntactic sugar.

Synchronous call:
    oracle = ActorRef(oracle_address)
    price = oracle.get_price("ETH")
    # equivalent to call(oracle_address, "get_price", ["ETH"])

Send message:
    oracle.send_message(payload)

Non-CBOR target:
    blob = ActorRef(addr, codec="raw")
    echoed = blob.call("echo", b"\x00\x01")   # bytes in, bytes back
```

### `derive_actor_address`

```python theme={"system"}
derive_actor_address(deployer: bytes, salt: bytes, code_hash: bytes, shard = None) -> Address
```

```text theme={"system"}
Derive an actor address; None inherits the deployer's two-byte group.
```

## Who may call a handler (@public, @callable\_by)

*Module: `cowboy_sdk.permissions`*

### `public`

```python theme={"system"}
public(func = None, *, decode = None)
```

```text theme={"system"}
Declare that any account may invoke this handler.

Required for the handler to be reachable from another account — the SDK
denies undecorated handlers by default.

Usable bare (``@public``) or parameterized (``@public(decode="cbor")``).
``decode`` selects the payload codec (``"raw"`` | ``"cbor"`` | ``"json"``);
see ``payload_codec.decode_payload`` for the codec contract. Omitting it
takes the default, which is ``"cbor"``; host-built ``init``/``on_fork`` and
event/stream entrypoints stay raw unless explicitly declared otherwise.

A handler with an encoded codec has one return rule: bytes-like is
already-encoded output and passes through, ``None`` is no output, and any
other value is encoded with the codec. A raw handler's return is never
encoded.
```

### `callable_by`

```python theme={"system"}
callable_by(*principals, decode = None)
```

```text theme={"system"}
Restrict this handler to a fixed set of principals.

Parameters
----------
*principals
    One or more of:
      - 20-byte address bytes, hex string, or Address object
      - the OWNER sentinel (resolved against runtime.get_owner())
      - the SELF sentinel (matches only intra-actor calls)
decode
    Payload codec (``"raw"`` | ``"cbor"`` | ``"json"``); see
    ``payload_codec.decode_payload`` for the codec contract and ``public``
    for the return rule. Omitting it takes the CBOR default — see
    ``public``.
```

## Handler modes (@pure, @deferred)

*Module: `cowboy_sdk.handler_mode`*

### `pure`

```python theme={"system"}
pure(func)
```

```text theme={"system"}
Declare a handler as a pure synchronous method.

Calling send(), submit_job(), or other async side-effect operations is
forbidden inside a @pure handler. call() (synchronous cross-Actor calls)
and state reads/writes are allowed.

This is the default behavior: a handler with no mode decorator runs as
@pure. Using @pure explicitly improves code readability.

Usage:
    class MyActor(Actor):
        @pure
        def compute(self, payload):
            ref = ActorRef(addr, cycles_limit=100000)
            result = ref.call("method", args)  # ✅ call() allowed
            # runtime.send(...)                 # ❌ raises PurityViolationError
            return codec.encode(result)
```

### `deferred`

```python theme={"system"}
deferred(func)
```

```text theme={"system"}
Declare that a handler may produce async side effects.

@deferred handlers are allowed to call send(), submit_job(), set_timer(), etc.
Callers should be aware: when a @deferred handler is called via call(), the synchronous
return value is immediate, but async side effects (deferred transactions) execute in
subsequent blocks and are not atomic.

Usage:
    from cowboy_sdk import Actor, deferred

    class MyActor(Actor):
        @deferred
        def trigger_job(self, payload):
            runtime.send(logger, "log", data)   # ✅ allowed
            return codec.encode({"status": "submitted"})
```

## Runtime — host calls (state, time, randomness, timers, tokens)

*Module: `cowboy_sdk.runtime`*

### `mode`

```python theme={"system"}
mode() -> str
```

```text theme={"system"}
Return the current Continuation execution mode.

Returns
-------
str
    "fsm" (production/default), "checkpoint" (development debug only), or "local" (local development)
```

### `is_production`

```python theme={"system"}
is_production() -> bool
```

```text theme={"system"}
Whether the current mode is production (on-chain consensus) mode.
```

### `is_development`

```python theme={"system"}
is_development() -> bool
```

```text theme={"system"}
Whether the current mode is local development mode (no PVM Host).
```

### `is_checkpoint_mode`

```python theme={"system"}
is_checkpoint_mode() -> bool
```

```text theme={"system"}
Whether the current mode is Checkpoint mode (for debugging only; must never enter consensus).
In this mode, developers are warned not to deploy to mainnet.
```

### `require_fsm`

```python theme={"system"}
require_fsm() -> None
```

```text theme={"system"}
Assert that the current mode is FSM (production) mode.
Raises DeterminismError on violation to prevent Checkpoint from accidentally entering consensus.
```

### `get_pvm_version`

```python theme={"system"}
get_pvm_version() -> str
```

```text theme={"system"}
Get the PVM version string.
```

### `get_chain_id`

```python theme={"system"}
get_chain_id() -> int
```

```text theme={"system"}
Return the genesis chain ID from the authenticated host context.
```

### `get_chain_instance_id`

```python theme={"system"}
get_chain_instance_id() -> bytes
```

```text theme={"system"}
Return the genesis instance ID (32 bytes) from the host context.
```

### `context`

```python theme={"system"}
context() -> Dict[str, Any]
```

```text theme={"system"}
Return the full execution context (read-only).
```

### `get_actor_address`

```python theme={"system"}
get_actor_address() -> bytes
```

```text theme={"system"}
Return the current Actor's own address (20-byte Ethereum address).

Prefers pvm_host.self_address(); falls back to context()['actor_addr'].
```

### `actor_address`

```python theme={"system"}
actor_address() -> 'Address'
```

```text theme={"system"}
Return this Actor's own address as an ``Address``.

``actor_addr`` is the actor *itself*, read from ``ctx["actor_addr"]`` (or
``pvm_host.self_address()`` when the host exposes it). Distinct from
:func:`_sender`, the caller (``ctx["sender"]``); don't conflate self with
caller.

Typed counterpart of :func:`get_actor_address`, which stays available as the
raw-bytes escape hatch. Returns ``Address.ZERO`` only when the address is
unset (``b""``); a corrupt non-20-byte value raises ``AddressError``.
```

### `get_tx_hash`

```python theme={"system"}
get_tx_hash() -> bytes
```

```text theme={"system"}
Return the current transaction hash (32 bytes).
```

### `get_block_height`

```python theme={"system"}
get_block_height() -> int
```

```text theme={"system"}
Return the current block height.
Prefers pvm_host.current_block(); falls back to context()['block_height'].
```

### `get_timestamp_ms`

```python theme={"system"}
get_timestamp_ms() -> int
```

```text theme={"system"}
Return the current block timestamp (milliseconds).
```

### `charge_gas`

```python theme={"system"}
charge_gas(amount: int) -> None
```

```text theme={"system"}
Report gas consumption to the PVM.
```

### `emit_event`

```python theme={"system"}
emit_event(name: str, payload: Any, *, schema: bytes | None = None) -> dict
```

```text theme={"system"}
Send an event to the chain and return its EmitResult dictionary.

Optional ``schema`` is a 32-byte payload schema identifier. Explicit
declarations must match every explicitly typed subscriber. The identifier
describes the codec and schema agreed by the parties; payload bytes are not
parsed or validated by the node.

``emit_id`` identifies this emit within the transaction (starting at 1).
``sync_outcomes`` contains attempted or skipped synchronous deliveries in
subscription order: ``sub_id`` (33-byte ID), ``status`` (0 success, 1 handler
error, 2 skipped/refused), and ``gas_used`` (inclusive subtree cycles).
``deferred_subs`` lists IDs queued for deferred delivery, including Access
overflow. Delivery remains subject to transaction commit and child admission.

Encoding: canonical CBOR (invariant I-1), plus a raw hatch keyed on the
payload's *type*.

- bytes-like (``bytes``/``bytearray``/``memoryview``): the raw hatch — sent
  verbatim, for a payload that is already serialized.
- anything else: canonical CBOR via ``codec.encode``. ``None`` emits CBOR
  null, the faithful encoding of the value that was passed.

Raises ``CodecError`` for a value the codec cannot encode, and for a str that
is already serialized JSON (see ``_reject_json_string``).

NOT interchangeable with ``send()``, which shares only the non-bytes -> CBOR
rule. ``send()``'s hatch is the ``raw=`` keyword, not the type, so
``send(t, b'x')`` CBOR-wraps the bytes where ``emit_event(t, b'x')`` passes
them verbatim; ``send(t)`` encodes ``b''`` where ``emit_event(t, None)``
emits CBOR null; and ``send()`` has no JSON-string guard.

NOTE (consensus): the encoded bytes are committed — the host folds them into
`compute_logs_root` -> `receipt_root`, and bills cells per encoded byte. See
the flag-day note in docs/dev/cip29-event-hooks.md before changing anything
here that moves the bytes.
```

### `get_state`

```python theme={"system"}
get_state(key: bytes) -> Optional[bytes]
```

```text theme={"system"}
Read a raw bytes value from on-chain storage. Prefer self.storage unless raw access is required.
```

### `set_state`

```python theme={"system"}
set_state(key: bytes, value: bytes) -> None
```

```text theme={"system"}
Write a raw bytes value to on-chain storage. Prefer self.storage unless raw access is required.

Refuses writes to keys in ``RESERVED_KEYS`` — those are managed by the
SDK and writing them from user code would void the permission and
initialization guarantees built on top. The reject is enforced both here
(friendly Python error) and in the Rust host bridge (authoritative).
```

### `delete_state`

```python theme={"system"}
delete_state(key: bytes) -> None
```

```text theme={"system"}
Delete a key from on-chain storage. Refuses deletes of reserved keys.
```

### `get_owner`

```python theme={"system"}
get_owner() -> bytes
```

```text theme={"system"}
Return the current protocol-owned ActorOwner account.

The host validates the executing actor's protected record. Missing or invalid
metadata raises a host error; application storage cannot supply ownership.
```

### `owner`

```python theme={"system"}
owner() -> 'Address'
```

```text theme={"system"}
Return the protocol owner as an ``Address``.

Ownership is assigned by deployment. Only a direct current-owner-signed
``TransferActorOwnership`` transaction can change it; actor code cannot.
```

### `is_initialized`

```python theme={"system"}
is_initialized() -> bool
```

```text theme={"system"}
Return True once a successful ``init`` handler has run on this actor.

The SDK auto-sets the ``__INITIALIZED__`` flag after ``init`` returns
without raising. Before that, ``init`` is implicitly callable by anyone
(the atomic-deploy bootstrap window); after, ``init`` follows the same
deny-by-default rules as every other handler.
```

### `scan_state_prefix`

```python theme={"system"}
scan_state_prefix(prefix: bytes, limit: int = 100) -> list[tuple[bytes, bytes]]
```

```text theme={"system"}
Return up to `limit` ``(key, value)`` pairs from on-chain storage whose
user-key starts with ``prefix``, in ascending key order (Model C).

Semantics:
- Only keys stored in verbatim mode (≤64 bytes) are visible; long keys
  (hashed mode) are never returned by prefix scan.
- ``limit`` is clamped to ``MAX_PREFIX_SCAN_LIMIT`` (1000) by the host.
- Pricing: ``500 + limit × 50`` cycles (by ``limit``, not returned
  count — prevents "wide scan narrow filter" free lunch) plus
  ``sum(len(k)+len(v))`` cells for returned entries.

Pagination: pass the last returned key (appended with ``b"\x00"``) as
the next ``prefix`` to continue past the current page — or use the
higher-level ``/actors/{addr}/storage`` RPC for offset/cursor pagination.

Returns ``[]`` when no key matches the prefix.

Example:
    entries = scan_state_prefix(b"user:", limit=50)
    for key, value in entries:
        ...
```

### `send_message`

```python theme={"system"}
send_message(target: bytes, payload: bytes) -> None
```

```text theme={"system"}
Send a raw message to ``target`` (0x-str / 20-byte bytes / Address).

This is the low-level binding (payload is sent verbatim); prefer ``send()``
for object payloads.
```

### `call_actor`

```python theme={"system"}
call_actor(target: bytes, method: str, payload: bytes, cycles_limit: int, access_limit: Optional[int] = None) -> bytes
```

```text theme={"system"}
Synchronously call a method on ``target`` (0x-str / 20-byte bytes / Address).

Low-level binding (payload is sent verbatim); prefer ``call()`` for object args.
``access_limit`` is unscaled nested-frame access authority. The SDK encodes
omission as the raw-host ``0`` sentinel, which grants floor(63/64 of the
caller's remaining authority). The Python SDK rejects an explicit SDK ``0``;
the preserved raw ABI collapses literal ``0`` and omission to that default,
so the host's ``Some(0)`` rejection is defense in depth and is unreachable
through this runtime. Strictness is inherited: a child is strict if its
parent is strict or allowance is below remaining. At remaining ``1``, the
default is ``0 < 1`` and strict/catchable; at remaining ``0``, it is ``0 ==
0`` and non-strict/fatal.
```

### `fork_actor`

```python theme={"system"}
fork_actor(endowment: int = 0) -> bytes
```

```text theme={"system"}
fork() prototype — low-level host binding for the self-clone primitive.

The calling Actor creates a NEW Actor that is a byte-exact copy of itself
(same code, same storage) at a new deterministic address, and becomes that
child's parent. Synchronous: returns the 20-byte child address.

``endowment`` is native CBY wei to debit from the parent and credit to the
child atomically with the fork. ``0`` keeps the child zero-balance.

Prefer the high-level :func:`cowboy_sdk.fork` wrapper in application code.
```

### `transfer_balance`

```python theme={"system"}
transfer_balance(to: bytes, amount: int) -> None
```

```text theme={"system"}
Move native CBY from this actor's balance to ``to``.

``to``: 0x-str / 20-byte bytes / Address.
```

### `schedule_timer`

```python theme={"system"}
schedule_timer(height: int, payload: bytes) -> bytes
```

```text theme={"system"}
Schedule a timer that fires at `height`, delivering `payload` to the
calling actor. Requires the ``timer.schedule`` entitlement. Returns a
timer id (opaque bytes) that can be passed to ``cancel_timer``.

Uses protocol defaults for ``fee_payer`` (actor pays itself),
``gas_limit`` (the CIP-5 cycle default below), ``access_limit``
(``DEFAULT_TIMER_ACCESS_PER_FIRE``), and ``expires_at``
(``current_height + TimerConfig.max_ttl_blocks``). Use
:func:`schedule_timer_ex` to override any of these.
```

### `schedule_timer_ex`

```python theme={"system"}
schedule_timer_ex(height: int, payload: bytes, fee_payer: Optional[bytes] = None, gas_limit: Optional[int] = None, access_limit: Optional[int] = None, expires_at: Optional[int] = None) -> bytes
```

```text theme={"system"}
Model B schedule with actor-specified economics (CIP-5 §4.1).

Args:
    height: block height at which the timer fires; MUST be strictly > current.
    payload: opaque bytes delivered to the handler (max 1 MiB).
    fee_payer: address debited at each fire (0x-str / 20-byte bytes /
        Address). Must be this actor's own address; ``None`` → actor pays
        itself. The caller/deployer cannot be billed for future fires.
        ZERO is rejected. System actors may fund themselves, but another
        address in the reserved system-actor band ``0x01..=0xFF`` is rejected.
        Canonical Watchtower provider funding uses its authenticated native
        start/restart/renewal path, not this generic scheduler (CIP-5 §4.2).
    gas_limit: per-fire cycle request. ``None`` or ``0`` selects the
        height-dependent CIP-5 default below. A positive request must
        fit the scheduling ceiling at that height.
    access_limit: declared per-fire committed-store access request.
        ``None`` → ``DEFAULT_TIMER_ACCESS_PER_FIRE``. Must be ≤ the
        protocol Timer access cap; ``0`` is rejected.
    expires_at: absolute block height after which the timer self-destructs.
        ``None`` → ``current_height + TimerConfig.max_ttl_blocks``. Must
        be strictly > current and ≤ ``current + max_ttl_blocks``.

Returns the timer id (opaque bytes).

Example — actor-funded oracle timer with a tighter budget::

    timer_id = schedule_timer_ex(
        cowboy_sdk.current_block() + 10,
        b"",
        fee_payer=None,
        gas_limit=200_000,
        access_limit=32,
        expires_at=cowboy_sdk.current_block() + 2_592_000,
    )
```

Both timer scheduling functions use the [CIP-5 cycle policy](https://docs.cowboy.inc/cips/cip-5-timers.md#41-python-host-api).
Let `G = TimerConfig.max_cycles_per_fire`. Omission, `None`, or `gas_limit=0` selects
`G` below `TIMER_FIRE_CYCLES_FOLLOW_CONFIG_ACTIVATION_HEIGHT`, and `min(550_000, G)`
from that height. At the ordinary governed maximum, this is 550,000 cycles. The SDK
sends `None` as the host ABI's zero sentinel; explicit zero uses the same default.

Once the gate is active and governance raises `G`, opt in to a larger fire with a
positive `gas_limit`, bounded by `min(G, 2_200_000)`. For example, a timer that does
handler work before submitting a Runner job can request `gas_limit=1_500_000` when
`G` is at least 1,500,000. The handler and its JobSubmit share that budget; select
enough for both. Governance alone does not increase a new default timer's request.
The fire-time cap and admission-shortfall receipt are defined in
[CIP-5 §6.2](https://docs.cowboy.inc/cips/cip-5-timers.md#62-execution-budget). This gate is currently dormant.

### `extend_timer`

```python theme={"system"}
extend_timer(timer_id: bytes, new_expires_at: int) -> None
```

```text theme={"system"}
Renew a timer's ``expires_at`` (Model B.6). Caller must own the timer
(timer.actor_address == executing actor); cross-actor renewal via this
syscall is rejected as ``Unauthorized``. ``new_expires_at`` must be
strictly > current block height and ≤ ``current + TimerConfig.max_ttl_blocks``.

A missing timer (already self-destructed) is a silent no-op — safe to
call idempotently from a handler that races self-destruct.
```

### `cancel_timer`

```python theme={"system"}
cancel_timer(timer_id: bytes) -> None
```

```text theme={"system"}
Cancel a previously scheduled timer by its opaque id.
```

### `schedule_after`

```python theme={"system"}
schedule_after(seconds: int, handler, payload: bytes = None, **opts) -> bytes
```

```text theme={"system"}
Run ``handler`` once ``seconds`` (>= 1) of block time have passed.

The timer fires at the height :func:`seconds_to_blocks` estimates; if
block time has not caught up by then, the SDK re-arms it for the time left
and the handler waits. The handler receives ``payload``. ``opts`` forwards
``fee_payer`` / ``gas_limit`` / ``access_limit`` / ``expires_at`` to the
timer; a re-arm uses the defaults. Returns the timer id.
```

### `seconds_to_blocks`

```python theme={"system"}
seconds_to_blocks(seconds: int, block_interval_ms: int = None) -> int
```

```text theme={"system"}
The blocks that span ``seconds`` of block time, rounded up.

``block_interval_ms`` defaults to :data:`BLOCK_INTERVAL_MS`, an estimate,
so the blocks can pass in less time. Write ``seconds`` with the package's
durations: ``seconds_to_blocks(HOUR)``.
```

### `subscribe_event`

```python theme={"system"}
subscribe_event(emitter: bytes, topic: bytes, handler: str, gas_prepaid: int, bid: int = 0, *, schema: bytes | None = None) -> bytes
```

```text theme={"system"}
CIP-29 §2.1: subscribe to a (emitter, topic) for synchronous fan-out.

Charges the calling actor:
  - SUBSCRIPTION_REGISTRATION_FEE cycles (burned, not refundable)
  - bid cycles (burned, not refundable)
  - gas_prepaid cycles (held in gas_remaining, refundable via unsubscribe_event)
  - cells for the EventSub record + index entry (refundable)

Returns the 33-byte sub_id. Optional ``schema`` is a 32-byte identifier.
If the emitter has declared a different identifier, the host raises
``event_schema_mismatch`` (117) before registration fees or writes.

Raises:
    ValueError: emitter not 20 bytes, topic empty or >64 bytes, handler invalid.
    HostError: gas_prepaid below MIN_SUBSCRIPTION_GAS_PREPAID; >= 512 subscribers
               already on this topic; insufficient balance.
```

### `unsubscribe_event`

```python theme={"system"}
unsubscribe_event(sub_id: bytes) -> int
```

```text theme={"system"}
CIP-29 §2.1: unsubscribe (caller must be the subscriber).

Refunds remaining gas_remaining cycles to the subscriber.
bid and REGISTRATION_FEE are NOT refundable.

Returns the cycles refunded.

Raises:
    ValueError: sub_id not 33 bytes.
    HostError: sub_id not found; caller is not the subscriber.
```

### `force_unsubscribe_event`

```python theme={"system"}
force_unsubscribe_event(sub_id: bytes) -> None
```

```text theme={"system"}
CIP-29 §2.1: force-remove a subscription (caller must be the emitter).

Refunds remaining gas + cells to the SUBSCRIBER (emitter gets nothing).

Raises:
    ValueError: sub_id not 33 bytes.
    HostError: sub_id not found; caller is not the emitter.
```

### `update_bid`

```python theme={"system"}
update_bid(sub_id: bytes, additional_bid: int) -> int
```

```text theme={"system"}
CIP-29 §2.1: increase the bid for an existing subscription (caller must be subscriber).

additional_bid is burned immediately. The index is re-sorted so a higher
cumulative bid moves toward the sync-fire window.

Returns the new cumulative bid.

Raises:
    ValueError: sub_id not 33 bytes; additional_bid < MIN_BID_STEP (1000).
    HostError: sub_id not found; caller is not the subscriber; bid overflow.
```

### `topup_subscription`

```python theme={"system"}
topup_subscription(sub_id: bytes, additional_gas: int) -> int
```

```text theme={"system"}
CIP-29 §2.1: add gas to an existing subscription. Any caller may call.

The caller's balance is debited (NOT the subscriber's). Used to keep a
long-lived subscription alive past initial gas_prepaid exhaustion.

Returns the new gas_remaining.

Raises:
    ValueError: sub_id not 33 bytes.
    HostError: sub_id not found; caller balance insufficient.
```

### `upgrade_self`

```python theme={"system"}
upgrade_self(new_code: bytes, new_manifest: Optional[bytes] = None, routes: Optional[bytes] = None, route_sponsorship: Optional[bytes] = None) -> None
```

```text theme={"system"}
Upgrade the calling actor's code (and optionally its manifest).

The calling actor's current manifest must declare ``sys.upgrade``. If a new
manifest is provided it must be a subset of the current one (no entitlement
broadening). On success the new code takes effect from the next handler
invocation; state (storage, balance, nonce, mailbox) is preserved.

The routes the new code serves travel with it (CIP-15 §6.9): ``routes``
replaces the installed table, and omitting it removes the installed routes.

Parameters
----------
new_code : bytes
    The new actor code (e.g., a UTF-8 encoded Python source).
new_manifest : Optional[bytes]
    Optional CBOR-encoded ``ActorManifest`` bytes. Pass ``None`` to keep
    the current manifest.
routes : Optional[bytes]
    The canonical CIP-15 routes table for the new code.
route_sponsorship : Optional[bytes]
    The CIP-11 sponsorship ceiling; required exactly when ``routes``
    contains native runner routes.

Raises
------
HostError
    ``missing_entitlement`` if the calling actor lacks ``sys.upgrade``;
    ``invalid_input`` if the new code, manifest or routes fail validation or
    the new manifest is not a subset of the current one.
```

### `submit_job`

```python theme={"system"}
submit_job(payload: bytes) -> None
```

```text theme={"system"}
Start a Runner job from an envelope the caller builds and encodes.

This is the low-level call, and the SDK's job protections do not apply to
it: no default deadline, no reaping or ``runner.cancel``, no per-caller
wait caps or ``@limit`` pending count, no ``@single_flight``, no
paused-resume rules, and no SDK secret check (only the runner's marked
slots, R8, apply). Start ordinary jobs with ``await runner.*``; this is for
system job types ``runner.*`` does not cover, such as ``publish_chain_root``.
```

### `intent_deposit`

```python theme={"system"}
intent_deposit(token_id: bytes, amount: int) -> None
```

```text theme={"system"}
CIP-34: deposit ``amount`` of ``token_id`` (str / bytes / TokenId;
``CBY_SENTINEL`` for native CBY) from this actor into the settlement ledger.
Enqueues a deferred ``IntentDeposit``; requires the ``econ.intent``
entitlement.
```

### `intent_withdraw`

```python theme={"system"}
intent_withdraw(token_id: bytes, amount: int) -> None
```

```text theme={"system"}
CIP-34: withdraw ``amount`` of ``token_id`` (str / bytes / TokenId) from
the settlement ledger back to this actor. Enqueues a deferred
``IntentWithdraw``.
```

### `intent_broadcast`

```python theme={"system"}
intent_broadcast(nonce: int, deadline: int, diffs, kind: str = 'Settle', dest_chain = None, dest_recipient = None) -> None
```

```text theme={"system"}
CIP-34: broadcast a resting Intent for this actor so a solver can later
match and settle it. ``diffs`` is an iterable of ``(token_id, amount: int)``
where ``token_id`` is str / bytes / TokenId and ``amount`` is a signed token
diff (negative = give, positive = want). Enqueues a deferred
``IntentBroadcast``; requires the ``econ.intent`` entitlement.

``kind`` is ``"Settle"`` (domestic, default) or ``"Withdraw"`` (cross-chain,
CIP-34 Phase 3); ``dest_chain`` (int) and ``dest_recipient`` (bytes) declare
the cross-chain destination for a Withdraw intent.
```

### `randomness`

```python theme={"system"}
randomness(domain: bytes) -> bytes
```

```text theme={"system"}
Get deterministic random bytes.
```

### `keccak256`

```python theme={"system"}
keccak256(data: bytes) -> bytes
```

```text theme={"system"}
Compute keccak256 (raises an exception if the Host does not provide it).
```

### `token_create`

```python theme={"system"}
token_create(name: bytes, symbol: bytes, decimals: int, initial_supply: int, max_supply: int | None, transfer_hook: bytes | None, metadata_uri: bytes | None) -> bytes
```

```text theme={"system"}
Create a new platform token. Returns token_id (32 bytes).

``transfer_hook`` (optional) is an address: str / bytes / Address.
```

### `token_balance_of`

```python theme={"system"}
token_balance_of(token_id: bytes, owner: bytes) -> int | None
```

```text theme={"system"}
Query token balance for owner. ``token_id``: str / bytes / TokenId.
Addresses: 0x-str / 20-byte bytes / Address.
```

### `token_total_supply`

```python theme={"system"}
token_total_supply(token_id: bytes) -> int | None
```

```text theme={"system"}
Query token total supply. ``token_id``: str / bytes / TokenId.
```

### `budget_left`

```python theme={"system"}
budget_left() -> int | None
```

```text theme={"system"}
Wei this actor may still commit this budget period, or None without an ``econ.budget``.
```

### `token_transfer`

```python theme={"system"}
token_transfer(token_id: bytes, to: bytes, amount: int) -> None
```

```text theme={"system"}
Transfer tokens from caller to recipient. ``token_id``: str / bytes /
TokenId. ``to``: str / bytes / Address.
```

### `token_approve`

```python theme={"system"}
token_approve(token_id: bytes, spender: bytes, amount: int) -> None
```

```text theme={"system"}
Approve spender to transfer up to amount. ``token_id``: str / bytes /
TokenId. ``spender``: str / bytes / Address.
```

### `token_allowance`

```python theme={"system"}
token_allowance(token_id: bytes, owner: bytes, spender: bytes) -> int | None
```

```text theme={"system"}
Query allowance (owner -> spender). ``token_id``: str / bytes / TokenId.
Addresses: str / bytes / Address.
```

### `token_transfer_from`

```python theme={"system"}
token_transfer_from(token_id: bytes, from_addr: bytes, to: bytes, amount: int) -> None
```

```text theme={"system"}
Transfer tokens using allowance. ``token_id``: str / bytes / TokenId.
Addresses: str / bytes / Address.
```

### `token_mint`

```python theme={"system"}
token_mint(token_id: bytes, to: bytes, amount: int) -> None
```

```text theme={"system"}
Mint new tokens (requires mint_authority). ``token_id``: str / bytes /
TokenId. ``to``: str / bytes / Address.
```

### `token_burn`

```python theme={"system"}
token_burn(token_id: bytes, amount: int) -> None
```

```text theme={"system"}
Burn tokens from caller's balance. ``token_id``: str / bytes / TokenId.
```

### `offchain_image_initialize`

```python theme={"system"}
offchain_image_initialize(image: bytes) -> None
```

```text theme={"system"}
Initialize the protected image during the outer atomic deployment only.

The host verifies deployment authority, sender ownership and absent state.
Ordinary calls cannot initialize or repair this slot.
```

### `offchain_image_update`

```python theme={"system"}
offchain_image_update(expected: bytes, image: bytes) -> None
```

```text theme={"system"}
Replace the protected image using owner-authenticated compare-and-set.

Both values are 64 lowercase ASCII hexadecimal bytes. Missing state,
stale expectations and non-owner callers fail without changing the image.
```

### `verify_signature`

```python theme={"system"}
verify_signature(algorithm: int, public_key: bytes, message: bytes, signature: bytes) -> bool
```

```text theme={"system"}
Verify a raw message using CIP-40 algorithm 2 (strict Ed25519).

Unsupported algorithms and wrong key/signature lengths raise ValueError
before crossing the host boundary. Host errors, including resource limits,
propagate; only a well-formed invalid signature returns False.
```

### `hire_id`

```python theme={"system"}
hire_id() -> Optional[int]
```

```text theme={"system"}
Return the CIP-33 hire this call is made under, or ``None``.

Set only when the caller's signed ``ExecuteActor`` names a hire and the
chain has checked it: the caller is the hire's hirer, the hire's
declaration names this actor, and the hire is Active and within its term.
A nested ``call()``, a message, a timer, a callback or a call made without
a hire reads ``None``. An actor that keeps per-hire state (a usage count, a
monthly allowance) keys it on this id rather than on a payload argument.
```

### `is_allowed_caller`

```python theme={"system"}
is_allowed_caller(hire_id: int, caller) -> bool
```

```text theme={"system"}
Whether ``caller`` may use Trading Post hire ``hire_id`` on this actor.

True for the hire's hirer, actors it owns (unless the hire turned that
off) and each allowed caller it granted, while the hire is Active, in term
and for this actor. An allowed caller's ``True`` spends one use; call once
per request. A revoke applies to every later transaction, including later
ones in the same block. A use spent inside a nested call that fails and is
caught stays spent; a reverted transaction spends none. ``caller``: str /
bytes / Address, usually ``bytes(self.sender)``.
```

## Types (Address, TokenId, ordered\_set)

*Module: `cowboy_sdk.types`*

### `ordered_set`

```python theme={"system"}
class ordered_set
```

```text theme={"system"}
Insertion-order-deterministic set (CIP-6 PVM compatibility golden rule 4).

The iteration order of the standard Python set is non-deterministic across
different Python implementations and versions, which can cause cross-node
state hash mismatches (chain forks). ordered_set uses a dict to guarantee
O(1) lookup while maintaining insertion order.

Compatible with the main interface of the standard set: add, discard, remove,
__contains__, __iter__, __len__, __repr__, union, intersection, difference.
```

### `BlockHeight`

```python theme={"system"}
class BlockHeight
```

```text theme={"system"}
Semantic wrapper type for block heights.

An int subclass, but __repr__ and __str__ display a friendly format.
Used for type annotations so developers can clearly tell that an integer represents a block height.
```

### `Address`

```python theme={"system"}
class Address
```

```text theme={"system"}
20-byte Ethereum-style address (ADDRESS_MIGRATION scheme A).

Address derivation: keccak256(secp256k1_pubkey[1:])[12:32]
Format: 0x + 40 hex characters (EIP-55 checksum encoding)

System Actors use low-value addresses (similar to EVM precompiles):
    Address.RUNNER_REGISTRY   = 0x0000...0001
    Address.JOB_DISPATCHER    = 0x0000...0002
    Address.RESULT_VERIFIER   = 0x0000...0003
    Address.SECRETS_MANAGER   = 0x0000...0004
    Address.TEE_VERIFIER      = 0x0000...0005
    Address.TOKEN_REGISTRY    = 0x0000...0006
```

### `to_address_bytes`

```python theme={"system"}
to_address_bytes(x) -> bytes
```

```text theme={"system"}
Normalize an address-like value to raw 20 bytes.

Accepts a 0x-hex str, 20-byte bytes/bytearray, or an Address. Public face of
the internal _addr normalizer, exported from cowboy_sdk so actors can accept
forgiving address inputs without re-implementing 0x/hex handling.

Strict: always returns exactly 20 bytes and rejects any other width. (The
runtime host-call wrappers use a separate, looser coercion that passes bytes
through untouched so the host can apply its own width rules — e.g. the
token bindings' 32-byte form.)
```

### `TokenId`

```python theme={"system"}
class TokenId
```

```text theme={"system"}
32-byte CIP-20 token identifier.

A token id is the opaque 32-byte handle returned by ``runtime.token_create``
and accepted by every ``runtime.token_*`` query/mutation. Mirrors the
``Address`` type, but is 32 bytes and has no EIP-55 checksum — ``to_hex`` is
a plain lowercase 0x-hex string.
```

## Sorted map

*Module: `cowboy_sdk.sorted_map`*

### `SortedMap`

```python theme={"system"}
class SortedMap
```

```text theme={"system"}
An ordered, unique-key map. Values live in a dict; keys are kept sorted.
```

## Actor signing keys and signature verification

*Module: `cowboy_sdk.signing`*

### `set_signing_key`

```python theme={"system"}
set_signing_key(state_key: bytes, algorithm: int, public_key: bytes) -> None
```

```text theme={"system"}
Create or replace a record, only when the current sender is the owner.

Initialize ownership atomically at deployment before calling this helper.
Unowned/renounced actors and self-calls by non-owners are refused. A failed
authorization or validation leaves the existing record unchanged.
```

### `get_signing_key`

```python theme={"system"}
get_signing_key(state_key: bytes) -> dict | None
```

```text theme={"system"}
Read a checked record; missing is None, malformed/unsupported raises.
```

### `verify_with_signing_key`

```python theme={"system"}
verify_with_signing_key(state_key: bytes, message: bytes, signature: bytes) -> bool
```

```text theme={"system"}
Verify against the stored algorithm and key; missing authority raises.

Callers must domain-separate messages and enforce their own nonce/replay
policy. This helper authenticates bytes, not an application's intent.
```

## Cross-actor calls

*Module: `cowboy_sdk.call`*

### `call`

```python theme={"system"}
call(target, method: str, args = None, cycles_limit: int = 100000, *, access_limit: int = None, codec: str = DEFAULT_CODEC)
```

```text theme={"system"}
Synchronously call a method on the target Actor.

Parameters
----------
target : bytes | str | Address
    Target Actor address (20-byte Ethereum address).
method : str
    The method name to call.
args : any, optional
    Arguments to pass to the method, encoded with ``codec``. Under an
    encoded codec, ``None`` sends *no payload* (empty bytes) rather than an
    encoded value, so it is distinct from ``[]`` — which encodes as ``0x80``
    under ``"cbor"`` and as ``[]`` under ``"json"``. A callee that decodes
    its payload sees the difference. Under ``"raw"``, ``args`` must be bytes
    and is sent verbatim (pass ``b""`` for no payload).
cycles_limit : int
    Maximum number of Cycles this call may consume, default 100,000.
access_limit : int, optional
    Positive structural Access allowance for the nested frame. When
    omitted, the host grants floor(63/64 of its remaining authority),
    reserving the balance for the caller to finish.
codec : str
    Codec for both the arguments and the return value — one of
    ``payload_codec.CODECS``, default ``"cbor"``. It must match the
    ``decode=`` the target handler declares: the codec is chosen by the
    caller and is not carried on the wire (the ``ExecuteActor`` payload is
    opaque bytes), so nothing on the callee side can correct a wrong pick.
    A mismatch usually raises — a ``CodecError`` from the callee's decode,
    or a decode failure here on the return — but small scalars can
    misdecode silently, so treat the callee's declared codec as part of its
    signature.

Returns
-------
any
    The return value of the target method, decoded with ``codec``.

Raises
------
ActorNotFoundError
    The host returned ``NotFound``. Typically no actor is deployed at
    ``target``, but an existing system actor also returns ``NotFound`` for a
    resource it cannot find (an unknown subscription id, say), and the two
    are indistinguishable from the host code alone — so this does not prove
    the address is empty. The concrete class is ``_ActorNotFoundCallError``,
    which both ``except ActorCallError`` and ``except ActorNotFoundError``
    catch.
CallDepthExceeded
    An in-process (local/checkpoint-mode) call chain overflowed Python's
    recursion limit. The on-chain 32-frame limit is NOT reported here: the
    host returns ``Forbidden`` for it — indistinguishable from a permission
    denial — so an on-chain depth overflow surfaces as ``ActorCallError``.
ActorCallError
    The callee raised, or the host rejected the call with any ``Forbidden``
    cause (depth limit, permission, re-entrancy).
```

### `ActorCallBuilder`

```python theme={"system"}
class ActorCallBuilder
```

```text theme={"system"}
Fluent call builder providing a more ergonomic call() API.

Usage:
    result = call_builder(target).method("get_price").args(["ETH"]).execute()
```

### `call_builder`

```python theme={"system"}
call_builder(target) -> ActorCallBuilder
```

```text theme={"system"}
Create an ActorCallBuilder instance.
```

## Async messages

*Module: `cowboy_sdk.send`*

### `send`

```python theme={"system"}
send(target, payload = None, *, raw: bool = False, codec: str = None) -> None
```

```text theme={"system"}
Send a one-way async message to the target Actor.

The message is delivered asynchronously; the current transaction does not wait
for the recipient to process the result. Messages cannot be revoked — once send()
is called, whether the message is delivered depends on the Host implementation,
even if the current transaction later fails (cycle exhaustion, state conflict, etc.).

Parameters
----------
target : bytes | str | Address
    Target Actor address (20-byte Ethereum address).
payload : any, optional
    Data to send, encoded with the selected codec.
raw : bool
    If True, payload must be bytes and is sent directly without encoding.
    Used for low-level message passing with already-encoded payloads. This
    is the original spelling of ``codec="raw"`` and stays equivalent to it.
codec : str, optional
    Codec for the payload — one of ``payload_codec.CODECS``, defaulting to
    ``"cbor"``. It must match the ``decode=`` the receiving handler declares;
    as with ``call()``, the choice is the caller's and is not carried on the
    wire. Passing a codec other than ``"raw"`` together with ``raw=True``
    raises ``ValueError``.

Raises
------
AddressError
    target is not a valid 20-byte address.
ValueError
    codec is not a known codec, or contradicts raw=True.
TypeError
    the codec is "raw" (or raw=True) but payload is not bytes.
```

### `send_raw`

```python theme={"system"}
send_raw(target, payload: bytes) -> None
```

```text theme={"system"}
Send a raw bytes message to the target Actor (without CBOR encoding).
Used for SDK internal communication (runner jobs, etc.).
```

## Self-clone (fork)

*Module: `cowboy_sdk.fork`*

### `fork`

```python theme={"system"}
fork(endowment: int = 0) -> Address
```

```text theme={"system"}
Fork the calling Actor — create a byte-exact self-clone.

Parameters
----------
endowment : int, optional
    Native CBY wei to seed the child with. The amount is debited from the
    parent and credited to the child atomically with the fork. ``0``
    creates a zero-balance child.

Returns
-------
Address
    The new child Actor's address (20 bytes). The calling Actor is the
    child's parent.

Raises
------
Exception
    Propagated from the host if the Actor lacks the ``exec.fork``
    entitlement, lacks ``econ.transfer`` for a non-zero endowment, has hit
    its ``max_children`` quota, lacks enough CBY for the endowment, or the
    optional ``on_fork`` hook faulted. A propagated error reverts the whole
    transaction, so the child un-exists and the parent's balance and child
    counter are restored.

Notes
-----
Self-fork only — there is no ``fork(other_actor)``; the primitive always
clones the caller.
```

## Timers (@timer)

*Module: `cowboy_sdk.timer`*

### `timer`

```python theme={"system"}
timer(func = None, *, deferred: bool = True, name = None)
```

```text theme={"system"}
Decorate an actor method as a timer-fire handler.

Forms::

    @timer
    def on_tick(self, payload): ...

    @timer(deferred=False, name="custom_fire")
    def on_tick(self, payload): ...
```

### `timer.schedule`

```python theme={"system"}
timer.schedule(height: int, payload: bytes = b'', *, handler = None, fee_payer: bytes = None, gas_limit: int = None, access_limit: int = None, expires_at: int = None) -> bytes
```

```text theme={"system"}
Schedule a timer that fires back into this actor.

Parameters
----------
height : int
    Block height at which the timer fires (MUST be > current).
payload : bytes
    Opaque bytes. With ``handler=None`` they are delivered raw to the
    default ``handle_timer``. With a ``handler`` set they are wrapped in
    a canonical CBOR routing envelope as a byte string; the named
    handler receives these original bytes.
handler : str | callable | None
    Target fire handler. ``None`` → default ``handle_timer``. A name or
    an ``@timer``-decorated function routes the fire to that method.
fee_payer : str | bytes | Address | None
    Address debited at each fire. Must be this actor's own address;
    ``None`` → actor pays itself. Invokers/deployers cannot be billed
    through this scheduler. A 0x-hex
    str / ``Address`` / 20-byte bytes is normalized to raw 20 bytes; a
    wrong-width address is rejected here. The empty-bytes ``b""`` host sentinel
    (also "actor pays itself") is passed through unchecked.
gas_limit, access_limit, expires_at
    Optional Model-B overrides; forwarded to ``schedule_timer_ex`` when
    any override (including ``fee_payer``) is set, otherwise the protocol
    defaults apply.

Returns the opaque timer id.
```

## Recurring work (@every)

*Module: `cowboy_sdk.every`*

```text theme={"system"}
cowboy_sdk.every — a handler that runs on a schedule

``@every(period)`` makes an actor method a tick that runs every ``period``
seconds of block time, once started::

    from cowboy_sdk import MINUTE, OWNER, Actor, callable_by, every

    class Feed(Actor):
        @every(10 * MINUTE)
        def refresh(self):
            ...

        @callable_by(OWNER)
        def start(self, _payload):
            every.start(self.refresh)   # replaces a running schedule

        @callable_by(OWNER)
        def stop(self, _payload):
            every.stop(self.refresh)

A handler has one schedule: ``every.start`` replaces a running one and
``every.stop`` ends it. A replaced or ended schedule's pending timer still
fires once, and runs nothing. Only the schedule's own timer runs the tick; any
other call, the actor's own included, is refused, so nothing can run it early
or push the schedule back.

The SDK re-arms before the tick runs. A caught Python exception rolls back
the tick's effects while the re-arm commits. Running out of cycles, cells or accesses
rolls back the entire handler, including the re-arm, and ends the schedule.
Events emitted by timer handlers, including ``cowboy.every.failed``, are
currently not recorded on chain. Once ``TIMER_FIRE_FAILED_ACTIVATION_HEIGHT``
is active, an unsuccessful fire is recorded as ``timer.fire_failed``. A tick
whose exception the SDK catches still completes successfully and does not
produce that protocol failure event.

Timers fire by block height, which estimates block time. An early tick re-arms
for the time left without running; a late tick runs once and keeps its phase.
While a ``Pausable`` actor is paused, ticks skip work and keep their schedule.
```

### `every`

```python theme={"system"}
every(period: int)
```

```text theme={"system"}
``@every(period)``, plus ``every.start`` and ``every.stop``.
```

### `every.start`

```python theme={"system"}
every.start(handler) -> None
```

```text theme={"system"}
Start ``handler``'s schedule, replacing a running one: its first
tick is one period from now.
```

### `every.stop`

```python theme={"system"}
every.stop(handler) -> None
```

```text theme={"system"}
End ``handler``'s schedule; one never started is left alone.
```

## Block time

*Module: `cowboy_sdk.pvm_time`*

### `time`

```python theme={"system"}
time() -> float
```

```text theme={"system"}
Return the current block timestamp (seconds, float).
Equivalent to the standard time.time(), but based on block time.
```

### `time_ns`

```python theme={"system"}
time_ns() -> int
```

```text theme={"system"}
Return the current block timestamp (nanoseconds, int).
Equivalent to the standard time.time_ns(), but based on block time.
```

### `time_ms`

```python theme={"system"}
time_ms() -> int
```

```text theme={"system"}
Return the current block timestamp (milliseconds, int).
```

### `monotonic`

```python theme={"system"}
monotonic() -> float
```

```text theme={"system"}
PVM-safe monotonic time.
Maps to the current block time (seconds), for compatibility with threading/time interfaces.
```

### `monotonic_ns`

```python theme={"system"}
monotonic_ns() -> int
```

```text theme={"system"}
PVM-safe monotonic_ns time.
Maps to the current block time (nanoseconds), for compatibility with threading/time interfaces.
```

### `localtime`

```python theme={"system"}
localtime(secs: float | None = None)
```

```text theme={"system"}
Compatible with the time.localtime interface required by logging.Formatter.converter.
Returns a fixed struct_time-style tuple to keep the implementation simple and deterministic.
Log timestamps do not affect consensus, so a constant value is sufficient.
```

### `strftime`

```python theme={"system"}
strftime(fmt: str, t = None) -> str
```

```text theme={"system"}
Minimal deterministic strftime, for the default logging date format.
Ignores the input time and always returns a fixed string to avoid depending on real time/timezone.
```

### `block_height`

```python theme={"system"}
block_height() -> int
```

```text theme={"system"}
Return the current block height.
Equivalent to runtime.get_block_height().
```

### `block_height_obj`

```python theme={"system"}
block_height_obj()
```

```text theme={"system"}
Return the current block height as a BlockHeight type.
```

## Deterministic randomness

*Module: `cowboy_sdk.pvm_random`*

### `seed`

```python theme={"system"}
seed(a = None, version = 2)
```

### `getstate`

```python theme={"system"}
getstate()
```

### `setstate`

```python theme={"system"}
setstate(state)
```

### `getrandbits`

```python theme={"system"}
getrandbits(k)
```

### `random`

```python theme={"system"}
random()
```

### `randbytes`

```python theme={"system"}
randbytes(n)
```

### `randint`

```python theme={"system"}
randint(a, b)
```

### `randrange`

```python theme={"system"}
randrange(start, stop = None, step = 1)
```

### `choice`

```python theme={"system"}
choice(seq)
```

### `shuffle`

```python theme={"system"}
shuffle(x)
```

### `uniform`

```python theme={"system"}
uniform(a, b)
```

### `sample`

```python theme={"system"}
sample(population, k)
```

## System metadata

*Module: `cowboy_sdk.pvm_sys`*

### `get_context`

```python theme={"system"}
get_context() -> dict
```

```text theme={"system"}
Return the full execution context (read-only).
```

### `get_actor_address`

```python theme={"system"}
get_actor_address() -> bytes
```

```text theme={"system"}
Return the current Actor's own address (20-byte Ethereum address).
Obtained via the runtime.
```

### `get_tx_hash`

```python theme={"system"}
get_tx_hash() -> bytes
```

```text theme={"system"}
Return the current transaction hash (32 bytes).
```

### `get_block_height`

```python theme={"system"}
get_block_height() -> int
```

```text theme={"system"}
Return the current block height.
```

### `get_timestamp_ms`

```python theme={"system"}
get_timestamp_ms() -> int
```

```text theme={"system"}
Return the current block timestamp (milliseconds).
```

## Escrow — CIP-20 tokens held for others

*Module: `cowboy_sdk.escrow`*

### `Escrow`

```python theme={"system"}
class Escrow
```

```text theme={"system"}
Deposits of one token, booked by id and payer.

Parameters
----------
name : str
    The escrow's storage namespace. Unique per actor.
refund_after : int
    Seconds of block time after a deposit before its payer may take it
    back, compared with block timestamps. Write it with the package's
    durations: ``2 * DAY``.
token : bytes | str | TokenId, optional
    The CIP-20 token every deposit is made in. Leave it out for a token
    the actor creates at run time, and bind that one with ``set_token``.
```

## Caller limits (@limit)

*Module: `cowboy_sdk.limits`*

### `limit`

```python theme={"system"}
limit(per_caller = None, every = None, pending = None)
```

```text theme={"system"}
Limit each caller's calls to this handler and its open waits.

``per_caller`` calls per ``every`` seconds of block time, counted from
the caller's first call in the period, and at most ``pending`` open waits
at a time. Give ``per_caller`` with ``every``, ``pending``, or both.
```

## Pause and exit (Pausable, @exit)

*Module: `cowboy_sdk.pausable`*

### `Paused`

```python theme={"system"}
class Paused
```

```text theme={"system"}
A call reached an effect while its actor is paused.
```

### `exit`

```python theme={"system"}
exit(func)
```

```text theme={"system"}
Keep a handler callable while its actor is paused.

For the handlers users take their funds out with, such as one that calls
``Escrow.refund``. It grants no permission: pair it with ``@public`` or
``@callable_by``.
```

### `Pausable`

```python theme={"system"}
class Pausable
```

```text theme={"system"}
Base class for an actor its owner can pause.

An actor inherits it in place of ``Actor``: ``class Vault(Pausable)``.
```

## Storage guards

*Module: `cowboy_sdk.guards`*

### `GuardedValue`

```python theme={"system"}
class GuardedValue
```

```text theme={"system"}
Guard wrapper around an on-chain storage key (CIP-6 Chapter 3 storage.guard()).

Brings the storage key under Continuation Guard monitoring.
Lazily loads the current value on .value access; writing to .value writes to storage and updates monitoring.

When the Continuation is suspended, the hash snapshot of the GuardedValue is recorded in the Continuation state.
On resume, if the corresponding storage key's value has changed (modified by another call),
StateConflictError is raised.

This provides "optimistic concurrency control":
- Does not prevent concurrent modifications
- But detects and rejects stale state on resume

Usage:
    @runner.continuation(guard_keys=['balance'])
    async def process(self, msg):
        balance = storage_guard('balance')        # monitor balance key
        initial_balance = balance.value          # read current value
        result = await runner.llm(...)           # suspend
        # If balance was modified during suspension, the following line raises StateConflictError
        new_balance = balance.value - initial_balance
        ...
```

### `storage_guard`

```python theme={"system"}
storage_guard(key) -> GuardedValue
```

```text theme={"system"}
Bring a storage key under Continuation Guard monitoring.

Parameters
----------
key : str | bytes
    The storage key to monitor.

Returns
-------
GuardedValue
    Guard wrapper object; access the storage value via the .value property.

Usage:
    balance_guard = storage_guard('user_balance')
    saved_balance = balance_guard.value
    order = await runner.llm(...)
    # If user_balance was modified during suspension, this will raise StateConflictError
    assert balance_guard.value == saved_balance
```

### `GuardSet`

```python theme={"system"}
class GuardSet
```

```text theme={"system"}
A collection of multiple GuardedValues for protecting a group of related storage keys.

Usage:
    guards = GuardSet('balance', 'allowance', 'nonce')
    with guards:
        # Modify state within this block
        ...
    # guard_keys = guards.keys  # pass to save_cont()
```

## Bounded loops

*Module: `cowboy_sdk.bounded_loop`*

### `bounded_loop`

```python theme={"system"}
bounded_loop(max_iterations: int = 1000)
```

```text theme={"system"}
Decorator that limits the number of loop iterations inside a function.

The decorated function receives an additional `_loop_limit` context;
the function uses that limit via check_iteration() or BoundedRange.

This decorator bounds synchronous loop iteration only. It does not enable
await expressions inside loops; continuation awaits must be direct
top-level statements.

Parameters
----------
max_iterations : int
    Maximum number of iterations (default 1000).

Usage:
    @bounded_loop(max_iterations=100)
    def process_batch(self, items):
        for item in BoundedRange(items):
            ...

    @public
    async def retry_once(self, prompt: str) -> str:
        # An await stays a top-level statement, outside any loop.
        result = await runner.llm(prompt)
        return result.text
```

### `check_iteration`

```python theme={"system"}
check_iteration() -> int
```

```text theme={"system"}
Explicitly check the iteration count in a manual for/while loop.
Calling this function outside a @bounded_loop context has no effect.

Returns the current iteration count (starting from 1).

Usage:
    @bounded_loop(max_iterations=50)
    def process(self, items):
        i = 0
        while i < len(items):
            check_iteration()
            ...
            i += 1
```

### `BoundedRange`

```python theme={"system"}
class BoundedRange
```

```text theme={"system"}
Bounded iteration range for use inside a @bounded_loop context.

Automatically calls check_iteration() on each iteration.

Usage:
    @bounded_loop(max_iterations=100)
    def process(self, items):
        for item in BoundedRange(items):
            ...
        for i in BoundedRange(10):
            ...
```

### `BoundedIterator`

```python theme={"system"}
class BoundedIterator
```

```text theme={"system"}
Bounded wrapper around any iterator for use in for loops.
Equivalent to BoundedRange but with a more explicit name.
```

## Off-chain runner jobs (LLM / HTTP / MCP)

*Module: `cowboy_sdk.runner`*

### `llm`

```python theme={"system"}
llm(prompt: str, /, *, response_model: type[_M], model: str = ..., system_prompt: str = ..., temperature: float = ..., max_tokens: int = ..., timeout_blocks: int = ..., secrets: list[Any] | tuple[Any, ...] = ..., verify: dict[str, Any] = ..., volumes: list[Any] | tuple[Any, ...] = ..., hire: dict[str, Any] = ..., resume_cycles: int = ..., resume_cells: int = ...) -> Awaitable[StructuredResult[_M]]
```

```text theme={"system"}
Structured LLM call (CIP-45): the reply is checked against the
class's schema by the runner and again by the chain. ``res.value`` is an
instance of ``response_model``, or ``None`` with the reason in
``res.failure`` (an ``LlmFailure`` code). ``cowboy build`` derives the
schema.

``res.value`` is typed when ``response_model`` is a top-level name of the
actor module, or an attribute or constant subscript of one (such as
``MODELS["refund"]``): the reply is read in a later transaction, where
only those can be evaluated again. For anything else (a local variable, a
call), ``res.value`` is plain data and ``res.parse(Model)`` builds the
instance.

Arguments (``prompt`` is the only positional one):

- ``prompt`` (str): the user prompt.
- ``response_model`` (a ``CowboyModel`` class): the type of the value the
  call returns.
- ``model`` (str): an exact model name. Only a runner that lists it serves
  the job, and it is never substituted. Leave it out to let the runner
  choose; ``res.model`` reports which model served the call.
- ``system_prompt`` (str): the system prompt.
- ``temperature`` (float, 0 to 2): sampling temperature; the provider's
  default when left out.
- ``max_tokens`` (int, 1 to 32,768): the most tokens the model may
  generate.
- ``timeout_blocks`` (int, 10 to 600, default 30): how long the chain
  waits for a runner before handing the job to another. Raise it for long
  generations.
- ``secrets``, ``verify``, ``volumes``, ``hire``: the job-level options
  every runner job accepts.
- ``resume_cycles``, ``resume_cells`` (int, 102,000 to 22,400,000;
  defaults 1,000,000 and 150,000): the budget of the callback that delivers the
  result, which every runner call accepts. The chain holds that budget's
  maximum fee from the actor before the callback runs, and refuses the
  job (E1622) when the actor, then its entitled owner, cannot fund it.

The runner asks the model once and does not retry; the actor decides
whether to call again. The arguments are checked before any job is
created: unknown or wrongly typed arguments, values outside the limits
above, and a class without a schema raise in the actor.
```

```python theme={"system"}
llm(prompt: str, /, *, response_schema: str, model: str = ..., system_prompt: str = ..., temperature: float = ..., max_tokens: int = ..., timeout_blocks: int = ..., secrets: list[Any] | tuple[Any, ...] = ..., verify: dict[str, Any] = ..., volumes: list[Any] | tuple[Any, ...] = ..., hire: dict[str, Any] = ..., resume_cycles: int = ..., resume_cells: int = ...) -> Awaitable[RunnerResult]
```

```text theme={"system"}
Structured LLM call with JSON Schema text instead of a model class,
for an actor not deployed with ``cowboy build``: ``res.value`` is plain
data, or ``None`` with the reason in ``res.failure``. The schema is a
JsonSchemaV1 (CIP-45) as canonical JSON text, such as CPython's
``json.dumps(schema, sort_keys=True, separators=(",", ":"), ensure_ascii=False)``.
Other arguments as for the ``response_model=`` call.
```

```python theme={"system"}
llm(*args, **kwargs) -> Awaitable[RunnerResult]
```

```text theme={"system"}
Plain LLM call: ``res = await runner.llm(prompt, ...)`` inside an
async actor method; ``res.text`` is the model's answer.

Takes the prompt and the same keyword arguments as a structured call
(``model``, ``system_prompt``, ``temperature``, ``max_tokens``,
``timeout_blocks`` and the job-level options). Pass ``response_model=`` a
``CowboyModel`` class to get a typed, schema-checked value instead.
```

### `http`

```python theme={"system"}
http(*args, **kwargs) -> Awaitable[RunnerResult]
```

```text theme={"system"}
Create an HTTP request task (for use in await expressions inside an async actor method).
```

### `agent`

```python theme={"system"}
agent(model: str, query: str, **kwargs) -> Awaitable[RunnerResult]
```

```text theme={"system"}
Create an Agent task: open-source LLM with tool-calling against mounted
CBFS volumes. The model can call read_file/grep/ls/glob over any volume
listed in the job's volume_attachments and returns a final answer.

Parameters
----------
model : str
    Model identifier ("kimi-k2", "qwen3-coder", "deepseek-v3",
    "self-hosted"). Routed to an OpenAI-compatible endpoint at the
    runner side.
query : str
    The question the model is answering.
system_prompt_path : str, optional
    Path inside one of the mounted volumes pointing at a system prompt.
    Resolved at runtime against JobExecutionContext.mount_paths.
system_prompt_inline : str, optional
    Inline system prompt; used when system_prompt_path is None.
session_id : str, optional
    Stable session id (e.g. sha256(channel:thread)) for conversation
    continuity across calls. None = stateless.
session_dir : str, optional
    Path inside a mounted rw volume where session JSON files are stored
    (e.g. ".sessions" relative to the volume root).
max_iterations : int, default 24
    Maximum agent-loop iterations before truncating with the partial answer.
max_tool_calls_per_iter : int, default 8
    Maximum tool calls executed within a single iteration.
timeout_seconds : int, default 120
    Hard wall-clock timeout for the whole loop.

Usage:
    class Cowbot(Actor):
        @public
        async def slack_event(self, msg: dict[str, str]) -> str:
            answer = await runner.agent(
                "kimi-k2",
                msg["text"],
                system_prompt_path="cowbot/system_prompt.txt",
                session_id=msg["thread_key"],
                session_dir=".sessions",
            )
            self.storage[msg["thread_key"]] = answer.text
            return answer.text
```

### `mcp`

```python theme={"system"}
mcp(server: str, tool: str, *args, **kwargs) -> Awaitable[RunnerResult]
```

```text theme={"system"}
Create an MCP (Model Context Protocol) tool call task.

Parameters
----------
server : str
    MCP server identifier (e.g., "filesystem", "github").
tool : str
    Name of the tool to call.
*args, **kwargs
    Arguments to pass to the tool.

Usage:
    class Analyst(Actor):
        @public
        async def analyze(self, path: str) -> str:
            files = await runner.mcp("filesystem", "read_file", path=path)
            analysis = await runner.llm(f"Analyze {path}: {files.text}")
            self.storage["analysis"] = analysis.text
            return analysis.text
```

### `container`

```python theme={"system"}
container(image: Any, command: Any, resource_tier: Any = ..., min_isolation_tier: Any = ..., volumes: Any = ..., **kwargs) -> Awaitable[Any]
```

```text theme={"system"}
CIP-10: run arbitrary/deterministic code in a sandboxed container on a
runner, with the job's CBFS volumes FUSE-mounted inside at
/mnt/volumes/{name}/. The container runs headless (no network egress in
Phase A); its stdout, exit code, and the selected isolation tier come back
in the result.

Parameters
----------
image : str
    A pinned protocol base image key ("cby-runner-base", "cby-runner-python") or
    a 64-hex registered image digest, which the runner fetches by its
    on-chain CBFS locator, verifies and caches (CIP-10 Part II §15).
command : list[str]
    Entrypoint argv run inside the sandbox, e.g.
    ["python3", "/mnt/volumes/code/main.py"]. User code is passed as data
    (task payload and/or a mounted volume) — never baked into an image.
resource_tier : str, optional
    Registered resource class name, e.g. "small-ephemeral" (default).
min_isolation_tier : str, optional
    Minimum isolation the runner must provide: "standard" (default,
    hardened rootless runc) or "strong" (gVisor/microVM). Public or
    adversarial code must require "strong".
volumes : list, optional
    CIP-9 volumes to attach, each either a name string (read-only) or a
    (name, mode) pair with mode "ro"/"rw"/"wo". Mounted at
    /mnt/volumes/{name}/.

Usage:
    class Writer(Actor):
        @public
        async def save_doc(self, body: str) -> str:
            path = "/mnt/volumes/ws/docs/note.md"
            await runner.container(
                "cby-runner-python",
                ["python3", "-c", f"open({path!r}, 'w').write({body!r})"],
                volumes=[("ws", "rw")],
            )
            self.storage["last_doc"] = path
            return path
```

### `continuation`

```python theme={"system"}
continuation(func: _F, /) -> _F
```

```python theme={"system"}
continuation(*, timeout: int | None = ..., guard_keys: list[str] | None = ...) -> Callable[[_F], _F]
```

```text theme={"system"}
Low-level continuation decorator, for a runner job that needs a deadline
or a state guard.

A method of the actor class, in the actor's own source, that awaits a runner
job needs no decorator: the actor compiler lowers it and carries its locals
across each ``await``. (A module-level function, or code in a pinned library,
still needs the decorator to ``await`` at all.) Decorate such a method only to
set one of these options:

- ``timeout=SECONDS``: the deadline, in seconds of block time (the block
  timestamp) from each suspension, written with the time constants
  (``2 * HOUR``). Past it the
  await raises ``JobFailed(reason="deadline")``. Without it the wait gets
  ``continuation.DEFAULT_TIMEOUT``, 7 weeks.
- ``guard_keys=[...]``: the resume raises ``StateConflictError`` when any
  listed storage key changed while the job was in flight.

Both take constant values. Use it called with options; a bare
``@runner.continuation`` adds nothing to a plain ``async`` method.

A decorated method follows the same rules as a plain one: its arguments and
locals carry across each ``await``. A value that cannot be stored
(a lambda, a parser object) fails where it is read after the ``await``, with
``UncarriedNameError``::

    class Treasury(Actor):
        @public
        @runner.continuation(timeout=2 * HOUR, guard_keys=["balance"])
        async def review(self, target: int) -> str:
            advice = await runner.llm(f"Should we rebalance toward {target}?")
            self.storage["advice"] = {"target": target, "text": advice.text}
            return advice.text
```

### `waits`

```python theme={"system"}
waits() -> list[dict[str, Any]]
```

```text theme={"system"}
The actor's open waits, soonest deadline first: ``cid``, ``handler``,
``caller`` and ``deadline`` (a block timestamp in ms).
```

### `cancel`

```python theme={"system"}
cancel(cid: bytes) -> bool
```

```text theme={"system"}
End the open wait ``cid``: free its slot, emit ``cowboy.wait.failed``
with reason ``"cancelled"``, and drop its job's answer if it comes.
```

### `single_flight`

```python theme={"system"}
single_flight(key: str) -> Callable[[_F], _F]
```

```text theme={"system"}
One open wait per ``payload[key]``: another call with the same value
raises ``Busy`` at once. The key is released however the wait ends.
```

### `extract_text`

```python theme={"system"}
extract_text(result) -> str
```

```text theme={"system"}
Canonical text of a runner result.

For a mapping, the first present of ``content`` / ``text`` / ``response`` /
``data`` / ``answer`` (recursing when that value is itself a mapping);
bytes are UTF-8 decoded; ``None`` is ``""``; anything else is ``str()``.

Matching is on key *presence*, not on a non-null value: a payload whose
first matching key holds ``None`` yields ``""``.
```

### `RunnerResult`

```python theme={"system"}
class RunnerResult
```

```text theme={"system"}
The value an ``await runner.<job>(...)`` yields inside a continuation.

Every reply:

- ``.raw`` / ``.data``: the decoded result exactly as received.
- ``.text``: the canonical text, e.g. a plain ``runner.llm`` answer.
- ``.json()``: ``.text`` parsed as JSON.

The reply to a structured ``runner.llm`` call (CIP-45) adds:

- ``.value``: the structured value (plain data for a ``response_schema=``
  call), or ``None`` for a runner failure.
- ``.failure``: the failure code (an ``LlmFailure`` constant), or ``None``
  for a value.
- ``.model``: the name of the model that served it, or ``None``.
- ``.parse(M)``: the value built as an instance of model class ``M``.

The chain's report that the job itself failed never reaches them: a
guarded ``await`` raises ``JobFailed``, and an unguarded one ends the
method. They raise ``RunnerValidationError`` when the reply is not a valid
structured result, a result shaped like the chain's report included.

Not a ``dict``, even when ``.raw`` is one. It is an ephemeral view: kept in
state across an ``await``, it comes back as its ``.raw``.
```

### `decode_reply`

```python theme={"system"}
decode_reply(fn, raw)
```

```text theme={"system"}
Bind one FSM reply to the value the awaited callable promises.

An off-chain proxy owns its own result frame, so it carries a
``__cowboy_decode__`` that validates and types the reply. Anything without
one keeps the ``RunnerResult`` wrapper, which is what every
``runner.<job>(...)`` await has always yielded.

A present-but-not-callable ``__cowboy_decode__`` is refused rather than
ignored: silently falling back to ``RunnerResult`` would hand the actor an
undecoded reply under a name that promised a typed one, and the mistake
would surface as a confusing attribute error somewhere downstream.
```

### `cowchat_room`

```python theme={"system"}
cowchat_room(model, service_id, room_owner, room_id, message_id, member_key_account, member_key_version = 1, **kwargs)
```

```text theme={"system"}
Create a CowchatRoom task: the assigned runner answers one addressed
Cowchat room message with this actor's member key. The job result is only
a content-free receipt (room id, message id, status); no room text ever
reaches the chain.

Parameters
----------
model : str
    Model identifier routed to the runner's OpenAI-compatible endpoint.
service_id : bytes
    32-byte hosted Cowchat service id.
room_owner : bytes
    20-byte address of the room's owner.
room_id, message_id : str
    The addressed message, as delivered by the room's wake.
member_key_account : str
    0x account owning the CBSS secret
    ``COWCHAT_MEMBER_KEY_V1_<THIS ACTOR ADDRESS HEX>`` (granted to this actor).
member_key_version : int, default 1
    CBSS version of that secret.
```

### `LlmFailure`

```python theme={"system"}
class LlmFailure
```

```text theme={"system"}
The codes a structured ``runner.llm`` failure reports as
``res.failure`` (CIP-45):

- ``PROVIDER_REFUSAL``: the model refused, or the provider filtered the
  output.
- ``INVALID_STRUCTURED_OUTPUT``: the model's reply did not fit the schema.
- ``OUTPUT_TOO_LARGE``: the value exceeded a size limit, or was too costly
  to check against its schema.
- ``MAX_TOKENS_EXCEEDED``: generation stopped at ``max_tokens`` before a
  complete value.
- ``CONTEXT_LENGTH_EXCEEDED``: the prompt exceeded the model's context
  window.
- ``UNSUPPORTED_FEATURE``: the runner cannot serve this structured call:
  the requested ``model`` is not one it serves for structured output, or
  the provider rejected the schema. Change or omit ``model=``, or simplify
  the schema.
- ``PROVIDER_ERROR``: the provider or the runner failed before an outcome.
- ``PROVIDER_TIMEOUT``: the provider did not answer in time.

The runner asks the model once, so a failure is final for that call; the
actor decides whether to call again.
```

### `StructuredResult`

```python theme={"system"}
class StructuredResult
```

```text theme={"system"}
The reply to ``runner.llm(..., response_model=M)``: ``.value`` is an
``M`` instance, or ``None`` with the reason in ``.failure``. Only when the
call names ``M`` so the resume can evaluate it again: a top-level name of
the actor module, or an attribute or constant subscript of one. Otherwise
the reply is a plain ``RunnerResult``, whose ``.value`` is plain data and
``.parse(M)`` builds the instance.
```

### `decode_reply`

```python theme={"system"}
decode_reply(fn, raw)
```

```text theme={"system"}
``decode_reply`` above, for the chain's failure report as well.

Only a decoder marked ``__cowboy_decodes_failure__`` sees the report: an
off-chain proxy's, which raises ``OffchainError("unavailable: <reason>")``
for it. Any other callee raises ``JobFailed`` without calling its decoder,
which expects a result.
```

### `Secret`

```python theme={"system"}
class Secret
```

```text theme={"system"}
One secret's slot in a runner job; see ``secret``.
```

### `secret`

```python theme={"system"}
secret(key: str, prefix: str = '', suffix: str = '', account: Any = None) -> Secret
```

```text theme={"system"}
Mark the one field the secret ``key`` fills: an http job's ``url=``, a
header value or a string inside a dict or list ``body=``, or a string in
an mcp job's tool arguments. The runner sends ``prefix + <the secret> +
suffix`` there and fills nothing else, so a ``${`` anywhere in the job is
sent as written. ``account`` holds the secret: the actor's owner by
default.

    await runner.http(url=SLACK_POST, method="POST",
                      headers={"Authorization": secret("SLACK_BOT_TOKEN", prefix="Bearer ")},
                      body=body)
```

## Continuation state

*Module: `cowboy_sdk.continuation`*

### `Capture`

```python theme={"system"}
class Capture
```

```text theme={"system"}
Explicitly declared persistent context across await points.

Intercepts assignments via __setattr__ to enforce the type whitelist.
All values stored in Capture must be primitive types that are CBOR-serializable.

Forbidden types:
- Functions / lambdas / closures
- Generators / coroutines
- File handles / network connections
- Any custom objects (except nested dict/list/tuple)
```

### `carry`

```python theme={"system"}
carry(ctx: Capture, name: str, value) -> None
```

```text theme={"system"}
Store ``value`` on ``ctx`` under ``name``, for the implicit lowering only.

Tolerant by design. The compiler picks the names that cross an await
syntactically, so it can pick one whose VALUE the capture refuses: a parser
object, a lambda, a module. Raising here would revert the send leg of a
handler that ran to completion before anything was carried, which is a
regression rather than a fix. A refused value leaves a marker instead, and
only a resume leg that actually READS the name fails -- see carried().

An author's own ``ctx.x = ...`` keeps going through Capture.__setattr__ and
keeps raising eagerly: they asked for the slot, so they get the diagnosis at
the point they wrote.
```

### `carried`

```python theme={"system"}
carried(ctx: Capture, name: str, rebuild = None)
```

```text theme={"system"}
Read ``name`` back off ``ctx`` on a resume leg, for the implicit lowering.

Raises UncarriedNameError -- which IS a NameError -- when the send leg could
not store the value, so a name that could not cross behaves like the unbound
local it effectively is, at the point it is read rather than at the point it
was stored.

``rebuild`` puts the author's type back when the capture reduced it. Only a
name bound from an earlier await needs it, and the compiler passes what that
await's callee implies:

* ``RunnerResult`` for a legacy ``runner.<job>`` target. Its
  ``__cbor_reduce__`` keeps only ``.raw``, so without this the resume leg
  would hand back a bare dict or str and ``.text`` would raise
  AttributeError.
* the off-chain proxy function for a name bound from ``await <proxy>(...)``.
  Its generated module carries ``__cowboy_restore__``, which rebuilds the
  record mirror the decoder originally returned.

A proxy generated before record restoration existed has no
``__cowboy_restore__``, and its reduced mapping is returned as it stands --
what the name held before this pass carried it at all.
```

### `new_cid`

```python theme={"system"}
new_cid(self_obj, name: str) -> bytes
```

```text theme={"system"}
Generate a deterministic Continuation ID.

Based on: sha256 of tx_hash + sender +
actor_addr + method_name + the number of waits the actor has started
before, where sender is ``runtime._get_sender()`` of the leg that starts
the continuation: the signer, the calling actor, the actor that sent the
triggering message, or this actor for its own deferred work. The number
tells apart two calls to one handler from one sender in one transaction.
Saving the wait advances it, so ids minted before either wait is saved
repeat; a send leg saves its wait before the next id is minted.
```

## Retry strategies (Retry)

*Module: `cowboy_sdk.retry`*

### `Retry`

```python theme={"system"}
class Retry
```

```text theme={"system"}
Backoff retry configuration.

Backoff sequence (in blocks): [1, 2, 4, 8] (exponential backoff, fixed deterministic sequence)

Usage 1: Inside @runner.continuation (recommended)
    @runner.continuation
    @bounded_loop(max_iterations=5)
    async def fetch_with_retry(self, msg):
        url = msg['url']
        retry = Retry(max_attempts=4)
        for attempt in BoundedRange(4):
            result = await runner.http(url)
            if result is not None:
                break
            if not retry.has_next():
                break
            # next iteration triggers after retry.next_delay() blocks
        return result

Usage 2: As Runner job configuration
    spec = {
        "job_type": "http",
        "retry": Retry(max_attempts=3, on_error=True).to_dict(),
        ...
    }
```

## Parallel runner jobs (JobGroup)

*Module: `cowboy_sdk.jobgroup`*

### `TaskHandle`

```python theme={"system"}
class TaskHandle
```

```text theme={"system"}
Represents a single parallel job in a JobGroup.

The result() method returns the result after the task completes.
Calling result() before the group's wait ends raises an error.
```

### `JobGroup`

```python theme={"system"}
class JobGroup
```

```text theme={"system"}
Container for submitting several Runner jobs in parallel.

Workflow in FSM mode:
1. Enter the `async with JobGroup() as group:` block
2. Call group.create_task(runner.llm(...)) to register jobs (not executed immediately)
3. On exit from the with block (__aexit__), all tasks are submitted in a batch
4. FSM saves the aggregated wait state
5. Each task's result updates the corresponding TaskHandle on arrival
6. Once all tasks are complete, resume execution is triggered

Determinism guarantees:
- create_task assigns indices in call order (0, 1, 2...)
- The same sequence of tasks always produces the same nonce
- Results are ordered by creation order
```

## Off-chain function errors

*Module: `cowboy_sdk.offchain`*

### `OffchainError`

```python theme={"system"}
class OffchainError
```

```text theme={"system"}
An off-chain call did not produce a usable value of its declared type.
```

## TEE-required jobs

*Module: `cowboy_sdk.tee`*

### `tee_call`

```python theme={"system"}
tee_call(job, *, deterministic = False, runners = None, required_tee_type = None, callback = None, max_price = None, tip = None, timeout_blocks = None)
```

```text theme={"system"}
Submit a TEE-required job.

Parameters
----------
job : dict
    The ``job_request_v1`` job body, e.g.
    ``{"type": "llm", "model": "m", "prompt": "p"}``.
deterministic : bool
    ``False`` (default) selects **TeeAttested**: committee = 1, confidential
    output, accepted on a passing CAE with no byte-match (§3.11). ``True``
    selects the reproducible **Deterministic** path: multiple runners whose
    results must be byte-identical.
runners : int | None
    Committee size override (default 1 for TeeAttested, 3 for deterministic).
required_tee_type : str | None
    Restrict to a CPU TEE type: ``"nitro"`` / ``"tdx"`` / ``"sev"``.
callback : dict | None
    Where the verified result is delivered, e.g.
    ``{"actor": "0x..", "handler": "on_chat_result", "correlation_id": id}``.
max_price, tip, timeout_blocks : int | None
    Optional job budget / timeout overrides.
```

## HTTP routes (CIP-15)

*Module: `cowboy_sdk.routes`*

### `Pays`

```python theme={"system"}
class Pays
```

```text theme={"system"}
Who pays the service price for a route (CIP-15 §6.2). Default is ACTOR.

ACTOR  — the caller pays no service price. Required for static (mount) routes.
CALLER — gateway returns 402 with x402 headers (CIP-18) until the caller
         has settled payment; requires a non-empty ``price``.

On-chain gas for gateway-submitted calls is paid by the gateway wallet,
independently of the service-price payer.
```

### `Access`

```python theme={"system"}
class Access
```

```text theme={"system"}
Viewer restriction intersected with the site's owner-controlled policy.
```

### `HttpRouteSpec`

```python theme={"system"}
class HttpRouteSpec
```

```text theme={"system"}
Metadata for a method-target route. Stamped on the handler.
```

### `StaticRouteSpec`

```python theme={"system"}
class StaticRouteSpec
```

```text theme={"system"}
Metadata for a volume-target (static asset) route.

Created via ``mount(path, volume=...)`` and declared at class scope on
the actor class as a ``routes = (mount(...), ...)`` tuple. Static
routes are always actor-paid (CIP-15 §6.2, §6.8).
```

### `route`

```python theme={"system"}
route(verbs, path, *, pays = Pays.ACTOR, price = None, priority = 0, mode = None, access = Access.SITE)
```

```text theme={"system"}
Declare an HTTP route on a handler.

Parameters
----------
verbs : str | sequence of str
    HTTP method(s); use ``"ANY"`` to match every verb (lowest priority
    in resolution).
path : str
    Route path; must start with '/'. Supports ``{name}`` segments and
    ``*`` / ``*name`` wildcards (CIP-15 §6.3).
pays : Pays
    ``Pays.ACTOR`` (default) or ``Pays.CALLER``.
price : str | None
    Required when ``pays=Pays.CALLER``. Free-form pricing string
    (parsed by the gateway and CIP-18 verifier).
priority : int
    Tiebreaker used by the gateway resolver (CIP-15 §6.6).
mode : str | None
    ``"read"``, ``"submit"`` or ``"submit_no_wait"`` to override the
    verb's dispatch (CIP-15 §6.2) — e.g. a POST that only reads.

Multiple route decorators on the same handler accumulate.
```

### `get`

```python theme={"system"}
get(path, **kw)
```

```text theme={"system"}
``@get(path)`` — sugar for ``@route(("GET", "HEAD"), path)``.

GET handlers also serve HEAD by convention; the gateway issues HEAD
by stripping the body from the GET response. Pass ``verbs="GET"``
explicitly via ``@route`` if you need GET-only.
```

### `head`

```python theme={"system"}
head(path, **kw)
```

```text theme={"system"}
``@head(path)`` — sugar for ``@route("HEAD", path)``.
```

### `post`

```python theme={"system"}
post(path, **kw)
```

```text theme={"system"}
``@post(path)`` — sugar for ``@route("POST", path)``.
```

### `put`

```python theme={"system"}
put(path, **kw)
```

```text theme={"system"}
``@put(path)`` — sugar for ``@route("PUT", path)``.
```

### `patch`

```python theme={"system"}
patch(path, **kw)
```

```text theme={"system"}
``@patch(path)`` — sugar for ``@route("PATCH", path)``.
```

### `delete`

```python theme={"system"}
delete(path, **kw)
```

```text theme={"system"}
``@delete(path)`` — sugar for ``@route("DELETE", path)``.
```

### `mount`

```python theme={"system"}
mount(path, *, volume, volume_id = None, strip_prefix = True, volume_path_prefix = '', fallback = None, fallback_status = 200, priority = 0, access = Access.SITE)
```

```text theme={"system"}
Mount a CBFS volume at ``path``. Returns a :class:`StaticRouteSpec`.

Declare the result inside a class-level ``routes`` tuple on the actor::

    class Site(Actor):
        routes = (
            mount("/assets/*", volume="web-assets"),
            mount("/", volume="web-assets", fallback="index.html"),
        )

Static routes are always Pays.ACTOR (CIP-15 §6.2). The gateway serves
the volume bytes directly from CBFS Relay Nodes — the actor handler is
never invoked. ``volume_name`` must be in the actor's
``static_volumes`` entitlement (validated on-chain at write time).

Parameters
----------
path : str
    Mount path; supports trailing ``*`` for prefix mounts.
volume : str
    Name of the CBFS volume (must be in the actor's entitlement).
volume_id : str | bytes | None
    Optional 32-byte volume id for cross-account mounts. When omitted,
    gateway derives the id from the actor owner wallet and ``volume``.
strip_prefix : bool
    If True (default), strip the matched route path before looking the
    request up in the volume manifest.
volume_path_prefix : str
    Optional prefix prepended to the resolved object key.
fallback : str | None
    Optional object key to serve when the resolved path is missing
    (SPA pattern: ``fallback="index.html", fallback_status=200``).
fallback_status : int
    HTTP status to use when serving the fallback. Default 200.
priority : int
    Resolver tiebreaker.
```

## Structured output models (CowboyModel)

*Module: `cowboy_sdk.models`*

### `CowboyModel`

```python theme={"system"}
class CowboyModel
```

```text theme={"system"}
Base class for on-chain structured data models.

Subclasses get dataclass fields, constructor, ``repr`` and equality.
Provides:
- CBOR serialization/deserialization
- JSON Schema generation
- Field type validation (PVM compatibility check)

As a ``runner.llm`` ``response_model`` (CIP-45), ``cowboy build`` gives a
class a schema when each field is ``str``, ``int``, ``float``, ``bool``,
``Literal``, ``list[T]``, ``Optional[T]``, a union (``A | B``) or a model
class, optionally in ``Annotated[T, "text"]``, and it has no ``__init__``
of its own. ``response_schema()`` returns the schema the class sends, or
raises with the reason it has none.

Usage:
    class Order(CowboyModel):
        id: str
        amount: int
        price: float
        buyer: bytes   # 20-byte address
        items: list

    order = Order(id="ord-001", amount=100, price=1.5,
                 buyer=b'\x00'*20, items=["token_a", "token_b"])
    cbor_bytes = order.to_cbor()
    restored = Order.from_cbor(cbor_bytes)
```

## Event hooks (emit / on\_event)

*Module: `cowboy_sdk.events`*

### `on_event`

```python theme={"system"}
on_event(emitter, topic, gas, bid = 0)
```

```text theme={"system"}
Mark a method as a CIP-29 subscription handler.

Sets `method._cip29_subscription = (emitter, topic_bytes, gas, bid)`.
An Actor's init (cowboy_sdk.actor) reads this attribute and calls
runtime.subscribe_event before the init handler runs.

Inputs:
    emitter: emitter actor address (0x-hex str / 20-byte bytes / Address);
        matches runtime.subscribe_event.
    topic: str | bytes, normalized to bytes for the protocol layer
    gas: int >= MIN_SUBSCRIPTION_GAS_PREPAID (50_000) — prepaid fire budget
    bid: int >= 0 — bid for sync-fire slot ordering (default 0)

Raises:
    ValueError if emitter is not a 20-byte address
    TypeError if topic, gas, or bid has the wrong type

Example:
    @on_event(emitter=b"\x01"*20, topic="liquidation_imminent",
              gas=500_000, bid=100_000)
    def on_liquidation(self, payload):
        self.bid_for_collateral(payload)
```

## Stream readers (@on\_stream)

*Module: `cowboy_sdk.on_stream`*

### `stream_cursor`

```python theme={"system"}
stream_cursor(feed)
```

```text theme={"system"}
The last sequence this actor has processed from ``feed`` (0 = none).
```

### `reset_stream_cursor`

```python theme={"system"}
reset_stream_cursor(feed, sequence)
```

```text theme={"system"}
Move this actor's cursor for ``feed`` to ``sequence``.

This is the documented recovery from a gap. It is not a handler: call it
only from a handler guarded by the actor's own access control, since moving
the cursor skips or replays messages.
```

### `on_stream`

```python theme={"system"}
on_stream(feed, *, guard = None, numeric_tag_scales = None, page_limit = 16)
```

```text theme={"system"}
Mark a method that processes ``feed``'s messages through ``read_streams``.

The method receives each message's canonical CBOR envelope bytes. ``guard``
optionally filters messages in the reader; the cursor still advances past
messages it rejects. A guard is evaluated against ``numeric_tag_scales``,
which must match the Feed's declared scales. ``page_limit`` bounds messages read per feed per call.
```

### `read_page`

```python theme={"system"}
read_page(actor, feed, method, guard, scales, page_limit)
```

```text theme={"system"}
Read one page of ``feed`` for ``actor`` and return its outcome row.
```

## Watchtower

*Module: `cowboy_sdk.watchtower`*

### `WatchtowerClient`

```python theme={"system"}
class WatchtowerClient
```

```text theme={"system"}
Typed reads of one Feed.
```

## Deterministic codec (CBOR)

*Module: `cowboy_sdk.codec`*

### `encode`

```python theme={"system"}
encode(value: object, *, _capture_encoding = None) -> bytes
```

```text theme={"system"}
Encode a Python value into a Canonical CBOR byte sequence.
```

### `decode`

```python theme={"system"}
decode(data: bytes, *, _capture_limits = None)
```

```text theme={"system"}
Decode a Canonical CBOR byte sequence into a Python value.
```

## Payload codecs — the handler/caller selector

*Module: `cowboy_sdk.payload_codec`*

### `normalize_codec`

```python theme={"system"}
normalize_codec(fmt)
```

```text theme={"system"}
Validate a caller-side ``codec=`` argument, failing loud on an unknown one.
```

### `decode_payload`

```python theme={"system"}
decode_payload(payload, fmt)
```

```text theme={"system"}
Decode a raw inbound handler payload using the named codec.

``fmt`` is one of ``"raw"``, ``"cbor"`` or ``"json"``:

  * ``"raw"``  — return ``payload`` unchanged (the pre-decode contract:
    handlers receive the exact bytes the host delivered; no type check).
  * ``"cbor"`` — strict canonical CBOR decode, including finite binary64 floats.
  * ``"json"`` — the strict JSON decode ``json_codec`` owns: UTF-8 only, no
    non-finite numbers, no surrogate escapes.

Both encoded codecs require a bytes-like payload; a non-bytes payload or any
decode failure (malformed bytes, over-nesting) raises ``CodecError`` (host
slug E1213).

An empty payload (no argument bytes) decodes to ``None`` for both encoded
codecs — symmetric with the return side, where ``None`` means "no output"
(``codec.decode(b"")`` / ``json_codec.decode(b"")`` would otherwise raise).
``raw`` returns the empty bytes unchanged.
```

### `encode_args`

```python theme={"system"}
encode_args(value, fmt)
```

```text theme={"system"}
Encode caller arguments into the payload bytes the handler receives.

Mirror of ``decode_payload``: for a handler declared ``decode=fmt``,
``decode_payload(encode_args(v, fmt), fmt)`` is ``v``.

  * ``"raw"``  — ``value`` must be ``bytes``/``bytearray`` and is sent
    verbatim; anything else (``None`` included) raises ``TypeError``. The
    accepted set is the one ``send(raw=True)`` has always taken, whose hatch
    this generalizes.
  * ``"cbor"`` / ``"json"`` — ``None`` sends *no payload* (empty bytes),
    which a callee can tell apart from an encoded value; everything else is
    encoded, canonically for ``cbor`` and under the strict profile for
    ``json``.

A ``cbor`` encode failure propagates as ``codec.encode`` raised it (a
``CodecError``, or a stdlib error). It is not re-classified as ``_encode_value``
re-classifies a handler return: this runs in the caller's own frame, where
the exception is the caller's to catch, not a fault the host has to slug.
``json`` still raises ``CodecError`` — its strict profile classifies its own
refusals, and a ``CowboyError`` is no harder for a caller to catch.
```

### `decode_return`

```python theme={"system"}
decode_return(result, fmt)
```

```text theme={"system"}
Decode a handler's return, using the codec the call was made with.

Mirror of ``_encode_return``. ``None`` — the host's "no output" — stays
``None`` under every codec; ``"cbor"`` and ``"json"`` run their decoder;
``"raw"`` hands back exactly what the host returned, the same untouched
contract ``decode_payload`` gives a raw handler inbound. Not
``bytes(result)``: that would turn a local harness's non-bytes reply into
that many zero bytes.

An encoded handler that returns bare ``bytes`` passes them through
unencoded (``_encode_return``'s one return rule), so they must already be
valid in the call's codec or decoding them raises here.
```

## Strict JSON codec

*Module: `cowboy_sdk.json_codec`*

### `encode`

```python theme={"system"}
encode(value) -> bytes
```

```text theme={"system"}
Serialize ``value`` as strict canonical JSON, UTF-8 encoded.

Raises ``CodecError`` (E1213) for a value JSON cannot represent: a
non-finite float, an unserializable type, or nesting deep enough to
overflow the recursion limit. Classifying them together matches
``payload_codec._encode_value``, so a serialization fault reaches the host
as a codec fault rather than ``HostError::Internal``.
```

### `decode`

```python theme={"system"}
decode(data: bytes)
```

```text theme={"system"}
Parse strict JSON bytes into a native value — the mirror of ``encode``.

The invariant is on the *value*, not on the bytes: whatever this returns,
``encode`` can serialize again, so a handler may pass its payload straight
back out. Input spelling is deliberately unconstrained — ordinary RFC 8259
that no encoder here would emit (whitespace, unsorted keys, duplicate keys
with last-wins, literal non-ASCII) is accepted and normalized on the way
back out. Demanding canonical input instead would reject what every stock
JSON encoder produces, which is the interop this codec exists for.

Refused is what would break that invariant:

  * UTF-8 only. ``json.loads`` on raw bytes sniffs for a UTF-16/32 BOM and
    would reinterpret the payload under an encoding nothing here emits.
  * no non-finite floats, spelled either as one of the bare tokens or
    through number syntax that overflows.
  * no surrogates (``_reject_surrogates``).

Raises ``CodecError`` (E1213) for each of those and for malformed JSON,
matching ``encode`` and ``codec.decode``.
```

## Errors

*Module: `cowboy_sdk.errors`*

### `CowboyError`

```python theme={"system"}
class CowboyError
```

```text theme={"system"}
Base class for all cowboy_sdk exceptions.
```

### `DeterminismError`

```python theme={"system"}
class DeterminismError
```

```text theme={"system"}
An operation was used that would break cross-node determinism.
```

### `StateConflictError`

```python theme={"system"}
class StateConflictError
```

```text theme={"system"}
A guard-monitored storage key changed while the Continuation was suspended.
```

### `LoopBoundExceeded`

```python theme={"system"}
class LoopBoundExceeded
```

```text theme={"system"}
A loop decorated with @bounded_loop exceeded the maximum iteration count.
```

### `CaptureTypeError`

```python theme={"system"}
class CaptureTypeError
```

```text theme={"system"}
A value carried across an await is not serializable.
```

### `UncarriedNameError`

```python theme={"system"}
class UncarriedNameError
```

```text theme={"system"}
A local the implicit continuation could not carry across an await.
```

### `ContinuationLimitError`

```python theme={"system"}
class ContinuationLimitError
```

```text theme={"system"}
A Continuation constraint was violated (too many awaits, nested await, etc.).
```

### `ContinuationNotFoundError`

```python theme={"system"}
class ContinuationNotFoundError
```

```text theme={"system"}
The requested Continuation state does not exist.
```

### `ContinuationCorruptedError`

```python theme={"system"}
class ContinuationCorruptedError
```

```text theme={"system"}
Continuation state data could not be decoded or failed integrity verification.
```

### `ContinuationSizeLimitError`

```python theme={"system"}
class ContinuationSizeLimitError
```

```text theme={"system"}
A single Continuation exceeded the 64 KiB limit.
```

### `ContinuationCountLimitError`

```python theme={"system"}
class ContinuationCountLimitError
```

```text theme={"system"}
The Actor's active Continuation count exceeded the limit of 100.
```

### `CycleLimitExceeded`

```python theme={"system"}
class CycleLimitExceeded
```

```text theme={"system"}
Execution exceeded the allocated Cycle (compute) quota.
```

### `CallDepthExceeded`

```python theme={"system"}
class CallDepthExceeded
```

```text theme={"system"}
A local (in-process) call chain overflowed Python's recursion limit.

The on-chain 32-frame cap does not arrive here. The host rejects it with
``Forbidden``, whose wire form is identical to a permission denial and a
re-entrancy reject, so ``call()`` cannot tell the three apart and surfaces
all of them as :class:`ActorCallError`. ``HOST_ERROR_CODE`` records the code
this failure belongs to, not one that maps back to this class — several
classes here share code 5.
```

### `RunnerTimeoutError`

```python theme={"system"}
class RunnerTimeoutError
```

```text theme={"system"}
The Continuation's timeout_blocks has expired.
```

### `RunnerValidationError`

```python theme={"system"}
class RunnerValidationError
```

```text theme={"system"}
The result returned by the Runner did not pass the validation checker.
```

### `DeterministicValidationError`

```python theme={"system"}
class DeterministicValidationError
```

```text theme={"system"}
Multiple Runners' execution results could not reach consensus.
```

### `CodecError`

```python theme={"system"}
class CodecError
```

```text theme={"system"}
Payload encoding or decoding failed.
```

### `AddressError`

```python theme={"system"}
class AddressError
```

```text theme={"system"}
Address format error (not a 20-byte Ethereum address).
```

### `TokenIdError`

```python theme={"system"}
class TokenIdError
```

```text theme={"system"}
Token id format error (not a 32-byte CIP-20 token id).
```

### `ActorNotFoundError`

```python theme={"system"}
class ActorNotFoundError
```

```text theme={"system"}
The target Actor address does not exist.
```

### `ActorCallError`

```python theme={"system"}
class ActorCallError
```

```text theme={"system"}
Actor synchronous call failed (callee raised an exception).
```

### `PurityViolationError`

```python theme={"system"}
class PurityViolationError
```

```text theme={"system"}
Async side effect called inside a @pure handler.
```

### `PermissionDeniedError`

```python theme={"system"}
class PermissionDeniedError
```

```text theme={"system"}
A cross-actor call targeted a handler the caller is not authorized to invoke.
```

### `JobFailed`

```python theme={"system"}
class JobFailed
```

```text theme={"system"}
The chain reported that the awaited job terminated without a result.

The chain gave up on the job (no runner was available, or every attempt
timed out) and called its callback with a ``JobFailure`` report under the
reply's ``failure`` key. The SDK recognizes it by that key, never by the
shape of a runner's result. An await inside ``try: ... except JobFailed:``
raises it there. Any other await ends the wait instead, as any error after
an await does: the wait is freed and emits
``cowboy.wait.failed`` (below), and the resume returns ``None``. A guarded
off-chain call raises ``OffchainError("unavailable: <reason>")``.
``reason`` is one of ``retries_exhausted``,
``no_replacement_available``, ``pending_key_delivery_timeout`` and
``private_attachment_timeout``; ``job_id`` is the failed job's 0x-prefixed
hex id and ``attempts`` the re-selection rounds it consumed. The SDK binds
it with reason ``deadline`` to a wait past its deadline, and ``paused`` to
one that resumes while its ``Pausable`` actor is paused.
```

### `Busy`

```python theme={"system"}
class Busy
```

```text theme={"system"}
Another open wait holds this call's ``@single_flight`` key.

The call is refused at once; it does not queue. The key is free again
once that wait ends: its answer, a failure, its deadline or a cancel.
```

### `LimitReached`

```python theme={"system"}
class LimitReached
```

```text theme={"system"}
A call is past one of its handler's ``@limit`` limits.

``limit`` names the limit (``"per_caller=20, every=3600"`` or
``"pending=2"``), and ``next_allowed_ms`` is the block time, in ms, from
which the next call is allowed: when the period ends, or by when one of
the caller's open waits ends at the latest. ``None`` when no deadline
bounds it.
```

## Test doubles (SimulatedChain, CallMock)

*Module: `cowboy_sdk.testing`*

### `CallMock`

```python theme={"system"}
class CallMock
```

```text theme={"system"}
Matcher-based mock for ``set_call_handler`` (see module docstring).
```

### `SimulatedChain`

```python theme={"system"}
class SimulatedChain
```

```text theme={"system"}
In-memory single-actor test harness over ``cowboy_sdk.mock_host``.

Drives one actor through a simulated chain:

    chain = SimulatedChain(MyActor())
    chain.call("init")
    chain.call("increment")
    chain.advance_block(5)            # fires any due timers
    chain.assert_state(b"count", ...) # snapshot assertions
    assert chain.check_determinism(scenario)
    chain.call("answer", b"q")        # a continuation sends a runner job
    chain.reply(llm_value(decision))  # the runner's reply resumes it

The actor's handlers are plain methods/functions invoked by name (or passed
directly). State, timers and the block clock live in the mock host.
```

### `llm_value`

```python theme={"system"}
llm_value(value, *, model = 'stub-model')
```

```text theme={"system"}
The result of a structured ``runner.llm`` call that returned ``value``,
a ``CowboyModel`` instance or a plain dict, served by ``model``.

    chain.call("answer", b"Where is my order?")
    chain.reply(llm_value(Decision(reasoning="Tracked", answer="Shipped",
                                   confidence="high", order_id=None)))
```

### `llm_failure`

```python theme={"system"}
llm_failure(code, *, model = None)
```

```text theme={"system"}
The result of a structured ``runner.llm`` call that failed with
``code``, one of the eight ``runner.LlmFailure`` codes. ``model`` names the
model that failed, or is ``None`` when none was reached.

    chain.call("answer", b"Where is my order?")
    chain.reply(llm_failure(LlmFailure.PROVIDER_REFUSAL))
```

## Mock host for tests

*Module: `cowboy_sdk.mock_host`*

### `HostError`

```python theme={"system"}
class HostError
```

```text theme={"system"}
Stand-in for the bridge's ``pvm_host.HostError``.

The SDK trusts this type — and only this type — when reading the structured
``code``/``name`` off a failed host call, so a local harness simulating a
host failure must raise it rather than a bare exception carrying a ``code``
attribute. Real bridge instances take the
message positionally and get ``code``/``name`` set on them afterwards.
```

### `reset`

```python theme={"system"}
reset()
```

```text theme={"system"}
Reset all state to ensure test isolation.
```

### `set_block_height`

```python theme={"system"}
set_block_height(h: int)
```

### `set_context`

```python theme={"system"}
set_context(**kwargs)
```

### `set_call_handler`

```python theme={"system"}
set_call_handler(fn)
```

```text theme={"system"}
Set call_actor response: fn(target, method, args, cycles_limit, access_limit).
```

### `context`

```python theme={"system"}
context() -> dict
```

### `seed_actor_owner`

```python theme={"system"}
seed_actor_owner(owner: bytes, actor: bytes | None = None)
```

```text theme={"system"}
Test-only protocol fixture; never populated from application storage.
```

### `actor_owner`

```python theme={"system"}
actor_owner() -> bytes
```

### `seed_hire`

```python theme={"system"}
seed_hire(hire_id: int, hirer: bytes, actor: bytes | None = None, active: bool = True, owned_actors_allowed: bool = True)
```

```text theme={"system"}
Test-only Trading Post fixture: an Active (or not) hire of ``actor``.
``owned_actors_allowed`` mirrors the hire's flag, on by default.
```

### `seed_allowed_caller`

```python theme={"system"}
seed_allowed_caller(hire_id: int, caller: bytes, max_uses: int = 0)
```

```text theme={"system"}
Test-only fixture: the hirer's allowed-caller grant; 0 = unlimited.
```

### `is_allowed_caller`

```python theme={"system"}
is_allowed_caller(hire_id: int, caller: bytes) -> bool
```

```text theme={"system"}
Mirror of the host rule: the hirer, and actors it owns while the hire
allows them, answer True without a grant or a use; any other caller
spends one use of its grant.
```

### `get_state`

```python theme={"system"}
get_state(key: bytes)
```

### `set_state`

```python theme={"system"}
set_state(key: bytes, value: bytes)
```

```text theme={"system"}
Mirrors the real host bridge: rejects reserved keys.

SDK internals must use ``set_reserved_state`` for
``__INITIALIZED__``. This guard exists in the mock host so unit tests
exercise the same boundary the production bridge enforces.
```

### `delete_state`

```python theme={"system"}
delete_state(key: bytes)
```

### `set_reserved_state`

```python theme={"system"}
set_reserved_state(key: bytes, value: bytes)
```

```text theme={"system"}
SDK-only escape hatch — accepts ONLY reserved keys.
```

### `delete_reserved_state`

```python theme={"system"}
delete_reserved_state(key: bytes)
```

```text theme={"system"}
Counterpart to ``set_reserved_state``.
```

### `scan_state_prefix`

```python theme={"system"}
scan_state_prefix(prefix: bytes, limit: int = 100)
```

```text theme={"system"}
Mock implementation of Model C's `state_scan_prefix` syscall. Sorts
the in-memory _storage dict and returns verbatim-key entries whose key
starts with `prefix`, up to `limit`. Mimics the real host's behavior
of skipping hashed-mode (>64-byte) keys so mock-based unit tests match
the on-chain semantics.
```

### `set_budget_left`

```python theme={"system"}
set_budget_left(wei)
```

```text theme={"system"}
Set what ``budget_left()`` answers: wei, or None for no budget.
```

### `budget_left`

```python theme={"system"}
budget_left()
```

### `current_block`

```python theme={"system"}
current_block() -> int
```

### `call_actor`

```python theme={"system"}
call_actor(target: bytes, method: str, payload: bytes, cycles_limit: int, access_limit: int = 0) -> bytes
```

```text theme={"system"}
Simulate an Actor call. Returns empty bytes by default; customizable via set_call_handler().
```

### `fork_actor`

```python theme={"system"}
fork_actor(endowment: int = 0) -> bytes
```

```text theme={"system"}
Simulate the fork() self-clone primitive. Records the call to _fork_log
and returns a deterministic dummy 20-byte child address (incrementing per
fork) so local-dev code can exercise the fork path without a real host.
```

### `get_fork_log`

```python theme={"system"}
get_fork_log() -> list
```

```text theme={"system"}
Return the log of fork_actor calls.
```

### `transfer_balance`

```python theme={"system"}
transfer_balance(to: bytes, amount: int) -> None
```

```text theme={"system"}
Simulate native CBY transfer between actors.
```

### `get_transfer_log`

```python theme={"system"}
get_transfer_log() -> list
```

```text theme={"system"}
Return the log of transfer_balance calls.
```

### `upgrade_self`

```python theme={"system"}
upgrade_self(new_code: bytes, new_manifest: bytes = None, routes: bytes = None, route_sponsorship: bytes = None) -> None
```

```text theme={"system"}
Simulate an actor self-upgrade. Records to _upgrade_log for test assertions.
```

### `get_upgrade_log`

```python theme={"system"}
get_upgrade_log() -> list
```

```text theme={"system"}
Return the log of upgrade_self calls.
```

### `send_message`

```python theme={"system"}
send_message(target: bytes, payload: bytes) -> None
```

```text theme={"system"}
Simulate async message send. Records to _send_log for test assertions.
```

### `get_send_log`

```python theme={"system"}
get_send_log() -> list
```

```text theme={"system"}
Return the log of sent messages.
```

### `keccak256`

```python theme={"system"}
keccak256(data: bytes) -> bytes
```

```text theme={"system"}
Real Keccak-256, matching the production host (see `cowboy_sdk._keccak`).
```

### `schedule_timer`

```python theme={"system"}
schedule_timer(height: int, payload: bytes) -> bytes
```

```text theme={"system"}
Mock schedule with protocol defaults (fee_payer = ZERO, no-override).
```

### `schedule_timer_ex`

```python theme={"system"}
schedule_timer_ex(height: int, payload: bytes, fee_payer: bytes = None, gas_limit: int = None, access_limit: int = None, expires_at: int = None) -> bytes
```

```text theme={"system"}
Mock extended schedule. Returns a deterministic opaque timer id.
```

### `extend_timer`

```python theme={"system"}
extend_timer(timer_id: bytes, new_expires_at: int) -> None
```

```text theme={"system"}
Mock TTL extension. Missing timer is a silent no-op (matches chain semantics).
```

### `cancel_timer`

```python theme={"system"}
cancel_timer(timer_id: bytes) -> None
```

```text theme={"system"}
Mock cancel. Missing timer is a silent no-op.
```

### `get_timers`

```python theme={"system"}
get_timers() -> dict
```

```text theme={"system"}
Test helper: return the current mock timer table.
```

### `subscribe_event`

```python theme={"system"}
subscribe_event(emitter: bytes, topic: bytes, handler: str, gas_prepaid: int, bid: int) -> bytes
```

### `unsubscribe_event`

```python theme={"system"}
unsubscribe_event(sub_id: bytes) -> int
```

### `force_unsubscribe_event`

```python theme={"system"}
force_unsubscribe_event(sub_id: bytes) -> None
```

### `update_bid`

```python theme={"system"}
update_bid(sub_id: bytes, additional_bid: int) -> int
```

### `topup_subscription`

```python theme={"system"}
topup_subscription(sub_id: bytes, additional_gas: int) -> int
```

### `get_subs`

```python theme={"system"}
get_subs() -> dict
```

### `offchain_image_initialize`

```python theme={"system"}
offchain_image_initialize(image)
```

### `offchain_image_update`

```python theme={"system"}
offchain_image_update(expected, image)
```

### `verify_signature`

```python theme={"system"}
verify_signature(algorithm, public_key, message, signature)
```

### `savepoint_effects`

```python theme={"system"}
savepoint_effects() -> int
```

### `rollback_effects`

```python theme={"system"}
rollback_effects(mark: int) -> None
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.