# ChainReader

> Reader for Algorand blockchain state via an Indexer client.

```python
from ai_economy_sdk import ChainReader
```

```python
class ChainReader(
    indexer_url: str = 'http://localhost:8980',
    indexer_token: str = '',
    indexer: Any = None,
)
```

Reader for Algorand blockchain state via an Indexer client.

Provides high-level queries for account payment history, recurring subscription
asset holdings, and time-bounded vendor passes.

## Constructor parameters

- `indexer_url` (`str`, default `'http://localhost:8980'`):
Base URL of the Algorand Indexer REST API.

- `indexer_token` (`str`, default `''`):
Authentication token header for the indexer API.

- `indexer` (`Any`, default `None`):
Pre-configured `algosdk.v2client.indexer.IndexerClient` instance. If provided,
overrides `indexer_url` and `indexer_token`.

## Attributes

- `indexer` (`algosdk.v2client.indexer.IndexerClient`):
Underlying indexer client used for network queries.

## Examples

```python
>>> from ai_economy_sdk.chain import ChainReader, PASS_NOTE_PREFIX
>>> PASS_NOTE_PREFIX
'x402-pass:'
>>> reader = ChainReader("http://localhost:8980")
>>> reader.indexer is not None
True
```

## Methods

### `for_network`

```python
@classmethod
def for_network(
    network: str,
    indexer_url: str | None = None,
    indexer_token: str | None = None,
) -> ChainReader
```

Construct a ChainReader configured for a specific Algorand network.

Resolves public indexer endpoints for `"mainnet"` and `"testnet"` (AlgoNode),
or localhost for `"localnet"`. Custom URLs/tokens override network defaults.

**Parameters**

- `network` (`str`, required):
Network name, alias, or CAIP-2 identifier (e.g., `"mainnet"`, `"testnet"`, `"localnet"`).

- `indexer_url` (`str | None`, default `None`):
Custom indexer endpoint URL. If None, uses default endpoint for the network.

- `indexer_token` (`str | None`, default `None`):
Custom indexer token. If None, uses default token for the network.

**Returns**

- `returns` (`ChainReader`):
Instantiated reader pointing to the appropriate indexer.

**Example**

```python
>>> from ai_economy_sdk.chain import ChainReader
>>> reader = ChainReader.for_network("mainnet")
>>> reader.indexer is not None
True
```

### `past_usage`

```python
def past_usage(
    address: str,
    pay_to: str,
    asset_id: int | str,
    days: int = 30,
    now: float | int | None = None,
) -> int
```

Calculate total amount paid by an address to a recipient within a time window.

Searches indexed transactions where `address` was the sender and `pay_to`
was the receiver for payment (ALGO) or asset transfer (ASA) transactions.

**Notes**

Paginates through all matching indexer transactions and tallies successful
payments matching the target recipient and asset ID.

**Parameters**

- `address` (`str`, required):
Algorand address of the sender/buyer.

- `pay_to` (`str`, required):
Algorand address of the service recipient/vendor.

- `asset_id` (`int | str`, required):
Asset ID: 0 for native ALGO (microALGO), or positive ASA ID.

- `days` (`int`, default `30`):
Number of days prior to `now` to inspect.

- `now` (`float | int | None`, default `None`):
Current unix timestamp. If None, uses system time (`time.time()`).

**Returns**

- `returns` (`int`):
Sum of transaction amounts transferred within the window, in base units
(microALGO for ALGO, or base atomic units for ASAs). Returns 0 on query errors.

**Example**

```python
# Needs LocalNet Indexer:
# total_microalgos = reader.past_usage(buyer_addr, vendor_addr, 0, days=30)
```

### `has_active_subscription`

```python
def has_active_subscription(
    address: str,
    asset_id: int | str | None,
    max_age_days: float = 30.0,
    now: float | int | None = None,
    issuer: str | None = None,
) -> bool
```

Check whether an account holds a subscription asset received within a time window.

Verifies that `address` currently holds a non-zero balance of `asset_id`,
and that the most recent incoming transfer of that asset occurred within the last
`max_age_days` days.

**Parameters**

- `address` (`str`, required):
Algorand address of the subscriber.

- `asset_id` (`int | str | None`, required):
ASA ID of the subscription token. Returns False if 0 or None.

- `max_age_days` (`float`, default `30.0`):
Maximum age in days of the latest incoming asset transfer.

- `now` (`float | int | None`, default `None`):
Reference unix timestamp. Defaults to `time.time()`.

- `issuer` (`str | None`, default `None`):
If provided, only transfers originating from this sender address count
as valid subscription issuances.

**Returns**

- `returns` (`bool`):
True if the subscriber currently holds the asset and the latest transfer
is within `max_age_days`, False otherwise.

**Example**

```python
>>> from ai_economy_sdk.chain import ChainReader
>>> reader = ChainReader("http://localhost:8980")
>>> reader.has_active_subscription("", None)
False
```

### `active_passes`

```python
def active_passes(
    address: str,
    pay_to: str,
    asset_id: int | str,
    scopes: dict[str, int],
    days: float = 30.0,
    now: float | int | None = None,
) -> list[dict[str, Any]]
```

Find valid passes purchased by an address from a vendor.

A pass is an on-chain payment from the buyer to the vendor's `pay_to` address
with note prefix `x402-pass:<scope>` whose transfer amount is at least the
price specified for that scope in `scopes`.

**Notes**

If multiple payments exist for the same scope, the newest payment within
the validity window takes precedence.

**Parameters**

- `address` (`str`, required):
Algorand address of the pass holder (buyer).

- `pay_to` (`str`, required):
Vendor receiver address.

- `asset_id` (`int | str`, required):
Asset ID used to purchase the pass (0 for ALGO, or ASA ID).

- `scopes` (`dict[str, int]`, required):
Mapping of pass scope names (e.g., `{"listing:tts-1": 50000}`) to their
minimum purchase prices.

- `days` (`float`, default `30.0`):
Pass validity window in days from the round time of payment.

- `now` (`float | int | None`, default `None`):
Reference unix timestamp. Defaults to `time.time()`.

**Returns**

- `returns` (`list of dict[str, Any]`):
Sorted list of active pass records ordered by round time. Each dictionary contains:
`"scope"` (str), `"txid"` (str), `"amount"` (int),
`"round_time"` (int), and `"expires"` (float).

**Example**

```python
>>> from ai_economy_sdk.chain import ChainReader
>>> reader = ChainReader("http://localhost:8980")
>>> reader.active_passes("", "", 0, {})
[]
```

### `has_pass`

```python
def has_pass(
    address: str,
    pay_to: str,
    asset_id: int | str,
    scopes: dict[str, int],
    days: float = 30.0,
    now: float | int | None = None,
) -> bool
```

Check whether an account holds at least one active pass for the specified vendor.

**Parameters**

- `address` (`str`, required):
Algorand address of the buyer/caller.

- `pay_to` (`str`, required):
Vendor receiver address.

- `asset_id` (`int | str`, required):
Asset ID used for pass payment (0 for ALGO, or positive ASA ID).

- `scopes` (`dict[str, int]`, required):
Mapping of eligible pass scope names to minimum prices.

- `days` (`float`, default `30.0`):
Pass validity duration in days.

- `now` (`float | int | None`, default `None`):
Reference unix timestamp. Defaults to `time.time()`.

**Returns**

- `returns` (`bool`):
True if any active pass matches the criteria, False otherwise.

**Example**

```python
>>> from ai_economy_sdk.chain import ChainReader
>>> reader = ChainReader("http://localhost:8980")
>>> reader.has_pass("", "", 0, {})
False
```

## See also

- `for_network`: Factory constructor resolving indexer endpoints by network name.

Source: [ai_economy_sdk/chain.py](https://github.com/x402-avm/ai-economy-sdk/blob/main/ai_economy_sdk/chain.py#L34)

Source: https://x402-avm.github.io/reference/python/ai-economy-sdk/chain-reader
