# PaymentGate

> Payment gate protecting FastMCP server tools with x402 on Algorand.

```python
from ai_economy_sdk import PaymentGate
```

```python
class PaymentGate(
    signer: ServerSigner,
    network: str,
    pay_to: str,
    asset_id: int | str = 0,
    prices: Prices | None = None,
    default_price: int = 0,
    chain: ChainLookup | None = None,
    subscription_asset_id: int | str | None = None,
    subscription_max_age_days: float = 30.0,
    bulk_threshold: int | None = None,
    bulk_discount: float = 0.5,
    bulk_days: int = 30,
    replay_cache_size: int = 5000,
    min_fee_per_txn: int = 1000,
    allow_loss: bool = False,
    replay_db: str | None = None,
    subscription_issuer: str | None = None,
    pass_scopes: dict[str, int] | None = None,
    pass_days: float = 30.0,
)
```

Payment gate protecting FastMCP server tools with x402 on Algorand.

Integrates payment challenges, verification, and settlement into FastMCP's HTTP
transports (Streamable HTTP and legacy SSE). Supports fixed, dynamic,
subscription-based, pass-based, and tiered bulk pricing.

**Notes**

When a tool is invoked, the gate checks identity proofs to identify the caller.
If the caller holds an unexpired pass or active subscription, price is 0.
The fee payer pays the 2,000 microALGO group fee in ALGO whatever asset the price is in.
Settles on chain only if tool succeeds.

## Constructor parameters

- `signer` (`ServerSigner`, required):
Signer (e.g., `DefaultAvmSigner`) providing merchant keys and node
connection to sponsor transaction fees as fee payer.

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

- `pay_to` (`str`, required):
Algorand address where service payments are collected.

- `asset_id` (`int | str`, default `0`):
Asset ID accepted for payments (0 for native ALGO in microALGO, or ASA ID).

- `prices` (`Prices | None`, default `None`):
Tool pricing mapping or callable with signature `(tool, args, sender) -> int`.

- `default_price` (`int`, default `0`):
Fallback price in base units for tools not explicitly listed in `prices`.

- `chain` (`ChainLookup | None`, default `None`):
`ChainReader` (or compatible object) for subscriptions, past usage, and passes.

- `subscription_asset_id` (`int | str | None`, default `None`):
ASA ID of the subscription token. If held by caller, tools are free.

- `subscription_max_age_days` (`float`, default `30.0`):
Maximum age in days of latest subscription token transfer.

- `bulk_threshold` (`int | None`, default `None`):
Cumulative spend threshold triggering the bulk discount rate.

- `bulk_discount` (`float`, default `0.5`):
Multiplier applied to base price when bulk threshold is exceeded.

- `bulk_days` (`int`, default `30`):
Window in days for computing cumulative past spend.

- `replay_cache_size` (`int`, default `5000`):
Maximum number of entries maintained in memory.

- `min_fee_per_txn` (`int`, default `1000`):
Network minimum transaction fee in microALGO.

- `allow_loss` (`bool`, default `False`):
If False, rejects or clamps ALGO prices in (0, 2000] that fail to cover
the 2-transaction fee-payer cost.

- `replay_db` (`str | None`, default `None`):
Path to SQLite database file for multi-process replay protection.

- `subscription_issuer` (`str | None`, default `None`):
Restricts valid subscription tokens to those received from this address.

- `pass_scopes` (`dict[str, int] | None`, default `None`):
Mapping of eligible pass scope names to minimum prices.

- `pass_days` (`float`, default `30.0`):
Validity window in days for vendor passes.

## Raises

- `ConfigurationError`: (a `ValueError`) If `allow_loss=False`, `asset_id=0`, and any configured price is in the loss-making range `(0, 2 * min_fee_per_txn]`; or if `subscription_issuer` is set but `chain.has_active_subscription` has no `issuer` parameter.

## Examples

```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> from ai_economy_sdk.gate import PaymentGate
>>> sk, addr = account.generate_account()
>>> signer = DefaultAvmSigner(sk)
>>> gate = PaymentGate(signer=signer, network="mainnet", pay_to=addr, asset_id=0, prices={"echo": 5000})
>>> gate.price_for("echo")
5000
>>> gate.price_for("unknown")
0
>>> gate.close()
```

## Methods

### `price_for`

```python
def price_for(
    tool: str,
    args: ToolArguments | None = None,
    sender: str | None = None,
) -> int
```

Compute the effective invocation price for a tool call.

Evaluates pricing based on pass holdings, subscription status, caller
identity, argument contents, and cumulative usage volume.

**Notes**

Clamps positive ALGO prices to 2001 microALGO (2 * minFee + 1) if `allow_loss=False`.

**Parameters**

- `tool` (`str`, required):
Name of the MCP tool requested.

- `args` (`ToolArguments | None`, default `None`):
Invocation argument mapping supplied to the tool.

- `sender` (`str | None`, default `None`):
Verified Algorand address of the caller.

**Returns**

- `returns` (`int`):
Effective price in base units (microALGO for ALGO, base units for ASA).
Returns 0 if the call is free, covered by a pass, or covered by subscription.

**Example**

```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> from ai_economy_sdk.gate import PaymentGate
>>> sk, addr = account.generate_account()
>>> gate = PaymentGate(signer=DefaultAvmSigner(sk), network="mainnet", pay_to=addr, asset_id=0, prices={"ping": 0, "calc": 3000})
>>> gate.price_for("ping")
0
>>> gate.price_for("calc")
3000
>>> gate.close()
```

### `middleware`

```python
def middleware() -> list[StarletteMiddleware]
```

Generate Starlette middleware definitions for an ASGI application.

The middleware inspects the JSON-RPC body of every HTTP `POST` (any path,
any transport) and gates each `tools/call`. Use it directly when you build
the FastMCP HTTP app yourself, together with `SettleOnSuccessMiddleware`
(priced calls are refused with HTTP 500 until that middleware exists)::

mcp.add_middleware(SettleOnSuccessMiddleware(gate))
app = mcp.http_app(middleware=gate.middleware())

`wrap` does both steps for you.

**Returns**

- `returns` (`list of StarletteMiddleware`):
Middleware stack handling x402 payment challenges and verification.

### `wrap`

```python
def wrap(
    mcp: FastMCP,
    transport: Transport | None = None,
    path: str | None = None,
    **http_app_kwargs: Any = {},
) -> Any
```

Wrap a FastMCP instance into an ASGI application protected by this PaymentGate.

Adds `SettleOnSuccessMiddleware` to `mcp` and builds the FastMCP HTTP
app with the gate's ASGI middleware.

**Parameters**

- `mcp` (`FastMCP`, required):
FastMCP application instance defining MCP tools.

- `transport` (`Transport | None`, default `None`):
HTTP transport to serve. `"streamable-http"` (alias `"http"`) serves the
MCP Streamable HTTP transport at `/mcp`; `"sse"` serves the legacy SSE
transport at `/sse` + `/messages/`. When omitted, SSE is used (the
0.4 behaviour) and a `FutureWarning` is emitted: the default will change
to `"streamable-http"` in a future release.

- `path` (`str | None`, default `None`):
Endpoint path, passed to `FastMCP.http_app` (`/mcp` or `/sse` by default).

- `http_app_kwargs` (`Any`, default `{}`):

**Returns**

- `returns` (`starlette.applications.Starlette`):
ASGI application ready to serve with uvicorn.

**Raises**

- `ConfigurationError`: If `transport` is not one of the supported values.

**Example**

```python
app = gate.wrap(mcp, transport="streamable-http")  # POST /mcp
app = gate.wrap(mcp, transport="sse")  # GET /sse + POST /messages/
```

### `close`

```python
def close() -> None
```

Close resources used by this PaymentGate, including the replay store.

**Returns**

- `returns` (`None`):

**Example**

```python
>>> from algosdk import account
>>> from ai_economy_sdk.signer import DefaultAvmSigner
>>> from ai_economy_sdk.gate import PaymentGate
>>> sk, addr = account.generate_account()
>>> gate = PaymentGate(signer=DefaultAvmSigner(sk), network="mainnet", pay_to=addr, asset_id=0)
>>> gate.close()
```

## See also

- `AIEconomySDK`: High-level builder encapsulating PaymentGate.
- `DefaultAvmSigner`: Default signing implementation.

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

Source: https://x402-avm.github.io/reference/python/ai-economy-sdk/payment-gate
